code stringlengths 2 1.05M |
|---|
// Make inheritance bearable: clone one level of properties
MM.extend = function(child, parent) {
for (var property in parent.prototype) {
if (typeof child.prototype[property] == "undefined") {
child.prototype[property] = parent.prototype[property];
}
}
return child;
};
MM.getFrame = function () {
// native animation frames
// http://webstuff.nfshost.com/anim-timing/Overview.html
// http://dev.chromium.org/developers/design-documents/requestanimationframe-implementation
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// can't apply these directly to MM because Chrome needs window
// to own webkitRequestAnimationFrame (for example)
// perhaps we should namespace an alias onto window instead?
// e.g. window.mmRequestAnimationFrame?
return function(callback) {
(window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
window.setTimeout(function () {
callback(+new Date());
}, 10);
})(callback);
};
}();
// Inspired by LeafletJS
MM.transformProperty = (function(props) {
if (!this.document) return; // node.js safety
var style = document.documentElement.style;
for (var i = 0; i < props.length; i++) {
if (props[i] in style) {
return props[i];
}
}
return false;
})(['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
MM.matrixString = function(point) {
// Make the result of point.scale * point.width a whole number.
if (point.scale * point.width % 1) {
point.scale += (1 - point.scale * point.width % 1) / point.width;
}
var scale = point.scale || 1;
if (MM._browser.webkit3d) {
return 'translate3d(' +
point.x.toFixed(0) + 'px,' + point.y.toFixed(0) + 'px, 0px)' +
'scale3d(' + scale + ',' + scale + ', 1)';
} else {
return 'translate(' +
point.x.toFixed(6) + 'px,' + point.y.toFixed(6) + 'px)' +
'scale(' + scale + ',' + scale + ')';
}
};
MM._browser = (function(window) {
return {
webkit: ('WebKitCSSMatrix' in window),
webkit3d: ('WebKitCSSMatrix' in window) && ('m11' in new WebKitCSSMatrix())
};
})(this); // use this for node.js global
MM.moveElement = function(el, point) {
if (MM.transformProperty) {
// Optimize for identity transforms, where you don't actually
// need to change this element's string. Browsers can optimize for
// the .style.left case but not for this CSS case.
if (!point.scale) point.scale = 1;
if (!point.width) point.width = 0;
if (!point.height) point.height = 0;
var ms = MM.matrixString(point);
if (el[MM.transformProperty] !== ms) {
el.style[MM.transformProperty] =
el[MM.transformProperty] = ms;
}
} else {
el.style.left = point.x + 'px';
el.style.top = point.y + 'px';
// Don't set width unless asked to: this is performance-intensive
// and not always necessary
if (point.width && point.height && point.scale) {
el.style.width = Math.ceil(point.width * point.scale) + 'px';
el.style.height = Math.ceil(point.height * point.scale) + 'px';
}
}
};
// Events
// Cancel an event: prevent it from bubbling
MM.cancelEvent = function(e) {
// there's more than one way to skin this cat
e.cancelBubble = true;
e.cancel = true;
e.returnValue = false;
if (e.stopPropagation) { e.stopPropagation(); }
if (e.preventDefault) { e.preventDefault(); }
return false;
};
MM.coerceLayer = function(layerish) {
if (typeof layerish == 'string') {
// Probably a template string
return new MM.Layer(new MM.TemplatedLayer(layerish));
} else if ('draw' in layerish && typeof layerish.draw == 'function') {
// good enough, though we should probably enforce .parent and .destroy() too
return layerish;
} else {
// probably a MapProvider
return new MM.Layer(layerish);
}
};
// see http://ejohn.org/apps/jselect/event.html for the originals
MM.addEvent = function(obj, type, fn) {
if (obj.addEventListener) {
obj.addEventListener(type, fn, false);
if (type == 'mousewheel') {
obj.addEventListener('DOMMouseScroll', fn, false);
}
} else if (obj.attachEvent) {
obj['e'+type+fn] = fn;
obj[type+fn] = function(){ obj['e'+type+fn](window.event); };
obj.attachEvent('on'+type, obj[type+fn]);
}
};
MM.removeEvent = function( obj, type, fn ) {
if (obj.removeEventListener) {
obj.removeEventListener(type, fn, false);
if (type == 'mousewheel') {
obj.removeEventListener('DOMMouseScroll', fn, false);
}
} else if (obj.detachEvent) {
obj.detachEvent('on'+type, obj[type+fn]);
obj[type+fn] = null;
}
};
// Cross-browser function to get current element style property
MM.getStyle = function(el,styleProp) {
if (el.currentStyle)
return el.currentStyle[styleProp];
else if (window.getComputedStyle)
return document.defaultView.getComputedStyle(el,null).getPropertyValue(styleProp);
};
|
/**
* Create the store with asynchronously loaded reducers
*/
import { createStore, applyMiddleware, compose } from 'redux';
import { fromJS } from 'immutable';
import { routerMiddleware } from 'react-router-redux';
import createSagaMiddleware from 'redux-saga';
import createReducer from './reducers';
const sagaMiddleware = createSagaMiddleware();
const devtools = window.devToolsExtension || (() => noop => noop);
export default function configureStore(initialState = {}, history) {
// Create the store with two middlewares
// 1. sagaMiddleware: Makes redux-sagas work
// 2. routerMiddleware: Syncs the location/URL path to the state
const middlewares = [
sagaMiddleware,
routerMiddleware(history),
];
const enhancers = [
applyMiddleware(...middlewares),
devtools(),
];
const store = createStore(
createReducer(),
fromJS(initialState),
compose(...enhancers)
);
// Extensions
store.runSaga = sagaMiddleware.run;
store.asyncReducers = {}; // Async reducer registry
store.asyncSagas = {};
// Make reducers hot reloadable, see http://mxs.is/googmo
/* istanbul ignore next */
if (module.hot) {
module.hot.accept('./reducers', () => {
System.import('./reducers').then((reducerModule) => {
const createReducers = reducerModule.default;
const nextReducers = createReducers(store.asyncReducers);
store.replaceReducer(nextReducers);
});
});
}
return store;
}
|
/*
* jQuery prettyDate v1.2.0pre
*
* @author John Resig (ejohn.org)
* @author Jörn Zaefferer
* @author Timo Tijhof
*
* Based on http://ejohn.org/blog/javascript-pretty-date
* Documentation: http://bassistance.de/jquery-plugins/jquery-plugin-prettydate/
*
* Copyright 2013 Jörn Zaefferer
* Released under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*/
(function ($) {
'use strict';
var slice = Array.prototype.slice,
rES5ts = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/,
// Indexes in a rES5ts match list that are required for Date.UTC,
// Use in a loop to replace undefined with 0 (otherwise Date.UTC would give NaN)
dateUrcReqIndx = [1, 4, 5, 6, 7, 10, 11];
$.prettyDate = {
/**
* Replace numerial placeholders ({0}, {1}, ..) with the value
* at that index in the array or variadic list of arugments.
* When called with only a source, a function is returned that calls itself
* again, that time with the arguments passed to apply the template.
*
* @param {string} source Text containing {#} placeholders where
* '#' is a number referring to an index in `params`.
* @param {string|Array} [params...] List of replacement values or a
* varadic argument list starting where this argument is the first one.
*/
template: function (source, params) {
if (arguments.length === 1) {
return function () {
var args = slice.call(arguments);
args.unshift(source);
return $.prettyDate.template.apply(this, args);
};
}
// Detect different call patterns:
// * template(source, [1, 2, 3])
// * template(source, 1, 2, 3)
if (!$.isArray(params)) {
params = slice.call(arguments, 1);
}
$.each(params, function (i, n) {
source = source.replace(new RegExp('\\{' + i + '\\}', 'g'), n);
});
return source;
},
/**
* Offset from which the relative date will be generated.
* @return {Date}
*/
now: function () {
return new Date();
},
/**
* Implementation of the ES5 Date.parse specification (ES5 §15.9.4.2,
* which is a subset of ISO 8601), see http://es5.github.com/#x15.9.1.15.
* Since Date.parse already existed in old browsers and there would be
* many forms to be tested for, don't use feature-detection but just
* implement it straight up.
*
* Based on https://github.com/csnover/js-iso8601
*
* @example
* '2012'
* '2012-01-07'
* '2012-01-07T23:30:59Z'
* '2012-01-07T23:30:59+01:00'
* '2012-01-07T23:30:59.001+01:00'
* @param {string} timestamp
* @return {number} Unix epoch or NaN.
*/
parse: function (timestamp) {
var i, k, minutesOffset,
m = rES5ts.exec(timestamp);
if (!m) {
return NaN;
}
for (i = 0; (k = dateUrcReqIndx[i]); i += 1) {
m[k] = +m[k] || 0;
}
// Undefined days and months are allowed
m[2] = +m[2] || 1;
m[3] = +m[3] || 1;
if (m[8] !== 'Z' && m[9] !== undefined) {
minutesOffset = m[10] * 60 + m[11];
if (m[9] === '+') {
minutesOffset = 0 - minutesOffset;
}
} else {
minutesOffset = 0;
}
return Date.UTC(
// Year
m[1],
// Month
m[2] - 1,
// Day
m[3],
// Hour
m[4],
// Minutes
// Date.UTC allows values higher than 59 here,
// it increments hours, days etc. if needed.
m[5] + minutesOffset,
// Seconds
m[6],
// Milliseconds
m[7]
);
},
/**
* Takes an ISO time and returns a string representing how
* long ago the date represents.
* @param {string} targetTs Timestamp in ISO 8601 format.
* @return {string}
*/
format: function (target) {
var messages,
targetTime = $.prettyDate.parse(target),
nowTime = $.prettyDate.now().getTime(),
diff = (nowTime - targetTime) / 1000,
dayDiff = Math.floor(diff / 86400);
if (isNaN(dayDiff) || dayDiff < 0) {
return;
}
messages = $.prettyDate.messages;
return dayDiff === 0 && (
diff < 60 && messages.now ||
diff < 120 && messages.minute ||
diff < 3600 && messages.minutes(Math.floor(diff / 60)) ||
diff < 7200 && messages.hour ||
diff < 86400 && messages.hours(Math.floor(diff / 3600))) ||
dayDiff === 1 && messages.yesterday ||
dayDiff === 2 && (messages.dayBeforeYesterday || messages.days(dayDiff)) ||
dayDiff < 7 && messages.days(dayDiff) ||
dayDiff < 8 && messages.week ||
dayDiff < 14 && messages.days(dayDiff) ||
dayDiff < 30 && messages.weeks(Math.ceil(dayDiff / 7)) ||
dayDiff < 32 && messages.month ||
dayDiff < 363 && messages.months(Math.ceil(dayDiff / 31)) ||
dayDiff <= 380 && messages.year ||
dayDiff > 380 && messages.years(Math.ceil(dayDiff / 365));
}
};
$.prettyDate.messages = {
now: 'just now',
minute: '1 minute ago',
minutes: $.prettyDate.template('{0} minutes ago'),
hour: '1 hour ago',
hours: $.prettyDate.template('{0} hours ago'),
yesterday: 'Yesterday',
dayBeforeYesterday: 'Two days ago',
days: $.prettyDate.template('{0} days ago'),
week: '1 week ago',
weeks: $.prettyDate.template('{0} weeks ago'),
month: '1 month ago',
months: $.prettyDate.template('{0} months ago'),
year: '1 year ago',
years: $.prettyDate.template('{0} years ago')
};
/**
* @context {jQuery}
* @param {Object} options
* - {number|false} interval Time in milliseconds between updates,
* or set to false to disable auto updating interval.
* - {string} attribute Name of attribute where the timestamp should
* be accessed from.
* - {Function} value Overrides 'attribute', a custom function to get the
* timestamp. 'this' context is set to the HTMLElement.
*/
$.fn.prettyDate = function (options) {
options = $.extend({
interval: 10000,
attribute: 'title',
value: function () {
return $(this).attr(options.attribute);
}
}, options);
var elements = this;
function format() {
elements.each(function () {
var date = $.prettyDate.format(options.value.apply(this));
if (date && $(this).text() !== date) {
$(this).text(date);
}
});
}
format();
if (options.interval) {
setInterval(format, options.interval);
}
return this;
};
}(jQuery));
|
/**
* @license Highcharts JS v8.2.2 (2020-10-22)
*
* (c) 2009-2019 Sebastian Bochan, Rafal Sebestjanski
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
factory['default'] = factory;
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
define('highcharts/modules/lollipop', ['highcharts'], function (Highcharts) {
factory(Highcharts);
factory.Highcharts = Highcharts;
return factory;
});
} else {
factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
}
}(function (Highcharts) {
var _modules = Highcharts ? Highcharts._modules : {};
function _registerModule(obj, path, args, fn) {
if (!obj.hasOwnProperty(path)) {
obj[path] = fn.apply(null, args);
}
}
_registerModule(_modules, 'Series/AreaRangeSeries.js', [_modules['Core/Series/Series.js'], _modules['Core/Globals.js'], _modules['Core/Series/Point.js'], _modules['Core/Utilities.js']], function (BaseSeries, H, Point, U) {
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var noop = H.noop;
var defined = U.defined,
extend = U.extend,
isArray = U.isArray,
isNumber = U.isNumber,
pick = U.pick;
var Series = H.Series,
areaProto = BaseSeries.seriesTypes.area.prototype,
columnProto = BaseSeries.seriesTypes.column.prototype,
pointProto = Point.prototype,
seriesProto = Series.prototype;
/**
* The area range series is a carteseian series with higher and lower values for
* each point along an X axis, where the area between the values is shaded.
*
* @sample {highcharts} highcharts/demo/arearange/
* Area range chart
* @sample {highstock} stock/demo/arearange/
* Area range chart
*
* @extends plotOptions.area
* @product highcharts highstock
* @excluding stack, stacking
* @requires highcharts-more
* @optionparent plotOptions.arearange
*/
BaseSeries.seriesType('arearange', 'area', {
/**
* @see [fillColor](#plotOptions.arearange.fillColor)
* @see [fillOpacity](#plotOptions.arearange.fillOpacity)
*
* @apioption plotOptions.arearange.color
*/
/**
* @default low
* @apioption plotOptions.arearange.colorKey
*/
/**
* @see [color](#plotOptions.arearange.color)
* @see [fillOpacity](#plotOptions.arearange.fillOpacity)
*
* @apioption plotOptions.arearange.fillColor
*/
/**
* @see [color](#plotOptions.arearange.color)
* @see [fillColor](#plotOptions.arearange.fillColor)
*
* @default {highcharts} 0.75
* @default {highstock} 0.75
* @apioption plotOptions.arearange.fillOpacity
*/
/**
* Whether to apply a drop shadow to the graph line. Since 2.3 the shadow
* can be an object configuration containing `color`, `offsetX`, `offsetY`,
* `opacity` and `width`.
*
* @type {boolean|Highcharts.ShadowOptionsObject}
* @product highcharts
* @apioption plotOptions.arearange.shadow
*/
/**
* Pixel width of the arearange graph line.
*
* @since 2.3.0
*
* @private
*/
lineWidth: 1,
threshold: null,
tooltip: {
pointFormat: '<span style="color:{series.color}">\u25CF</span> ' +
'{series.name}: <b>{point.low}</b> - <b>{point.high}</b><br/>'
},
/**
* Whether the whole area or just the line should respond to mouseover
* tooltips and other mouse or touch events.
*
* @since 2.3.0
*
* @private
*/
trackByArea: true,
/**
* Extended data labels for range series types. Range series data labels use
* no `x` and `y` options. Instead, they have `xLow`, `xHigh`, `yLow` and
* `yHigh` options to allow the higher and lower data label sets
* individually.
*
* @declare Highcharts.SeriesAreaRangeDataLabelsOptionsObject
* @exclude x, y
* @since 2.3.0
* @product highcharts highstock
*
* @private
*/
dataLabels: {
align: void 0,
verticalAlign: void 0,
/**
* X offset of the lower data labels relative to the point value.
*
* @sample highcharts/plotoptions/arearange-datalabels/
* Data labels on range series
* @sample highcharts/plotoptions/arearange-datalabels/
* Data labels on range series
*/
xLow: 0,
/**
* X offset of the higher data labels relative to the point value.
*
* @sample highcharts/plotoptions/arearange-datalabels/
* Data labels on range series
*/
xHigh: 0,
/**
* Y offset of the lower data labels relative to the point value.
*
* @sample highcharts/plotoptions/arearange-datalabels/
* Data labels on range series
*/
yLow: 0,
/**
* Y offset of the higher data labels relative to the point value.
*
* @sample highcharts/plotoptions/arearange-datalabels/
* Data labels on range series
*/
yHigh: 0
}
// Prototype members
}, {
pointArrayMap: ['low', 'high'],
pointValKey: 'low',
deferTranslatePolar: true,
/* eslint-disable valid-jsdoc */
/**
* @private
*/
toYData: function (point) {
return [point.low, point.high];
},
/**
* Translate a point's plotHigh from the internal angle and radius measures
* to true plotHigh coordinates. This is an addition of the toXY method
* found in Polar.js, because it runs too early for arearanges to be
* considered (#3419).
* @private
*/
highToXY: function (point) {
// Find the polar plotX and plotY
var chart = this.chart,
xy = this.xAxis.postTranslate(point.rectPlotX,
this.yAxis.len - point.plotHigh);
point.plotHighX = xy.x - chart.plotLeft;
point.plotHigh = xy.y - chart.plotTop;
point.plotLowX = point.plotX;
},
/**
* Translate data points from raw values x and y to plotX and plotY.
* @private
*/
translate: function () {
var series = this,
yAxis = series.yAxis,
hasModifyValue = !!series.modifyValue;
areaProto.translate.apply(series);
// Set plotLow and plotHigh
series.points.forEach(function (point) {
var high = point.high,
plotY = point.plotY;
if (point.isNull) {
point.plotY = null;
}
else {
point.plotLow = plotY;
point.plotHigh = yAxis.translate(hasModifyValue ?
series.modifyValue(high, point) :
high, 0, 1, 0, 1);
if (hasModifyValue) {
point.yBottom = point.plotHigh;
}
}
});
// Postprocess plotHigh
if (this.chart.polar) {
this.points.forEach(function (point) {
series.highToXY(point);
point.tooltipPos = [
(point.plotHighX + point.plotLowX) / 2,
(point.plotHigh + point.plotLow) / 2
];
});
}
},
/**
* Extend the line series' getSegmentPath method by applying the segment
* path to both lower and higher values of the range.
* @private
*/
getGraphPath: function (points) {
var highPoints = [],
highAreaPoints = [],
i,
getGraphPath = areaProto.getGraphPath,
point,
pointShim,
linePath,
lowerPath,
options = this.options,
polar = this.chart.polar,
connectEnds = polar && options.connectEnds !== false,
connectNulls = options.connectNulls,
step = options.step,
higherPath,
higherAreaPath;
points = points || this.points;
// Create the top line and the top part of the area fill. The area fill
// compensates for null points by drawing down to the lower graph,
// moving across the null gap and starting again at the lower graph.
i = points.length;
while (i--) {
point = points[i];
// Support for polar
var highAreaPoint = polar ? {
plotX: point.rectPlotX,
plotY: point.yBottom,
doCurve: false // #5186, gaps in areasplinerange fill
} : {
plotX: point.plotX,
plotY: point.plotY,
doCurve: false // #5186, gaps in areasplinerange fill
};
if (!point.isNull &&
!connectEnds &&
!connectNulls &&
(!points[i + 1] || points[i + 1].isNull)) {
highAreaPoints.push(highAreaPoint);
}
pointShim = {
polarPlotY: point.polarPlotY,
rectPlotX: point.rectPlotX,
yBottom: point.yBottom,
// plotHighX is for polar charts
plotX: pick(point.plotHighX, point.plotX),
plotY: point.plotHigh,
isNull: point.isNull
};
highAreaPoints.push(pointShim);
highPoints.push(pointShim);
if (!point.isNull &&
!connectEnds &&
!connectNulls &&
(!points[i - 1] || points[i - 1].isNull)) {
highAreaPoints.push(highAreaPoint);
}
}
// Get the paths
lowerPath = getGraphPath.call(this, points);
if (step) {
if (step === true) {
step = 'left';
}
options.step = {
left: 'right',
center: 'center',
right: 'left'
}[step]; // swap for reading in getGraphPath
}
higherPath = getGraphPath.call(this, highPoints);
higherAreaPath = getGraphPath.call(this, highAreaPoints);
options.step = step;
// Create a line on both top and bottom of the range
linePath = []
.concat(lowerPath, higherPath);
// For the area path, we need to change the 'move' statement
// into 'lineTo'
if (!this.chart.polar && higherAreaPath[0] && higherAreaPath[0][0] === 'M') {
// This probably doesn't work for spline
higherAreaPath[0] = ['L', higherAreaPath[0][1], higherAreaPath[0][2]];
}
this.graphPath = linePath;
this.areaPath = lowerPath.concat(higherAreaPath);
// Prepare for sideways animation
linePath.isArea = true;
linePath.xMap = lowerPath.xMap;
this.areaPath.xMap = lowerPath.xMap;
return linePath;
},
/**
* Extend the basic drawDataLabels method by running it for both lower and
* higher values.
* @private
*/
drawDataLabels: function () {
var data = this.points,
length = data.length,
i,
originalDataLabels = [],
dataLabelOptions = this.options.dataLabels,
point,
up,
inverted = this.chart.inverted,
upperDataLabelOptions,
lowerDataLabelOptions;
// Split into upper and lower options. If data labels is an array, the
// first element is the upper label, the second is the lower.
//
// TODO: We want to change this and allow multiple labels for both upper
// and lower values in the future - introducing some options for which
// point value to use as Y for the dataLabel, so that this could be
// handled in Series.drawDataLabels. This would also improve performance
// since we now have to loop over all the points multiple times to work
// around the data label logic.
if (isArray(dataLabelOptions)) {
upperDataLabelOptions = dataLabelOptions[0] || { enabled: false };
lowerDataLabelOptions = dataLabelOptions[1] || { enabled: false };
}
else {
// Make copies
upperDataLabelOptions = extend({}, dataLabelOptions);
upperDataLabelOptions.x = dataLabelOptions.xHigh;
upperDataLabelOptions.y = dataLabelOptions.yHigh;
lowerDataLabelOptions = extend({}, dataLabelOptions);
lowerDataLabelOptions.x = dataLabelOptions.xLow;
lowerDataLabelOptions.y = dataLabelOptions.yLow;
}
// Draw upper labels
if (upperDataLabelOptions.enabled || this._hasPointLabels) {
// Set preliminary values for plotY and dataLabel
// and draw the upper labels
i = length;
while (i--) {
point = data[i];
if (point) {
up = upperDataLabelOptions.inside ?
point.plotHigh < point.plotLow :
point.plotHigh > point.plotLow;
point.y = point.high;
point._plotY = point.plotY;
point.plotY = point.plotHigh;
// Store original data labels and set preliminary label
// objects to be picked up in the uber method
originalDataLabels[i] = point.dataLabel;
point.dataLabel = point.dataLabelUpper;
// Set the default offset
point.below = up;
if (inverted) {
if (!upperDataLabelOptions.align) {
upperDataLabelOptions.align = up ? 'right' : 'left';
}
}
else {
if (!upperDataLabelOptions.verticalAlign) {
upperDataLabelOptions.verticalAlign = up ?
'top' :
'bottom';
}
}
}
}
this.options.dataLabels = upperDataLabelOptions;
if (seriesProto.drawDataLabels) {
// #1209:
seriesProto.drawDataLabels.apply(this, arguments);
}
// Reset state after the upper labels were created. Move
// it to point.dataLabelUpper and reassign the originals.
// We do this here to support not drawing a lower label.
i = length;
while (i--) {
point = data[i];
if (point) {
point.dataLabelUpper = point.dataLabel;
point.dataLabel = originalDataLabels[i];
delete point.dataLabels;
point.y = point.low;
point.plotY = point._plotY;
}
}
}
// Draw lower labels
if (lowerDataLabelOptions.enabled || this._hasPointLabels) {
i = length;
while (i--) {
point = data[i];
if (point) {
up = lowerDataLabelOptions.inside ?
point.plotHigh < point.plotLow :
point.plotHigh > point.plotLow;
// Set the default offset
point.below = !up;
if (inverted) {
if (!lowerDataLabelOptions.align) {
lowerDataLabelOptions.align = up ? 'left' : 'right';
}
}
else {
if (!lowerDataLabelOptions.verticalAlign) {
lowerDataLabelOptions.verticalAlign = up ?
'bottom' :
'top';
}
}
}
}
this.options.dataLabels = lowerDataLabelOptions;
if (seriesProto.drawDataLabels) {
seriesProto.drawDataLabels.apply(this, arguments);
}
}
// Merge upper and lower into point.dataLabels for later destroying
if (upperDataLabelOptions.enabled) {
i = length;
while (i--) {
point = data[i];
if (point) {
point.dataLabels = [
point.dataLabelUpper,
point.dataLabel
].filter(function (label) {
return !!label;
});
}
}
}
// Reset options
this.options.dataLabels = dataLabelOptions;
},
alignDataLabel: function () {
columnProto.alignDataLabel.apply(this, arguments);
},
drawPoints: function () {
var series = this,
pointLength = series.points.length,
point,
i;
// Draw bottom points
seriesProto.drawPoints
.apply(series, arguments);
// Prepare drawing top points
i = 0;
while (i < pointLength) {
point = series.points[i];
// Save original props to be overridden by temporary props for top
// points
point.origProps = {
plotY: point.plotY,
plotX: point.plotX,
isInside: point.isInside,
negative: point.negative,
zone: point.zone,
y: point.y
};
point.lowerGraphic = point.graphic;
point.graphic = point.upperGraphic;
point.plotY = point.plotHigh;
if (defined(point.plotHighX)) {
point.plotX = point.plotHighX;
}
point.y = point.high;
point.negative = point.high < (series.options.threshold || 0);
point.zone = (series.zones.length && point.getZone());
if (!series.chart.polar) {
point.isInside = point.isTopInside = (typeof point.plotY !== 'undefined' &&
point.plotY >= 0 &&
point.plotY <= series.yAxis.len && // #3519
point.plotX >= 0 &&
point.plotX <= series.xAxis.len);
}
i++;
}
// Draw top points
seriesProto.drawPoints.apply(series, arguments);
// Reset top points preliminary modifications
i = 0;
while (i < pointLength) {
point = series.points[i];
point.upperGraphic = point.graphic;
point.graphic = point.lowerGraphic;
extend(point, point.origProps);
delete point.origProps;
i++;
}
},
/* eslint-enable valid-jsdoc */
setStackedPoints: noop
}, {
/**
* Range series only. The high or maximum value for each data point.
* @name Highcharts.Point#high
* @type {number|undefined}
*/
/**
* Range series only. The low or minimum value for each data point.
* @name Highcharts.Point#low
* @type {number|undefined}
*/
/* eslint-disable valid-jsdoc */
/**
* @private
*/
setState: function () {
var prevState = this.state,
series = this.series,
isPolar = series.chart.polar;
if (!defined(this.plotHigh)) {
// Boost doesn't calculate plotHigh
this.plotHigh = series.yAxis.toPixels(this.high, true);
}
if (!defined(this.plotLow)) {
// Boost doesn't calculate plotLow
this.plotLow = this.plotY = series.yAxis.toPixels(this.low, true);
}
if (series.stateMarkerGraphic) {
series.lowerStateMarkerGraphic = series.stateMarkerGraphic;
series.stateMarkerGraphic = series.upperStateMarkerGraphic;
}
// Change state also for the top marker
this.graphic = this.upperGraphic;
this.plotY = this.plotHigh;
if (isPolar) {
this.plotX = this.plotHighX;
}
// Top state:
pointProto.setState.apply(this, arguments);
this.state = prevState;
// Now restore defaults
this.plotY = this.plotLow;
this.graphic = this.lowerGraphic;
if (isPolar) {
this.plotX = this.plotLowX;
}
if (series.stateMarkerGraphic) {
series.upperStateMarkerGraphic = series.stateMarkerGraphic;
series.stateMarkerGraphic = series.lowerStateMarkerGraphic;
// Lower marker is stored at stateMarkerGraphic
// to avoid reference duplication (#7021)
series.lowerStateMarkerGraphic = void 0;
}
pointProto.setState.apply(this, arguments);
},
haloPath: function () {
var isPolar = this.series.chart.polar,
path = [];
// Bottom halo
this.plotY = this.plotLow;
if (isPolar) {
this.plotX = this.plotLowX;
}
if (this.isInside) {
path = pointProto.haloPath.apply(this, arguments);
}
// Top halo
this.plotY = this.plotHigh;
if (isPolar) {
this.plotX = this.plotHighX;
}
if (this.isTopInside) {
path = path.concat(pointProto.haloPath.apply(this, arguments));
}
return path;
},
destroyElements: function () {
var graphics = ['lowerGraphic', 'upperGraphic'];
graphics.forEach(function (graphicName) {
if (this[graphicName]) {
this[graphicName] =
this[graphicName].destroy();
}
}, this);
// Clear graphic for states, removed in the above each:
this.graphic = null;
return pointProto.destroyElements.apply(this, arguments);
},
isValid: function () {
return isNumber(this.low) && isNumber(this.high);
}
/* eslint-enable valid-jsdoc */
});
/**
* A `arearange` series. If the [type](#series.arearange.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
*
* @extends series,plotOptions.arearange
* @excluding dataParser, dataURL, stack, stacking
* @product highcharts highstock
* @requires highcharts-more
* @apioption series.arearange
*/
/**
* @see [fillColor](#series.arearange.fillColor)
* @see [fillOpacity](#series.arearange.fillOpacity)
*
* @apioption series.arearange.color
*/
/**
* An array of data points for the series. For the `arearange` series type,
* points can be given in the following ways:
*
* 1. An array of arrays with 3 or 2 values. In this case, the values
* correspond to `x,low,high`. If the first value is a string, it is
* applied as the name of the point, and the `x` value is inferred.
* The `x` value can also be omitted, in which case the inner arrays
* should be of length 2\. Then the `x` value is automatically calculated,
* either starting at 0 and incremented by 1, or from `pointStart`
* and `pointInterval` given in the series options.
* ```js
* data: [
* [0, 8, 3],
* [1, 1, 1],
* [2, 6, 8]
* ]
* ```
*
* 2. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.arearange.turboThreshold),
* this option is not available.
* ```js
* data: [{
* x: 1,
* low: 9,
* high: 0,
* name: "Point2",
* color: "#00FF00"
* }, {
* x: 1,
* low: 3,
* high: 4,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @sample {highcharts} highcharts/series/data-array-of-arrays/
* Arrays of numeric x and y
* @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/
* Arrays of datetime x and y
* @sample {highcharts} highcharts/series/data-array-of-name-value/
* Arrays of point.name and y
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<Array<(number|string),number>|Array<(number|string),number,number>|*>}
* @extends series.line.data
* @excluding marker, y
* @product highcharts highstock
* @apioption series.arearange.data
*/
/**
* @extends series.arearange.dataLabels
* @product highcharts highstock
* @apioption series.arearange.data.dataLabels
*/
/**
* @see [color](#series.arearange.color)
* @see [fillOpacity](#series.arearange.fillOpacity)
*
* @apioption series.arearange.fillColor
*/
/**
* @see [color](#series.arearange.color)
* @see [fillColor](#series.arearange.fillColor)
*
* @default {highcharts} 0.75
* @default {highstock} 0.75
* @apioption series.arearange.fillOpacity
*/
/**
* The high or maximum value for each data point.
*
* @type {number}
* @product highcharts highstock
* @apioption series.arearange.data.high
*/
/**
* The low or minimum value for each data point.
*
* @type {number}
* @product highcharts highstock
* @apioption series.arearange.data.low
*/
''; // adds doclets above to tranpiled file
});
_registerModule(_modules, 'Series/ColumnRangeSeries.js', [_modules['Core/Series/Series.js'], _modules['Core/Globals.js'], _modules['Core/Options.js'], _modules['Core/Utilities.js']], function (BaseSeries, H, O, U) {
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var noop = H.noop;
var defaultOptions = O.defaultOptions;
var clamp = U.clamp,
merge = U.merge,
pick = U.pick;
var columnProto = BaseSeries.seriesTypes.column.prototype;
/**
* The column range is a cartesian series type with higher and lower
* Y values along an X axis. To display horizontal bars, set
* [chart.inverted](#chart.inverted) to `true`.
*
* @sample {highcharts|highstock} highcharts/demo/columnrange/
* Inverted column range
*
* @extends plotOptions.column
* @since 2.3.0
* @excluding negativeColor, stacking, softThreshold, threshold
* @product highcharts highstock
* @requires highcharts-more
* @optionparent plotOptions.columnrange
*/
var columnRangeOptions = {
/**
* Extended data labels for range series types. Range series data labels
* have no `x` and `y` options. Instead,
they have `xLow`,
`xHigh`,
* `yLow` and `yHigh` options to allow the higher and lower data label
* sets individually.
*
* @declare Highcharts.SeriesAreaRangeDataLabelsOptionsObject
* @extends plotOptions.arearange.dataLabels
* @since 2.3.0
* @product highcharts highstock
* @apioption plotOptions.columnrange.dataLabels
*/
pointRange: null,
/** @ignore-option */
marker: null,
states: {
hover: {
/** @ignore-option */
halo: false
}
}
};
/**
* The ColumnRangeSeries class
*
* @private
* @class
* @name Highcharts.seriesTypes.columnrange
*
* @augments Highcharts.Series
*/
BaseSeries.seriesType('columnrange', 'arearange', merge(defaultOptions.plotOptions.column, defaultOptions.plotOptions.arearange, columnRangeOptions), {
// eslint-disable-next-line valid-jsdoc
/**
* Translate data points from raw values x and y to plotX and plotY
* @private
*/
translate: function () {
var series = this,
yAxis = series.yAxis,
xAxis = series.xAxis,
startAngleRad = xAxis.startAngleRad,
start,
chart = series.chart,
isRadial = series.xAxis.isRadial,
safeDistance = Math.max(chart.chartWidth,
chart.chartHeight) + 999,
plotHigh;
// eslint-disable-next-line valid-jsdoc
/**
* Don't draw too far outside plot area (#6835)
* @private
*/
function safeBounds(pixelPos) {
return clamp(pixelPos, -safeDistance, safeDistance);
}
columnProto.translate.apply(series);
// Set plotLow and plotHigh
series.points.forEach(function (point) {
var shapeArgs = point.shapeArgs,
minPointLength = series.options.minPointLength,
heightDifference,
height,
y;
point.plotHigh = plotHigh = safeBounds(yAxis.translate(point.high, 0, 1, 0, 1));
point.plotLow = safeBounds(point.plotY);
// adjust shape
y = plotHigh;
height = pick(point.rectPlotY, point.plotY) - plotHigh;
// Adjust for minPointLength
if (Math.abs(height) < minPointLength) {
heightDifference = (minPointLength - height);
height += heightDifference;
y -= heightDifference / 2;
// Adjust for negative ranges or reversed Y axis (#1457)
}
else if (height < 0) {
height *= -1;
y -= height;
}
if (isRadial) {
start = point.barX + startAngleRad;
point.shapeType = 'arc';
point.shapeArgs = series.polarArc(y + height, y, start, start + point.pointWidth);
}
else {
shapeArgs.height = height;
shapeArgs.y = y;
point.tooltipPos = chart.inverted ?
[
yAxis.len + yAxis.pos - chart.plotLeft - y -
height / 2,
xAxis.len + xAxis.pos - chart.plotTop -
shapeArgs.x - shapeArgs.width / 2,
height
] : [
xAxis.left - chart.plotLeft + shapeArgs.x +
shapeArgs.width / 2,
yAxis.pos - chart.plotTop + y + height / 2,
height
]; // don't inherit from column tooltip position - #3372
}
});
},
directTouch: true,
trackerGroups: ['group', 'dataLabelsGroup'],
drawGraph: noop,
getSymbol: noop,
// Overrides from modules that may be loaded after this module
crispCol: function () {
return columnProto.crispCol.apply(this, arguments);
},
drawPoints: function () {
return columnProto.drawPoints.apply(this, arguments);
},
drawTracker: function () {
return columnProto.drawTracker.apply(this, arguments);
},
getColumnMetrics: function () {
return columnProto.getColumnMetrics.apply(this, arguments);
},
pointAttribs: function () {
return columnProto.pointAttribs.apply(this, arguments);
},
animate: function () {
return columnProto.animate.apply(this, arguments);
},
polarArc: function () {
return columnProto.polarArc.apply(this, arguments);
},
translate3dPoints: function () {
return columnProto.translate3dPoints.apply(this, arguments);
},
translate3dShapes: function () {
return columnProto.translate3dShapes.apply(this, arguments);
}
}, {
setState: columnProto.pointClass.prototype.setState
});
/**
* A `columnrange` series. If the [type](#series.columnrange.type)
* option is not specified, it is inherited from
* [chart.type](#chart.type).
*
* @extends series,plotOptions.columnrange
* @excluding dataParser, dataURL, stack, stacking
* @product highcharts highstock
* @requires highcharts-more
* @apioption series.columnrange
*/
/**
* An array of data points for the series. For the `columnrange` series
* type, points can be given in the following ways:
*
* 1. An array of arrays with 3 or 2 values. In this case, the values correspond
* to `x,low,high`. If the first value is a string, it is applied as the name
* of the point, and the `x` value is inferred. The `x` value can also be
* omitted, in which case the inner arrays should be of length 2\. Then the
* `x` value is automatically calculated, either starting at 0 and
* incremented by 1, or from `pointStart` and `pointInterval` given in the
* series options.
* ```js
* data: [
* [0, 4, 2],
* [1, 2, 1],
* [2, 9, 10]
* ]
* ```
*
* 2. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.columnrange.turboThreshold), this option is not
* available.
* ```js
* data: [{
* x: 1,
* low: 0,
* high: 4,
* name: "Point2",
* color: "#00FF00"
* }, {
* x: 1,
* low: 5,
* high: 3,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @sample {highcharts} highcharts/series/data-array-of-arrays/
* Arrays of numeric x and y
* @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/
* Arrays of datetime x and y
* @sample {highcharts} highcharts/series/data-array-of-name-value/
* Arrays of point.name and y
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<Array<(number|string),number>|Array<(number|string),number,number>|*>}
* @extends series.arearange.data
* @excluding marker
* @product highcharts highstock
* @apioption series.columnrange.data
*/
/**
* @extends series.columnrange.dataLabels
* @product highcharts highstock
* @apioption series.columnrange.data.dataLabels
*/
/**
* @excluding halo, lineWidth, lineWidthPlus, marker
* @product highcharts highstock
* @apioption series.columnrange.states.hover
*/
/**
* @excluding halo, lineWidth, lineWidthPlus, marker
* @product highcharts highstock
* @apioption series.columnrange.states.select
*/
''; // adds doclets above into transpiled
});
_registerModule(_modules, 'Series/DumbbellSeries.js', [_modules['Core/Series/Series.js'], _modules['Core/Renderer/SVG/SVGRenderer.js'], _modules['Core/Globals.js'], _modules['Core/Utilities.js']], function (BaseSeries, SVGRenderer, H, U) {
/* *
*
* (c) 2010-2020 Sebastian Bochan, Rafal Sebestjanski
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var noop = H.noop;
var extend = U.extend,
pick = U.pick;
var seriesProto = H.Series.prototype, seriesTypes = BaseSeries.seriesTypes, areaRangeProto = seriesTypes.arearange.prototype, columnRangeProto = seriesTypes.columnrange.prototype, colProto = seriesTypes.column.prototype, areaRangePointProto = areaRangeProto.pointClass.prototype, TrackerMixin = H.TrackerMixin; // Interaction
/**
* The dumbbell series is a cartesian series with higher and lower values for
* each point along an X axis, connected with a line between the values.
* Requires `highcharts-more.js` and `modules/dumbbell.js`.
*
* @sample {highcharts} highcharts/demo/dumbbell/
* Dumbbell chart
* @sample {highcharts} highcharts/series-dumbbell/styled-mode-dumbbell/
* Styled mode
*
* @extends plotOptions.arearange
* @product highcharts highstock
* @excluding fillColor, fillOpacity, lineWidth, stack, stacking,
* stickyTracking, trackByArea, boostThreshold, boostBlending
* @since 8.0.0
* @optionparent plotOptions.dumbbell
*/
BaseSeries.seriesType('dumbbell', 'arearange', {
/** @ignore-option */
trackByArea: false,
/** @ignore-option */
fillColor: 'none',
/** @ignore-option */
lineWidth: 0,
pointRange: 1,
/**
* Pixel width of the line that connects the dumbbell point's values.
*
* @since 8.0.0
* @product highcharts highstock
*/
connectorWidth: 1,
/** @ignore-option */
stickyTracking: false,
groupPadding: 0.2,
crisp: false,
pointPadding: 0.1,
/**
* Color of the start markers in a dumbbell graph.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @since 8.0.0
* @product highcharts highstock
*/
lowColor: '#333333',
/**
* Color of the line that connects the dumbbell point's values.
* By default it is the series' color.
*
* @type {string}
* @product highcharts highstock
* @since 8.0.0
* @apioption plotOptions.dumbbell.connectorColor
*/
states: {
hover: {
/** @ignore-option */
lineWidthPlus: 0,
/**
* The additional connector line width for a hovered point.
*
* @since 8.0.0
* @product highcharts highstock
*/
connectorWidthPlus: 1,
/** @ignore-option */
halo: false
}
}
}, {
trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'],
drawTracker: TrackerMixin.drawTrackerPoint,
drawGraph: noop,
crispCol: colProto.crispCol,
/**
* Get connector line path and styles that connects dumbbell point's low and
* high values.
* @private
*
* @param {Highcharts.Series} this The series of points.
* @param {Highcharts.Point} point The point to inspect.
*
* @return {Highcharts.SVGAttributes} attribs The path and styles.
*/
getConnectorAttribs: function (point) {
var series = this, chart = series.chart, pointOptions = point.options, seriesOptions = series.options, xAxis = series.xAxis, yAxis = series.yAxis, connectorWidth = pick(pointOptions.connectorWidth, seriesOptions.connectorWidth), connectorColor = pick(pointOptions.connectorColor, seriesOptions.connectorColor, pointOptions.color, point.zone ? point.zone.color : void 0, point.color), connectorWidthPlus = pick(seriesOptions.states &&
seriesOptions.states.hover &&
seriesOptions.states.hover.connectorWidthPlus, 1), dashStyle = pick(pointOptions.dashStyle, seriesOptions.dashStyle), pointTop = pick(point.plotLow, point.plotY), pxThreshold = yAxis.toPixels(seriesOptions.threshold || 0, true), pointHeight = chart.inverted ?
yAxis.len - pxThreshold : pxThreshold, pointBottom = pick(point.plotHigh, pointHeight), attribs, origProps;
if (point.state) {
connectorWidth = connectorWidth + connectorWidthPlus;
}
if (pointTop < 0) {
pointTop = 0;
}
else if (pointTop >= yAxis.len) {
pointTop = yAxis.len;
}
if (pointBottom < 0) {
pointBottom = 0;
}
else if (pointBottom >= yAxis.len) {
pointBottom = yAxis.len;
}
if (point.plotX < 0 || point.plotX > xAxis.len) {
connectorWidth = 0;
}
// Connector should reflect upper marker's zone color
if (point.upperGraphic) {
origProps = {
y: point.y,
zone: point.zone
};
point.y = point.high;
point.zone = point.zone ? point.getZone() : void 0;
connectorColor = pick(pointOptions.connectorColor, seriesOptions.connectorColor, pointOptions.color, point.zone ? point.zone.color : void 0, point.color);
extend(point, origProps);
}
attribs = {
d: SVGRenderer.prototype.crispLine([[
'M',
point.plotX,
pointTop
], [
'L',
point.plotX,
pointBottom
]], connectorWidth, 'ceil')
};
if (!chart.styledMode) {
attribs.stroke = connectorColor;
attribs['stroke-width'] = connectorWidth;
if (dashStyle) {
attribs.dashstyle = dashStyle;
}
}
return attribs;
},
/**
* Draw connector line that connects dumbbell point's low and high values.
* @private
*
* @param {Highcharts.Series} this The series of points.
* @param {Highcharts.Point} point The point to inspect.
*
* @return {void}
*/
drawConnector: function (point) {
var series = this,
animationLimit = pick(series.options.animationLimit, 250),
verb = point.connector && series.chart.pointCount < animationLimit ?
'animate' : 'attr';
if (!point.connector) {
point.connector = series.chart.renderer.path()
.addClass('highcharts-lollipop-stem')
.attr({
zIndex: -1
})
.add(series.markerGroup);
}
point.connector[verb](this.getConnectorAttribs(point));
},
/**
* Return the width and x offset of the dumbbell adjusted for grouping,
* groupPadding, pointPadding, pointWidth etc.
*
* @private
*
* @function Highcharts.seriesTypes.column#getColumnMetrics
*
* @param {Highcharts.Series} this The series of points.
*
* @return {Highcharts.ColumnMetricsObject} metrics shapeArgs
*
*/
getColumnMetrics: function () {
var metrics = colProto.getColumnMetrics.apply(this,
arguments);
metrics.offset += metrics.width / 2;
return metrics;
},
translatePoint: areaRangeProto.translate,
setShapeArgs: columnRangeProto.translate,
/**
* Translate each point to the plot area coordinate system and find
* shape positions
*
* @private
*
* @function Highcharts.seriesTypes.dumbbell#translate
*
* @param {Highcharts.Series} this The series of points.
*
* @return {void}
*/
translate: function () {
// Calculate shapeargs
this.setShapeArgs.apply(this);
// Calculate point low / high values
this.translatePoint.apply(this, arguments);
// Correct x position
this.points.forEach(function (point) {
var shapeArgs = point.shapeArgs,
pointWidth = point.pointWidth;
point.plotX = shapeArgs.x;
shapeArgs.x = point.plotX - pointWidth / 2;
point.tooltipPos = null;
});
this.columnMetrics.offset -= this.columnMetrics.width / 2;
},
seriesDrawPoints: areaRangeProto.drawPoints,
/**
* Extend the arearange series' drawPoints method by applying a connector
* and coloring markers.
* @private
*
* @function Highcharts.Series#drawPoints
*
* @param {Highcharts.Series} this The series of points.
*
* @return {void}
*/
drawPoints: function () {
var series = this,
chart = series.chart,
pointLength = series.points.length,
seriesLowColor = series.lowColor = series.options.lowColor,
i = 0,
lowerGraphicColor,
point,
zoneColor;
this.seriesDrawPoints.apply(series, arguments);
// Draw connectors and color upper markers
while (i < pointLength) {
point = series.points[i];
series.drawConnector(point);
if (point.upperGraphic) {
point.upperGraphic.element.point = point;
point.upperGraphic.addClass('highcharts-lollipop-high');
}
point.connector.element.point = point;
if (point.lowerGraphic) {
zoneColor = point.zone && point.zone.color;
lowerGraphicColor = pick(point.options.lowColor, seriesLowColor, point.options.color, zoneColor, point.color, series.color);
if (!chart.styledMode) {
point.lowerGraphic.attr({
fill: lowerGraphicColor
});
}
point.lowerGraphic.addClass('highcharts-lollipop-low');
}
i++;
}
},
/**
* Get non-presentational attributes for a point. Used internally for
* both styled mode and classic. Set correct position in link with connector
* line.
*
* @see Series#pointAttribs
*
* @function Highcharts.Series#markerAttribs
*
* @param {Highcharts.Series} this The series of points.
*
* @return {Highcharts.SVGAttributes}
* A hash containing those attributes that are not settable from
* CSS.
*/
markerAttribs: function () {
var ret = areaRangeProto.markerAttribs.apply(this,
arguments);
ret.x = Math.floor(ret.x);
ret.y = Math.floor(ret.y);
return ret;
},
/**
* Get presentational attributes
*
* @private
* @function Highcharts.seriesTypes.column#pointAttribs
*
* @param {Highcharts.Series} this The series of points.
* @param {Highcharts.Point} point The point to inspect.
* @param {string} state current state of point (normal, hover, select)
*
* @return {Highcharts.SVGAttributes} pointAttribs SVGAttributes
*/
pointAttribs: function (point, state) {
var pointAttribs;
pointAttribs = seriesProto.pointAttribs.apply(this, arguments);
if (state === 'hover') {
delete pointAttribs.fill;
}
return pointAttribs;
}
}, {
// seriesTypes doesn't inherit from arearange point proto so put below
// methods rigidly.
destroyElements: areaRangePointProto.destroyElements,
isValid: areaRangePointProto.isValid,
pointSetState: areaRangePointProto.setState,
/**
* Set the point's state extended by have influence on the connector
* (between low and high value).
*
* @private
* @param {Highcharts.Point} this The point to inspect.
*
* @return {void}
*/
setState: function () {
var point = this,
series = point.series,
chart = series.chart,
seriesLowColor = series.options.lowColor,
seriesMarker = series.options.marker,
pointOptions = point.options,
pointLowColor = pointOptions.lowColor,
zoneColor = point.zone && point.zone.color,
lowerGraphicColor = pick(pointLowColor,
seriesLowColor,
pointOptions.color,
zoneColor,
point.color,
series.color),
verb = 'attr',
upperGraphicColor,
origProps;
this.pointSetState.apply(this, arguments);
if (!point.state) {
verb = 'animate';
if (point.lowerGraphic && !chart.styledMode) {
point.lowerGraphic.attr({
fill: lowerGraphicColor
});
if (point.upperGraphic) {
origProps = {
y: point.y,
zone: point.zone
};
point.y = point.high;
point.zone = point.zone ? point.getZone() : void 0;
upperGraphicColor = pick(point.marker ? point.marker.fillColor : void 0, seriesMarker ? seriesMarker.fillColor : void 0, pointOptions.color, point.zone ? point.zone.color : void 0, point.color);
point.upperGraphic.attr({
fill: upperGraphicColor
});
extend(point, origProps);
}
}
}
point.connector[verb](series.getConnectorAttribs(point));
}
});
/**
* The `dumbbell` series. If the [type](#series.dumbbell.type) option is
* not specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.dumbbell
* @excluding boostThreshold, boostBlending
* @product highcharts highstock
* @requires highcharts-more
* @requires modules/dumbbell
* @apioption series.dumbbell
*/
/**
* An array of data points for the series. For the `dumbbell` series
* type, points can be given in the following ways:
*
* 1. An array of arrays with 3 or 2 values. In this case, the values correspond
* to `x,low,high`. If the first value is a string, it is applied as the name
* of the point, and the `x` value is inferred. The `x` value can also be
* omitted, in which case the inner arrays should be of length 2\. Then the
* `x` value is automatically calculated, either starting at 0 and
* incremented by 1, or from `pointStart` and `pointInterval` given in the
* series options.
* ```js
* data: [
* [0, 4, 2],
* [1, 2, 1],
* [2, 9, 10]
* ]
* ```
*
* 2. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.dumbbell.turboThreshold), this option is not
* available.
* ```js
* data: [{
* x: 1,
* low: 0,
* high: 4,
* name: "Point2",
* color: "#00FF00",
* lowColor: "#00FFFF",
* connectorWidth: 3,
* connectorColor: "#FF00FF"
* }, {
* x: 1,
* low: 5,
* high: 3,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @sample {highcharts} highcharts/series/data-array-of-arrays/
* Arrays of numeric x and y
* @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/
* Arrays of datetime x and y
* @sample {highcharts} highcharts/series/data-array-of-name-value/
* Arrays of point.name and y
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<Array<(number|string),number>|Array<(number|string),number,number>|*>}
* @extends series.arearange.data
* @product highcharts highstock
* @apioption series.dumbbell.data
*/
/**
* Color of the line that connects the dumbbell point's values.
* By default it is the series' color.
*
* @type {string}
* @since 8.0.0
* @product highcharts highstock
* @apioption series.dumbbell.data.connectorColor
*/
/**
* Pixel width of the line that connects the dumbbell point's values.
*
* @type {number}
* @since 8.0.0
* @default 1
* @product highcharts highstock
* @apioption series.dumbbell.data.connectorWidth
*/
/**
* Color of the start markers in a dumbbell graph.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @since 8.0.0
* @default #333333
* @product highcharts highstock
* @apioption series.dumbbell.data.lowColor
*/
''; // adds doclets above to transpiled file
});
_registerModule(_modules, 'Series/LollipopSeries.js', [_modules['Core/Series/Point.js'], _modules['Core/Series/Series.js'], _modules['Core/Globals.js'], _modules['Core/Utilities.js']], function (Point, BaseSeries, H, U) {
/* *
*
* (c) 2010-2020 Sebastian Bochan, Rafal Sebestjanski
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var isObject = U.isObject,
pick = U.pick;
var seriesTypes = BaseSeries.seriesTypes,
areaProto = seriesTypes.area.prototype,
colProto = seriesTypes.column.prototype;
/**
* The lollipop series is a carteseian series with a line anchored from
* the x axis and a dot at the end to mark the value.
* Requires `highcharts-more.js`, `modules/dumbbell.js` and
* `modules/lollipop.js`.
*
* @sample {highcharts} highcharts/demo/lollipop/
* Lollipop chart
* @sample {highcharts} highcharts/series-dumbbell/styled-mode-dumbbell/
* Styled mode
*
* @extends plotOptions.dumbbell
* @product highcharts highstock
* @excluding fillColor, fillOpacity, lineWidth, stack, stacking, lowColor,
* stickyTracking, trackByArea
* @since 8.0.0
* @optionparent plotOptions.lollipop
*/
BaseSeries.seriesType('lollipop', 'dumbbell', {
/** @ignore-option */
lowColor: void 0,
/** @ignore-option */
threshold: 0,
/** @ignore-option */
connectorWidth: 1,
/** @ignore-option */
groupPadding: 0.2,
/** @ignore-option */
pointPadding: 0.1,
/** @ignore-option */
states: {
hover: {
/** @ignore-option */
lineWidthPlus: 0,
/** @ignore-option */
connectorWidthPlus: 1,
/** @ignore-option */
halo: false
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">●</span> {series.name}: <b>{point.y}</b><br/>'
}
}, {
pointArrayMap: ['y'],
pointValKey: 'y',
toYData: function (point) {
return [pick(point.y, point.low)];
},
translatePoint: areaProto.translate,
drawPoint: areaProto.drawPoints,
drawDataLabels: colProto.drawDataLabels,
setShapeArgs: colProto.translate
}, {
pointSetState: areaProto.pointClass.prototype.setState,
setState: H.seriesTypes.dumbbell.prototype.pointClass.prototype.setState,
init: function (series, options, x) {
if (isObject(options) && 'low' in options) {
options.y = options.low;
delete options.low;
}
return Point.prototype.init.apply(this, arguments);
}
});
/**
* The `lollipop` series. If the [type](#series.lollipop.type) option is
* not specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.lollipop,
* @excluding boostThreshold, boostBlending
* @product highcharts highstock
* @requires highcharts-more
* @requires modules/dumbbell
* @requires modules/lollipop
* @apioption series.lollipop
*/
/**
* An array of data points for the series. For the `lollipop` series type,
* points can be given in the following ways:
*
* 1. An array of numerical values. In this case, the numerical values will be
* interpreted as `y` options. The `x` values will be automatically
* calculated, either starting at 0 and incremented by 1, or from
* `pointStart` and `pointInterval` given in the series options. If the axis
* has categories, these will be used. Example:
* ```js
* data: [0, 5, 3, 5]
* ```
*
* 2. An array of arrays with 2 values. In this case, the values correspond to
* `x,y`. If the first value is a string, it is applied as the name of the
* point, and the `x` value is inferred.
* ```js
* data: [
* [0, 6],
* [1, 2],
* [2, 6]
* ]
* ```
*
* 3. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.lollipop.turboThreshold), this option is not
* available.
* ```js
* data: [{
* x: 1,
* y: 9,
* name: "Point2",
* color: "#00FF00",
* connectorWidth: 3,
* connectorColor: "#FF00FF"
* }, {
* x: 1,
* y: 6,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @sample {highcharts} highcharts/chart/reflow-true/
* Numerical values
* @sample {highcharts} highcharts/series/data-array-of-arrays/
* Arrays of numeric x and y
* @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/
* Arrays of datetime x and y
* @sample {highcharts} highcharts/series/data-array-of-name-value/
* Arrays of point.name and y
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<number|Array<(number|string),(number|null)>|null|*>}
* @extends series.dumbbell.data
* @excluding high, low, lowColor
* @product highcharts highstock
* @apioption series.lollipop.data
*/
/**
* The y value of the point.
*
* @type {number|null}
* @product highcharts highstock
* @apioption series.line.data.y
*/
''; // adds doclets above to transpiled file
});
_registerModule(_modules, 'masters/modules/lollipop.src.js', [], function () {
});
})); |
/*!
* Bootstrap-select v1.13.18 (https://developer.snapappointments.com/bootstrap-select)
*
* Copyright 2012-2020 SnapAppointments, LLC
* Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE)
*/
!function(e,t){void 0===e&&void 0!==window&&(e=window),"function"==typeof define&&define.amd?define(["jquery"],function(e){return t(e)}):"object"==typeof module&&module.exports?module.exports=t(require("jquery")):t(e.jQuery)}(this,function(e){e.fn.selectpicker.defaults={noneSelectedText:"V\xe1lasszon!",noneResultsText:"Nincs tal\xe1lat {0}",countSelectedText:function(e,t){return"{0} elem kiv\xe1lasztva"},maxOptionsText:function(e,t){return["Legfeljebb {n} elem v\xe1laszthat\xf3","A csoportban legfeljebb {n} elem v\xe1laszthat\xf3"]},selectAllText:"Mind",deselectAllText:"Egyik sem",multipleSeparator:", "}}); |
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<e8b636a26472c96224e2eadc9f2d6038>>
* @flow
* @lightSyntaxTransform
* @nogrep
*/
/* eslint-disable */
'use strict';
/*::
import type { NormalizationSplitOperation } from 'relay-runtime';
*/
var node/*: NormalizationSplitOperation*/ = {
"kind": "SplitOperation",
"metadata": {},
"name": "RelayModernEnvironmentExecuteSubscriptionWithMatchTestPlainUserNameRenderer_name$normalization",
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "plaintext",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "PlainUserNameData",
"kind": "LinkedField",
"name": "data",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "text",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
}
],
"storageKey": null
}
]
};
if (__DEV__) {
(node/*: any*/).hash = "66782037b8711299a7b744a9ff2840c5";
}
module.exports = node;
|
#pragma strict
private var originalScale: Vector3;
var playSound: boolean = true;
function Start () {
originalScale = this.transform.localScale;
this.transform.localScale *= 0.9;
}
function OnMouseEnter () {
this.transform.localScale = originalScale;
}
function OnMouseExit () {
this.transform.localScale = originalScale * 0.9;
}
function OnMouseDown () {
if (playSound) {
new OTSound('N4');
}
this.transform.localScale = originalScale * 0.8;
}
function OnMouseUp () {
this.transform.localScale = originalScale * 0.9;
} |
import React from 'react';
import { EmojiButton } from './emoji-button';
export default { component: EmojiButton, title: 'Examples / Emoji Button' };
export const WithArgs = (args) => <EmojiButton {...args} />;
WithArgs.args = { label: 'With args' };
export const Basic = () => <EmojiButton label="Click me" />;
|
/**
* @ngdoc service
* @name umbraco.resources.contentTypeResource
* @description Loads in data for content types
**/
function contentTypeResource($q, $http, umbRequestHelper, umbDataFormatter) {
return {
getCount: function () {
return umbRequestHelper.resourcePromise(
$http.get(
umbRequestHelper.getApiUrl(
"contentTypeApiBaseUrl",
"GetCount")),
'Failed to retrieve count');
},
getAvailableCompositeContentTypes: function (contentTypeId, filterContentTypes, filterPropertyTypes) {
if (!filterContentTypes) {
filterContentTypes = [];
}
if (!filterPropertyTypes) {
filterPropertyTypes = [];
}
var query = {
contentTypeId: contentTypeId,
filterContentTypes: filterContentTypes,
filterPropertyTypes: filterPropertyTypes
};
return umbRequestHelper.resourcePromise(
$http.post(
umbRequestHelper.getApiUrl(
"contentTypeApiBaseUrl",
"GetAvailableCompositeContentTypes"),
query),
'Failed to retrieve data for content type id ' + contentTypeId);
},
/**
* @ngdoc method
* @name umbraco.resources.contentTypeResource#getAllowedTypes
* @methodOf umbraco.resources.contentTypeResource
*
* @description
* Returns a list of allowed content types underneath a content item with a given ID
*
* ##usage
* <pre>
* contentTypeResource.getAllowedTypes(1234)
* .then(function(array) {
* $scope.type = type;
* });
* </pre>
* @param {Int} contentTypeId id of the content item to retrive allowed child types for
* @returns {Promise} resourcePromise object.
*
*/
getAllowedTypes: function (contentTypeId) {
return umbRequestHelper.resourcePromise(
$http.get(
umbRequestHelper.getApiUrl(
"contentTypeApiBaseUrl",
"GetAllowedChildren",
[{ contentId: contentTypeId }])),
'Failed to retrieve data for content id ' + contentTypeId);
},
/**
* @ngdoc method
* @name umbraco.resources.contentTypeResource#getAllPropertyTypeAliases
* @methodOf umbraco.resources.contentTypeResource
*
* @description
* Returns a list of defined property type aliases
*
* @returns {Promise} resourcePromise object.
*
*/
getAllPropertyTypeAliases: function () {
return umbRequestHelper.resourcePromise(
$http.get(
umbRequestHelper.getApiUrl(
"contentTypeApiBaseUrl",
"GetAllPropertyTypeAliases")),
'Failed to retrieve property type aliases');
},
getAllStandardFields: function () {
return umbRequestHelper.resourcePromise(
$http.get(
umbRequestHelper.getApiUrl(
"contentTypeApiBaseUrl",
"GetAllStandardFields")),
'Failed to retrieve standard fields');
},
getPropertyTypeScaffold : function (id) {
return umbRequestHelper.resourcePromise(
$http.get(
umbRequestHelper.getApiUrl(
"contentTypeApiBaseUrl",
"GetPropertyTypeScaffold",
[{ id: id }])),
'Failed to retrieve property type scaffold');
},
getById: function (id) {
return umbRequestHelper.resourcePromise(
$http.get(
umbRequestHelper.getApiUrl(
"contentTypeApiBaseUrl",
"GetById",
[{ id: id }])),
'Failed to retrieve content type');
},
deleteById: function (id) {
return umbRequestHelper.resourcePromise(
$http.post(
umbRequestHelper.getApiUrl(
"contentTypeApiBaseUrl",
"DeleteById",
[{ id: id }])),
'Failed to delete content type');
},
deleteContainerById: function (id) {
return umbRequestHelper.resourcePromise(
$http.post(
umbRequestHelper.getApiUrl(
"contentTypeApiBaseUrl",
"DeleteContainer",
[{ id: id }])),
'Failed to delete content type contaier');
},
/**
* @ngdoc method
* @name umbraco.resources.contentTypeResource#getAll
* @methodOf umbraco.resources.contentTypeResource
*
* @description
* Returns a list of all content types
*
* @returns {Promise} resourcePromise object.
*
*/
getAll: function () {
return umbRequestHelper.resourcePromise(
$http.get(
umbRequestHelper.getApiUrl(
"contentTypeApiBaseUrl",
"GetAll")),
'Failed to retrieve all content types');
},
getScaffold: function (parentId) {
return umbRequestHelper.resourcePromise(
$http.get(
umbRequestHelper.getApiUrl(
"contentTypeApiBaseUrl",
"GetEmpty", { parentId: parentId })),
'Failed to retrieve content type scaffold');
},
/**
* @ngdoc method
* @name umbraco.resources.contentTypeResource#save
* @methodOf umbraco.resources.contentTypeResource
*
* @description
* Saves or update a content type
*
* @param {Object} content data type object to create/update
* @returns {Promise} resourcePromise object.
*
*/
save: function (contentType) {
var saveModel = umbDataFormatter.formatContentTypePostData(contentType);
return umbRequestHelper.resourcePromise(
$http.post(umbRequestHelper.getApiUrl("contentTypeApiBaseUrl", "PostSave"), saveModel),
'Failed to save data for content type id ' + contentType.id);
},
/**
* @ngdoc method
* @name umbraco.resources.contentTypeResource#move
* @methodOf umbraco.resources.contentTypeResource
*
* @description
* Moves a node underneath a new parentId
*
* ##usage
* <pre>
* contentTypeResource.move({ parentId: 1244, id: 123 })
* .then(function() {
* alert("node was moved");
* }, function(err){
* alert("node didnt move:" + err.data.Message);
* });
* </pre>
* @param {Object} args arguments object
* @param {Int} args.idd the ID of the node to move
* @param {Int} args.parentId the ID of the parent node to move to
* @returns {Promise} resourcePromise object.
*
*/
move: function (args) {
if (!args) {
throw "args cannot be null";
}
if (!args.parentId) {
throw "args.parentId cannot be null";
}
if (!args.id) {
throw "args.id cannot be null";
}
return umbRequestHelper.resourcePromise(
$http.post(umbRequestHelper.getApiUrl("contentTypeApiBaseUrl", "PostMove"),
{
parentId: args.parentId,
id: args.id
}),
'Failed to move content');
},
copy: function(args) {
if (!args) {
throw "args cannot be null";
}
if (!args.parentId) {
throw "args.parentId cannot be null";
}
if (!args.id) {
throw "args.id cannot be null";
}
return umbRequestHelper.resourcePromise(
$http.post(umbRequestHelper.getApiUrl("contentTypeApiBaseUrl", "PostCopy"),
{
parentId: args.parentId,
id: args.id
}),
'Failed to copy content');
},
createContainer: function(parentId, name) {
return umbRequestHelper.resourcePromise(
$http.post(umbRequestHelper.getApiUrl("contentTypeApiBaseUrl", "PostCreateContainer", { parentId: parentId, name: name })),
'Failed to create a folder under parent id ' + parentId);
},
renameContainer: function(id, name) {
return umbRequestHelper.resourcePromise(
$http.post(umbRequestHelper.getApiUrl("contentTypeApiBaseUrl",
"PostRenameContainer",
{ id: id, name: name })),
"Failed to rename the folder with id " + id
);
}
};
}
angular.module('umbraco.resources').factory('contentTypeResource', contentTypeResource);
|
import { useRouter } from 'next/router'
export const getServerSideProps = () => {
return {
props: {
hello: 'world',
random: Math.random(),
},
}
}
export default (props) => (
<>
<h3 id="gssp">getServerSideProps</h3>
<p id="props">{JSON.stringify(props)}</p>
<div id="pathname">{useRouter().pathname}</div>
<div id="asPath">{useRouter().asPath}</div>
</>
)
|
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
const common = require('../common');
const assert = require('assert');
const dgram = require('dgram');
{
// IPv4 Test
const socket = dgram.createSocket('udp4');
socket.on('listening', common.mustCall(() => {
const address = socket.address();
assert.strictEqual(address.address, common.localhostIPv4);
assert.strictEqual(typeof address.port, 'number');
assert.ok(isFinite(address.port));
assert.ok(address.port > 0);
assert.strictEqual(address.family, 'IPv4');
socket.close();
}));
socket.on('error', (err) => {
socket.close();
assert.fail(`Unexpected error on udp4 socket. ${err.toString()}`);
});
socket.bind(0, common.localhostIPv4);
}
if (common.hasIPv6) {
// IPv6 Test
const socket = dgram.createSocket('udp6');
const localhost = '::1';
socket.on('listening', common.mustCall(() => {
const address = socket.address();
assert.strictEqual(address.address, localhost);
assert.strictEqual(typeof address.port, 'number');
assert.ok(isFinite(address.port));
assert.ok(address.port > 0);
assert.strictEqual(address.family, 'IPv6');
socket.close();
}));
socket.on('error', (err) => {
socket.close();
assert.fail(`Unexpected error on udp6 socket. ${err.toString()}`);
});
socket.bind(0, localhost);
}
{
// Verify that address() throws if the socket is not bound.
const socket = dgram.createSocket('udp4');
assert.throws(() => {
socket.address();
}, /^Error: getsockname EINVAL$/);
}
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: match returns array as specified in 15.10.6.2
es5id: 15.5.4.10_A2_T12
description: >
Regular expression is variable that have value /([\d]{5})([-\
]?[\d]{4})?$/g
---*/
var __matches=["02134"];
var __string = "Boston, MA 02134";
var __re = /([\d]{5})([-\ ]?[\d]{4})?$/g;
//////////////////////////////////////////////////////////////////////////////
//CHECK#1
if (__string.match(__re).length!== __matches.length) {
$ERROR('#1: __string.match(__re).length=== __matches.length. Actual: '+__string.match(__re).length);
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//CHECK#2
if (__string.match(__re)[0]!==__matches[0]) {
$ERROR('#2: __string.match(__re)[0]===__matches[0]. Actual: '+__string.match(__re)[0]);
}
//
//////////////////////////////////////////////////////////////////////////////
|
module.exports={"zones":{"America/Anguilla":["z",{"wallclock":-1825113600000,"format":"AST","abbrev":"AST","offset":-14400000,"posix":-1825098464000,"save":0},{"wallclock":-1.7976931348623157e+308,"format":"LMT","abbrev":"LMT","offset":-15136000,"posix":-1.7976931348623157e+308,"save":0}]},"rules":{}} |
var pex = pex || require('../../build/pex');
pex.sys.Window.create({
settings: {
width: 1280,
height: 720,
type: '3d',
vsync: true,
multisample: true,
fullscreen: false,
center: true,
canvas : pex.sys.Platform.isBrowser ? document.getElementById('canvas') : null
},
init: function() {
this.camera = new pex.scene.PerspectiveCamera(60, this.width/this.height);
this.rtCamera = new pex.scene.PerspectiveCamera(60, 1);
this.arcball = new pex.scene.Arcball(this, this.camera, 2);
this.rt = new pex.gl.RenderTarget(512, 512, { depth : true });
this.renderedMesh = new pex.gl.Mesh(new pex.geom.gen.Cube(2), new pex.materials.ShowNormals());
this.cubeMesh = new pex.gl.Mesh(new pex.geom.gen.Cube(), new pex.materials.Textured({ texture : this.rt.getColorAttachement(0)}));
},
draw: function() {
var gl = this.gl;
gl.enable(gl.DEPTH_TEST);
this.rt.bind();
gl.clearColor(0.2, 0.2, 0.2, 1);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
this.renderedMesh.rotation.setAxisAngle(this.camera.up, pex.utils.Time.seconds);
gl.viewport(0, 0, this.rt.width, this.rt.height);
this.renderedMesh.draw(this.rtCamera);
this.rt.unbind();
gl.viewport(0, 0, this.width, this.height);
gl.clearColor(0, 0, 0, 1);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
this.cubeMesh.draw(this.camera);
}
});
|
import valid from "card-validator";
import { removeNonNumber, removeLeadingSpaces } from "./Utilities";
import pick from "lodash.pick";
const limitLength = (string = "", maxLength) => string.substr(0, maxLength);
const addGaps = (string = "", gaps) => {
const offsets = [0].concat(gaps).concat([string.length]);
return offsets.map((end, index) => {
if (index === 0) return "";
const start = offsets[index - 1];
return string.substr(start, end - start);
}).filter(part => part !== "").join(" ");
};
const FALLBACK_CARD = { gaps: [4, 8, 12], lengths: [16], code: { size: 3 } };
export default class CCFieldFormatter {
constructor(displayedFields) {
this._displayedFields = [...displayedFields, "type"];
}
formatValues = (values) => {
const card = valid.number(values.number).card || FALLBACK_CARD;
return pick({
type: card.type,
number: this._formatNumber(values.number, card),
expiry: this._formatExpiry(values.expiry),
cvc: this._formatCVC(values.cvc, card),
name: removeLeadingSpaces(values.name),
postalCode: removeNonNumber(values.postalCode),
}, this._displayedFields);
};
_formatNumber = (number, card) => {
const numberSanitized = removeNonNumber(number);
const maxLength = card.lengths[card.lengths.length - 1];
const lengthSanitized = limitLength(numberSanitized, maxLength);
const formatted = addGaps(lengthSanitized, card.gaps);
return formatted;
};
_formatExpiry = (expiry) => {
const sanitized = limitLength(removeNonNumber(expiry), 4);
if (sanitized.match(/^[2-9]$/)) { return `0${sanitized}`; }
if (sanitized.length > 2) { return `${sanitized.substr(0, 2)}/${sanitized.substr(2, sanitized.length)}`; }
return sanitized;
};
_formatCVC = (cvc, card) => {
const maxCVCLength = card.code.size;
return limitLength(removeNonNumber(cvc), maxCVCLength);
};
}
|
exports.title = 'Camera';
exports.run = function(UI, Map) {
var win = UI.createWindow();
var rows = [
{
title: 'Set Camera',
run: function(){
map.camera = Map.createCamera({
centerCoordinate: {
latitude: -33.87365, longitude: 151.20689
},
altitude: 3000,
pitch: 40
});
}
},
{
title: 'Zoom out',
run: function(){
// Camera will not exist if run on pre iOS 7
if (map.camera) {
map.camera.altitude = map.camera.altitude*2;
}
}
},
{
title: 'Go to Melbourne animated',
run: function(){
map.animateCamera({
camera: midpointCam,
duration: 1500
}, function() {
// This will be run once the first animation completes.
map.animateCamera({
camera: melbourneCam,
duration: 1500
});
});
}
},
{
title: 'Go to Sydney animated',
run: function(){
map.animateCamera({
camera: midpointCam,
duration: 1500
}, function() {
// This will be run once the first animation completes.
map.animateCamera({
camera: sydneyCam,
duration: 1500
});
});
}
}
];
// Location Cameras
var sydneyCam = Map.createCamera({
altitude: 244,
centerCoordinate: {
longitude: 151.2152523799932,
latitude: -33.85666173702788
},
heading: -131.1528177444374,
pitch: 61.2794189453125
});
var melbourneCam = Map.createCamera({
altitude: 14877, centerCoordinate: {
longitude: 144.95771473524832,
latitude: -37.82064895691708
},
heading: 0,
pitch: 0
});
// The midpoint between Sydney and Melbourne will make the animation look nicer.
var midpointCam = Map.createCamera({
altitude: 1074069,
centerCoordinate: {
longitude: 148.01178350216657,
latitude: -36.048428214025066
},
heading: 0,
pitch: 0
});
// Table View
var tableView = Ti.UI.createTableView({
top: '10%',
bottom: '50%',
data: rows
});
win.add(tableView);
tableView.addEventListener('click', function(e) {
rows[e.index].run && rows[e.index].run();
});
// Map
var map = Map.createView({
userLocation: true,
mapType: Map.NORMAL_TYPE,
animate: true,
region: {latitude: -33.87365, longitude: 151.20689, latitudeDelta: 0.02, longitudeDelta: 0.02 }, //Sydney
top: '50%'
});
win.add(map);
map.addEventListener('regionwillchange', function(e) {
Ti.API.warn('The current region will change now!');
});
// Check camera properties on location change to find the current values
map.addEventListener('regionchanged', function(e) {
// We don't want to know the location when the change was animated, we told it where to animate to.
var cam;
if (!e.animated && (cam = map.camera)) {
Ti.API.info('Camera Properties --> {altitude: '+cam.altitude+
', centerCoordinate: '+JSON.stringify(cam.centerCoordinate)+
', heading: '+cam.heading+
', pitch: '+cam.pitch+
'}');
}
});
win.open();
}
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* @class
* Initializes a new instance of the A class.
* @constructor
* @member {string} [statusCode]
*
*/
class A {
constructor() {
}
/**
* Defines the metadata of A
*
* @returns {object} metadata of A
*
*/
mapper() {
return {
required: false,
serializedName: 'A',
type: {
name: 'Composite',
className: 'A',
modelProperties: {
statusCode: {
required: false,
serializedName: 'statusCode',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = A;
|
// If no env is set, default to development
// This needs to be above all other require()
// modules to ensure config gets right setting.
// Module dependencies
var config = require('./config'),
express = require('express'),
when = require('when'),
_ = require('underscore'),
semver = require('semver'),
fs = require('fs'),
errors = require('./errorHandling'),
plugins = require('./plugins'),
path = require('path'),
Polyglot = require('node-polyglot'),
mailer = require('./mail'),
Ghost = require('../ghost'),
helpers = require('./helpers'),
middleware = require('./middleware'),
routes = require('./routes'),
packageInfo = require('../../package.json'),
// Variables
ghost = new Ghost(),
setup,
init;
// If we're in development mode, require "when/console/monitor"
// for help in seeing swallowed promise errors, and log any
// stderr messages from bluebird promises.
if (process.env.NODE_ENV === 'development') {
require('when/monitor/console');
}
// Sets up the express server instance.
// Instantiates the ghost singleton,
// helpers, routes, middleware, and plugins.
// Finally it starts the http server.
function setup(server) {
// Set up Polygot instance on the require module
Polyglot.instance = new Polyglot();
when(ghost.init()).then(function () {
return when.join(
// Initialise mail after first run,
// passing in config module to prevent
// circular dependencies.
mailer.init(ghost, config),
helpers.loadCoreHelpers(ghost, config)
);
}).then(function () {
// ##Configuration
// set the view engine
server.set('view engine', 'hbs');
// set the configured URL
server.set('ghost root', ghost.blogGlobals().path);
// return the correct mime type for woff filess
express['static'].mime.define({'application/font-woff': ['woff']});
// ## Middleware
middleware(server);
// ## Routing
// Set up API routes
routes.api(server);
// Set up Admin routes
routes.admin(server);
// Set up Frontend routes
routes.frontend(server);
// Are we using sockets? Custom socket or the default?
function getSocket() {
if (config().server.hasOwnProperty('socket')) {
return _.isString(config().server.socket) ? config().server.socket : path.join(__dirname, '../content/', process.env.NODE_ENV + '.socket');
}
return false;
}
function startGhost() {
// Tell users if their node version is not supported, and exit
if (!semver.satisfies(process.versions.node, packageInfo.engines.node)) {
console.log(
"\nERROR: Unsupported version of Node".red,
"\nGhost needs Node version".red,
packageInfo.engines.node.yellow,
"you are using version".red,
process.versions.node.yellow,
"\nPlease go to http://nodejs.org to get the latest version".green
);
process.exit(0);
}
// Startup & Shutdown messages
if (process.env.NODE_ENV === 'production') {
console.log(
"Ghost is running...".green,
"\nYour blog is now available on",
config().url,
"\nCtrl+C to shut down".grey
);
// ensure that Ghost exits correctly on Ctrl+C
process.on('SIGINT', function () {
console.log(
"\nGhost has shut down".red,
"\nYour blog is now offline"
);
process.exit(0);
});
} else {
console.log(
("Ghost is running in " + process.env.NODE_ENV + "...").green,
"\nListening on",
getSocket() || config().server.host + ':' + config().server.port,
"\nUrl configured as:",
config().url,
"\nCtrl+C to shut down".grey
);
// ensure that Ghost exits correctly on Ctrl+C
process.on('SIGINT', function () {
console.log(
"\nGhost has shutdown".red,
"\nGhost was running for",
Math.round(process.uptime()),
"seconds"
);
process.exit(0);
});
}
}
// Expose the express server on the ghost instance.
ghost.server = server;
// Initialize plugins then start the server
plugins.init(ghost).then(function () {
// ## Start Ghost App
if (getSocket()) {
// Make sure the socket is gone before trying to create another
fs.unlink(getSocket(), function (err) {
/*jslint unparam:true*/
server.listen(
getSocket(),
startGhost
);
fs.chmod(getSocket(), '0744');
});
} else {
server.listen(
config().server.port,
config().server.host,
startGhost
);
}
});
}, function (err) {
errors.logErrorAndExit(err);
});
}
// Initializes the ghost application.
function init(app) {
if (!app) {
app = express();
}
// The server and its dependencies require a populated config
setup(app);
}
module.exports = init;
|
/*!
* jQuery JavaScript Library v2.0.3 -event-alias,-effects,-offset,-dimensions
* 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-07T17:13Z
*/
(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
// A central reference to the root jQuery(document)
rootjQuery,
// The deferred used on DOM ready
readyList,
// Support: IE9
// 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 = "2.0.3 -event-alias,-effects,-offset,-dimensions",
// 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,
// 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>|)$/,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
// The ready event handler and self cleanup method
completed = function() {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
jQuery.ready();
};
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 ) {
// 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 options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
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;
}
// 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,
isWindow: function( obj ) {
return obj != null && obj === obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
if ( obj == null ) {
return String( obj );
}
// Support: Safari <= 5.1 (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},
isPlainObject: function( obj ) {
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
// Support: Firefox <20
// The try/catch suppresses exceptions thrown when attempting to access
// the "constructor" property of certain host objects, ie. |window.location|
// https://bugzilla.mozilla.org/show_bug.cgi?id=814622
try {
if ( obj.constructor &&
!core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
return false;
}
} catch ( e ) {
return false;
}
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
},
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: JSON.parse,
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
// Support: IE9
try {
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} catch ( e ) {
xml = undefined;
}
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
globalEval: function( code ) {
var script,
indirect = eval;
code = jQuery.trim( code );
if ( code ) {
// If the code includes a valid, prologue position
// strict mode pragma, execute code by injecting a
// script tag into the document.
if ( code.indexOf("use strict") === 1 ) {
script = document.createElement("script");
script.text = code;
document.head.appendChild( script ).parentNode.removeChild( script );
} else {
// Otherwise, avoid the DOM node creation, insertion
// and removal by using an indirect global eval
indirect( code );
}
}
},
// 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;
},
trim: function( text ) {
return text == null ? "" : core_trim.call( text );
},
// 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 ) {
return arr == null ? -1 : core_indexOf.call( arr, elem, i );
},
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 tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || 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: Date.now,
// 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 );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
}
}
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.9.4-pre
* http://sizzlejs.com/
*
* Copyright 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-06-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 // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// 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 input = document.createElement("input"),
fragment = document.createDocumentFragment(),
div = document.createElement("div"),
select = document.createElement("select"),
opt = select.appendChild( document.createElement("option") );
// Finish early in limited environments
if ( !input.type ) {
return support;
}
input.type = "checkbox";
// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
// Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere)
support.checkOn = input.value !== "";
// Must access the parent to make an option select properly
// Support: IE9, IE10
support.optSelected = opt.selected;
// Will be defined later
support.reliableMarginRight = true;
support.boxSizingReliable = true;
support.pixelPosition = false;
// Make sure checked status is properly cloned
// Support: IE9, IE10
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;
// Check if an input maintains its value after becoming a radio
// Support: IE9, IE10
input = document.createElement("input");
input.value = "t";
input.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.appendChild( input );
// Support: Safari 5.1, Android 4.x, Android 2.3
// old WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: Firefox, Chrome, Safari
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
support.focusinBubbles = "onfocusin" in window;
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Run tests that need a body at doc ready
jQuery(function() {
var container, marginDiv,
// Support: Firefox, Android 2.3 (Prefixed box-sizing versions).
divReset = "padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;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";
// Check box-sizing and margin behavior.
body.appendChild( container ).appendChild( div );
div.innerHTML = "";
// Support: Firefox, Android 2.3 (Prefixed box-sizing versions).
div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;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";
// Support: Android 2.3
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// 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 );
}
body.removeChild( container );
});
return support;
})( {} );
/*
Implementation Summary
1. Enforce API surface and semantic compatibility with 1.9.x branch
2. Improve the module's maintainability by reducing the storage
paths to a single mechanism.
3. Use the same single mechanism to support "private" and "user" data.
4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
5. Avoid exposing implementation details on user objects (eg. expando properties)
6. Provide a clear path for implementation upgrade to WeakMap in 2014
*/
var data_user, data_priv,
rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
function Data() {
// Support: Android < 4,
// Old WebKit does not have Object.preventExtensions/freeze method,
// return new empty object instead with no [[set]] accessor
Object.defineProperty( this.cache = {}, 0, {
get: function() {
return {};
}
});
this.expando = jQuery.expando + Math.random();
}
Data.uid = 1;
Data.accepts = function( owner ) {
// Accepts only:
// - Node
// - Node.ELEMENT_NODE
// - Node.DOCUMENT_NODE
// - Object
// - Any
return owner.nodeType ?
owner.nodeType === 1 || owner.nodeType === 9 : true;
};
Data.prototype = {
key: function( owner ) {
// We can accept data for non-element nodes in modern browsers,
// but we should not, see #8335.
// Always return the key for a frozen object.
if ( !Data.accepts( owner ) ) {
return 0;
}
var descriptor = {},
// Check if the owner object already has a cache key
unlock = owner[ this.expando ];
// If not, create one
if ( !unlock ) {
unlock = Data.uid++;
// Secure it in a non-enumerable, non-writable property
try {
descriptor[ this.expando ] = { value: unlock };
Object.defineProperties( owner, descriptor );
// Support: Android < 4
// Fallback to a less secure definition
} catch ( e ) {
descriptor[ this.expando ] = unlock;
jQuery.extend( owner, descriptor );
}
}
// Ensure the cache object
if ( !this.cache[ unlock ] ) {
this.cache[ unlock ] = {};
}
return unlock;
},
set: function( owner, data, value ) {
var prop,
// There may be an unlock assigned to this node,
// if there is no entry for this "owner", create one inline
// and set the unlock as though an owner entry had always existed
unlock = this.key( owner ),
cache = this.cache[ unlock ];
// Handle: [ owner, key, value ] args
if ( typeof data === "string" ) {
cache[ data ] = value;
// Handle: [ owner, { properties } ] args
} else {
// Fresh assignments by object are shallow copied
if ( jQuery.isEmptyObject( cache ) ) {
jQuery.extend( this.cache[ unlock ], data );
// Otherwise, copy the properties one-by-one to the cache object
} else {
for ( prop in data ) {
cache[ prop ] = data[ prop ];
}
}
}
return cache;
},
get: function( owner, key ) {
// Either a valid cache is found, or will be created.
// New caches will be created and the unlock returned,
// allowing direct access to the newly created
// empty data object. A valid owner object must be provided.
var cache = this.cache[ this.key( owner ) ];
return key === undefined ?
cache : cache[ key ];
},
access: function( owner, key, value ) {
var stored;
// In cases where either:
//
// 1. No key was specified
// 2. A string key was specified, but no value provided
//
// Take the "read" path and allow the get method to determine
// which value to return, respectively either:
//
// 1. The entire cache object
// 2. The data stored at the key
//
if ( key === undefined ||
((key && typeof key === "string") && value === undefined) ) {
stored = this.get( owner, key );
return stored !== undefined ?
stored : this.get( owner, jQuery.camelCase(key) );
}
// [*]When the key is not a string, or both a key and value
// are specified, set or extend (existing objects) with either:
//
// 1. An object of properties
// 2. A key and value
//
this.set( owner, key, value );
// Since the "set" path can have two possible entry points
// return the expected data based on which path was taken[*]
return value !== undefined ? value : key;
},
remove: function( owner, key ) {
var i, name, camel,
unlock = this.key( owner ),
cache = this.cache[ unlock ];
if ( key === undefined ) {
this.cache[ unlock ] = {};
} else {
// Support array or space separated string of keys
if ( jQuery.isArray( key ) ) {
// 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 = key.concat( key.map( jQuery.camelCase ) );
} else {
camel = jQuery.camelCase( key );
// Try the string as a key before any manipulation
if ( key in cache ) {
name = [ key, camel ];
} else {
// If a key with the spaces exists, use it.
// Otherwise, create an array by matching non-whitespace
name = camel;
name = name in cache ?
[ name ] : ( name.match( core_rnotwhite ) || [] );
}
}
i = name.length;
while ( i-- ) {
delete cache[ name[ i ] ];
}
}
},
hasData: function( owner ) {
return !jQuery.isEmptyObject(
this.cache[ owner[ this.expando ] ] || {}
);
},
discard: function( owner ) {
if ( owner[ this.expando ] ) {
delete this.cache[ owner[ this.expando ] ];
}
}
};
// These may be used throughout the jQuery core codebase
data_user = new Data();
data_priv = new Data();
jQuery.extend({
acceptData: Data.accepts,
hasData: function( elem ) {
return data_user.hasData( elem ) || data_priv.hasData( elem );
},
data: function( elem, name, data ) {
return data_user.access( elem, name, data );
},
removeData: function( elem, name ) {
data_user.remove( elem, name );
},
// TODO: Now that all calls to _data and _removeData have been replaced
// with direct calls to data_priv methods, these can be deprecated.
_data: function( elem, name, data ) {
return data_priv.access( elem, name, data );
},
_removeData: function( elem, name ) {
data_priv.remove( elem, name );
}
});
jQuery.fn.extend({
data: function( key, value ) {
var attrs, name,
elem = this[ 0 ],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = data_user.get( elem );
if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) {
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 ] );
}
}
data_priv.set( elem, "hasDataAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
data_user.set( this, key );
});
}
return jQuery.access( this, function( value ) {
var data,
camelKey = jQuery.camelCase( key );
// The calling jQuery object (element matches) is not empty
// (and therefore has an element appears at this[ 0 ]) and the
// `value` parameter was not undefined. An empty jQuery object
// will result in `undefined` for elem = this[ 0 ] which will
// throw an exception if an attempt to read a data cache is made.
if ( elem && value === undefined ) {
// Attempt to get data from the cache
// with the key as-is
data = data_user.get( elem, key );
if ( data !== undefined ) {
return data;
}
// Attempt to get data from the cache
// with the key camelized
data = data_user.get( elem, camelKey );
if ( data !== undefined ) {
return data;
}
// Attempt to "discover" the data in
// HTML5 custom data-* attrs
data = dataAttr( elem, camelKey, undefined );
if ( data !== undefined ) {
return data;
}
// We tried really hard, but the data doesn't exist.
return;
}
// Set the data...
this.each(function() {
// First, attempt to store a copy or reference of any
// data that might've been store with a camelCased key.
var data = data_user.get( this, camelKey );
// For HTML5 data-* attribute interop, we have to
// store property names with dashes in a camelCase form.
// This might not apply to all properties...*
data_user.set( this, camelKey, value );
// *... In the case of properties that might _actually_
// have dashes, we need to also store a copy of that
// unchanged property.
if ( key.indexOf("-") !== -1 && data !== undefined ) {
data_user.set( this, key, value );
}
});
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each(function() {
data_user.remove( this, key );
});
}
});
function dataAttr( elem, key, data ) {
var name;
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
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 ) ? JSON.parse( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
data_user.set( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = data_priv.get( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray( data ) ) {
queue = data_priv.access( 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 data_priv.get( elem, key ) || data_priv.access( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
data_priv.remove( elem, [ type + "queue", 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 = data_priv.get( 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)$/i;
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 ) {
return this.each(function() {
delete this[ jQuery.propFix[ name ] || name ];
});
},
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
data_priv.set( 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 ? "" : data_priv.get( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val;
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 ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// IE6-9 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
elem[ propName ] = false;
}
elem.removeAttribute( name );
}
}
},
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 ) {
return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ?
elem.tabIndex :
-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 {
elem.setAttribute( name, name );
}
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 ] = function( elem, name, isXML ) {
var fn = jQuery.expr.attrHandle[ name ],
ret = isXML ?
undefined :
/* jshint eqeqeq: false */
// Temporarily disable this handler to check existence
(jQuery.expr.attrHandle[ name ] = undefined) !=
getter( elem, name, isXML ) ?
name.toLowerCase() :
null;
// Restore handler
jQuery.expr.attrHandle[ name ] = fn;
return ret;
};
});
// Support: IE9+
// Selectedness for an option in an optgroup can be inaccurate
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent && 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;
});
// 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 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 handleObjIn, eventHandle, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.get( 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 if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
}
}
}
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, origCount, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.hasData( elem ) && data_priv.get( 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;
data_priv.remove( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var i, cur, tmp, bubbleType, ontype, handle, special,
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 = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( 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.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && jQuery.isFunction( 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;
elem[ type ]();
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, j, ret, matched, handleObj,
handlerQueue = [],
args = core_slice.call( arguments ),
handlers = ( data_priv.get( 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 i, matches, sel, handleObj,
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") ) {
for ( ; cur !== this; cur = cur.parentNode || this ) {
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( 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;
},
// 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 offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button;
// 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 which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, 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: Cordova 2.5 (WebKit) (#13255)
// All events should have a target; Cordova deviceready doesn't
if ( !event.target ) {
event.target = document;
}
// Support: Safari 6.0+, Chrome < 28
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
return fixHook.filter? fixHook.filter( event, originalEvent ) : 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 ) {
this.focus();
return false;
}
},
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 ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) {
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 ) {
// Support: Firefox 20+
// Firefox doesn't alert if the returnValue field is not set.
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 = function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
};
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.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 && e.preventDefault ) {
e.preventDefault();
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( e && e.stopPropagation ) {
e.stopPropagation();
}
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
// Support: Chrome 15+
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;
}
};
});
// Create "bubbling" focus and blur events
// Support: Firefox, Chrome, Safari
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( 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 targets = jQuery( target, this ),
l = targets.length;
return this.filter(function() {
var i = 0;
for ( ; i < l; 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,
matched = [],
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 = matched.push( cur );
break;
}
}
}
return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched );
},
// 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 core_indexOf.call( jQuery( elem ), this[ 0 ] );
}
// Locate the position of the desired element
return core_indexOf.call( this,
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[ 0 ] : elem
);
},
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 ) {
while ( (cur = cur[dir]) && 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 elem.contentDocument || jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var matched = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
matched = jQuery.filter( selector, matched );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
jQuery.unique( matched );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
matched.reverse();
}
}
return this.pushStack( matched );
};
});
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 = [],
truncate = until !== undefined;
while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) {
if ( elem.nodeType === 1 ) {
if ( truncate && jQuery( elem ).is( until ) ) {
break;
}
matched.push( elem );
}
}
return matched;
},
sibling: function( n, elem ) {
var matched = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
matched.push( n );
}
}
return matched;
}
});
// 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 ( core_indexOf.call( qualifier, elem ) >= 0 ) !== not;
});
}
var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
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 = {
// Support: IE 9
option: [ 1, "<select multiple='multiple'>", "</select>" ],
thead: [ 1, "<table>", "</table>" ],
col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
_default: [ 0, "", "" ]
};
// Support: IE 9
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++ ) {
if ( elem.nodeType === 1 ) {
// Prevent memory leaks
jQuery.cleanData( getAll( elem, false ) );
// Remove any remaining nodes
elem.textContent = "";
}
}
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 && elem.nodeType === 1 ) {
return elem.innerHTML;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for ( ; i < l; i++ ) {
elem = this[ i ] || {};
// Remove element nodes and prevent memory leaks
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 fragment, first, scripts, hasScripts, node, doc,
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 ) {
// Support: QtWebKit
// jQuery.merge because core_push.apply(_, arraylike) throws
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 || "" ) &&
!data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Hope ajax is available...
jQuery._evalUrl( node.src );
} else {
jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) );
}
}
}
}
}
}
return this;
}
});
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1,
i = 0;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone( true );
jQuery( insert[ i ] )[ original ]( elems );
// Support: QtWebKit
// .get() because core_push.apply(_, arraylike) throws
core_push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var i, l, srcElements, destElements,
clone = elem.cloneNode( true ),
inPage = jQuery.contains( elem.ownerDocument, elem );
// Support: IE >= 9
// Fix Cloning issues
if ( !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 );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
fixInput( srcElements[ i ], 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, l = srcElements.length; i < l; i++ ) {
cloneCopyEvent( srcElements[ i ], destElements[ i ] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var elem, tmp, tag, wrap, contains, j,
i = 0,
l = elems.length,
fragment = context.createDocumentFragment(),
nodes = [];
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
// Support: QtWebKit
// jQuery.merge because core_push.apply(_, arraylike) throws
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 || fragment.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;
}
// Support: QtWebKit
// jQuery.merge because core_push.apply(_, arraylike) throws
jQuery.merge( nodes, tmp.childNodes );
// Remember the top-level container
tmp = fragment.firstChild;
// Fixes #12346
// Support: Webkit, IE
tmp.textContent = "";
}
}
}
// Remove wrapper from fragment
fragment.textContent = "";
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( fragment.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 );
}
}
}
}
return fragment;
},
cleanData: function( elems ) {
var data, elem, events, type, key, j,
special = jQuery.event.special,
i = 0;
for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
if ( Data.accepts( elem ) ) {
key = elem[ data_priv.expando ];
if ( key && (data = data_priv.cache[ key ]) ) {
events = Object.keys( data.events || {} );
if ( events.length ) {
for ( j = 0; (type = events[j]) !== undefined; j++ ) {
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 );
}
}
}
if ( data_priv.cache[ key ] ) {
// Discard any remaining `private` data
delete data_priv.cache[ key ];
}
}
}
// Discard any remaining `user` data
delete data_user.cache[ elem[ data_user.expando ] ];
}
},
_evalUrl: function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
}
});
// Support: 1.x compatibility
// 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 = (elem.getAttribute("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 l = elems.length,
i = 0;
for ( ; i < l; i++ ) {
data_priv.set(
elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" )
);
}
}
function cloneCopyEvent( src, dest ) {
var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
if ( dest.nodeType !== 1 ) {
return;
}
// 1. Copy private data: events, handlers, etc.
if ( data_priv.hasData( src ) ) {
pdataOld = data_priv.access( src );
pdataCur = data_priv.set( dest, pdataOld );
events = pdataOld.events;
if ( events ) {
delete pdataCur.handle;
pdataCur.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
}
// 2. Copy user data
if ( data_user.hasData( src ) ) {
udataOld = data_user.access( src );
udataCur = jQuery.extend( {}, udataOld );
data_user.set( dest, udataCur );
}
}
function getAll( context, tag ) {
var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) :
context.querySelectorAll ? context.querySelectorAll( tag || "*" ) :
[];
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], ret ) :
ret;
}
// Support: IE >= 9
function fixInput( src, dest ) {
var nodeName = dest.nodeName.toLowerCase();
// Fails to persist the checked state of a cloned checkbox or radio button.
if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) {
dest.checked = src.checked;
// Fails to return the selected option to the default selected state when cloning options
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.fn.extend({
wrapAll: function( html ) {
var wrap;
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
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.firstElementChild ) {
elem = elem.firstElementChild;
}
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 curCSS, iframe,
// 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 );
}
// NOTE: we've included the "window" in window.getComputedStyle
// because jsdom on node.js will break without it.
function getStyles( elem ) {
return window.getComputedStyle( elem, null );
}
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 ] = data_priv.get( 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 ] = data_priv.access( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
if ( !values[ index ] ) {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
data_priv.set( 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 styles, len,
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": "cssFloat"
},
// 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 specifying 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 ) {
style[ name ] = value;
}
} 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 val, num, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, 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;
}
});
curCSS = function( elem, name, _computed ) {
var width, minWidth, maxWidth,
computed = _computed || getStyles( elem ),
// Support: IE9
// 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 );
}
// Support: Safari 5.1
// A tribute to the "awesome hack by Dean Edwards"
// 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;
};
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
);
}
};
});
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
// Support: Android 2.3
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
if ( computed ) {
// Support: Android 2.3
// 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.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 );
}
}
var
// Document location
ajaxLocParts,
ajaxLocation,
ajax_nonce = jQuery.now(),
ajax_rquery = /\?/,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
// #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 key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off );
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 transport,
// URL without anti-cache param
cacheURL,
// Response headers
responseHeadersString,
responseHeaders,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events 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 (prefilters might expect it)
// 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 ct, type, finalDataType, firstDataType,
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 crossDomain
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function( s ) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script, callback;
return {
send: function( _, complete ) {
script = jQuery("<script>").prop({
async: true,
charset: s.scriptCharset,
src: s.url
}).on(
"load error",
callback = function( evt ) {
script.remove();
callback = null;
if ( evt ) {
complete( evt.type === "error" ? 404 : 200, evt.type );
}
}
);
document.head.appendChild( script[ 0 ] );
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
});
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";
}
});
jQuery.ajaxSettings.xhr = function() {
try {
return new XMLHttpRequest();
} catch( e ) {}
};
var xhrSupported = jQuery.ajaxSettings.xhr(),
xhrSuccessStatus = {
// file protocol always yields status code 0, assume 200
0: 200,
// Support: IE9
// #1450: sometimes IE returns 1223 when it should be 204
1223: 204
},
// Support: IE9
// We need to keep track of outbound xhr and abort them manually
// because IE is not smart enough to do it all by itself
xhrId = 0,
xhrCallbacks = {};
if ( window.ActiveXObject ) {
jQuery( window ).on( "unload", function() {
for( var key in xhrCallbacks ) {
xhrCallbacks[ key ]();
}
xhrCallbacks = undefined;
});
}
jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
jQuery.support.ajax = xhrSupported = !!xhrSupported;
jQuery.ajaxTransport(function( options ) {
var callback;
// Cross domain only allowed if supported through XMLHttpRequest
if ( jQuery.support.cors || xhrSupported && !options.crossDomain ) {
return {
send: function( headers, complete ) {
var i, id,
xhr = options.xhr();
xhr.open( options.type, options.url, options.async, options.username, options.password );
// Apply custom fields if provided
if ( options.xhrFields ) {
for ( i in options.xhrFields ) {
xhr[ i ] = options.xhrFields[ i ];
}
}
// Override mime type if needed
if ( options.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( options.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 ( !options.crossDomain && !headers["X-Requested-With"] ) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Set headers
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
// Callback
callback = function( type ) {
return function() {
if ( callback ) {
delete xhrCallbacks[ id ];
callback = xhr.onload = xhr.onerror = null;
if ( type === "abort" ) {
xhr.abort();
} else if ( type === "error" ) {
complete(
// file protocol always yields status 0, assume 404
xhr.status || 404,
xhr.statusText
);
} else {
complete(
xhrSuccessStatus[ xhr.status ] || xhr.status,
xhr.statusText,
// Support: IE9
// #11426: When requesting binary data, IE9 will throw an exception
// on any attempt to access responseText
typeof xhr.responseText === "string" ? {
text: xhr.responseText
} : undefined,
xhr.getAllResponseHeaders()
);
}
}
};
};
// Listen to events
xhr.onload = callback();
xhr.onerror = callback("error");
// Create the abort callback
callback = xhrCallbacks[( id = xhrId++ )] = callback("abort");
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( options.hasContent && options.data || null );
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
});
// 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 {
// 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; } );
}
}
// If there is a window object, that at least has a document property,
// define jQuery and $ identifiers
if ( typeof window === "object" && typeof window.document === "object" ) {
window.jQuery = window.$ = jQuery;
}
})( window );
|
import { requireComponentDependancyByName } from '../dependancies'
export default function ContentZone(props) {
function RenderModules() {
let modules = props.page.zones[props.name]
return modules.map((m, i) => {
const AgilityModule = requireComponentDependancyByName(m.moduleName)
return <AgilityModule key={i} {...m.item} />
})
}
return (
<div>
<RenderModules />
</div>
)
}
|
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
var React;
var ReactDOM;
describe('SyntheticWheelEvent', () => {
var container;
beforeEach(() => {
React = require('react');
ReactDOM = require('react-dom');
// The container has to be attached for events to fire.
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
document.body.removeChild(container);
container = null;
});
it('should normalize properties from the Event interface', () => {
const events = [];
var onWheel = event => {
event.persist();
events.push(event);
};
ReactDOM.render(<div onWheel={onWheel} />, container);
const event = new MouseEvent('wheel', {
bubbles: true,
});
// Emulate IE8
Object.defineProperty(event, 'target', {
get() {},
});
Object.defineProperty(event, 'srcElement', {
get() {
return container.firstChild;
},
});
container.firstChild.dispatchEvent(event);
expect(events.length).toBe(1);
expect(events[0].target).toBe(container.firstChild);
expect(events[0].type).toBe('wheel');
});
it('should normalize properties from the MouseEvent interface', () => {
const events = [];
var onWheel = event => {
event.persist();
events.push(event);
};
ReactDOM.render(<div onWheel={onWheel} />, container);
container.firstChild.dispatchEvent(
new MouseEvent('wheel', {
bubbles: true,
button: 1,
}),
);
expect(events.length).toBe(1);
expect(events[0].button).toBe(1);
});
it('should normalize properties from the WheelEvent interface', () => {
var events = [];
var onWheel = event => {
event.persist();
events.push(event);
};
ReactDOM.render(<div onWheel={onWheel} />, container);
var event = new MouseEvent('wheel', {
bubbles: true,
});
// jsdom doesn't support these so we add them manually.
Object.assign(event, {
deltaX: 10,
deltaY: -50,
});
container.firstChild.dispatchEvent(event);
event = new MouseEvent('wheel', {
bubbles: true,
});
// jsdom doesn't support these so we add them manually.
Object.assign(event, {
wheelDeltaX: -10,
wheelDeltaY: 50,
});
container.firstChild.dispatchEvent(event);
expect(events.length).toBe(2);
expect(events[0].deltaX).toBe(10);
expect(events[0].deltaY).toBe(-50);
expect(events[1].deltaX).toBe(10);
expect(events[1].deltaY).toBe(-50);
});
it('should be able to `preventDefault` and `stopPropagation`', () => {
var events = [];
var onWheel = event => {
expect(event.isDefaultPrevented()).toBe(false);
event.preventDefault();
expect(event.isDefaultPrevented()).toBe(true);
event.persist();
events.push(event);
};
ReactDOM.render(<div onWheel={onWheel} />, container);
container.firstChild.dispatchEvent(
new MouseEvent('wheel', {
bubbles: true,
deltaX: 10,
deltaY: -50,
}),
);
container.firstChild.dispatchEvent(
new MouseEvent('wheel', {
bubbles: true,
deltaX: 10,
deltaY: -50,
}),
);
expect(events.length).toBe(2);
});
it('should be able to `persist`', () => {
var events = [];
var onWheel = event => {
expect(event.isPersistent()).toBe(false);
event.persist();
expect(event.isPersistent()).toBe(true);
events.push(event);
};
ReactDOM.render(<div onWheel={onWheel} />, container);
container.firstChild.dispatchEvent(
new MouseEvent('wheel', {
bubbles: true,
}),
);
expect(events.length).toBe(1);
expect(events[0].type).toBe('wheel');
});
});
|
/*! @license Firebase v4.3.0
Build: rev-bd8265e
Terms: https://firebase.google.com/terms/
---
typedarray.js
Copyright (c) 2010, Linden Research, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
/**
* Copyright 2017 Google 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.
*/
/**
* @fileoverview Firebase Database API.
* Version: 4.3.0
*
* Copyright 2017 Google Inc. 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
*
* 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.
*
* @externs
*/
/**
* Gets the {@link firebase.database.Database `Database`} service for the
* default app or a given app.
*
* `firebase.database()` can be called with no arguments to access the default
* app's {@link firebase.database.Database `Database`} service or as
* `firebase.database(app)` to access the
* {@link firebase.database.Database `Database`} service associated with a
* specific app.
*
* `firebase.database` is also a namespace that can be used to access global
* constants and methods associated with the `Database` service.
*
* @example
* // Get the Database service for the default app
* var defaultDatabase = firebase.database();
*
* @example
* // Get the Database service for a specific app
* var otherDatabase = firebase.database(app);
*
* @namespace
* @param {!firebase.app.App=} app Optional app whose Database service to
* return. If not provided, the default Database service will be returned.
* @return {!firebase.database.Database} The default Database service if no app
* is provided or the Database service associated with the provided app.
*/
firebase.database = function(app) {};
/**
* Gets the {@link firebase.database.Database `Database`} service for the
* current app.
*
* @example
* var database = app.database();
* // The above is shorthand for:
* // var database = firebase.database(app);
*
* @return {!firebase.database.Database}
*/
firebase.app.App.prototype.database = function() {};
/**
* The Firebase Database service interface.
*
* Do not call this constructor directly. Instead, use
* {@link firebase.database `firebase.database()`}.
*
* See
* {@link
* https://firebase.google.com/docs/database/web/start/
* Installation & Setup in JavaScript}
* for a full guide on how to use the Firebase Database service.
*
* @interface
*/
firebase.database.Database = function() {};
/**
* Logs debugging information to the console.
*
* @example
* // Enable logging
* firebase.database.enableLogging(true);
*
* @example
* // Disable logging
* firebase.database.enableLogging(false);
*
* @example
* // Enable logging across page refreshes
* firebase.database.enableLogging(true, true);
*
* @example
* // Provide custom logger which prefixes log statements with "[FIREBASE]"
* firebase.database.enableLogging(function(message) {
* console.log("[FIREBASE]", message);
* });
*
* @param {(boolean|function(string))=} logger Enables logging if `true`;
* disables logging if `false`. You can also provide a custom logger function
* to control how things get logged.
* @param {boolean=} persistent Remembers the logging state between page
* refreshes if `true`.
*/
firebase.database.enableLogging = function(logger, persistent) {};
/**
* @namespace
*/
firebase.database.ServerValue = {}
/**
* A placeholder value for auto-populating the current timestamp (time
* since the Unix epoch, in milliseconds) as determined by the Firebase
* servers.
*
* @example
* var sessionsRef = firebase.database().ref("sessions");
* sessionsRef.push({
* startedAt: firebase.database.ServerValue.TIMESTAMP
* });
*
* @const {!Object}
*/
firebase.database.ServerValue.TIMESTAMP;
/**
* The {@link firebase.app.App app} associated with the `Database` service
* instance.
*
* @example
* var app = database.app;
*
* @type {!firebase.app.App}
*/
firebase.database.Database.prototype.app;
/**
* Returns a `Reference` representing the location in the Database
* corresponding to the provided path. If no path is provided, the `Reference`
* will point to the root of the Database.
*
* @example
* // Get a reference to the root of the Database
* var rootRef = firebase.database().ref();
*
* @example
* // Get a reference to the /users/ada node
* var adaRef = firebase.database().ref("users/ada");
* // The above is shorthand for the following operations:
* //var rootRef = firebase.database().ref();
* //var adaRef = rootRef.child("users/ada");
*
* @param {string=} path Optional path representing the location the returned
* `Reference` will point. If not provided, the returned `Reference` will
* point to the root of the Database.
* @return {!firebase.database.Reference} If a path is provided, a `Reference`
* pointing to the provided path. Otherwise, a `Reference` pointing to the
* root of the Database.
*/
firebase.database.Database.prototype.ref = function(path) {};
/**
* Returns a `Reference` representing the location in the Database
* corresponding to the provided Firebase URL.
*
* An exception is thrown if the URL is not a valid Firebase Database URL or it
* has a different domain than the current `Database` instance.
*
* Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored
* and are not applied to the returned `Reference`.
*
* @example
* // Get a reference to the root of the Database
* var rootRef = firebase.database().ref("https://<DATABASE_NAME>.firebaseio.com");
*
* @example
* // Get a reference to the /users/ada node
* var adaRef = firebase.database().ref("https://<DATABASE_NAME>.firebaseio.com/users/ada");
*
* @param {string} url The Firebase URL at which the returned `Reference` will
* point.
* @return {!firebase.database.Reference} A `Reference` pointing to the provided
* Firebase URL.
*/
firebase.database.Database.prototype.refFromURL = function(url) {};
/**
* Disconnects from the server (all Database operations will be completed
* offline).
*
* The client automatically maintains a persistent connection to the Database
* server, which will remain active indefinitely and reconnect when
* disconnected. However, the `goOffline()` and `goOnline()` methods may be used
* to control the client connection in cases where a persistent connection is
* undesirable.
*
* While offline, the client will no longer receive data updates from the
* Database. However, all Database operations performed locally will continue to
* immediately fire events, allowing your application to continue behaving
* normally. Additionally, each operation performed locally will automatically
* be queued and retried upon reconnection to the Database server.
*
* To reconnect to the Database and begin receiving remote events, see
* `goOnline()`.
*
* @example
* firebase.database().goOffline();
*/
firebase.database.Database.prototype.goOffline = function() {};
/**
* Reconnects to the server and synchronizes the offline Database state
* with the server state.
*
* This method should be used after disabling the active connection with
* `goOffline()`. Once reconnected, the client will transmit the proper data
* and fire the appropriate events so that your client "catches up"
* automatically.
*
* @example
* firebase.database().goOnline();
*/
firebase.database.Database.prototype.goOnline = function() {};
/**
* A `Reference` represents a specific location in your Database and can be used
* for reading or writing data to that Database location.
*
* You can reference the root or child location in your Database by calling
* `firebase.database().ref()` or `firebase.database().ref("child/path")`.
*
* Writing is done with the `set()` method and reading can be done with the
* `on()` method. See
* {@link
* https://firebase.google.com/docs/database/web/read-and-write
* Read and Write Data on the Web}
*
* @interface
* @extends {firebase.database.Query}
*/
firebase.database.Reference = function() {};
/**
* The last part of the `Reference`'s path.
*
* For example, `"ada"` is the key for
* `https://<DATABASE_NAME>.firebaseio.com/users/ada`.
*
* The key of a root `Reference` is `null`.
*
* @example
* // The key of a root reference is null
* var rootRef = firebase.database().ref();
* var key = rootRef.key; // key === null
*
* @example
* // The key of any non-root reference is the last token in the path
* var adaRef = firebase.database().ref("users/ada");
* var key = adaRef.key; // key === "ada"
* key = adaRef.child("name/last").key; // key === "last"
*
* @type {string|null}
*/
firebase.database.Reference.prototype.key;
/**
* Gets a `Reference` for the location at the specified relative path.
*
* The relative path can either be a simple child name (for example, "ada") or
* a deeper slash-separated path (for example, "ada/name/first").
*
* @example
* var usersRef = firebase.database().ref('users');
* var adaRef = usersRef.child('ada');
* var adaFirstNameRef = adaRef.child('name/first');
* var path = adaFirstNameRef.toString();
* // path is now 'https://sample-app.firebaseio.com/users/ada/name/first'
*
* @param {string} path A relative path from this location to the desired child
* location.
* @return {!firebase.database.Reference} The specified child location.
*/
firebase.database.Reference.prototype.child = function(path) {};
/**
* The parent location of a `Reference`.
*
* The parent of a root `Reference` is `null`.
*
* @example
* // The parent of a root reference is null
* var rootRef = firebase.database().ref();
* parent = rootRef.parent; // parent === null
*
* @example
* // The parent of any non-root reference is the parent location
* var usersRef = firebase.database().ref("users");
* var adaRef = firebase.database().ref("users/ada");
* // usersRef and adaRef.parent represent the same location
*
* @type {?firebase.database.Reference}
*/
firebase.database.Reference.prototype.parent;
/**
* The root `Reference` of the Database.
*
* @example
* // The root of a root reference is itself
* var rootRef = firebase.database().ref();
* // rootRef and rootRef.root represent the same location
*
* @example
* // The root of any non-root reference is the root location
* var adaRef = firebase.database().ref("users/ada");
* // rootRef and adaRef.root represent the same location
*
* @type {!firebase.database.Reference}
*/
firebase.database.Reference.prototype.root;
/**
* @type {string}
*/
firebase.database.Reference.prototype.path;
/**
* Writes data to this Database location.
*
* This will overwrite any data at this location and all child locations.
*
* The effect of the write will be visible immediately, and the corresponding
* events ("value", "child_added", etc.) will be triggered. Synchronization of
* the data to the Firebase servers will also be started, and the returned
* Promise will resolve when complete. If provided, the `onComplete` callback
* will be called asynchronously after synchronization has finished.
*
* Passing `null` for the new value is equivalent to calling `remove()`; namely,
* all data at this location and all child locations will be deleted.
*
* `set()` will remove any priority stored at this location, so if priority is
* meant to be preserved, you need to use `setWithPriority()` instead.
*
* Note that modifying data with `set()` will cancel any pending transactions
* at that location, so extreme care should be taken if mixing `set()` and
* `transaction()` to modify the same data.
*
* A single `set()` will generate a single "value" event at the location where
* the `set()` was performed.
*
* @example
* var adaNameRef = firebase.database().ref('users/ada/name');
* adaNameRef.child('first').set('Ada');
* adaNameRef.child('last').set('Lovelace');
* // We've written 'Ada' to the Database location storing Ada's first name,
* // and 'Lovelace' to the location storing her last name.
*
* @example
* adaNameRef.set({ first: 'Ada', last: 'Lovelace' });
* // Exact same effect as the previous example, except we've written
* // Ada's first and last name simultaneously.
*
* @example
* adaNameRef.set({ first: 'Ada', last: 'Lovelace' })
* .then(function() {
* console.log('Synchronization succeeded');
* })
* .catch(function(error) {
* console.log('Synchronization failed');
* });
* // Same as the previous example, except we will also log a message
* // when the data has finished synchronizing.
*
* @param {*} value The value to be written (string, number, boolean, object,
* array, or null).
* @param {function(?Error)=} onComplete Callback called when write to server is
* complete.
* @return {!firebase.Promise<void>} Resolves when write to server is complete.
*/
firebase.database.Reference.prototype.set = function(value, onComplete) {};
/**
* Writes multiple values to the Database at once.
*
* The `values` argument contains multiple property-value pairs that will be
* written to the Database together. Each child property can either be a simple
* property (for example, "name") or a relative path (for example,
* "name/first") from the current location to the data to update.
*
* As opposed to the `set()` method, `update()` can be use to selectively update
* only the referenced properties at the current location (instead of replacing
* all the child properties at the current location).
*
* The effect of the write will be visible immediately, and the corresponding
* events ('value', 'child_added', etc.) will be triggered. Synchronization of
* the data to the Firebase servers will also be started, and the returned
* Promise will resolve when complete. If provided, the `onComplete` callback
* will be called asynchronously after synchronization has finished.
*
* A single `update()` will generate a single "value" event at the location
* where the `update()` was performed, regardless of how many children were
* modified.
*
* Note that modifying data with `update()` will cancel any pending
* transactions at that location, so extreme care should be taken if mixing
* `update()` and `transaction()` to modify the same data.
*
* Passing `null` to `update()` will remove the data at this location.
*
* See
* {@link
* https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html
* Introducing multi-location updates and more}.
*
* @example
* var adaNameRef = firebase.database().ref('users/ada/name');
* // Modify the 'first' and 'last' properties, but leave other data at
* // adaNameRef unchanged.
* adaNameRef.update({ first: 'Ada', last: 'Lovelace' });
*
* @param {!Object} values Object containing multiple values.
* @param {function(?Error)=} onComplete Callback called when write to server is
* complete.
* @return {!firebase.Promise<void>} Resolves when update on server is complete.
*/
firebase.database.Reference.prototype.update = function(values, onComplete) {};
/**
* Writes data the Database location. Like `set()` but also specifies the
* priority for that data.
*
* Applications need not use priority but can order collections by
* ordinary properties (see
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data
* Sorting and filtering data}).
*
* @param {*} newVal
* @param {string|number|null} newPriority
* @param {function(?Error)=} onComplete
* @return {!firebase.Promise<void>}
*/
firebase.database.Reference.prototype.setWithPriority =
function(newVal, newPriority, onComplete) {};
/**
* Removes the data at this Database location.
*
* Any data at child locations will also be deleted.
*
* The effect of the remove will be visible immediately and the corresponding
* event 'value' will be triggered. Synchronization of the remove to the
* Firebase servers will also be started, and the returned Promise will resolve
* when complete. If provided, the onComplete callback will be called
* asynchronously after synchronization has finished.
*
* @example
* var adaRef = firebase.database().ref('users/ada');
* adaRef.remove()
* .then(function() {
* console.log("Remove succeeded.")
* })
* .catch(function(error) {
* console.log("Remove failed: " + error.message)
* });
*
* @param {function(?Error)=} onComplete Callback called when write to server is
* complete.
* @return {!firebase.Promise<void>} Resolves when remove on server is complete.
*/
firebase.database.Reference.prototype.remove = function(onComplete) {};
/**
* Atomically modifies the data at this location.
*
* Atomically modify the data at this location. Unlike a normal `set()`, which
* just overwrites the data regardless of its previous value, `transaction()` is
* used to modify the existing value to a new value, ensuring there are no
* conflicts with other clients writing to the same location at the same time.
*
* To accomplish this, you pass `transaction()` an update function which is used
* to transform the current value into a new value. If another client writes to
* the location before your new value is successfully written, your update
* function will be called again with the new current value, and the write will
* be retried. This will happen repeatedly until your write succeeds without
* conflict or you abort the transaction by not returning a value from your
* update function.
*
* Note: Modifying data with `set()` will cancel any pending transactions at
* that location, so extreme care should be taken if mixing `set()` and
* `transaction()` to update the same data.
*
* Note: When using transactions with Security and Firebase Rules in place, be
* aware that a client needs `.read` access in addition to `.write` access in
* order to perform a transaction. This is because the client-side nature of
* transactions requires the client to read the data in order to transactionally
* update it.
*
* @example
* // Increment Ada's rank by 1.
* var adaRankRef = firebase.database().ref('users/ada/rank');
* adaRankRef.transaction(function(currentRank) {
* // If users/ada/rank has never been set, currentRank will be `null`.
* return currentRank + 1;
* });
*
* @example
* // Try to create a user for ada, but only if the user id 'ada' isn't
* // already taken
* var adaRef = firebase.database().ref('users/ada');
* adaRef.transaction(function(currentData) {
* if (currentData === null) {
* return { name: { first: 'Ada', last: 'Lovelace' } };
* } else {
* console.log('User ada already exists.');
* return; // Abort the transaction.
* }
* }, function(error, committed, snapshot) {
* if (error) {
* console.log('Transaction failed abnormally!', error);
* } else if (!committed) {
* console.log('We aborted the transaction (because ada already exists).');
* } else {
* console.log('User ada added!');
* }
* console.log("Ada's data: ", snapshot.val());
* });
*
*
* @param {function(*): *} transactionUpdate A developer-supplied function which
* will be passed the current data stored at this location (as a JavaScript
* object). The function should return the new value it would like written (as
* a JavaScript object). If `undefined` is returned (i.e. you return with no
* arguments) the transaction will be aborted and the data at this location
* will not be modified.
* @param {(function(?Error, boolean,
* ?firebase.database.DataSnapshot))=} onComplete A callback
* function that will be called when the transaction completes. The callback
* is passed three arguments: a possibly-null `Error`, a `boolean` indicating
* whether the transaction was committed, and a `DataSnapshot` indicating the
* final result. If the transaction failed abnormally, the first argument will
* be an `Error` object indicating the failure cause. If the transaction
* finished normally, but no data was committed because no data was returned
* from `transactionUpdate`, then second argument will be false. If the
* transaction completed and committed data to Firebase, the second argument
* will be true. Regardless, the third argument will be a `DataSnapshot`
* containing the resulting data in this location.
* @param {boolean=} applyLocally By default, events are raised each time the
* transaction update function runs. So if it is run multiple times, you may
* see intermediate states. You can set this to false to suppress these
* intermediate states and instead wait until the transaction has completed
* before events are raised.
* @return {!firebase.Promise<{
* committed: boolean,
* snapshot: ?firebase.database.DataSnapshot
* }>} Returns a Promise that can optionally be used instead of the onComplete
* callback to handle success and failure.
*/
firebase.database.Reference.prototype.transaction =
function(transactionUpdate, onComplete, applyLocally) {};
/**
* Sets a priority for the data at this Database location.
*
* Applications need not use priority but can order collections by
* ordinary properties (see
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data
* Sorting and filtering data}).
*
* @param {string|number|null} priority
* @param {function(?Error)} onComplete
* @return {!firebase.Promise<void>}
*/
firebase.database.Reference.prototype.setPriority =
function(priority, onComplete) {};
/**
* @interface
* @extends {firebase.database.Reference}
* @extends {firebase.Thenable<void>}
*/
firebase.database.ThenableReference = function() {};
/**
* Generates a new child location using a unique key and returns its
* `Reference`.
*
* This is the most common pattern for adding data to a collection of items.
*
* If you provide a value to `push()`, the value will be written to the
* generated location. If you don't pass a value, nothing will be written to the
* Database and the child will remain empty (but you can use the `Reference`
* elsewhere).
*
* The unique key generated by `push()` are ordered by the current time, so the
* resulting list of items will be chronologically sorted. The keys are also
* designed to be unguessable (they contain 72 random bits of entropy).
*
*
* See
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data
* Append to a list of data}
* </br>See
* {@link
* https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html
* The 2^120 Ways to Ensure Unique Identifiers}
*
* @example
* var messageListRef = firebase.database().ref('message_list');
* var newMessageRef = messageListRef.push();
* newMessageRef.set({
* 'user_id': 'ada',
* 'text': 'The Analytical Engine weaves algebraical patterns just as the Jacquard loom weaves flowers and leaves.'
* });
* // We've appended a new message to the message_list location.
* var path = newMessageRef.toString();
* // path will be something like
* // 'https://sample-app.firebaseio.com/message_list/-IKo28nwJLH0Nc5XeFmj'
*
* @param {*=} value Optional value to be written at the generated location.
* @param {function(?Error)=} onComplete Callback called when write to server is
* complete.
* @return {!firebase.database.ThenableReference} Combined `Promise` and
* `Reference`; resolves when write is complete, but can be used immediately
* as the `Reference` to the child location.
*/
firebase.database.Reference.prototype.push = function(value, onComplete) {};
/**
* Returns an `OnDisconnect` object - see
* {@link
* https://firebase.google.com/docs/database/web/offline-capabilities
* Enabling Offline Capabilities in JavaScript} for more information on how
* to use it.
*
* @return {!firebase.database.OnDisconnect}
*/
firebase.database.Reference.prototype.onDisconnect = function() {};
/**
* A `Query` sorts and filters the data at a Database location so only a subset
* of the child data is included. This can be used to order a collection of
* data by some attribute (for example, height of dinosaurs) as well as to
* restrict a large list of items (for example, chat messages) down to a number
* suitable for synchronizing to the client. Queries are created by chaining
* together one or more of the filter methods defined here.
*
* Just as with a `Reference`, you can receive data from a `Query` by using the
* `on()` method. You will only receive events and `DataSnapshot`s for the
* subset of the data that matches your query.
*
* Read our documentation on
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data
* Sorting and filtering data} for more information.
*
* @interface
*/
firebase.database.Query = function() {}
/**
* Returns a `Reference` to the `Query`'s location.
*
* @type {!firebase.database.Reference}
*/
firebase.database.Query.prototype.ref;
/**
* Returns whether or not the current and provided queries represent the same
* location, have the same query parameters, and are from the same instance of
* `firebase.app.App`.
*
* Two `Reference` objects are equivalent if they represent the same location
* and are from the same instance of `firebase.app.App`.
*
* Two `Query` objects are equivalent if they represent the same location, have
* the same query parameters, and are from the same instance of
* `firebase.app.App`. Equivalent queries share the same sort order, limits, and
* starting and ending points.
*
* @example
* var rootRef = firebase.database.ref();
* var usersRef = rootRef.child("users");
*
* usersRef.isEqual(rootRef); // false
* usersRef.isEqual(rootRef.child("users")); // true
* usersRef.parent.isEqual(rootRef); // true
*
* @example
* var rootRef = firebase.database.ref();
* var usersRef = rootRef.child("users");
* var usersQuery = usersRef.limitToLast(10);
*
* usersQuery.isEqual(usersRef); // false
* usersQuery.isEqual(usersRef.limitToLast(10)); // true
* usersQuery.isEqual(rootRef.limitToLast(10)); // false
* usersQuery.isEqual(usersRef.orderByKey().limitToLast(10)); // false
*
* @param {firebase.database.Query} other The query to compare against.
* @return {boolean} Whether or not the current and provided queries are
* equivalent.
*/
firebase.database.Query.prototype.isEqual = function(other) {};
/**
* Listens for data changes at a particular location.
*
* This is the primary way to read data from a Database. Your callback
* will be triggered for the initial data and again whenever the data changes.
* Use `off( )` to stop receiving updates. See
* {@link https://firebase.google.com/docs/database/web/retrieve-data
* Retrieve Data on the Web}
* for more details.
*
* <h4>value event</h4>
*
* This event will trigger once with the initial data stored at this location,
* and then trigger again each time the data changes. The `DataSnapshot` passed
* to the callback will be for the location at which `on()` was called. It
* won't trigger until the entire contents has been synchronized. If the
* location has no data, it will be triggered with an empty `DataSnapshot`
* (`val()` will return `null`).
*
* <h4>child_added event</h4>
*
* This event will be triggered once for each initial child at this location,
* and it will be triggered again every time a new child is added. The
* `DataSnapshot` passed into the callback will reflect the data for the
* relevant child. For ordering purposes, it is passed a second argument which
* is a string containing the key of the previous sibling child by sort order,
* or `null` if it is the first child.
*
* <h4>child_removed event</h4>
*
* This event will be triggered once every time a child is removed. The
* `DataSnapshot` passed into the callback will be the old data for the child
* that was removed. A child will get removed when either:
*
* - a client explicitly calls `remove()` on that child or one of its ancestors
* - a client calls `set(null)` on that child or one of its ancestors
* - that child has all of its children removed
* - there is a query in effect which now filters out the child (because it's
* sort order changed or the max limit was hit)
*
* <h4>child_changed event</h4>
*
* This event will be triggered when the data stored in a child (or any of its
* descendants) changes. Note that a single `child_changed` event may represent
* multiple changes to the child. The `DataSnapshot` passed to the callback will
* contain the new child contents. For ordering purposes, the callback is also
* passed a second argument which is a string containing the key of the previous
* sibling child by sort order, or `null` if it is the first child.
*
* <h4>child_moved event</h4>
*
* This event will be triggered when a child's sort order changes such that its
* position relative to its siblings changes. The `DataSnapshot` passed to the
* callback will be for the data of the child that has moved. It is also passed
* a second argument which is a string containing the key of the previous
* sibling child by sort order, or `null` if it is the first child.
*
* @example <caption>Handle a new value:</caption>
* ref.on('value', function(dataSnapshot) {
* ...
* });
*
* @example <caption>Handle a new child:</caption>
* ref.on('child_added', function(childSnapshot, prevChildKey) {
* ...
* });
*
* @example <caption>Handle child removal:</caption>
* ref.on('child_removed', function(oldChildSnapshot) {
* ...
* });
*
* @example <caption>Handle child data changes:</caption>
* ref.on('child_changed', function(childSnapshot, prevChildKey) {
* ...
* });
*
* @example <caption>Handle child ordering changes:</caption>
* ref.on('child_moved', function(childSnapshot, prevChildKey) {
* ...
* });
*
* @param {string} eventType One of the following strings: "value",
* "child_added", "child_changed", "child_removed", or "child_moved."
* @param {!function(firebase.database.DataSnapshot, string=)} callback A
* callback that fires when the specified event occurs. The callback will be
* passed a DataSnapshot. For ordering purposes, "child_added",
* "child_changed", and "child_moved" will also be passed a string containing
* the key of the previous child, by sort order, or `null` if it is the
* first child.
* @param {(function(Error)|Object)=} cancelCallbackOrContext An optional
* callback that will be notified if your event subscription is ever canceled
* because your client does not have permission to read this data (or it had
* permission but has now lost it). This callback will be passed an `Error`
* object indicating why the failure occurred.
* @param {Object=} context If provided, this object will be used as `this`
* when calling your callback(s).
* @return {!function(firebase.database.DataSnapshot, string=)} The provided
* callback function is returned unmodified. This is just for convenience if
* you want to pass an inline function to `on()` but store the callback
* function for later passing to `off()`.
*/
firebase.database.Query.prototype.on =
function(eventType, callback, cancelCallbackOrContext, context) {};
/**
* Detaches a callback previously attached with `on()`.
*
* Detach a callback previously attached with `on()`. Note that if `on()` was
* called multiple times with the same eventType and callback, the callback
* will be called multiple times for each event, and `off()` must be called
* multiple times to remove the callback. Calling `off()` on a parent listener
* will not automatically remove listeners registered on child nodes, `off()`
* must also be called on any child listeners to remove the callback.
*
* If a callback is not specified, all callbacks for the specified eventType
* will be removed. Similarly, if no eventType or callback is specified, all
* callbacks for the `Reference` will be removed.
*
* @example
* var onValueChange = function(dataSnapshot) { ... };
* ref.on('value', onValueChange);
* ref.child('meta-data').on('child_added', onChildAdded);
* // Sometime later...
* ref.off('value', onValueChange);
*
* // You must also call off() for any child listeners on ref
* // to cancel those callbacks
* ref.child('meta-data').off('child_added', onValueAdded);
*
* @example
* // Or you can save a line of code by using an inline function
* // and on()'s return value.
* var onValueChange = ref.on('value', function(dataSnapshot) { ... });
* // Sometime later...
* ref.off('value', onValueChange);
*
* @param {string=} eventType One of the following strings: "value",
* "child_added", "child_changed", "child_removed", or "child_moved."
* @param {function(!firebase.database.DataSnapshot, ?string=)=} callback The
* callback function that was passed to `on()`.
* @param {Object=} context The context that was passed to `on()`.
*/
firebase.database.Query.prototype.off =
function(eventType, callback, context) {};
/**
* Listens for exactly one event of the specified event type, and then stops
* listening.
*
* This is equivalent to calling {@link firebase.database.Query#on `on()`}, and
* then calling {@link firebase.database.Query#off `off()`} inside the callback
* function. See {@link firebase.database.Query#on `on()`} for details on the
* event types.
*
* @example
* // Basic usage of .once() to read the data located at ref.
* ref.once('value')
* .then(function(dataSnapshot) {
* // handle read data.
* });
*
* @param {string} eventType One of the following strings: "value",
* "child_added", "child_changed", "child_removed", or "child_moved."
* @param {function(!firebase.database.DataSnapshot, string=)=} successCallback A
* callback that fires when the specified event occurs. The callback will be
* passed a DataSnapshot. For ordering purposes, "child_added",
* "child_changed", and "child_moved" will also be passed a string containing
* the key of the previous child by sort order, or `null` if it is the
* first child.
* @param {(function(Error)|Object)=} failureCallbackOrContext An optional
* callback that will be notified if your client does not have permission to
* read the data. This callback will be passed an `Error` object indicating
* why the failure occurred.
* @param {Object=} context If provided, this object will be used as `this`
* when calling your callback(s).
* @return {!firebase.Promise<*>}
*/
firebase.database.Query.prototype.once =
function(eventType, successCallback, failureCallbackOrContext, context) {};
/**
* Generates a new `Query` limited to the first specific number of children.
*
* The `limitToFirst()` method is used to set a maximum number of children to be
* synced for a given callback. If we set a limit of 100, we will initially only
* receive up to 100 `child_added` events. If we have fewer than 100 messages
* stored in our Database, a `child_added` event will fire for each message.
* However, if we have over 100 messages, we will only receive a `child_added`
* event for the first 100 ordered messages. As items change, we will receive
* `child_removed` events for each item that drops out of the active list so
* that the total number stays at 100.
*
* You can read more about `limitToFirst()` in
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#filtering_data
* Filtering data}.
*
* @example
* // Find the two shortest dinosaurs.
* var ref = firebase.database().ref("dinosaurs");
* ref.orderByChild("height").limitToFirst(2).on("child_added", function(snapshot) {
* // This will be called exactly two times (unless there are less than two
* // dinosaurs in the Database).
*
* // It will also get fired again if one of the first two dinosaurs is
* // removed from the data set, as a new dinosaur will now be the second
* // shortest.
* console.log(snapshot.key);
* });
*
* @param {number} limit The maximum number of nodes to include in this query.
* @return {!firebase.database.Query}
*/
firebase.database.Query.prototype.limitToFirst = function(limit) {};
/**
* Generates a new `Query` object limited to the last specific number of
* children.
*
* The `limitToLast()` method is used to set a maximum number of children to be
* synced for a given callback. If we set a limit of 100, we will initially only
* receive up to 100 `child_added` events. If we have fewer than 100 messages
* stored in our Database, a `child_added` event will fire for each message.
* However, if we have over 100 messages, we will only receive a `child_added`
* event for the last 100 ordered messages. As items change, we will receive
* `child_removed` events for each item that drops out of the active list so
* that the total number stays at 100.
*
* You can read more about `limitToLast()` in
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#filtering_data
* Filtering data}.
*
* @example
* // Find the two heaviest dinosaurs.
* var ref = firebase.database().ref("dinosaurs");
* ref.orderByChild("weight").limitToLast(2).on("child_added", function(snapshot) {
* // This callback will be triggered exactly two times, unless there are
* // fewer than two dinosaurs stored in the Database. It will also get fired
* // for every new, heavier dinosaur that gets added to the data set.
* console.log(snapshot.key);
* });
*
* @param {number} limit The maximum number of nodes to include in this query.
* @return {!firebase.database.Query}
*/
firebase.database.Query.prototype.limitToLast = function(limit) {};
/**
* Generates a new `Query` object ordered by the specified child key.
*
* Queries can only order by one key at a time. Calling `orderByChild()`
* multiple times on the same query is an error.
*
* Firebase queries allow you to order your data by any child key on the fly.
* However, if you know in advance what your indexes will be, you can define
* them via the .indexOn rule in your Security Rules for better performance. See
* the {@link https://firebase.google.com/docs/database/security/indexing-data
* .indexOn} rule for more information.
*
* You can read more about `orderByChild()` in
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#sort_data
* Sort data}.
*
* @example
* var ref = firebase.database().ref("dinosaurs");
* ref.orderByChild("height").on("child_added", function(snapshot) {
* console.log(snapshot.key + " was " + snapshot.val().height + " m tall");
* });
*
* @param {string} path
* @return {!firebase.database.Query}
*/
firebase.database.Query.prototype.orderByChild = function(path) {};
/**
* Generates a new `Query` object ordered by key.
*
* Sorts the results of a query by their (ascending) key values.
*
* You can read more about `orderByKey()` in
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#sort_data
* Sort data}.
*
* @example
* var ref = firebase.database().ref("dinosaurs");
* ref.orderByKey().on("child_added", function(snapshot) {
* console.log(snapshot.key);
* });
*
* @return {!firebase.database.Query}
*/
firebase.database.Query.prototype.orderByKey = function() {};
/**
* Generates a new `Query` object ordered by priority.
*
* Applications need not use priority but can order collections by
* ordinary properties (see
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#sort_data
* Sort data} for alternatives to priority.
*
* @return {!firebase.database.Query}
*/
firebase.database.Query.prototype.orderByPriority = function() {};
/**
* Generates a new `Query` object ordered by value.
*
* If the children of a query are all scalar values (string, number, or
* boolean), you can order the results by their (ascending) values.
*
* You can read more about `orderByValue()` in
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#sort_data
* Sort data}.
*
* @example
* var scoresRef = firebase.database().ref("scores");
* scoresRef.orderByValue().limitToLast(3).on("value", function(snapshot) {
* snapshot.forEach(function(data) {
* console.log("The " + data.key + " score is " + data.val());
* });
* });
*
* @return {!firebase.database.Query}
*/
firebase.database.Query.prototype.orderByValue = function() {};
/**
* Creates a `Query` with the specified starting point.
*
* Using `startAt()`, `endAt()`, and `equalTo()` allows you to choose arbitrary
* starting and ending points for your queries.
*
* The starting point is inclusive, so children with exactly the specified value
* will be included in the query. The optional key argument can be used to
* further limit the range of the query. If it is specified, then children that
* have exactly the specified value must also have a key name greater than or
* equal to the specified key.
*
* You can read more about `startAt()` in
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#filtering_data
* Filtering data}.
*
* @example
* // Find all dinosaurs that are at least three meters tall.
* var ref = firebase.database().ref("dinosaurs");
* ref.orderByChild("height").startAt(3).on("child_added", function(snapshot) {
* console.log(snapshot.key)
* });
*
* @param {number|string|boolean|null} value The value to start at. The argument
* type depends on which `orderBy*()` function was used in this query.
* Specify a value that matches the `orderBy*()` type. When used in
* combination with `orderByKey()`, the value must be a string.
* @param {string=} key The child key to start at. This argument is only allowed
* if ordering by child, value, or priority.
* @return {!firebase.database.Query}
*/
firebase.database.Query.prototype.startAt = function(value, key) {};
/**
* Creates a `Query` with the specified ending point.
*
* Using `startAt()`, `endAt()`, and `equalTo()` allows you to choose arbitrary
* starting and ending points for your queries.
*
* The ending point is inclusive, so children with exactly the specified value
* will be included in the query. The optional key argument can be used to
* further limit the range of the query. If it is specified, then children that
* have exactly the specified value must also have a key name less than or equal
* to the specified key.
*
* You can read more about `endAt()` in
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#filtering_data
* Filtering data}.
*
* @example
* // Find all dinosaurs whose names come before Pterodactyl lexicographically.
* var ref = firebase.database().ref("dinosaurs");
* ref.orderByKey().endAt("pterodactyl").on("child_added", function(snapshot) {
* console.log(snapshot.key);
* });
*
* @param {number|string|boolean|null} value The value to end at. The argument
* type depends on which `orderBy*()` function was used in this query.
* Specify a value that matches the `orderBy*()` type. When used in
* combination with `orderByKey()`, the value must be a string.
* @param {string=} key The child key to end at, among the children with the
* previously specified priority. This argument is only allowed if ordering by
* child, value, or priority.
* @return {!firebase.database.Query}
*/
firebase.database.Query.prototype.endAt = function(value, key) {};
/**
* Creates a `Query` that includes children that match the specified value.
*
* Using `startAt()`, `endAt()`, and `equalTo()` allows us to choose arbitrary
* starting and ending points for our queries.
*
* The optional key argument can be used to further limit the range of the
* query. If it is specified, then children that have exactly the specified
* value must also have exactly the specified key as their key name. This can be
* used to filter result sets with many matches for the same value.
*
* You can read more about `equalTo()` in
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#filtering_data
* Filtering data}.
*
* @example
* // Find all dinosaurs whose height is exactly 25 meters.
* var ref = firebase.database().ref("dinosaurs");
* ref.orderByChild("height").equalTo(25).on("child_added", function(snapshot) {
* console.log(snapshot.key);
* });
*
* @param {number|string|boolean|null} value The value to match for. The
* argument type depends on which `orderBy*()` function was used in this
* query. Specify a value that matches the `orderBy*()` type. When used in
* combination with `orderByKey()`, the value must be a string.
* @param {string=} key The child key to start at, among the children with the
* previously specified priority. This argument is only allowed if ordering by
* child, value, or priority.
* @return {!firebase.database.Query}
*/
firebase.database.Query.prototype.equalTo = function(value, key) {};
/**
* Gets the absolute URL for this location.
*
* The `toString()` method returns a URL that is ready to be put into a browser,
* curl command, or a `firebase.database().refFromURL()` call. Since all of
* those expect the URL to be url-encoded, `toString()` returns an encoded URL.
*
* Append '.json' to the returned URL when typed into a browser to download
* JSON-formatted data. If the location is secured (that is, not publicly
* readable), you will get a permission-denied error.
*
* @example
* // Calling toString() on a root Firebase reference returns the URL where its
* // data is stored within the Database:
* var rootRef = firebase.database().ref();
* var rootUrl = rootRef.toString();
* // rootUrl === "https://sample-app.firebaseio.com/".
*
* // Calling toString() at a deeper Firebase reference returns the URL of that
* // deep path within the Database:
* var adaRef = rootRef.child('users/ada');
* var adaURL = adaRef.toString();
* // adaURL === "https://sample-app.firebaseio.com/users/ada".
*
* @return {string} The absolute URL for this location.
* @override
*/
firebase.database.Query.prototype.toString = function() {};
/**
* Returns a JSON-serializable representation of this object.
*
* @return {!Object} A JSON-serializable representation of this object.
*/
firebase.database.Query.prototype.toJSON = function() {};
/**
* A `DataSnapshot` contains data from a Database location.
*
* Any time you read data from the Database, you receive the data as a
* `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach
* with `on()` or `once()`. You can extract the contents of the snapshot as a
* JavaScript object by calling the `val()` method. Alternatively, you can
* traverse into the snapshot by calling `child()` to return child snapshots
* (which you could then call `val()` on).
*
* A `DataSnapshot` is an efficiently generated, immutable copy of the data at
* a Database location. It cannot be modified and will never change (to modify
* data, you always call the `set()` method on a `Reference` directly).
*
* @interface
*/
firebase.database.DataSnapshot = function() {};
/**
* Extracts a JavaScript value from a `DataSnapshot`.
*
* Depending on the data in a `DataSnapshot`, the `val()` method may return a
* scalar type (string, number, or boolean), an array, or an object. It may also
* return null, indicating that the `DataSnapshot` is empty (contains no data).
*
* @example
* // Write and then read back a string from the Database.
* ref.set("hello")
* .then(function() {
* return ref.once("value");
* })
* .then(function(snapshot) {
* var data = snapshot.val(); // data === "hello"
* });
*
* @example
* // Write and then read back a JavaScript object from the Database.
* ref.set({ name: "Ada", age: 36 })
* .then(function() {
* return ref.once("value");
* })
* .then(function(snapshot) {
* var data = snapshot.val();
* // data is { "name": "Ada", "age": 36 }
* // data.name === "Ada"
* // data.age === 36
* });
*
* @return {*} The DataSnapshot's contents as a JavaScript value (Object,
* Array, string, number, boolean, or `null`).
*/
firebase.database.DataSnapshot.prototype.val = function() {};
/**
* Exports the entire contents of the DataSnapshot as a JavaScript object.
*
* The `exportVal()` method is similar to `val()`, except priority information
* is included (if available), making it suitable for backing up your data.
*
* @return {*} The DataSnapshot's contents as a JavaScript value (Object,
* Array, string, number, boolean, or `null`).
*/
firebase.database.DataSnapshot.prototype.exportVal = function() {};
/**
* Returns true if this `DataSnapshot` contains any data. It is slightly more
* efficient than using `snapshot.val() !== null`.
*
* @example
* // Assume we have the following data in the Database:
* {
* "name": {
* "first": "Ada",
* "last": "Lovelace"
* }
* }
*
* // Test for the existence of certain keys within a DataSnapshot
* var ref = firebase.database().ref("users/ada");
* ref.once("value")
* .then(function(snapshot) {
* var a = snapshot.exists(); // true
* var b = snapshot.child("name").exists(); // true
* var c = snapshot.child("name/first").exists(); // true
* var d = snapshot.child("name/middle").exists(); // false
* });
*
* @return {boolean}
*/
firebase.database.DataSnapshot.prototype.exists = function() {};
/**
* Gets another `DataSnapshot` for the location at the specified relative path.
*
* Passing a relative path to the `child()` method of a DataSnapshot returns
* another `DataSnapshot` for the location at the specified relative path. The
* relative path can either be a simple child name (for example, "ada") or a
* deeper, slash-separated path (for example, "ada/name/first"). If the child
* location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`
* whose value is `null`) is returned.
*
* @example
* // Assume we have the following data in the Database:
* {
* "name": {
* "first": "Ada",
* "last": "Lovelace"
* }
* }
*
* // Test for the existence of certain keys within a DataSnapshot
* var ref = firebase.database().ref("users/ada");
* ref.once("value")
* .then(function(snapshot) {
* var name = snapshot.child("name").val(); // {first:"Ada",last:"Lovelace"}
* var firstName = snapshot.child("name/first").val(); // "Ada"
* var lastName = snapshot.child("name").child("last").val(); // "Lovelace"
* var age = snapshot.child("age").val(); // null
* });
*
* @param {string} path A relative path to the location of child data.
* @return {!firebase.database.DataSnapshot}
*/
firebase.database.DataSnapshot.prototype.child = function(path) {};
/**
* Returns true if the specified child path has (non-null) data.
*
* @example
* // Assume we have the following data in the Database:
* {
* "name": {
* "first": "Ada",
* "last": "Lovelace"
* }
* }
*
* // Determine which child keys in DataSnapshot have data.
* var ref = firebase.database().ref("users/ada");
* ref.once("value")
* .then(function(snapshot) {
* var hasName = snapshot.hasChild("name"); // true
* var hasAge = snapshot.hasChild("age"); // false
* });
*
* @param {string} path A relative path to the location of a potential child.
* @return {boolean} `true` if data exists at the specified child path; else
* `false`.
*/
firebase.database.DataSnapshot.prototype.hasChild = function(path) {};
/**
* Gets the priority value of the data in this `DataSnapshot`.
*
* Applications need not use priority but can order collections by
* ordinary properties (see
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data
* Sorting and filtering data}).
*
* @return {string|number|null}
*/
firebase.database.DataSnapshot.prototype.getPriority = function() {};
/**
* Enumerates the top-level children in the `DataSnapshot`.
*
* Because of the way JavaScript objects work, the ordering of data in the
* JavaScript object returned by `val()` is not guaranteed to match the ordering
* on the server nor the ordering of `child_added` events. That is where
* `forEach()` comes in handy. It guarantees the children of a `DataSnapshot`
* will be iterated in their query order.
*
* If no explicit `orderBy*()` method is used, results are returned
* ordered by key (unless priorities are used, in which case, results are
* returned by priority).
*
* @example
*
* // Assume we have the following data in the Database:
* {
* "users": {
* "ada": {
* "first": "Ada",
* "last": "Lovelace"
* },
* "alan": {
* "first": "Alan",
* "last": "Turing"
* }
* }
* }
*
* // Loop through users in order with the forEach() method. The callback
* // provided to forEach() will be called synchronously with a DataSnapshot
* // for each child:
* var query = firebase.database().ref("users").orderByKey();
* query.once("value")
* .then(function(snapshot) {
* snapshot.forEach(function(childSnapshot) {
* // key will be "ada" the first time and "alan" the second time
* var key = childSnapshot.key;
* // childData will be the actual contents of the child
* var childData = childSnapshot.val();
* });
* });
*
* @example
* // You can cancel the enumeration at any point by having your callback
* // function return true. For example, the following code sample will only
* // fire the callback function one time:
* var query = firebase.database().ref("users").orderByKey();
* query.once("value")
* .then(function(snapshot) {
* snapshot.forEach(function(childSnapshot) {
* var key = childSnapshot.key; // "ada"
*
* // Cancel enumeration
* return true;
* });
* });
*
* @param {function(!firebase.database.DataSnapshot): boolean} action A function
* that will be called for each child DataSnapshot. The callback can return
* true to cancel further enumeration.
* @return {boolean} true if enumeration was canceled due to your callback
* returning true.
*/
firebase.database.DataSnapshot.prototype.forEach = function(action) {};
/**
* Returns whether or not the `DataSnapshot` has any non-`null` child
* properties.
*
* You can use `hasChildren()` to determine if a `DataSnapshot` has any
* children. If it does, you can enumerate them using `forEach()`. If it
* doesn't, then either this snapshot contains a primitive value (which can be
* retrieved with `val()`) or it is empty (in which case, `val()` will return
* `null`).
*
* @example
* // Assume we have the following data in the Database:
* {
* "name": {
* "first": "Ada",
* "last": "Lovelace"
* }
* }
*
* var ref = firebase.database().ref("users/ada");
* ref.once("value")
* .then(function(snapshot) {
* var a = snapshot.hasChildren(); // true
* var b = snapshot.child("name").hasChildren(); // true
* var c = snapshot.child("name/first").hasChildren(); // false
* });
*
* @return {boolean} true if this snapshot has any children; else false.
*/
firebase.database.DataSnapshot.prototype.hasChildren = function() {};
/**
* The key (last part of the path) of the location of this `DataSnapshot`.
*
* The last token in a Database location is considered its key. For example,
* "ada" is the key for the /users/ada/ node. Accessing the key on any
* `DataSnapshot` will return the key for the location that generated it.
* However, accessing the key on the root URL of a Database will return `null`.
*
* @example
* // Assume we have the following data in the Database:
* {
* "name": {
* "first": "Ada",
* "last": "Lovelace"
* }
* }
*
* var ref = firebase.database().ref("users/ada");
* ref.once("value")
* .then(function(snapshot) {
* var key = snapshot.key; // "ada"
* var childKey = snapshot.child("name/last").key; // "last"
* });
*
* @example
* var rootRef = firebase.database().ref();
* rootRef.once("value")
* .then(function(snapshot) {
* var key = snapshot.key; // null
* var childKey = snapshot.child("users/ada").key; // "ada"
* });
*
* @type {string|null}
*/
firebase.database.DataSnapshot.prototype.key;
/**
* Returns the number of child properties of this `DataSnapshot`.
*
* @example
* // Assume we have the following data in the Database:
* {
* "name": {
* "first": "Ada",
* "last": "Lovelace"
* }
* }
*
* var ref = firebase.database().ref("users/ada");
* ref.once("value")
* .then(function(snapshot) {
* var a = snapshot.numChildren(); // 1 ("name")
* var b = snapshot.child("name").numChildren(); // 2 ("first", "last")
* var c = snapshot.child("name/first").numChildren(); // 0
* });
*
* @return {number}
*/
firebase.database.DataSnapshot.prototype.numChildren = function() {};
/**
* The `Reference` for the location that generated this `DataSnapshot`.
*
* @type {!firebase.database.Reference}
*/
firebase.database.DataSnapshot.prototype.ref;
/**
* Returns a JSON-serializable representation of this object.
*
* @return {?Object} A JSON-serializable representation of this object.
*/
firebase.database.DataSnapshot.prototype.toJSON = function() {};
/**
* The `onDisconnect` class allows you to write or clear data when your client
* disconnects from the Database server. These updates occur whether your
* client disconnects cleanly or not, so you can rely on them to clean up data
* even if a connection is dropped or a client crashes.
*
* The `onDisconnect` class is most commonly used to manage presence in
* applications where it is useful to detect how many clients are connected and
* when other clients disconnect. See
* {@link
* https://firebase.google.com/docs/database/web/offline-capabilities
* Enabling Offline Capabilities in JavaScript} for more information.
*
* To avoid problems when a connection is dropped before the requests can be
* transferred to the Database server, these functions should be called before
* writing any data.
*
* Note that `onDisconnect` operations are only triggered once. If you want an
* operation to occur each time a disconnect occurs, you'll need to re-establish
* the `onDisconnect` operations each time you reconnect.
*
* @interface
*/
firebase.database.OnDisconnect = function() {};
/**
* Cancels all previously queued `onDisconnect()` set or update events for this
* location and all children.
*
* If a write has been queued for this location via a `set()` or `update()` at a
* parent location, the write at this location will be canceled, though writes
* to sibling locations will still occur.
*
* @example
* var ref = firebase.database().ref("onlineState");
* ref.onDisconnect().set(false);
* // ... sometime later
* ref.onDisconnect().cancel();
*
* @param {function(?Error)=} onComplete An optional callback function that will
* be called when synchronization to the server has completed. The callback
* will be passed a single parameter: null for success, or an Error object
* indicating a failure.
* @return {!firebase.Promise<void>} Resolves when synchronization to the server
* is complete.
*/
firebase.database.OnDisconnect.prototype.cancel = function(onComplete) {};
/**
* Ensures the data at this location is deleted when the client is disconnected
* (due to closing the browser, navigating to a new page, or network issues).
*
* @param {function(?Error)=} onComplete An optional callback function that will
* be called when synchronization to the server has completed. The callback
* will be passed a single parameter: null for success, or an Error object
* indicating a failure.
* @return {!firebase.Promise<void>} Resolves when synchronization to the server
* is complete.
*/
firebase.database.OnDisconnect.prototype.remove = function(onComplete) {};
/**
* Ensures the data at this location is set to the specified value when the
* client is disconnected (due to closing the browser, navigating to a new page,
* or network issues).
*
* `set()` is especially useful for implementing "presence" systems, where a
* value should be changed or cleared when a user disconnects so that they
* appear "offline" to other users. See
* {@link
* https://firebase.google.com/docs/database/web/offline-capabilities
* Enabling Offline Capabilities in JavaScript} for more information.
*
* Note that `onDisconnect` operations are only triggered once. If you want an
* operation to occur each time a disconnect occurs, you'll need to re-establish
* the `onDisconnect` operations each time.
*
* @example
* var ref = firebase.database().ref("users/ada/status");
* ref.onDisconnect().set("I disconnected!");
*
* @param {*} value The value to be written to this location on
* disconnect (can be an object, array, string, number, boolean, or null).
* @param {function(?Error)=} onComplete An optional callback function that
* will be called when synchronization to the Database server has completed.
* The callback will be passed a single parameter: null for success, or an
* `Error` object indicating a failure.
* @return {!firebase.Promise<void>} Resolves when synchronization to the
* Database is complete.
*/
firebase.database.OnDisconnect.prototype.set = function(value, onComplete) {};
/**
* Ensures the data at this location is set to the specified value and priority
* when the client is disconnected (due to closing the browser, navigating to a
* new page, or network issues).
*
* @param {*} value
* @param {number|string|null} priority
* @param {function(?Error)=} onComplete
* @return {!firebase.Promise<void>}
*/
firebase.database.OnDisconnect.prototype.setWithPriority =
function(value, priority, onComplete) {};
/**
* Writes multiple values at this location when the client is disconnected (due
* to closing the browser, navigating to a new page, or network issues).
*
* The `values` argument contains multiple property-value pairs that will be
* written to the Database together. Each child property can either be a simple
* property (for example, "name") or a relative path (for example, "name/first")
* from the current location to the data to update.
*
* As opposed to the `set()` method, `update()` can be use to selectively update
* only the referenced properties at the current location (instead of replacing
* all the child properties at the current location).
*
* See more examples using the connected version of
* {@link firebase.database.Reference#update `update()`}.
*
* @example
* var ref = firebase.database().ref("users/ada");
* ref.update({
* onlineState: true,
* status: "I'm online."
* });
* ref.onDisconnect().update({
* onlineState: false,
* status: "I'm offline."
* });
*
* @param {!Object} values Object containing multiple values.
* @param {function(?Error)=} onComplete An optional callback function that will
* be called when synchronization to the server has completed. The
* callback will be passed a single parameter: null for success, or an Error
* object indicating a failure.
* @return {!firebase.Promise<void>} Resolves when synchronization to the
* Database is complete.
*/
firebase.database.OnDisconnect.prototype.update =
function(values, onComplete) {};
|
'use strict';
var React = require('react');
var PureRenderMixin = require('react-addons-pure-render-mixin');
var SvgIcon = require('../../svg-icon');
var DeviceBrightnessLow = React.createClass({
displayName: 'DeviceBrightnessLow',
mixins: [PureRenderMixin],
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: 'M20 15.31L23.31 12 20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69zM12 18c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6z' })
);
}
});
module.exports = DeviceBrightnessLow; |
import { ClientFunction } from 'testcafe';
fixture `Fixture`
.clientScripts({ content: 'window["property1"] = true;' });
const getPropertyValue = ClientFunction(propName => window[propName]);
test('test', async t => {
await t
.expect(getPropertyValue('property1')).ok()
.expect(getPropertyValue('property2')).ok();
}).clientScripts({ content: 'window["property2"] = true;' });
|
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var userSchema = new Schema({
// The firstname of the user
firstname: {
type: String,
required: true
},
// The lastname of the user
lastname: {
type: String,
required: true
},
// When the user was created
createdAt: {
type: Date,
default: Date.now,
required: true
}
});
// Assign the schema to a collection
mongoose.model('User', userSchema);
|
YUI.add('inputex-serialize', function (Y, NAME) {
/**
* @module inputex-serialize
*/
var inputEx = Y.inputEx;
/**
* SerializeField allows to serialize/deserialize a complex sub-group to a string
* @class inputEx.SerializeField
* @extends inputEx.Field
* @constructor
* @param {Object} options Standard inputEx options definition
*/
inputEx.SerializeField = function(options) {
inputEx.SerializeField.superclass.constructor.call(this, options);
};
Y.extend(inputEx.SerializeField, inputEx.Field, {
/**
* Adds some options: subfield & serializer
* @method setOptions
* @param {Object} options Options object as passed to the constructor
*/
setOptions: function(options) {
inputEx.SerializeField.superclass.setOptions.call(this, options);
this.options.className = options.className || 'inputEx-SerializedField';
this.options.subfield = options.subfield || {type: 'string'};
this.options.serializer = options.serializer || "json";
},
/**
* Render the subfield
* @method renderComponent
*/
renderComponent: function() {
this.subfieldWrapper = inputEx.cn('div', {className: "inputEx-SerializedField-SubFieldWrapper"});
this.fieldContainer.appendChild( this.subfieldWrapper );
var config = {parentEl: this.subfieldWrapper};
Y.mix(config, this.options.subfield);
this.subField = inputEx( config, this);
},
/**
* Subscribe the subField
* @method initEvents
*/
initEvents: function() {
inputEx.SerializeField.superclass.initEvents.call(this);
this.subField.on('updated', this.fireUpdatedEvt, this, true);
},
/**
* Use the subField getValue and serialize it with the selected serializing method
* @method getValue
*/
getValue: function() {
var val = this.subField.getValue();
return this.serialize(val);
},
/**
* Use the deserialize method and set the value of the subField
* @method setValue
*/
setValue: function(sValue, sendUpdatedEvt) {
var obj = this.deserialize(sValue);
this.subField.setValue(obj, sendUpdatedEvt);
},
/**
* Use the configured serializer
* @method serialize
*/
serialize: function(o) {
return inputEx.SerializeField.serializers[this.options.serializer].serialize(o);
},
/**
* Use the configured deserializer
* @method deserialize
*/
deserialize: function(sValue) {
return inputEx.SerializeField.serializers[this.options.serializer].deserialize(sValue);
},
/**
* Sets the focus on this field
* @method focus
*/
focus: function() {
this.subField.focus();
}
});
/**
* Default serializers for the SerializeField
* @class inputEx.SerializeField.serializers
* @static
*/
inputEx.SerializeField.serializers = {
/**
* JSON Serializer
* @class inputEx.SerializeField.serializers.json
* @static
*/
json: {
/**
* serialize to JSON
* @method serialize
* @static
*/
serialize: function(o) {
return Y.JSON.stringify(o);
},
/**
* deserialize from JSON
* @method deserialize
* @static
*/
deserialize: function(sValue) {
return Y.JSON.parse(sValue);
}
},
/**
* XML Serializer (uses the ObjTree library)
* @class inputEx.SerializeField.serializers.xml
* @static
*/
xml: {
/**
* serialize to XML
* @method serialize
* @static
*/
serialize: function(o) {
if(!XML || !Y.Lang.isFunction(XML.ObjTree) ) {
alert("ObjTree.js not loaded.");
return null;
}
var xotree = new XML.ObjTree();
return xotree.writeXML(o);
},
/**
* deserialize from XML
* @method deserialize
* @static
*/
deserialize: function(sValue) {
if(!XML || !Y.Lang.isFunction(XML.ObjTree) ) {
alert("ObjTree.js not loaded.");
return null;
}
var xotree = new XML.ObjTree(),
tree = xotree.parseXML(sValue);
return tree;
}
}/*,
flatten: {
serialize: function(o) {
// TODO
},
deserialize: function(sValue) {
// TODO
}
}*/
};
// Register this class as "serialize" type
inputEx.registerType("serialize", inputEx.SerializeField, [
{ type:'type', label: 'SubField', name: 'subfield'},
{ type:'select', name: 'serializer', label: 'Serializer', choices: [{ value: 'json' }, { value: 'xml' }/*, { value: 'flatten' }*/], value: 'json'}
]);
}, '@VERSION@', {"requires": ["inputex-string", "json"], "ix_provides": "serialize"});
|
var UIconfig = require('../vue/UIconfig');
var config = {};
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// GENERAL SETTINGS
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
config.silent = false;
config.debug = true;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// CONFIGURING TRADING ADVICE
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
config.tradingAdvisor = {
talib: {
enabled: require('../supportsTalib'),
version: '1.0.2'
}
}
config.candleWriter = {
enabled: false
}
config.adviceWriter = {
enabled: false,
muteSoft: true,
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// CONFIGURING ADAPTER
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// configurable in the UIconfig
config.adapter = UIconfig.adapter;
config.sqlite = {
path: 'plugins/sqlite',
dataDirectory: 'history',
version: 0.1,
dependencies: [{
module: 'sqlite3',
version: '3.1.4'
}]
}
// Postgres adapter example config (please note: requires postgres >= 9.5):
config.postgresql = {
path: 'plugins/postgresql',
version: 0.1,
connectionString: 'postgres://user:pass@localhost:5432', // if default port
database: null, // if set, we'll put all tables into a single database.
dependencies: [{
module: 'pg',
version: '6.1.0'
}]
}
// Mongodb adapter, requires mongodb >= 3.3 (no version earlier tested)
config.mongodb = {
path: 'plugins/mongodb',
version: 0.1,
connectionString: 'mongodb://mongodb/gekko', // connection to mongodb server
dependencies: [{
module: 'mongojs',
version: '2.4.0'
}]
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// CONFIGURING BACKTESTING
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Note that these settings are only used in backtesting mode, see here:
// @link: https://github.com/askmike/gekko/blob/stable/docs/Backtesting.md
config.backtest = {
daterange: 'scan',
batchSize: 50
}
config.importer = {
daterange: {
// NOTE: these dates are in UTC
from: "2016-06-01 12:00:00"
}
}
module.exports = config;
|
tinymce.addI18n('zh_CN.GB2312',{
"Cut": "\u526a\u5207",
"Heading 5": "\u7ae0\u8282\u6807\u98985",
"Header 2": "\u6807\u98982",
"Your browser doesn't support direct access to the clipboard. Please use the Ctrl+X\/C\/V keyboard shortcuts instead.": "\u4f60\u7684\u6d4f\u89c8\u5668\u4e0d\u652f\u6301\u8bbf\u95ee\u526a\u5207\u677f\uff0c\u8bf7\u4f7f\u7528Ctrl+X\/C\/V\u5feb\u6377\u952e\u66ff\u4ee3\u3002",
"Heading 4": "\u7ae0\u8282\u6807\u98984",
"Div": "\u5411\u540e",
"Heading 2": "\u7ae0\u8282\u6807\u98982",
"Paste": "\u7c98\u5e16",
"Close": "\u5173\u95ed",
"Font Family": "\u5b57\u4f53",
"Pre": "\u5411\u524d",
"Align right": "\u5c45\u4e2d\u5bf9\u9f50",
"New document": "\u65b0\u6587\u6863",
"Blockquote": "\u5757\u5f15\u7528",
"Numbered list": "\u6570\u5b57\u5217\u8868",
"Heading 1": "\u7ae0\u8282\u6807\u98981",
"Headings": "\u7ae0\u8282\u6807\u9898",
"Increase indent": "\u589e\u52a0\u7f29\u8fdb",
"Formats": "\u683c\u5f0f\u5316",
"Headers": " \u6807\u9898",
"Select all": "\u5168\u9009",
"Header 3": "\u6807\u98983",
"Blocks": "\u5757",
"Undo": "\u64a4\u9500",
"Strikethrough": "\u5220\u9664\u7ebf",
"Bullet list": "\u7b26\u53f7\u5217\u8868",
"Header 1": "\u6807\u98981",
"Superscript": "\u4e0a\u89d2\u6807",
"Clear formatting": "\u6e05\u9664\u683c\u5f0f",
"Font Sizes": "\u5b57\u53f7",
"Subscript": "\u4e0b\u89d2\u6807",
"Header 6": "\u6807\u98986",
"Redo": "\u91cd\u505a",
"Paragraph": "\u6bb5\u843d",
"Ok": "\u786e\u8ba4",
"Bold": "\u7c97\u4f53",
"Code": "\u4ee3\u7801",
"Italic": "\u659c\u4f53",
"Align center": "\u5c45\u4e2d\u5bf9\u9f50",
"Header 5": "\u6807\u98985",
"Heading 6": "\u7ae0\u8282\u6807\u98986",
"Heading 3": "\u7ae0\u8282\u6807\u98983",
"Decrease indent": "\u51cf\u5c0f\u7f29\u8fdb",
"Header 4": "\u6807\u98984",
"Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off.": "\u7c98\u8d34\u73b0\u5728\u662f\u7eaf\u6587\u672c\u6a21\u5f0f\u3002\u5185\u5bb9\u5c06\u7c98\u8d34\u4e3a\u7eaf\u6587\u672c\u5f62\u5f0f\uff0c\b\u76f4\u5230\u60a8\u5207\u6362\u9009\u9879\u5f00\u5173\u3002",
"Underline": "\u4e0b\u5212\u7ebf",
"Cancel": "\u53d6\u6d88",
"Justify": "\u4e24\u7aef\u5bf9\u9f50",
"Inline": "\u5185\u5d4c",
"Copy": "\u590d\u5236",
"Align left": "\u5de6\u5bf9\u9f50",
"Visual aids": "\u53ef\u89c6\u5316\u5de5\u5177",
"Lower Greek": "\u5c0f\u5199\u5e0c\u814a\u5b57\u6bcd",
"Square": "\u65b9\u5f62",
"Default": "\u9ed8\u8ba4",
"Lower Alpha": "\u5c0f\u5199\u5b57\u6bcd",
"Circle": "\u5706\u5f62",
"Disc": "\u78c1\u76d8",
"Upper Alpha": "\u5927\u5199\u5b57\u6bcd",
"Upper Roman": "\u5927\u5199\u7f57\u9a6c\u5b57\u6bcd",
"Lower Roman": "\u5c0f\u5199\u7f57\u9a6c\u5b57\u6bcd",
"Id should start with a letter, followed only by letters, numbers, dashes, dots, colons or underscores.": "\u6807\u8bc6\u7b26\u5e94\u8be5\u4ee5\u5b57\u6bcd\u5f00\u5934\uff0c\u540e\u8ddf\u5b57\u6bcd\u3001\u6570\u5b57\u3001\u7834\u6298\u53f7\u3001\u70b9\u3001\u5192\u53f7\u6216\u4e0b\u5212\u7ebf\u3002",
"Name": "\u540d\u79f0",
"Anchor": "\u951a\u70b9",
"Id": "\u6807\u8bc6\u7b26",
"You have unsaved changes are you sure you want to navigate away?": "\u60a8\u8fd8\u6ca1\u6709\u4fdd\u5b58\uff0c\u60a8\u786e\u5b9a\u8981\u79bb\u5f00\uff1f",
"Restore last draft": "\u6062\u590d\u6700\u540e\u8349\u7a3f",
"Special character": "\u7279\u6b8a\u5b57\u7b26",
"Source code": "\u6e90\u4ee3\u7801",
"Language": "\u8bed\u8a00",
"Insert\/Edit code sample": "\u63d2\u5165\/\u7f16\u8f91\u4ee3\u7801\u793a\u4f8b",
"B": "B\u503c",
"R": "R\u503c",
"G": "G\u503c",
"Color": "\u989c\u8272",
"Right to left": "\u4ece\u53f3\u5230\u5de6",
"Left to right": "\u4ece\u5de6\u5230\u53f3",
"Emoticons": "\u8868\u60c5",
"Robots": "\u641c\u7d22\u673a\u5668\u4eba\u7528Robots\u6587\u4ef6",
"Document properties": "\u6587\u6863\u5c5e\u6027",
"Title": "\u6807\u9898",
"Keywords": "\u5173\u952e\u5b57",
"Encoding": "\u7f16\u7801",
"Description": "\u63cf\u8ff0",
"Author": "\u4f5c\u8005",
"Fullscreen": "\u5168\u5c4f",
"Horizontal line": "\u6c34\u5e73\u7ebf",
"Horizontal space": "\u6c34\u5e73\u95f4\u8ddd",
"Insert\/edit image": "\u63d2\u5165\/\u7f16\u8f91 \u56fe\u7247",
"General": "\u5e38\u89c4",
"Advanced": "\u9ad8\u7ea7\u9009\u9879",
"Source": "\u6e90",
"Border": "\u8fb9",
"Constrain proportions": "\u9650\u5236\u6bd4\u4f8b",
"Vertical space": "\u5782\u76f4\u95f4\u8ddd",
"Image description": "\u56fe\u7247\u63cf\u8ff0",
"Style": "\u6837\u5f0f",
"Dimensions": "\u5c3a\u5bf8",
"Insert image": "\u63d2\u5165\u56fe\u7247",
"Image": "Image",
"Zoom in": "\u653e\u5927",
"Contrast": "\u5bf9\u6bd4\u5ea6",
"Back": "\u8fd4\u56de",
"Gamma": "\u7070\u5ea6",
"Flip horizontally": "\u6c34\u5e73\u7ffb\u8f6c",
"Resize": "\u8c03\u6574\u5927\u5c0f",
"Sharpen": "\u9510\u5316",
"Zoom out": "\u7f29\u5c0f",
"Image options": "\u56fe\u7247\u9009\u9879",
"Apply": "\u5e94\u7528",
"Brightness": "\u4eae\u5ea6",
"Rotate clockwise": "\u987a\u65f6\u9488\u65cb\u8f6c",
"Rotate counterclockwise": "\u9006\u65f6\u9488\u65cb\u8f6c",
"Edit image": "\u7f16\u8f91\u56fe\u7247",
"Color levels": "\u8272\u9636",
"Crop": "\u526a\u88c1",
"Orientation": "\u65b9\u5411",
"Flip vertically": "\u5782\u76f4\u7ffb\u8f6c",
"Invert": "\u53cd\u8272",
"Date\/time": "Date\/time",
"Insert date\/time": "\u63d2\u5165\u65e5\u671f\/\u65f6\u95f4",
"Remove link": "\u5220\u9664\u94fe\u63a5",
"Url": "URL\u94fe\u63a5",
"Text to display": "\u8981\u663e\u793a\u7684\u6587\u5b57",
"Anchors": "\u951a\u70b9",
"Insert link": "\u63d2\u5165\u94fe\u63a5",
"Link": "Link",
"New window": "\u65b0\u7a97\u53e3",
"None": "\u65e0\u503c",
"The URL you entered seems to be an external link. Do you want to add the required http:\/\/ prefix?": "\u60a8\u8f93\u5165\u7684\u7f51\u5740\u4f3c\u4e4e\u662f\u4e00\u4e2a\u5916\u90e8\u94fe\u63a5\u3002\u662f\u5426\u9700\u8981\u6dfb\u52a0HTTP:\/\/\u524d\u7f00\uff1f",
"Paste or type a link": "Paste or type a link",
"Target": "\u76ee\u6807",
"The URL you entered seems to be an email address. Do you want to add the required mailto: prefix?": "\u60a8\u8f93\u5165\u7684\u7f51\u5740\u4f3c\u4e4e\u662f\u4e00\u4e2a\u7535\u5b50\u90ae\u4ef6\u5730\u5740\u3002\u662f\u5426\u9700\u8981\u6dfb\u52a0mailto\uff1a\u524d\u7f00\uff1f",
"Insert\/edit link": "\u63d2\u5165\/\u7f16\u8f91 \u94fe\u63a5",
"Insert\/edit video": "\u63d2\u5165\/\u7f16\u8f91 \u89c6\u9891",
"Media": "Media",
"Alternative source": "\u66ff\u4ee3\u6e90",
"Paste your embed code below:": "\u4e0b\u9762\u7c98\u8d34\u60a8\u7684\u5d4c\u5165\u4ee3\u7801\uff1a",
"Insert video": "\u63d2\u5165\u89c6\u9891",
"Poster": "\u6d77\u62a5",
"Insert\/edit media": "Insert\/edit media",
"Embed": "\u5185\u5d4c",
"Nonbreaking space": "\u4e0d\u95f4\u65ad\u7a7a\u683c",
"Page break": "\u5206\u9875\u7b26",
"Paste as text": "\u4f5c\u4e3a\u6587\u672c\u7c98\u5e16",
"Preview": "\u9884\u89c8",
"Print": "\u6253\u5370",
"Save": "\u4fdd\u5b58",
"Could not find the specified string.": "\u627e\u4e0d\u5230\u6307\u5b9a\u7684\u5b57\u7b26\u4e32\u3002",
"Replace": "\u66ff\u6362",
"Next": "\u5148\u4e00\u4e2a",
"Whole words": "\b\u5168\u90e8\u5b57\u7b26",
"Find and replace": "\u67e5\u627e\u548c\u66ff\u6362",
"Replace with": "\u7528...\u6765\u4ee3\u66ff",
"Find": "\u67e5\u627e",
"Replace all": "\u66ff\u6362\u5168\u90e8",
"Match case": "\u76f8\u7b26",
"Prev": "\u4e0a\u4e00\u4e2a",
"Spellcheck": "\u62fc\u5199\u68c0\u67e5",
"Finish": "\u5b8c\u6210",
"Ignore all": "\u5168\u90e8\u5ffd\u7565",
"Ignore": "\u5ffd\u7565",
"Add to Dictionary": "\u52a0\u5165\u5230\u5b57\u5178",
"Insert row before": "\u5728\u524d\u63d2\u5165\b\b\u884c",
"Rows": "\b\u884c\u6570",
"Height": "\u9ad8",
"Paste row after": "\u5728\u540e\u7c98\u5e16\b\u884c",
"Alignment": "\u5bf9\u9f50\u65b9\u5f0f",
"Border color": "\u8fb9\u6846\u989c\u8272",
"Column group": "\u521b\u5efa\u5217\u7ec4",
"Row": "\u884c",
"Insert column before": "\u5728\u524d\u63d2\u5165\b\u5217",
"Split cell": "\u5206\u5272\u5355\u5143\u683c",
"Cell padding": "\u5355\u5143\u683c\u8fb9\u8ddd",
"Cell spacing": "\u5355\u5143\u683c\u95f4\u8ddd",
"Row type": "\u884c\u7c7b\u578b",
"Insert table": "\u63d2\u5165\u8868\u683c",
"Body": "\u4f53\u90e8",
"Caption": "\u8bf4\u660e\u6587\u5b57",
"Footer": "\u811a\u90e8",
"Delete row": "\u5220\u9664\b\u884c",
"Paste row before": "\u5728\u524d\u7c98\u5e16\b\u884c",
"Scope": "\u9002\u7528\u8303\u56f4",
"Delete table": "\u5220\u9664\u8868\u683c",
"H Align": "\u6c34\u5e73\u5bf9\u9f50",
"Top": "\u4e0a",
"Header cell": "\b\u6807\u9898\u5355\u5143",
"Column": "\b\u5217",
"Row group": "\b\u521b\u5efa\u884c\u7ec4",
"Cell": "\u5355\u5143\u683c",
"Middle": "\u4e2d",
"Cell type": "\u5355\u5143\u683c\u7c7b\u578b",
"Copy row": "\u590d\u5236\b\u884c",
"Row properties": "\b\u884c\u5c5e\u6027",
"Table properties": "\u8868\u683c\u5c5e\u6027",
"Bottom": "\u4e0b",
"V Align": "\u5782\u76f4\u5bf9\u9f50",
"Header": "\u5934\u90e8",
"Right": "\u53f3",
"Insert column after": "\u5728\u540e\u63d2\u5165\b\u5217",
"Cols": "\u5217\u6570",
"Insert row after": "\u5728\u540e\u63d2\u5165\b\u884c",
"Width": "\u5bbd",
"Cell properties": "\u884c\u5c5e\u6027",
"Left": "\u5de6",
"Cut row": "\u526a\u5207\b\u884c",
"Delete column": "\u5220\u9664\b\u5217",
"Center": "\u4e2d\u95f4",
"Merge cells": "\u5408\u5e76\u5355\u5143\u683c",
"Insert template": "\u63d2\u5165\u6a21\u677f",
"Templates": "\u6a21\u677f",
"Background color": "\u80cc\u666f\u989c\u8272",
"Custom...": "\u81ea\u5b9a\u4e49...",
"Custom color": "\u81ea\u5b9a\u4e49\u989c\u8272",
"No color": "\u65e0\u989c\u8272",
"Text color": "\u6587\u5b57\u989c\u8272",
"Table of Contents": "Table of Contents",
"Show blocks": "\u663e\u793a\u5757",
"Show invisible characters": "\u663e\u793a\u4e0d\u53ef\u89c1\u5b57\u7b26",
"Words: {0}": "\u5b57\u7b26\u6570:{0}",
"Insert": "\u63d2\u5165",
"File": "\u6587\u4ef6",
"Edit": "\u7f16\u8f91",
"Rich Text Area. Press ALT-F9 for menu. Press ALT-F10 for toolbar. Press ALT-0 for help": "\u5bcc\u6587\u5b57\u57df\u3002\u83dc\u5355\u6309 ALT-F9 \uff0c\u5de5\u5177\u6761\u6309ALT-F10\uff0c\u5e2e\u52a9\u6309ALT-0",
"Tools": "\u5de5\u5177",
"View": "\u89c6\u56fe",
"Table": "\u8868\u683c",
"Format": "\u683c\u5f0f"
}); |
(function e(t, n, r) {
function s(o, u) {
if (!n[o]) {
if (!t[o]) {
var a = typeof require == "function" && require;
if (!u && a)return a(o, !0);
if (i)return i(o, !0);
var f = new Error("Cannot find module '" + o + "'");
throw f.code = "MODULE_NOT_FOUND", f
}
var l = n[o] = {exports: {}};
t[o][0].call(l.exports, function (e) {
var n = t[o][1][e];
return s(n ? n : e)
}, l, l.exports, e, t, n, r)
}
return n[o].exports
}
var i = typeof require == "function" && require;
for (var o = 0; o < r.length; o++)s(r[o]);
return s
})({
1: [function (require, module, exports) {
module.exports = minimatch
minimatch.Minimatch = Minimatch
var path = {sep: '/'}
try {
path = require('path')
} catch (er) {
}
var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}
var expand = require('brace-expansion')
// any single thing other than /
// don't need to escape / when using new RegExp()
var qmark = '[^/]'
// * => any number of characters
var star = qmark + '*?'
// ** when dots are allowed. Anything goes, except .. and .
// not (^ or / followed by one or two dots followed by $ or /),
// followed by anything, any number of times.
var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'
// not a ^ or / followed by a dot,
// followed by anything, any number of times.
var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'
// characters that need to be escaped in RegExp.
var reSpecials = charSet('().*{}+?[]^$\\!')
// "abc" -> { a:true, b:true, c:true }
function charSet(s) {
return s.split('').reduce(function (set, c) {
set[c] = true
return set
}, {})
}
// normalizes slashes.
var slashSplit = /\/+/
minimatch.filter = filter
function filter(pattern, options) {
options = options || {}
return function (p, i, list) {
return minimatch(p, pattern, options)
}
}
function ext(a, b) {
a = a || {}
b = b || {}
var t = {}
Object.keys(b).forEach(function (k) {
t[k] = b[k]
})
Object.keys(a).forEach(function (k) {
t[k] = a[k]
})
return t
}
minimatch.defaults = function (def) {
if (!def || !Object.keys(def).length) return minimatch
var orig = minimatch
var m = function minimatch(p, pattern, options) {
return orig.minimatch(p, pattern, ext(def, options))
}
m.Minimatch = function Minimatch(pattern, options) {
return new orig.Minimatch(pattern, ext(def, options))
}
return m
}
Minimatch.defaults = function (def) {
if (!def || !Object.keys(def).length) return Minimatch
return minimatch.defaults(def).Minimatch
}
function minimatch(p, pattern, options) {
if (typeof pattern !== 'string') {
throw new TypeError('glob pattern string required')
}
if (!options) options = {}
// shortcut: comments match nothing.
if (!options.nocomment && pattern.charAt(0) === '#') {
return false
}
// "" only matches ""
if (pattern.trim() === '') return p === ''
return new Minimatch(pattern, options).match(p)
}
function Minimatch(pattern, options) {
if (!(this instanceof Minimatch)) {
return new Minimatch(pattern, options)
}
if (typeof pattern !== 'string') {
throw new TypeError('glob pattern string required')
}
if (!options) options = {}
pattern = pattern.trim()
// windows support: need to use /, not \
if (path.sep !== '/') {
pattern = pattern.split(path.sep).join('/')
}
this.options = options
this.set = []
this.pattern = pattern
this.regexp = null
this.negate = false
this.comment = false
this.empty = false
// make the set of regexps etc.
this.make()
}
Minimatch.prototype.debug = function () {
}
Minimatch.prototype.make = make
function make() {
// don't do it more than once.
if (this._made) return
var pattern = this.pattern
var options = this.options
// empty patterns and comments match nothing.
if (!options.nocomment && pattern.charAt(0) === '#') {
this.comment = true
return
}
if (!pattern) {
this.empty = true
return
}
// step 1: figure out negation, etc.
this.parseNegate()
// step 2: expand braces
var set = this.globSet = this.braceExpand()
if (options.debug) this.debug = console.error
this.debug(this.pattern, set)
// step 3: now we have a set, so turn each one into a series of path-portion
// matching patterns.
// These will be regexps, except in the case of "**", which is
// set to the GLOBSTAR object for globstar behavior,
// and will not contain any / characters
set = this.globParts = set.map(function (s) {
return s.split(slashSplit)
})
this.debug(this.pattern, set)
// glob --> regexps
set = set.map(function (s, si, set) {
return s.map(this.parse, this)
}, this)
this.debug(this.pattern, set)
// filter out everything that didn't compile properly.
set = set.filter(function (s) {
return s.indexOf(false) === -1
})
this.debug(this.pattern, set)
this.set = set
}
Minimatch.prototype.parseNegate = parseNegate
function parseNegate() {
var pattern = this.pattern
var negate = false
var options = this.options
var negateOffset = 0
if (options.nonegate) return
for (var i = 0, l = pattern.length
; i < l && pattern.charAt(i) === '!'
; i++) {
negate = !negate
negateOffset++
}
if (negateOffset) this.pattern = pattern.substr(negateOffset)
this.negate = negate
}
// Brace expansion:
// a{b,c}d -> abd acd
// a{b,}c -> abc ac
// a{0..3}d -> a0d a1d a2d a3d
// a{b,c{d,e}f}g -> abg acdfg acefg
// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
//
// Invalid sets are not expanded.
// a{2..}b -> a{2..}b
// a{b}c -> a{b}c
minimatch.braceExpand = function (pattern, options) {
return braceExpand(pattern, options)
}
Minimatch.prototype.braceExpand = braceExpand
function braceExpand(pattern, options) {
if (!options) {
if (this instanceof Minimatch) {
options = this.options
} else {
options = {}
}
}
pattern = typeof pattern === 'undefined'
? this.pattern : pattern
if (typeof pattern === 'undefined') {
throw new Error('undefined pattern')
}
if (options.nobrace || !pattern.match(/\{.*\}/)) {
// shortcut. no need to expand.
return [pattern]
}
return expand(pattern)
}
// parse a component of the expanded set.
// At this point, no pattern may contain "/" in it
// so we're going to return a 2d array, where each entry is the full
// pattern, split on '/', and then turned into a regular expression.
// A regexp is made at the end which joins each array with an
// escaped /, and another full one which joins each regexp with |.
//
// Following the lead of Bash 4.1, note that "**" only has special meaning
// when it is the *only* thing in a path portion. Otherwise, any series
// of * is equivalent to a single *. Globstar behavior is enabled by
// default, and can be disabled by setting options.noglobstar.
Minimatch.prototype.parse = parse
var SUBPARSE = {}
function parse(pattern, isSub) {
var options = this.options
// shortcuts
if (!options.noglobstar && pattern === '**') return GLOBSTAR
if (pattern === '') return ''
var re = ''
var hasMagic = !!options.nocase
var escaping = false
// ? => one single character
var patternListStack = []
var plType
var stateChar
var inClass = false
var reClassStart = -1
var classStart = -1
// . and .. never match anything that doesn't start with .,
// even when options.dot is set.
var patternStart = pattern.charAt(0) === '.' ? '' // anything
// not (start or / followed by . or .. followed by / or end)
: options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
: '(?!\\.)'
var self = this
function clearStateChar() {
if (stateChar) {
// we had some state-tracking character
// that wasn't consumed by this pass.
switch (stateChar) {
case '*':
re += star
hasMagic = true
break
case '?':
re += qmark
hasMagic = true
break
default:
re += '\\' + stateChar
break
}
self.debug('clearStateChar %j %j', stateChar, re)
stateChar = false
}
}
for (var i = 0, len = pattern.length, c
; (i < len) && (c = pattern.charAt(i))
; i++) {
this.debug('%s\t%s %s %j', pattern, i, re, c)
// skip over any that are escaped.
if (escaping && reSpecials[c]) {
re += '\\' + c
escaping = false
continue
}
switch (c) {
case '/':
// completely not allowed, even escaped.
// Should already be path-split by now.
return false
case '\\':
clearStateChar()
escaping = true
continue
// the various stateChar values
// for the "extglob" stuff.
case '?':
case '*':
case '+':
case '@':
case '!':
this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)
// all of those are literals inside a class, except that
// the glob [!a] means [^a] in regexp
if (inClass) {
this.debug(' in class')
if (c === '!' && i === classStart + 1) c = '^'
re += c
continue
}
// if we already have a stateChar, then it means
// that there was something like ** or +? in there.
// Handle the stateChar, then proceed with this one.
self.debug('call clearStateChar %j', stateChar)
clearStateChar()
stateChar = c
// if extglob is disabled, then +(asdf|foo) isn't a thing.
// just clear the statechar *now*, rather than even diving into
// the patternList stuff.
if (options.noext) clearStateChar()
continue
case '(':
if (inClass) {
re += '('
continue
}
if (!stateChar) {
re += '\\('
continue
}
plType = stateChar
patternListStack.push({type: plType, start: i - 1, reStart: re.length})
// negation is (?:(?!js)[^/]*)
re += stateChar === '!' ? '(?:(?!' : '(?:'
this.debug('plType %j %j', stateChar, re)
stateChar = false
continue
case ')':
if (inClass || !patternListStack.length) {
re += '\\)'
continue
}
clearStateChar()
hasMagic = true
re += ')'
plType = patternListStack.pop().type
// negation is (?:(?!js)[^/]*)
// The others are (?:<pattern>)<type>
switch (plType) {
case '!':
re += '[^/]*?)'
break
case '?':
case '+':
case '*':
re += plType
break
case '@':
break // the default anyway
}
continue
case '|':
if (inClass || !patternListStack.length || escaping) {
re += '\\|'
escaping = false
continue
}
clearStateChar()
re += '|'
continue
// these are mostly the same in regexp and glob
case '[':
// swallow any state-tracking char before the [
clearStateChar()
if (inClass) {
re += '\\' + c
continue
}
inClass = true
classStart = i
reClassStart = re.length
re += c
continue
case ']':
// a right bracket shall lose its special
// meaning and represent itself in
// a bracket expression if it occurs
// first in the list. -- POSIX.2 2.8.3.2
if (i === classStart + 1 || !inClass) {
re += '\\' + c
escaping = false
continue
}
// handle the case where we left a class open.
// "[z-a]" is valid, equivalent to "\[z-a\]"
if (inClass) {
// split where the last [ was, make sure we don't have
// an invalid re. if so, re-walk the contents of the
// would-be class to re-translate any characters that
// were passed through as-is
// TODO: It would probably be faster to determine this
// without a try/catch and a new RegExp, but it's tricky
// to do safely. For now, this is safe and works.
var cs = pattern.substring(classStart + 1, i)
try {
RegExp('[' + cs + ']')
} catch (er) {
// not a valid class!
var sp = this.parse(cs, SUBPARSE)
re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'
hasMagic = hasMagic || sp[1]
inClass = false
continue
}
}
// finish up the class.
hasMagic = true
inClass = false
re += c
continue
default:
// swallow any state char that wasn't consumed
clearStateChar()
if (escaping) {
// no need
escaping = false
} else if (reSpecials[c]
&& !(c === '^' && inClass)) {
re += '\\'
}
re += c
} // switch
} // for
// handle the case where we left a class open.
// "[abc" is valid, equivalent to "\[abc"
if (inClass) {
// split where the last [ was, and escape it
// this is a huge pita. We now have to re-walk
// the contents of the would-be class to re-translate
// any characters that were passed through as-is
cs = pattern.substr(classStart + 1)
sp = this.parse(cs, SUBPARSE)
re = re.substr(0, reClassStart) + '\\[' + sp[0]
hasMagic = hasMagic || sp[1]
}
// handle the case where we had a +( thing at the *end*
// of the pattern.
// each pattern list stack adds 3 chars, and we need to go through
// and escape any | chars that were passed through as-is for the regexp.
// Go through and escape them, taking care not to double-escape any
// | chars that were already escaped.
for (var pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
var tail = re.slice(pl.reStart + 3)
// maybe some even number of \, then maybe 1 \, followed by a |
tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) {
if (!$2) {
// the | isn't already escaped, so escape it.
$2 = '\\'
}
// need to escape all those slashes *again*, without escaping the
// one that we need for escaping the | character. As it works out,
// escaping an even number of slashes can be done by simply repeating
// it exactly after itself. That's why this trick works.
//
// I am sorry that you have to see this.
return $1 + $1 + $2 + '|'
})
this.debug('tail=%j\n %s', tail, tail)
var t = pl.type === '*' ? star
: pl.type === '?' ? qmark
: '\\' + pl.type
hasMagic = true
re = re.slice(0, pl.reStart) + t + '\\(' + tail
}
// handle trailing things that only matter at the very end.
clearStateChar()
if (escaping) {
// trailing \\
re += '\\\\'
}
// only need to apply the nodot start if the re starts with
// something that could conceivably capture a dot
var addPatternStart = false
switch (re.charAt(0)) {
case '.':
case '[':
case '(':
addPatternStart = true
}
// if the re is not "" at this point, then we need to make sure
// it doesn't match against an empty path part.
// Otherwise a/* will match a/, which it should not.
if (re !== '' && hasMagic) re = '(?=.)' + re
if (addPatternStart) re = patternStart + re
// parsing just a piece of a larger pattern.
if (isSub === SUBPARSE) {
return [re, hasMagic]
}
// skip the regexp for non-magical patterns
// unescape anything in it, though, so that it'll be
// an exact match against a file etc.
if (!hasMagic) {
return globUnescape(pattern)
}
var flags = options.nocase ? 'i' : ''
var regExp = new RegExp('^' + re + '$', flags)
regExp._glob = pattern
regExp._src = re
return regExp
}
minimatch.makeRe = function (pattern, options) {
return new Minimatch(pattern, options || {}).makeRe()
}
Minimatch.prototype.makeRe = makeRe
function makeRe() {
if (this.regexp || this.regexp === false) return this.regexp
// at this point, this.set is a 2d array of partial
// pattern strings, or "**".
//
// It's better to use .match(). This function shouldn't
// be used, really, but it's pretty convenient sometimes,
// when you just want to work with a regex.
var set = this.set
if (!set.length) {
this.regexp = false
return this.regexp
}
var options = this.options
var twoStar = options.noglobstar ? star
: options.dot ? twoStarDot
: twoStarNoDot
var flags = options.nocase ? 'i' : ''
var re = set.map(function (pattern) {
return pattern.map(function (p) {
return (p === GLOBSTAR) ? twoStar
: (typeof p === 'string') ? regExpEscape(p)
: p._src
}).join('\\\/')
}).join('|')
// must match entire pattern
// ending in a * or ** will make it less strict.
re = '^(?:' + re + ')$'
// can match anything, as long as it's not this.
if (this.negate) re = '^(?!' + re + ').*$'
try {
this.regexp = new RegExp(re, flags)
} catch (ex) {
this.regexp = false
}
return this.regexp
}
minimatch.match = function (list, pattern, options) {
options = options || {}
var mm = new Minimatch(pattern, options)
list = list.filter(function (f) {
return mm.match(f)
})
if (mm.options.nonull && !list.length) {
list.push(pattern)
}
return list
}
Minimatch.prototype.match = match
function match(f, partial) {
this.debug('match', f, this.pattern)
// short-circuit in the case of busted things.
// comments, etc.
if (this.comment) return false
if (this.empty) return f === ''
if (f === '/' && partial) return true
var options = this.options
// windows: need to use /, not \
if (path.sep !== '/') {
f = f.split(path.sep).join('/')
}
// treat the test path as a set of pathparts.
f = f.split(slashSplit)
this.debug(this.pattern, 'split', f)
// just ONE of the pattern sets in this.set needs to match
// in order for it to be valid. If negating, then just one
// match means that we have failed.
// Either way, return on the first hit.
var set = this.set
this.debug(this.pattern, 'set', set)
// Find the basename of the path by looking for the last non-empty segment
var filename
var i
for (i = f.length - 1; i >= 0; i--) {
filename = f[i]
if (filename) break
}
for (i = 0; i < set.length; i++) {
var pattern = set[i]
var file = f
if (options.matchBase && pattern.length === 1) {
file = [filename]
}
var hit = this.matchOne(file, pattern, partial)
if (hit) {
if (options.flipNegate) return true
return !this.negate
}
}
// didn't get any hits. this is success if it's a negative
// pattern, failure otherwise.
if (options.flipNegate) return false
return this.negate
}
// set partial to true to test if, for example,
// "/a/b" matches the start of "/*/b/*/d"
// Partial means, if you run out of file before you run
// out of pattern, then that's fine, as long as all
// the parts match.
Minimatch.prototype.matchOne = function (file, pattern, partial) {
var options = this.options
this.debug('matchOne',
{'this': this, file: file, pattern: pattern})
this.debug('matchOne', file.length, pattern.length)
for (var fi = 0,
pi = 0,
fl = file.length,
pl = pattern.length
; (fi < fl) && (pi < pl)
; fi++, pi++) {
this.debug('matchOne loop')
var p = pattern[pi]
var f = file[fi]
this.debug(pattern, p, f)
// should be impossible.
// some invalid regexp stuff in the set.
if (p === false) return false
if (p === GLOBSTAR) {
this.debug('GLOBSTAR', [pattern, p, f])
// "**"
// a/**/b/**/c would match the following:
// a/b/x/y/z/c
// a/x/y/z/b/c
// a/b/x/b/x/c
// a/b/c
// To do this, take the rest of the pattern after
// the **, and see if it would match the file remainder.
// If so, return success.
// If not, the ** "swallows" a segment, and try again.
// This is recursively awful.
//
// a/**/b/**/c matching a/b/x/y/z/c
// - a matches a
// - doublestar
// - matchOne(b/x/y/z/c, b/**/c)
// - b matches b
// - doublestar
// - matchOne(x/y/z/c, c) -> no
// - matchOne(y/z/c, c) -> no
// - matchOne(z/c, c) -> no
// - matchOne(c, c) yes, hit
var fr = fi
var pr = pi + 1
if (pr === pl) {
this.debug('** at the end')
// a ** at the end will just swallow the rest.
// We have found a match.
// however, it will not swallow /.x, unless
// options.dot is set.
// . and .. are *never* matched by **, for explosively
// exponential reasons.
for (; fi < fl; fi++) {
if (file[fi] === '.' || file[fi] === '..' ||
(!options.dot && file[fi].charAt(0) === '.')) return false
}
return true
}
// ok, let's see if we can swallow whatever we can.
while (fr < fl) {
var swallowee = file[fr]
this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)
// XXX remove this slice. Just pass the start index.
if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
this.debug('globstar found match!', fr, fl, swallowee)
// found a match.
return true
} else {
// can't swallow "." or ".." ever.
// can only swallow ".foo" when explicitly asked.
if (swallowee === '.' || swallowee === '..' ||
(!options.dot && swallowee.charAt(0) === '.')) {
this.debug('dot detected!', file, fr, pattern, pr)
break
}
// ** swallows a segment, and continue.
this.debug('globstar swallow a segment, and continue')
fr++
}
}
// no match was found.
// However, in partial mode, we can't say this is necessarily over.
// If there's more *pattern* left, then
if (partial) {
// ran out of file
this.debug('\n>>> no match, partial?', file, fr, pattern, pr)
if (fr === fl) return true
}
return false
}
// something other than **
// non-magic patterns just have to match exactly
// patterns with magic have been turned into regexps.
var hit
if (typeof p === 'string') {
if (options.nocase) {
hit = f.toLowerCase() === p.toLowerCase()
} else {
hit = f === p
}
this.debug('string match', p, f, hit)
} else {
hit = f.match(p)
this.debug('pattern match', p, f, hit)
}
if (!hit) return false
}
// Note: ending in / means that we'll get a final ""
// at the end of the pattern. This can only match a
// corresponding "" at the end of the file.
// If the file ends in /, then it can only match a
// a pattern that ends in /, unless the pattern just
// doesn't have any more for it. But, a/b/ should *not*
// match "a/b/*", even though "" matches against the
// [^/]*? pattern, except in partial mode, where it might
// simply not be reached yet.
// However, a/b/ should still satisfy a/*
// now either we fell off the end of the pattern, or we're done.
if (fi === fl && pi === pl) {
// ran out of pattern and filename at the same time.
// an exact hit!
return true
} else if (fi === fl) {
// ran out of file, but still had pattern left.
// this is ok if we're doing the match as part of
// a glob fs traversal.
return partial
} else if (pi === pl) {
// ran out of pattern, still have file left.
// this is only acceptable if we're on the very last
// empty segment of a file with a trailing slash.
// a/* should match a/b/
var emptyFileEnd = (fi === fl - 1) && (file[fi] === '')
return emptyFileEnd
}
// should be unreachable.
throw new Error('wtf?')
}
// replace stuff like \* with *
function globUnescape(s) {
return s.replace(/\\(.)/g, '$1')
}
function regExpEscape(s) {
return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
}
}, {"brace-expansion": 2, "path": undefined}], 2: [function (require, module, exports) {
var concatMap = require('concat-map');
var balanced = require('balanced-match');
module.exports = expandTop;
var escSlash = '\0SLASH' + Math.random() + '\0';
var escOpen = '\0OPEN' + Math.random() + '\0';
var escClose = '\0CLOSE' + Math.random() + '\0';
var escComma = '\0COMMA' + Math.random() + '\0';
var escPeriod = '\0PERIOD' + Math.random() + '\0';
function numeric(str) {
return parseInt(str, 10) == str
? parseInt(str, 10)
: str.charCodeAt(0);
}
function escapeBraces(str) {
return str.split('\\\\').join(escSlash)
.split('\\{').join(escOpen)
.split('\\}').join(escClose)
.split('\\,').join(escComma)
.split('\\.').join(escPeriod);
}
function unescapeBraces(str) {
return str.split(escSlash).join('\\')
.split(escOpen).join('{')
.split(escClose).join('}')
.split(escComma).join(',')
.split(escPeriod).join('.');
}
// Basically just str.split(","), but handling cases
// where we have nested braced sections, which should be
// treated as individual members, like {a,{b,c},d}
function parseCommaParts(str) {
if (!str)
return [''];
var parts = [];
var m = balanced('{', '}', str);
if (!m)
return str.split(',');
var pre = m.pre;
var body = m.body;
var post = m.post;
var p = pre.split(',');
p[p.length - 1] += '{' + body + '}';
var postParts = parseCommaParts(post);
if (post.length) {
p[p.length - 1] += postParts.shift();
p.push.apply(p, postParts);
}
parts.push.apply(parts, p);
return parts;
}
function expandTop(str) {
if (!str)
return [];
var expansions = expand(escapeBraces(str));
return expansions.filter(identity).map(unescapeBraces);
}
function identity(e) {
return e;
}
function embrace(str) {
return '{' + str + '}';
}
function isPadded(el) {
return /^-?0\d/.test(el);
}
function lte(i, y) {
return i <= y;
}
function gte(i, y) {
return i >= y;
}
function expand(str) {
var expansions = [];
var m = balanced('{', '}', str);
if (!m || /\$$/.test(m.pre)) return [str];
var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
var isSequence = isNumericSequence || isAlphaSequence;
var isOptions = /^(.*,)+(.+)?$/.test(m.body);
if (!isSequence && !isOptions) {
// {a},b}
if (m.post.match(/,.*}/)) {
str = m.pre + '{' + m.body + escClose + m.post;
return expand(str);
}
return [str];
}
var n;
if (isSequence) {
n = m.body.split(/\.\./);
} else {
n = parseCommaParts(m.body);
if (n.length === 1) {
// x{{a,b}}y ==> x{a}y x{b}y
n = expand(n[0]).map(embrace);
if (n.length === 1) {
var post = m.post.length
? expand(m.post)
: [''];
return post.map(function (p) {
return m.pre + n[0] + p;
});
}
}
}
// at this point, n is the parts, and we know it's not a comma set
// with a single entry.
// no need to expand pre, since it is guaranteed to be free of brace-sets
var pre = m.pre;
var post = m.post.length
? expand(m.post)
: [''];
var N;
if (isSequence) {
var x = numeric(n[0]);
var y = numeric(n[1]);
var width = Math.max(n[0].length, n[1].length)
var incr = n.length == 3
? Math.abs(numeric(n[2]))
: 1;
var test = lte;
var reverse = y < x;
if (reverse) {
incr *= -1;
test = gte;
}
var pad = n.some(isPadded);
N = [];
for (var i = x; test(i, y); i += incr) {
var c;
if (isAlphaSequence) {
c = String.fromCharCode(i);
if (c === '\\')
c = '';
} else {
c = String(i);
if (pad) {
var need = width - c.length;
if (need > 0) {
var z = new Array(need + 1).join('0');
if (i < 0)
c = '-' + z + c.slice(1);
else
c = z + c;
}
}
}
N.push(c);
}
} else {
N = concatMap(n, function (el) {
return expand(el)
});
}
for (var j = 0; j < N.length; j++) {
for (var k = 0; k < post.length; k++) {
expansions.push([pre, N[j], post[k]].join(''))
}
}
return expansions;
}
}, {"balanced-match": 3, "concat-map": 4}], 3: [function (require, module, exports) {
module.exports = balanced;
function balanced(a, b, str) {
var bal = 0;
var m = {};
var ended = false;
for (var i = 0; i < str.length; i++) {
if (a == str.substr(i, a.length)) {
if (!('start' in m)) m.start = i;
bal++;
}
else if (b == str.substr(i, b.length) && 'start' in m) {
ended = true;
bal--;
if (!bal) {
m.end = i;
m.pre = str.substr(0, m.start);
m.body = (m.end - m.start > 1)
? str.substring(m.start + a.length, m.end)
: '';
m.post = str.slice(m.end + b.length);
return m;
}
}
}
// if we opened more than we closed, find the one we closed
if (bal && ended) {
var start = m.start + a.length;
m = balanced(a, b, str.substr(start));
if (m) {
m.start += start;
m.end += start;
m.pre = str.slice(0, start) + m.pre;
}
return m;
}
}
}, {}], 4: [function (require, module, exports) {
module.exports = function (xs, fn) {
var res = [];
for (var i = 0; i < xs.length; i++) {
var x = fn(xs[i], i);
if (Array.isArray(x)) res.push.apply(res, x);
else res.push(x);
}
return res;
};
}, {}]
}, {}, [1]);
|
import { Base } from './_Base';
export class OmnichannelQueue extends Base {
constructor() {
super('omnichannel_queue');
}
}
export default new OmnichannelQueue();
|
/**
* @requires OpenLayers/Lang.js
*/
/**
* Namespace: OpenLayers.Lang["en"]
* Dictionary for English. Keys for entries are used in calls to
* <OpenLayers.Lang.translate>. Entry bodies are normal strings or
* strings formatted for use with <OpenLayers.String.format> calls.
*/
OpenLayers.Lang.en = {
'unhandledRequest': "Unhandled request return ${statusText}",
'Permalink': "Permalink",
'Overlays': "Overlays",
'Base Layer': "Base Layer",
'noFID': "Can't update a feature for which there is no FID.",
'browserNotSupported':
"Your browser does not support vector rendering. Currently supported renderers are:\n${renderers}",
// console message
'minZoomLevelError':
"The minZoomLevel property is only intended for use " +
"with the FixedZoomLevels-descendent layers. That this " +
"wfs layer checks for minZoomLevel is a relic of the" +
"past. We cannot, however, remove it without possibly " +
"breaking OL based applications that may depend on it." +
" Therefore we are deprecating it -- the minZoomLevel " +
"check below will be removed at 3.0. Please instead " +
"use min/max resolution setting as described here: " +
"http://trac.openlayers.org/wiki/SettingZoomLevels",
'commitSuccess': "WFS Transaction: SUCCESS ${response}",
'commitFailed': "WFS Transaction: FAILED ${response}",
'googleWarning':
"The Google Layer was unable to load correctly.<br><br>" +
"To get rid of this message, select a new BaseLayer " +
"in the layer switcher in the upper-right corner.<br><br>" +
"Most likely, this is because the Google Maps library " +
"script was either not included, or does not contain the " +
"correct API key for your site.<br><br>" +
"Developers: For help getting this working correctly, " +
"<a href='http://trac.openlayers.org/wiki/Google' " +
"target='_blank'>click here</a>",
'getLayerWarning':
"The ${layerType} Layer was unable to load correctly.<br><br>" +
"To get rid of this message, select a new BaseLayer " +
"in the layer switcher in the upper-right corner.<br><br>" +
"Most likely, this is because the ${layerLib} library " +
"script was not correctly included.<br><br>" +
"Developers: For help getting this working correctly, " +
"<a href='http://trac.openlayers.org/wiki/${layerLib}' " +
"target='_blank'>click here</a>",
'Scale = 1 : ${scaleDenom}': "Scale = 1 : ${scaleDenom}",
//labels for the graticule control
'W': 'W',
'E': 'E',
'N': 'N',
'S': 'S',
'Graticule': 'Graticule',
// console message
'reprojectDeprecated':
"You are using the 'reproject' option " +
"on the ${layerName} layer. This option is deprecated: " +
"its use was designed to support displaying data over commercial " +
"basemaps, but that functionality should now be achieved by using " +
"Spherical Mercator support. More information is available from " +
"http://trac.openlayers.org/wiki/SphericalMercator.",
// console message
'methodDeprecated':
"This method has been deprecated and will be removed in 3.0. " +
"Please use ${newMethod} instead.",
'proxyNeeded': "You probably need to set OpenLayers.ProxyHost to access ${url}."+
"See http://trac.osgeo.org/openlayers/wiki/FrequentlyAskedQuestions#ProxyHost",
// **** end ****
'end': ''
};
|
var cookieParser = require('..')
var http = require('http')
var request = require('supertest')
var signature = require('cookie-signature')
describe('connect.cookieParser()', function(){
var server
before(function(){
server = createServer('keyboard cat')
})
describe('when no cookies are sent', function(){
it('should default req.cookies to {}', function(done){
request(server)
.get('/')
.expect(200, '{}', done)
})
it('should default req.signedCookies to {}', function(done){
request(server)
.get('/signed')
.expect(200, '{}', done)
})
})
describe('when cookies are sent', function(){
it('should populate req.cookies', function(done){
request(server)
.get('/')
.set('Cookie', 'foo=bar; bar=baz')
.expect(200, '{"foo":"bar","bar":"baz"}', done)
})
})
describe('when a secret is given', function(){
var val = signature.sign('foobarbaz', 'keyboard cat');
// TODO: "bar" fails...
it('should populate req.signedCookies', function(done){
request(server)
.get('/signed')
.set('Cookie', 'foo=s:' + val)
.expect(200, '{"foo":"foobarbaz"}', done)
})
it('should remove the signed value from req.cookies', function(done){
request(server)
.get('/')
.set('Cookie', 'foo=s:' + val)
.expect(200, '{}', done)
})
it('should omit invalid signatures', function(done){
server.listen()
request(server)
.get('/signed')
.set('Cookie', 'foo=' + val + '3')
.expect(200, '{}', function(err){
if (err) return done(err)
request(server)
.get('/')
.set('Cookie', 'foo=' + val + '3')
.expect(200, '{"foo":"foobarbaz.CP7AWaXDfAKIRfH49dQzKJx7sKzzSoPq7/AcBBRVwlI3"}', done)
});
})
})
})
function createServer(secret) {
var _parser = cookieParser(secret)
return http.createServer(function(req, res){
_parser(req, res, function(err){
if (err) {
res.statusCode = 500
res.end(err.message)
return
}
var cookies = '/signed' === req.url
? req.signedCookies
: req.cookies
res.end(JSON.stringify(cookies))
})
})
}
|
/*
Highcharts JS v7.0.3 (2019-02-06)
Indicator series type for Highstock
(c) 2010-2019 Sebastian Bochan
License: www.highcharts.com/license
*/
(function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define(function(){return a}):a("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(a){(function(a){function m(a,b,c,f,d){c=c[f-1][3]-c[f-d-1][3];b=b[f-1];a.shift();return[b,c]}var n=a.isArray;a=a.seriesType;a("momentum","sma",{params:{period:14}},{nameBase:"Momentum",getValues:function(a,b){b=b.period;var c=a.xData,f=(a=a.yData)?a.length:0,d=c[0],g=[],h=[],k=[],
l,e;if(c.length<=b||!n(a[0]))return!1;l=[[d,a[0][3]]];for(d=b+1;d<f;d++)e=m(l,c,a,d,b,void 0),g.push(e),h.push(e[0]),k.push(e[1]);e=m(l,c,a,d,b,void 0);g.push(e);h.push(e[0]);k.push(e[1]);return{values:g,xData:h,yData:k}}})})(a)});
//# sourceMappingURL=momentum.js.map |
// validate.js v 1.98
// a generic form validator
// (cc) Brian Lalonde http://webcoder.info/downloads/validate.html
// License: http://creativecommons.org/licenses/by-sa/2.0/
//TODO: figure out why javascript form validation doesnt verify required select-one boxes
function formFocus(frm)
{ // convenient way to start the form onLoad
if(!document.forms.length) return;
var els= ( frm || document.forms[0] ).elements;
for(var i= 0; i < els.length; i++)
if(els[i].type != 'hidden') { els[i].focus(); return; }
}
function formChanged(frm)
{ // determine whether any form fields have changed
if(!document.forms.length) return;
var els= ( frm || document.forms[0] ).elements;
for(var i= 0; i < els.length; i++)
switch(els[i].type)
{
case 'text':
case 'textarea':
case 'password':
case 'hidden':
case 'file':
if(els[i].defaultValue!=els[i].value)
{ status= 'The '+fieldname(els[i])+' field has changed.'; return true; }
break;
case 'checkbox':
if(els[i].defaultChecked!=els[i].checked)
{ status= 'The '+fieldname(els[i])+' checkbox has changed.'; return true; }
break;
case 'select-one':
for(var j= 1; j < els[i].options.length; j++)
if(els[i].options[j].defaultSelected!=els[i].options[j].selected)
{ status= 'The '+fieldname(els[i])+' selection has changed.'; return true; }
break;
case 'select-multiple':
for(var j= 0; j < els[i].options.length; j++)
if(els[i].options[j].defaultSelected!=els[i].options[j].selected)
{ status= 'The '+fieldname(els[i])+' selections have changed.'; return true; }
break;
case 'radio':
if(els[i].length)
for(var j= 0; j < els[i].length; j++)
if(els[i][j].defaultChecked!=els[i][j].checked)
{ status= 'The '+fieldname(els[i])+' choice has changed.'; return true; }
break;
}
return false;
}
function fieldname(fld)
{ // get the field label text or name
if(fld.id && document.getElementsByTagName)
{
for(var i= 0, lbl= document.getElementsByTagName('LABEL'); i < lbl.length; i++)
if(lbl[i].htmlFor==fld.id) return lbl[i].nodeValue||lbl[i].textContent||lbl[i].innerText;
for(var i= 0, lbl= document.getElementsByTagName('label'); i < lbl.length; i++)
if(lbl[i].htmlFor==fld.id) return lbl[i].nodeValue||lbl[i].textContent||lbl[i].innerText;
}
return fld.name||fld.type;
}
function requireValue(fld)
{ // disallow a blank field
if(fld.disabled) return true;
if(!fld.value.length)
{ status= 'The '+fieldname(fld)+' field cannot be left blank.'; return false; }
return true;
}
function requireChecked(fld)
{ // require a checkbox to be checked
if(fld.disabled) return true;
if(!fld.checked)
{ status= 'The '+fieldname(fld)+' checkbox must be checked.'; return false; }
return true;
}
function requireConfirmation(fld,confirmfld)
{ // require fields to match
if(fld.disabled) return true;
if(fld.value != confirmfld.value)
{ status= 'The '+fieldname(fld)+' field does not match the '+fieldname(confirmfld)+' field.'; return false; }
return true;
}
function requireRadio(radios)
{ // require at least one radio in this group to be checked
if(!radios.length) return true; // invalid parameter
var visible= false, enabled= false;
for(var i= 0; i < radios.length; i++)
{
if(!enabled) enabled= !radios[i].disabled;
if(radios[i].checked) return true;
else if(radios[i].offsetWidth == undefined || radios[i].offsetWidth > 0) visible= true;
}
if(!visible||!enabled) return true; // no visible/enabled options in this group
status= 'You must select one of the '+radios[0].name+' options.';
return false;
}
function requireLength(fld,min,max)
{ // set minimum and/or maximum field lengths
if(!fld.value.length||fld.disabled) return true; // blank fields are the domain of requireValue
var len= fld.value.length;
if(min > -1 && len < min)
{ status= 'The '+fieldname(fld)+' field must be at least '+min+
' characters long; it is currently '+len+' characters long.'; return false; }
if(max > -1 && len > max)
{ status= 'The '+fieldname(fld)+' field must be no more than '+max+
' characters long; it is currently '+len+' characters long.'; return false; }
return true;
}
function dependants(enabled,elements)
{ // convenience function to enable/disable dependant fields, passed in as an array
if(!elements.length) return true;
for(var i= 0; i < elements.length; i++)
elements[i].disabled= !enabled;
}
function allowChars(fld,chars)
{ // provide a string of acceptable chars for a field
if(fld.disabled) return true;
for(var i= 0; i < fld.value.length; i++)
{
if(chars.indexOf(fld.value.charAt(i)) == -1)
{ status= 'The '+fieldname(fld)+' field may not contain "'+fld.value.charAt(i)+'" characters.'; return false; }
}
return true;
}
function disallowChars(fld,chars)
{ // provide a string of unacceptable chars for a field
if(fld.disabled) return true;
for(var i= 0; i < fld.value.length; i++)
{
if(chars.indexOf(fld.value.charAt(i)) != -1)
{ status= 'The '+fieldname(fld)+' field may not contain "'+fld.value.charAt(i)+'" characters.'; return false; }
}
return true;
}
function checkEmail(fld)
{ // simple email check
if(!fld.value.length||fld.disabled) return true; // blank fields are the domain of requireValue
var phony= /@(\w+\.)*example\.(com|net|org)$/i;
if(phony.test(fld.value))
{ status= 'Please enter your email address in the '+fieldname(fld)+' field.'; return false; }
var emailfmt= /^\w+([.-]\w+)*@\w+([.-]\w+)*\.\w{2,8}$/;
if(!emailfmt.test(fld.value))
{ status= 'The '+fieldname(fld)+' field must contain a valid email address.'; return false; }
return true;
}
function checkIntRange(fld,minVal,maxVal,sep)
{
if(!fixInt(fld)) return false;
var val= parseInt(fld.value);
if(val < minVal) { status= 'The '+fieldname(fld)+' field must be no less than '+minVal+'.'; return false; }
if(val > maxVal) { status= 'The '+fieldname(fld)+' field must be no greater than than '+maxVal+'.'; return false; }
return true;
}
function checkFloatRange(fld,minVal,maxVal,sep)
{
if(!fixFloat(fld)) return false;
var val= parseFloat(fld.value);
if(val < minVal) { status= 'The '+fieldname(fld)+' field must be no less than '+minVal+'.'; return false; }
if(val > maxVal) { status= 'The '+fieldname(fld)+' field must be no greater than than '+maxVal+'.'; return false; }
return true;
}
function fixInt(fld,sep)
{ // integer check/complainer
if(!fld.value.length||fld.disabled) return true; // blank fields are the domain of requireValue
var val= fld.value;
if(typeof(sep)!='undefined') val= val.replace(new RegExp(sep,'g'),'');
val= parseInt(val);
if(isNaN(val))
{ // parse error
status= 'The '+fieldname(fld)+' field must contain a whole number.';
return false;
}
fld.value= val;
return true;
}
function fixFloat(fld,sep)
{ // decimal number check/complainer
if(!fld.value.length||fld.disabled) return true; // blank fields are the domain of requireValue
var val= fld.value;
if(typeof(sep)!='undefined') val= val.replace(new RegExp(sep,'g'),'');
val= parseFloat(fld.value);
if(isNaN(val))
{ // parse error
status= 'The '+fieldname(fld)+' field must contain a number.';
return false;
}
fld.value= val;
return true;
}
function fixMoney(fld,sep)
{ // monetary field check
if(!fld.value.length||fld.disabled) return true; // blank fields are the domain of requireValue
var val= fld.value;
if(typeof(sep)!='undefined') val= val.replace(new RegExp(sep,'g'),'');
if(val.indexOf('$') == 0)
{
val= parseFloat(val.substring(1,40));
if (!val.length) return true;
}
else
val= parseFloat(val);
if(isNaN(val))
{ // parse error
status= 'The '+fieldname(fld)+' field must contain a dollar amount.';
return false;
}
var sign= ( val < 0 ? '-': '' );
val= Number(Math.round(Math.abs(val)*100)).toString();
while(val.length < 2) val= '0'+val;
var len= val.length;
val= sign + ( len == 2 ? '0' : val.substring(0,len-2) ) + '.' + val.substring(len-2,len+1);
fld.value= val;
return true;
}
function fixFixed(fld,dec,sep)
{ // fixed decimal fields
if(!fld.value.length||fld.disabled) return true; // blank fields are the domain of requireValue
var val= fld.value;
if(typeof(sep)!='undefined') val= val.replace(new RegExp(sep,'g'),'');
val= parseFloat(fld.value);
if(isNaN(val))
{ // parse error
status= 'The '+fieldname(fld)+' field must contain a number.';
return false;
}
var sign= ( val < 0 ? '-': '' );
val= Number(Math.round(Math.abs(val)*Math.pow(10,dec))).toString();
while(val.length < dec) val= '0'+val;
var len= val.length;
val= sign + ( len == dec ? '0' : val.substring(0,len-dec) ) + '.' + val.substring(len-dec,len+1);
fld.value= val;
return true;
}
function fixDate(fld)
{ // tenacious date correction
if(!fld.value.length||fld.disabled) return true; // blank fields are the domain of requireValue
var val= fld.value;
var dt= new Date(val.replace(/\D/g,'/'));
if(!dt.valueOf())
{ // the date was unparseable
status= 'The '+fieldname(fld)+' field has the wrong date.';
return false;
}
fld.value= (dt.getMonth()+1)+'/'+dt.getDate()+'/'+dt.getFullYear();
return true;
}
function fixRecentDate(fld,minyear)
{ // tenacious date correction
if(!fld.value.length||fld.disabled) return true; // blank fields are the domain of requireValue
var val= fld.value;
var dt= new Date(val.replace(/\D/g,'/'));
if(!dt.valueOf())
{ // the date was unparseable
status= 'The '+fieldname(fld)+' field has the wrong date.';
return false;
}
while(dt.getFullYear() < minyear) { dt.setFullYear(dt.getFullYear()+100); }
fld.value= (dt.getMonth()+1)+'/'+dt.getDate()+'/'+dt.getFullYear();
return true;
}
function fixTime(fld,starthour)
{ // tenacious time correction
if(!fld.value.length||fld.disabled) return true; // blank fields are the domain of requireValue
var hour= 0;
var mins= 0;
var ampm= 'am';
val= fld.value;
var dt= new Date('1/1/2000 ' + val);
if(('9'+val) == parseInt('9'+val))
{ hour= val; }
else if(dt.valueOf())
{ hour= dt.getHours(); mins= dt.getMinutes(); }
else
{
val= val.replace(/\D+/g,':');
hour= parseInt(val);
mins= parseInt(val.substring(val.indexOf(':')+1,20));
if(val.indexOf('pm') > -1) ampm= 'pm';
if(isNaN(hour)) hour= 0;
if(isNaN(mins)) mins= 0;
}
if(hour < starthour) { ampm= 'pm'; }
while(hour > 12) { hour-= 12; ampm= 'pm'; }
while(mins > 60) { mins-= 60; hour++; }
if(mins < 10) mins= '0' + mins;
if(!hour)
{ // the date was unparseable
status= 'The '+fieldname(fld)+' field has the wrong time.';
return false;
}
fld.value= hour + ':' + mins + ampm;
return true;
}
function fixTime24(fld)
{ // tenacious time correction
if(!fld.value.length||fld.disabled) return true; // blank fields are the domain of requireValue
var hour= 0;
var mins= 0;
val= fld.value;
var dt= new Date('1/1/2000 ' + val);
if(('9'+val) == parseInt('9'+val))
{ hour= val; }
else if(dt.valueOf())
{ hour= dt.getHours(); mins= dt.getMinutes(); }
else
{
val= val.replace(/\D+/g,':');
hour= parseInt(val);
mins= parseInt(val.substring(val.indexOf(':')+1,20));
if(isNaN(hour)) hour= 0;
if(isNaN(mins)) mins= 0;
if(val.indexOf('pm') > -1) hour+= 12;
}
hour%= 24;
mins%= 60;
if(mins < 10) mins= '0' + mins;
fld.value= hour + ':' + mins;
return true;
}
function fixPhone(fld,defaultAreaCode,sep,noext)
{ // tenacious phone # correction
if(!fld.value.length||fld.disabled) return true; // blank fields are the domain of requireValue
if(typeof(sep)=='undefined') sep= '-';
if(typeof(defaultAreaCode)!='undefined') defaultAreaCode= defaultAreaCode + sep;
var ext= '', val= fld.value.toLowerCase();
if(val.indexOf('x') > 0)
{
if(!noext) ext= ' x'+val.substr(val.indexOf('x')).replace(/\D/g,'');
val= val.substr(0,val.indexOf('x'));
}
val= val.replace(/\D/g,'');
if(val.length == 7)
{
fld.value= defaultAreaCode + val.substring(0,3) + sep + val.substring(3,20) + ext;
return true;
}
if(val.length == 10)
{
fld.value= val.substring(0,3) + sep + val.substring(3,6) + sep + val.substring(6,20) + ext;
return true;
}
if(val.length < 7)
{
status= 'The phone number you supplied for the '+fieldname(fld)+' field was too short.';
return false;
}
if(val.length > 10)
{
status= 'The phone number you supplied for the '+fieldname(fld)+' field was too long.';
return false;
}
status= 'The phone number you supplied for the '+fieldname(fld)+' field was wrong.';
return false;
}
function fixSSN(fld)
{ // tenacious SSN correction; fieldname isn't a big consideration, probably only one SSN per form
if(!fld.value.length||fld.disabled) return true; // blank fields are the domain of requireValue
var val= fld.value;
val= val.replace(/\D/g,'');
if( val.length < 9 )
{
status= 'The Social Security Number you provided is not long enough.';
return false;
}
if( val.length > 9 )
{
status= 'The Social Security Number you provided is too long.';
return false;
}
fld.value= val.substring(0,3)+'-'+val.substring(3,5)+'-'+val.substring(5,12);
return true;
}
function fixCreditCard(fld)
{ // tenacious credit card correction; fieldname isn't a big consideration, probably only one card per form
if(!fld.value.length||fld.disabled) return true; // blank fields are the domain of requireValue
var val= fld.value, ctype= 'credit card';
val= val.replace(/\D/g,'');
var prefix2= parseInt(val.substr(0,2));
if( val.substr(0,1) == '4' )
{ // Visa
ctype= 'Visa\xae';
if( val.length == 16 );
else if( val.length == 13 ); // very old #, should be reassigned
else if( val.length < 13 )
{ status= 'The Visa\xae number you provided is not long enough.'; return false; }
else if( val.length > 16 )
{ status= 'The Visa\xae number you provided is too long.'; return false; }
else
{ status= 'The Visa\xae number you provided is either not long enough, or too long.'; return false; }
}
else if( prefix2 >= 51 && prefix2 <= 55 )
{ // MC
ctype= 'MasterCard\xae';
if( val.length < 16 )
{ status= 'The MasterCard\xae number you provided is not long enough.'; return false; }
else if( val.length > 16 )
{ status= 'The MasterCard\xae number you provided is too long.'; return false; }
}
else if( (prefix2 == 34) || (prefix2 == 37) )
{ // AmEx
ctype= 'American Express\xae card';
if( val.length < 15 )
{ status= 'The American Express\xae card number you provided is not long enough.'; return false; }
else if( val.length > 15 )
{ status= 'The American Express\xae card number you provided is too long.'; return false; }
}
else if( val.substr(0,4) == '6011' )
{ // Novus/Discover
ctype= 'Discover\xae card';
if( val.length < 16 )
{ status= 'The Discover\xae card number you provided is not long enough.'; return false; }
else if( val.length > 16 )
{ status= 'The Discover\xae card number you provided is too long.'; return false; }
}
else
{ // other
if( val.length < 13 )
{ status= 'The credit card number you provided is not long enough.'; return false; }
if( val.length > 19 )
{ status= 'The credit card number you provided is too long.'; return false; }
}
var sum= 0, dbl= false;
for(var i= val.length-1; i >= 0; i--)
{
var digit= parseInt(val.charAt(i))*((dbl=!dbl)?1:2);
sum+= ( digit > 9 ? (digit%10)+1 : digit );
}
if(sum%10)
{
status= 'The '+ctype+' number you provided is not valid.\nPlease double-check it and try again.';
return false;
}
fld.value= val;
return true;
}
function nameContains(name,str)
{ // Check for nontrivial inclusion
// OK, *some* trivial cases must be handled...
if(name == str || name.toLowerCase() == str.toLowerCase()) return true;
var nlen= name.length;
var slen= str.length;
var endat= nlen - slen;
// too small to fit?
if(nlen > str) return false;
if(name.toLowerCase() == name || name.toUpperCase() == name)
{ // all lower/upper case name? underscores separate
if(name.indexOf('_') == -1) return false;
str= str.toLowerCase();
if( name.indexOf(str+'_') == 0 ||
name.indexOf('_'+str+'_') > -1 ||
name.substring(endat-1,nlen+1) == ('_'+str) )
return true;
}
else
{ // proper case name? uppercase starts new words
var sep= name.substring(slen,slen+1);
if( name.indexOf(str) == 0 && sep == sep.toUpperCase() ) return true;
if( name.indexOf(str.toLowerCase()) == 0 && sep == sep.toUpperCase() ) return true;
var sep= name.substring(endat-1,endat);
if( name.substring(endat,nlen+1) == str ) return true;
for(var index= name.indexOf(str); index > -1; index= name.indexOf(str,index+1))
{ // for each occurence of the word, is it followed by a non-lowercase char?
endat= index+slen;
sep= name.substring(endat,endat+1);
if(sep == sep.toUpperCase()) return true;
}
}
return false;
}
function autocheckByName(frm)
{ // uses names of form elements to determine type
for(var index= 0; index < frm.elements.length; index++)
{
var el= frm.elements[index];
if(!el.type) continue;
if(el.type == 'text' || el.type == 'password')
{ // text fields
if(( /*el.name.substring(0,1) == el.name.substring(0,1).toUpperCase() || */ nameContains(el.name,'Required')) && el.value.length == 0)
{ alert('The '+fieldname(el)+' field cannot be left blank.'); el.focus(); return false; }
if(nameContains(el.name,'Date') && !fixDate(el))
{ alert(status); el.focus(); return false; }
if(nameContains(el.name,'Time24') && !fixTime24(el))
{ alert(status); el.focus(); return false; }
if(nameContains(el.name,'Time') && !fixTime(el))
{ alert(status); el.focus(); return false; }
if(nameContains(el.name,'SSN') && !fixSSN(el))
{ alert(status); el.focus(); return false; }
if(nameContains(el.name,'CC') && !fixCreditCard(el))
{ alert(status); el.focus(); return false; }
if(nameContains(el.name,'Email') && !checkEmail(el))
{ alert(status); el.focus(); return false; }
if( ( nameContains(el.name,'Phone') ||
nameContains(el.name,'Fax') ||
nameContains(el.name,'Pager') ) &&
!fixPhone(el))
{ alert(status); el.focus(); return false; }
}
// handle required select and select-multiple
else if(el.type.substring(0,3) == 'sel' &&
(el.name.substring(0,1) == el.name.substring(0,1).toUpperCase() ||
nameContains(el.name,'Required')) && el.selectedIndex == -1)
{ alert(status); el.focus(); return false; }
// handle required checkbox
else if(el.type == 'checkbox' &&
(el.name.substring(0,1) == el.name.substring(0,1).toUpperCase() ||
nameContains(el.name,'Required')) && !requireChecked(el))
{ alert(status); el.focus(); return false; }
else if(el.type == 'radio' && !requireRadio(frm[el.name]))
{ alert(status); frm.elements[index].focus(); return false; }
}
for(var index= 0; index < frm.elements.length; index++)
if(frm.elements[index].type == 'submit') frm.elements[index].disabled= true;
return true;
}
function isMemberOf(elem,classname)
{ // checks to see if elem is a member of the (style) class
// trivial cases first: no membership or simple equality
if(!elem.className)
return false
else if(elem.className == classname)
return true;
else if(elem.className.indexOf(' ') > -1)
{ // multiple class names; use split, if avail
if(parseInt(navigator.appVersion) >= 4)
{
var names= elem.className.split(' ');
for(var index= 0; index < names.length; index++)
if(names[index] == classname)
return true;
}
// older browsers can fake it
// WARNING: "fine" can be found in "oldRefined"
else if(elem.className.indexOf(classname) > -1)
return true;
}
return false;
}
function checkClass(el)
{ // validate the field, based on class membership
if(el.type == 'text' || el.type == 'password')
{ // text fields
if(isMemberOf(el,'required') && !requireValue(el)) return false;
if(isMemberOf(el,'date') && !fixDate(el)) return false;
if(isMemberOf(el,'time') && !fixTime(el)) return false;
if(isMemberOf(el,'time24') && !fixTime24(el)) return false;
if(isMemberOf(el,'ssn') && !fixSSN(el)) return false;
if(isMemberOf(el,'cc') && !fixCreditCard(el)) return false;
if(isMemberOf(el,'phone') && !fixPhone(el)) return false;
if(isMemberOf(el,'money') && !fixMoney(el)) return false;
if(isMemberOf(el,'int') && !fixInt(el)) return false;
if(isMemberOf(el,'float') && !fixFloat(el)) return false;
if(isMemberOf(el,'email') && !checkEmail(el)) return false;
} // handle required select and select-multiple
else if(el.type == 'checkbox' &&
isMemberOf(el,'required') && !requireChecked(el)) return false;
else if(el.type.substring(0,3) == 'sel' &&
isMemberOf(el,'required') && el.selectedIndex == -1) return false;
return true;
}
function autocheckByClass(frm)
{ // uses the CSS class of form elements to determine type
for(var index= 0; index < frm.elements.length; index++)
{
var el= frm.elements[index];
if(!el.type) continue;
if(el.type == 'radio' && !requireRadio(frm[el.name]))
{ alert(status); frm.elements[index].focus(); return false; }
else if(!checkClass(frm.elements[index]))
{ alert(status); frm.elements[index].focus(); return false; }
}
for(var index= 0; index < frm.elements.length; index++)
if(frm.elements[index].type == 'submit') frm.elements[index].disabled= true;
return true;
}
function autocheckByBlur(frm)
{ // uses the onBlur handler of form elements to check value
status= '';
for(var index= 0; index < frm.elements.length; index++)
{
var el= frm.elements[index];
if(!el.type) continue;
if(el.type == 'radio' && !requireRadio(frm[el.name]))
{ alert(status); frm.elements[index].focus(); return false; }
else if(el.type != 'hidden' && el.name && el.onblur)
{
el.onblur();
if(status) { alert(status); el.focus(); return false; }
}
}
for(var index= 0; index < frm.elements.length; index++)
if(frm.elements[index].type == 'submit') frm.elements[index].disabled= true;
return true;
}
function canCheckByBlur(frm)
{ // determines whether programmatic invocation of form element onblur is available
for(var index= 0; index < frm.elements.length; index++)
{
var el= frm.elements[index];
if(!el.type) continue;
if(el.type != 'hidden' && el.name && typeof(el.onblur)=='function') return true;
}
return false;
}
function autocheck(frm)
{ // uses the best available method to check form values
var bchar= navigator.appName.substring(0,1);
var result = true
if(canCheckByBlur(frm)) { result = autocheckByBlur(frm) && result; }
if(isMemberOf(frm,'autocheck')) { result = autocheckByClass(frm) && result; }
else { result = autocheckByName(frm) && result; }
return result;
}
|
var _idToPagePanelInfo = {};
var _url2link = {};
_getPanels = function ( panelEL ) {
var panels = [];
var panelDOM = Polymer.dom(panelEL);
for ( var i = 0; i < panelDOM.children.length; ++i ) {
var childEL = panelDOM.children[i];
var id = childEL.getAttribute('id');
panels.push(id);
}
return panels;
};
_getDocks = function ( dockEL ) {
var docks = [];
var dockDOM = Polymer.dom(dockEL);
for ( var i = 0; i < dockDOM.children.length; ++i ) {
var childEL = dockDOM.children[i];
if ( !childEL['ui-dockable'] )
continue;
var rect = childEL.getBoundingClientRect();
var info = {
'row': childEL.row,
'width': rect.width,
'height': rect.height,
};
if ( childEL instanceof EditorUI.Panel ) {
info.type = 'panel';
info.active = childEL.activeIndex;
info.panels = _getPanels(childEL);
}
else {
info.type = 'dock';
info.docks = _getDocks(childEL);
}
docks.push(info);
}
return docks;
};
function _registerIpc ( panelID, frameEL, ipcListener, ipcName ) {
var fn = frameEL[ipcName];
if ( !fn || typeof fn !== 'function' ) {
if ( ipcName !== 'panel:open') {
Editor.warn('Failed to register ipc message %s in panel %s, Can not find implementation', ipcName, panelID );
}
return;
}
ipcListener.on( ipcName, function () {
var fn = frameEL[ipcName];
if ( !fn || typeof fn !== 'function' ) {
Editor.warn('Failed to respond ipc message %s in panel %s, Can not find implementation', ipcName, panelID );
return;
}
fn.apply( frameEL, arguments );
} );
}
function _registerProfile ( panelID, type, profile ) {
profile.save = function () {
Editor.sendToCore('panel:save-profile', panelID, type, profile);
};
}
function _registerShortcut ( panelID, mousetrap, frameEL, shortcut, methodName ) {
var fn = frameEL[methodName];
if ( typeof fn === 'function' ) {
mousetrap.bind(shortcut, fn.bind(frameEL) );
}
else {
Editor.warn('Failed to register shortcut for method %s in panel %s, can not find it.', methodName, panelID );
}
}
var Panel = {};
Panel.load = function ( panelID, cb ) {
Editor.sendRequestToCore('panel:query-info', panelID, function ( panelInfo ) {
if ( !panelInfo ) {
Editor.error('Panel %s import faield. panelInfo not found', panelID );
cb ( new Error('Panel info not found') );
return;
}
var Path = require('fire-path');
var framePath = Path.join( panelInfo.path, panelInfo.frame );
EditorUI.import( framePath, function ( err ) {
if ( err ) {
Editor.error( 'Failed to import %s. message: %s', url, err.message );
cb ( new Error('Panel import failed.') );
return;
}
var frameCtor = Editor.panels[panelID];
if ( !frameCtor ) {
Editor.error('Can not find constructor for panelID %s', panelID );
cb ( new Error( panelID + '\'s constructor not found' ) );
return;
}
Editor.sendToCore('panel:dock', panelID, Editor.requireIpcEvent);
var frameEL = new frameCtor();
if ( panelInfo.icon ) {
frameEL.icon = new Image();
frameEL.icon.src = Path.join( panelInfo.path, panelInfo.icon );
}
frameEL.setAttribute('id', panelID);
frameEL.setAttribute('name', panelInfo.title);
frameEL.classList.add('fit');
frameEL.tabIndex = 1;
// set size attribute
if ( panelInfo.width )
frameEL.setAttribute( 'width', panelInfo.width );
if ( panelInfo.height )
frameEL.setAttribute( 'height', panelInfo.height );
if ( panelInfo['min-width'] )
frameEL.setAttribute( 'min-width', panelInfo['min-width'] );
if ( panelInfo['min-height'] )
frameEL.setAttribute( 'min-height', panelInfo['min-height'] );
if ( panelInfo['max-width'] )
frameEL.setAttribute( 'max-width', panelInfo['max-width'] );
if ( panelInfo['max-height'] )
frameEL.setAttribute( 'max-height', panelInfo['max-height'] );
// register ipc events
var ipcListener = new Editor.IpcListener();
// always have panel:open message
if ( panelInfo.messages.indexOf('panel:open') === -1 ) {
panelInfo.messages.push('panel:open');
}
for ( var i = 0; i < panelInfo.messages.length; ++i ) {
_registerIpc( panelID, frameEL, ipcListener, panelInfo.messages[i] );
}
// register profiles
frameEL.profiles = panelInfo.profiles;
for ( var type in panelInfo.profiles ) {
_registerProfile ( panelID, type, panelInfo.profiles[type] );
}
// register shortcuts
// TODO: load overwrited shortcuts from profile?
var mousetrapList = [];
if ( panelInfo.shortcuts ) {
var mousetrap = new Mousetrap(frameEL);
mousetrapList.push(mousetrap);
for ( var shortcut in panelInfo.shortcuts ) {
if ( shortcut.length > 1 && shortcut[0] === '#' ) {
var elementID = shortcut.substring(1);
var subElement = frameEL.$[elementID];
if ( subElement ) {
var subShortcuts = panelInfo.shortcuts[shortcut];
var subMousetrap = new Mousetrap(subElement);
mousetrapList.push(subMousetrap);
for ( var subShortcut in subShortcuts ) {
_registerShortcut(panelID,
subMousetrap,
frameEL, // NOTE: here must be frameEL
subShortcut,
subShortcuts[subShortcut]
);
}
}
else {
Editor.warn('Failed to register shortcut for method %s for element %s, can not find it.', methodName, shortcut );
}
}
else {
_registerShortcut(panelID,
mousetrap,
frameEL,
shortcut,
panelInfo.shortcuts[shortcut]
);
}
}
}
//
_idToPagePanelInfo[panelID] = {
frameEL: frameEL,
messages: panelInfo.messages,
popable: panelInfo.popable,
ipcListener: ipcListener,
mousetrapList: mousetrapList,
};
// done
cb ( null, frameEL, panelInfo );
});
});
};
Panel.unload = function ( panelID ) {
// remove pagePanelInfo
var pagePanelInfo = _idToPagePanelInfo[panelID];
if ( pagePanelInfo) {
pagePanelInfo.ipcListener.clear();
for ( var i = 0; i < pagePanelInfo.mousetrapList.length; ++i ) {
pagePanelInfo.mousetrapList[i].reset();
}
delete _idToPagePanelInfo[panelID];
}
};
Panel.open = function ( panelID, argv ) {
Editor.sendToCore('panel:open', panelID, argv);
};
Panel.popup = function ( panelID ) {
var panelCounts = 0;
for ( var id in _idToPagePanelInfo ) {
++panelCounts;
}
if ( panelCounts > 1 ) {
Panel.close(panelID);
Editor.sendToCore('panel:open', panelID);
}
};
Panel.close = function ( panelID ) {
Panel.undock(panelID);
Editor.sendToCore('panel:close', panelID);
};
Panel.closeAll = function ( cb ) {
// if we have root, clear all children in it
var rootEL = EditorUI.DockUtils.root;
if ( rootEL ) {
rootEL.remove();
EditorUI.DockUtils.root = null;
}
var panelIDs = [];
for ( var id in _idToPagePanelInfo ) {
// unload pagePanelInfo
Editor.Panel.unload(id);
panelIDs.push(id);
}
var finishCount = panelIDs.length;
if ( panelIDs.length === 0 ) {
if ( cb ) cb();
}
else {
var checkIfDone = function () {
--finishCount;
if ( finishCount === 0 && cb ) cb();
};
for ( var i = 0; i < panelIDs.length; ++i ) {
Editor.sendRequestToCore('panel:wait-for-close', panelIDs[i], checkIfDone );
}
}
};
Panel.undock = function ( panelID ) {
// remove panel element from tab
var frameEL = Editor.Panel.find(panelID);
if ( frameEL ) {
var parentEL = Polymer.dom(frameEL).parentNode;
if ( parentEL instanceof EditorUI.Panel ) {
var currentTabEL = parentEL.$.tabs.findTab(frameEL);
parentEL.close(currentTabEL);
}
else {
Polymer.dom(parentEL).removeChild(frameEL);
}
EditorUI.DockUtils.flush();
Editor.saveLayout();
}
// unload pagePanelInfo
Editor.Panel.unload(panelID);
};
Panel.dispatch = function ( panelID, ipcName ) {
var pagePanelInfo = _idToPagePanelInfo[panelID];
if ( !pagePanelInfo ) {
Editor.warn( 'Failed to receive ipc %s, can not find panel %s', ipcName, panelID);
return;
}
// messages
var idx = pagePanelInfo.messages.indexOf(ipcName);
if ( idx === -1 ) {
Editor.warn('Can not find ipc message %s register in panel %s', ipcName, panelID );
return;
}
if ( ipcName === 'panel:open' ) {
Panel.focus(panelID);
}
var fn = pagePanelInfo.frameEL[ipcName];
if ( !fn || typeof fn !== 'function' ) {
if ( ipcName !== 'panel:open') {
Editor.warn('Failed to respond ipc message %s in panel %s, Can not find implementation', ipcName, panelID );
}
return;
}
var args = [].slice.call( arguments, 2 );
fn.apply( pagePanelInfo.frameEL, args );
};
Panel.dumpLayout = function () {
var root = EditorUI.DockUtils.root;
if ( !root )
return null;
if ( root['ui-dockable'] ) {
return {
'type': 'dock',
'row': root.row,
'no-collapse': true,
'docks': _getDocks(root),
};
}
else {
var id = root.getAttribute('id');
var rect = root.getBoundingClientRect();
return {
'type': 'standalone',
'panel': id,
'width': rect.width,
'height': rect.height,
};
}
};
Panel.find = function ( panelID ) {
var pagePanelInfo = _idToPagePanelInfo[panelID];
if ( !pagePanelInfo ) {
return null;
}
return pagePanelInfo.frameEL;
};
Panel.focus = function ( panelID ) {
var frameEL = Panel.find(panelID);
var parentEL = Polymer.dom(frameEL).parentNode;
if ( parentEL instanceof EditorUI.Panel ) {
parentEL.select(frameEL);
parentEL.setFocus();
}
};
Panel.getPanelInfo = function ( panelID ) {
return _idToPagePanelInfo[panelID];
};
// position: top, bottom, left, right, top-left, top-right, bottom-left, bottom-right
Panel.dockAt = function ( position, panelEL ) {
var root = EditorUI.DockUtils.root;
if ( !root ) {
return null;
}
if ( !root['ui-dockable'] ) {
return null;
}
// TODO
};
Panel.isDirty = function ( panelID ) {
return _outOfDatePanels.indexOf(panelID) !== -1;
};
// ==========================
// Ipc events
// ==========================
var Ipc = require('ipc');
Ipc.on('panel:close', function ( panelID ) {
// NOTE: if we don't do this in requestAnimationFrame,
// the tab will remain, something wrong for Polymer.dom
// operation when they are in ipc callback.
window.requestAnimationFrame( function () {
Editor.Panel.close(panelID);
});
});
Ipc.on('panel:popup', function ( panelID ) {
window.requestAnimationFrame( function () {
Editor.Panel.close(panelID);
Editor.sendToCore('panel:open', panelID);
});
});
Ipc.on('panel:undock', function ( panelID ) {
window.requestAnimationFrame( function () {
Editor.Panel.undock(panelID);
});
});
var _outOfDatePanels = [];
Ipc.on('panel:out-of-date', function ( panelID ) {
var frameEL = Editor.Panel.find(panelID);
if ( frameEL ) {
var parentEL = Polymer.dom(frameEL).parentNode;
if ( parentEL instanceof EditorUI.Panel ) {
parentEL.outOfDate(frameEL);
}
}
if ( _outOfDatePanels.indexOf(panelID) === -1 ) {
_outOfDatePanels.push(panelID);
}
});
module.exports = Panel;
|
/*
Highcharts JS v7.1.1 (2019-04-09)
Item series type for Highcharts
(c) 2019 Torstein Honsi
License: www.highcharts.com/license
*/
(function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/modules/item-series",["highcharts"],function(b){a(b);a.Highcharts=b;return a}):a("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(a){function b(m,a,b,h){m.hasOwnProperty(a)||(m[a]=h.apply(null,b))}a=a?a._modules:{};b(a,"modules/item-series.src.js",[a["parts/Globals.js"]],function(a){var b=a.extend,m=a.merge,h=a.seriesTypes.pie.prototype.pointClass.prototype;
a.seriesType("item","pie",{endAngle:void 0,innerSize:"40%",itemPadding:.1,layout:"vertical",marker:m(a.defaultOptions.plotOptions.line.marker,{radius:null}),rows:void 0,showInLegend:!0,startAngle:void 0},{translate:function(){this.slots||(this.slots=[]);a.isNumber(this.options.startAngle)&&a.isNumber(this.options.endAngle)?(a.seriesTypes.pie.prototype.translate.call(this),this.slots=this.getSlots()):this.generatePoints()},getSlots:function(){function a(a){0<C&&(a.row.colCount--,C--)}for(var y=this.center,
k=y[2],b=y[3],r,n=this.slots,t,h,u,v,w,g,c,l,q=0,d,m=this.endAngleRad-this.startAngleRad,x=Number.MAX_VALUE,z,e,A,B=this.options.rows,p=(k-b)/k;x>this.total;)for(z=x,x=n.length=0,e=A,A=[],q++,d=k/q/2,B?(b=(d-B)/d*k,0<=b?d=B:(b=0,p=1)):d=Math.floor(d*p),r=d;0<r;r--)u=(b+r/d*(k-b-q))/2,v=m*u,w=Math.ceil(v/q),A.push({rowRadius:u,rowLength:v,colCount:w}),x+=w+1;if(e){for(var C=z-this.total;0<C;)e.map(function(a){return{angle:a.colCount/a.rowLength,row:a}}).sort(function(a,f){return f.angle-a.angle}).slice(0,
Math.min(C,Math.ceil(e.length/2))).forEach(a);e.forEach(function(a){var f=a.rowRadius;g=(a=a.colCount)?m/a:0;for(l=0;l<=a;l+=1)c=this.startAngleRad+l*g,t=y[0]+Math.cos(c)*f,h=y[1]+Math.sin(c)*f,n.push({x:t,y:h,angle:c})},this);n.sort(function(a,f){return a.angle-f.angle});this.itemSize=q;return n}},getRows:function(){var a=this.options.rows,b,k;if(!a)if(k=this.chart.plotWidth/this.chart.plotHeight,a=Math.sqrt(this.total),1<k)for(a=Math.ceil(a);0<a;){b=this.total/a;if(b/a>k)break;a--}else for(a=Math.floor(a);a<
this.total;){b=this.total/a;if(b/a<k)break;a++}return a},drawPoints:function(){var f=this,h=this.options,k=f.chart.renderer,m=h.marker,r=this.borderWidth%2?.5:1,n=0,t=this.getRows(),D=Math.ceil(this.total/t),u=this.chart.plotWidth/D,v=this.chart.plotHeight/t,w=this.itemSize||Math.min(u,v);this.points.forEach(function(g){var c,l,q,d=g.marker||{},y=d.symbol||m.symbol,d=a.pick(d.radius,m.radius),x=a.defined(d)?2*d:w,z=x*h.itemPadding,e,A,B;g.graphics=l=g.graphics||{};f.chart.styledMode||(q=f.pointAttribs(g,
g.selected&&"select"));if(!g.isNull&&g.visible){g.graphic||(g.graphic=k.g("point").add(f.group));for(var p=0;p<g.y;p++)f.center&&f.slots?(e=f.slots.shift(),c=e.x-w/2,e=e.y-w/2):"horizontal"===h.layout?(c=n%D*u,e=v*Math.floor(n/D)):(c=u*Math.floor(n/t),e=n%t*v),c+=z,e+=z,B=A=Math.round(x-2*z),f.options.crisp&&(c=Math.round(c)-r,e=Math.round(e)+r),c={x:c,y:e,width:A,height:B},void 0!==d&&(c.r=d),l[p]?l[p].animate(c):l[p]=k.symbol(y,null,null,null,null,{backgroundSize:"within"}).attr(b(c,q)).add(g.graphic),
l[p].isActive=!0,n++}a.objectEach(l,function(a,b){a.isActive?a.isActive=!1:(a.destroy(),delete l[b])})})},drawDataLabels:function(){this.center&&this.slots?a.seriesTypes.pie.prototype.drawDataLabels.call(this):this.points.forEach(function(a){a.destroyElements({dataLabel:1})})},animate:function(a){a?this.group.attr({opacity:0}):(this.group.animate({opacity:1},this.options.animation),this.animate=null)}},{connectorShapes:h.connectorShapes,getConnectorPath:h.getConnectorPath,setVisible:h.setVisible,
getTranslate:h.getTranslate})});b(a,"masters/modules/item-series.src.js",[],function(){})});
//# sourceMappingURL=item-series.js.map |
/*!
* froala_editor v3.0.5 (https://www.froala.com/wysiwyg-editor)
* License https://froala.com/wysiwyg-editor/terms/
* Copyright 2014-2019 Froala Labs
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('froala-editor')) :
typeof define === 'function' && define.amd ? define(['froala-editor'], factory) :
(factory(global.FroalaEditor));
}(this, (function (FE) { 'use strict';
FE = FE && FE.hasOwnProperty('default') ? FE['default'] : FE;
/**
* Portuguese spoken in Portugal
*/
FE.LANGUAGE['pt_pt'] = {
translation: {
// Place holder
'Type something': 'Digite algo',
// Basic formatting
'Bold': 'Negrito',
'Italic': "It\xE1lico",
'Underline': 'Sublinhado',
'Strikethrough': 'Rasurado',
// Main buttons
'Insert': 'Inserir',
'Delete': 'Apagar',
'Cancel': 'Cancelar',
'OK': 'Ok',
'Back': 'Voltar',
'Remove': 'Remover',
'More': 'Mais',
'Update': 'Atualizar',
'Style': 'Estilo',
// Font
'Font Family': 'Fonte',
'Font Size': 'Tamanho da fonte',
// Colors
'Colors': 'Cores',
'Background': 'Fundo',
'Text': 'Texto',
'HEX Color': 'Cor hexadecimal',
// Paragraphs
'Paragraph Format': 'Formatos',
'Normal': 'Normal',
'Code': "C\xF3digo",
'Heading 1': "Cabe\xE7alho 1",
'Heading 2': "Cabe\xE7alho 2",
'Heading 3': "Cabe\xE7alho 3",
'Heading 4': "Cabe\xE7alho 4",
// Style
'Paragraph Style': "Estilo de par\xE1grafo",
'Inline Style': 'Estilo embutido',
// Alignment
'Align': 'Alinhar',
'Align Left': "Alinhar \xE0 esquerda",
'Align Center': 'Alinhar ao centro',
'Align Right': "Alinhar \xE0 direita",
'Align Justify': 'Justificado',
'None': 'Nenhum',
// Lists
'Ordered List': 'Lista ordenada',
'Unordered List': "Lista n\xE3o ordenada",
// Indent
'Decrease Indent': "Diminuir avan\xE7o",
'Increase Indent': "Aumentar avan\xE7o",
// Links
'Insert Link': 'Inserir link',
'Open in new tab': 'Abrir em uma nova aba',
'Open Link': 'Abrir link',
'Edit Link': 'Editar link',
'Unlink': 'Remover link',
'Choose Link': 'Escolha o link',
// Images
'Insert Image': 'Inserir imagem',
'Upload Image': 'Carregar imagem',
'By URL': 'Por URL',
'Browse': 'Procurar',
'Drop image': 'Largue imagem',
'or click': 'ou clique em',
'Manage Images': 'Gerenciar as imagens',
'Loading': 'Carregando',
'Deleting': 'Excluindo',
'Tags': 'Etiquetas',
'Are you sure? Image will be deleted.': "Voc\xEA tem certeza? Imagem ser\xE1 apagada.",
'Replace': 'Substituir',
'Uploading': 'Carregando imagem',
'Loading image': 'Carregando imagem',
'Display': 'Exibir',
'Inline': 'Em linha',
'Break Text': 'Texto de quebra',
'Alternative Text': 'Texto alternativo',
'Change Size': 'Alterar tamanho',
'Width': 'Largura',
'Height': 'Altura',
'Something went wrong. Please try again.': 'Algo deu errado. Por favor, tente novamente.',
'Image Caption': 'Legenda da imagem',
'Advanced Edit': 'Edição avançada',
// Video
'Insert Video': "Inserir v\xEDdeo",
'Embedded Code': "C\xF3digo embutido",
'Paste in a video URL': 'Colar em um URL de vídeo',
'Drop video': 'Solte o video',
'Your browser does not support HTML5 video.': 'Seu navegador não suporta o vídeo html5.',
'Upload Video': 'Envio vídeo',
// Tables
'Insert Table': 'Inserir tabela',
'Table Header': "Cabe\xE7alho da tabela",
'Remove Table': 'Remover tabela',
'Table Style': 'estilo de tabela',
'Horizontal Align': 'Alinhamento horizontal',
'Row': 'Linha',
'Insert row above': 'Inserir linha antes',
'Insert row below': 'Inserir linha depois',
'Delete row': 'Eliminar linha',
'Column': 'Coluna',
'Insert column before': 'Inserir coluna antes',
'Insert column after': 'Inserir coluna depois',
'Delete column': 'Eliminar coluna',
'Cell': "C\xE9lula",
'Merge cells': "Unir c\xE9lulas",
'Horizontal split': "Divis\xE3o horizontal",
'Vertical split': "Divis\xE3o vertical",
'Cell Background': "Fundo da c\xE9lula",
'Vertical Align': 'Alinhar vertical',
'Top': 'Topo',
'Middle': 'Meio',
'Bottom': 'Fundo',
'Align Top': 'Alinhar topo',
'Align Middle': 'Alinhar meio',
'Align Bottom': 'Alinhar fundo',
'Cell Style': "Estilo de c\xE9lula",
// Files
'Upload File': 'Upload de arquivo',
'Drop file': 'Largar arquivo',
// Emoticons
'Emoticons': 'Emoticons',
'Grinning face': 'Sorrindo a cara',
'Grinning face with smiling eyes': 'Sorrindo rosto com olhos sorridentes',
'Face with tears of joy': "Rosto com l\xE1grimas de alegria",
'Smiling face with open mouth': 'Rosto de sorriso com a boca aberta',
'Smiling face with open mouth and smiling eyes': 'Rosto de sorriso com a boca aberta e olhos sorridentes',
'Smiling face with open mouth and cold sweat': 'Rosto de sorriso com a boca aberta e suor frio',
'Smiling face with open mouth and tightly-closed eyes': 'Rosto de sorriso com a boca aberta e os olhos bem fechados',
'Smiling face with halo': 'Rosto de sorriso com halo',
'Smiling face with horns': 'Rosto de sorriso com chifres',
'Winking face': 'Pisc a rosto',
'Smiling face with smiling eyes': 'Rosto de sorriso com olhos sorridentes',
'Face savoring delicious food': 'Rosto saboreando uma deliciosa comida',
'Relieved face': 'Rosto aliviado',
'Smiling face with heart-shaped eyes': "Rosto de sorriso com os olhos em forma de cora\xE7\xE3o",
'Smiling face with sunglasses': "Rosto de sorriso com \xF3culos de sol",
'Smirking face': 'Rosto sorridente',
'Neutral face': 'Rosto neutra',
'Expressionless face': 'Rosto inexpressivo',
'Unamused face': "O rosto n\xE3o divertido",
'Face with cold sweat': 'Rosto com suor frio',
'Pensive face': 'O rosto pensativo',
'Confused face': 'Cara confusa',
'Confounded face': "Rosto at\xF4nito",
'Kissing face': 'Beijar Rosto',
'Face throwing a kiss': 'Rosto jogando um beijo',
'Kissing face with smiling eyes': 'Beijar rosto com olhos sorridentes',
'Kissing face with closed eyes': 'Beijando a cara com os olhos fechados',
'Face with stuck out tongue': "Preso de cara com a l\xEDngua para fora",
'Face with stuck out tongue and winking eye': "Rosto com estendeu a l\xEDngua e olho piscando",
'Face with stuck out tongue and tightly-closed eyes': 'Rosto com estendeu a língua e os olhos bem fechados',
'Disappointed face': 'Rosto decepcionado',
'Worried face': 'O rosto preocupado',
'Angry face': 'Rosto irritado',
'Pouting face': 'Beicinho Rosto',
'Crying face': 'Cara de choro',
'Persevering face': 'Perseverar Rosto',
'Face with look of triumph': 'Rosto com olhar de triunfo',
'Disappointed but relieved face': 'Fiquei Desapontado mas aliviado Rosto',
'Frowning face with open mouth': 'Sobrancelhas franzidas rosto com a boca aberta',
'Anguished face': 'O rosto angustiado',
'Fearful face': 'Cara com medo',
'Weary face': 'Rosto cansado',
'Sleepy face': 'Cara de sono',
'Tired face': 'Rosto cansado',
'Grimacing face': 'Fazendo caretas face',
'Loudly crying face': 'Alto chorando rosto',
'Face with open mouth': 'Enfrentar com a boca aberta',
'Hushed face': 'Flagrantes de rosto',
'Face with open mouth and cold sweat': 'Enfrentar com a boca aberta e suor frio',
'Face screaming in fear': 'Cara gritando de medo',
'Astonished face': 'Cara de surpresa',
'Flushed face': 'Rosto vermelho',
'Sleeping face': 'O rosto de sono',
'Dizzy face': 'Cara tonto',
'Face without mouth': 'Rosto sem boca',
'Face with medical mask': "Rosto com m\xE1scara m\xE9dica",
// Line breaker
'Break': 'Partir',
// Math
'Subscript': 'Subscrito',
'Superscript': 'Sobrescrito',
// Full screen
'Fullscreen': 'Tela cheia',
// Horizontal line
'Insert Horizontal Line': 'Inserir linha horizontal',
// Clear formatting
'Clear Formatting': "Remover formata\xE7\xE3o",
// Save
'Save': "Salve",
// Undo, redo
'Undo': 'Anular',
'Redo': 'Restaurar',
// Select all
'Select All': 'Seleccionar tudo',
// Code view
'Code View': "Exibi\xE7\xE3o de c\xF3digo",
// Quote
'Quote': "Cita\xE7\xE3o",
'Increase': 'Aumentar',
'Decrease': 'Diminuir',
// Quick Insert
'Quick Insert': "Inser\xE7\xE3o r\xE1pida",
// Spcial Characters
'Special Characters': 'Caracteres especiais',
'Latin': 'Latino',
'Greek': 'Grego',
'Cyrillic': 'Cirílico',
'Punctuation': 'Pontuação',
'Currency': 'Moeda',
'Arrows': 'Setas; flechas',
'Math': 'Matemática',
'Misc': 'Misc',
// Print.
'Print': 'Impressão',
// Spell Checker.
'Spell Checker': 'Verificador ortográfico',
// Help
'Help': 'Socorro',
'Shortcuts': 'Atalhos',
'Inline Editor': 'Editor em linha',
'Show the editor': 'Mostre o editor',
'Common actions': 'Ações comuns',
'Copy': 'Cópia de',
'Cut': 'Cortar',
'Paste': 'Colar',
'Basic Formatting': 'Formatação básica',
'Increase quote level': 'Aumentar o nível de cotação',
'Decrease quote level': 'Diminuir o nível de cotação',
'Image / Video': 'Imagem / video',
'Resize larger': 'Redimensionar maior',
'Resize smaller': 'Redimensionar menor',
'Table': 'Tabela',
'Select table cell': 'Selecione a célula da tabela',
'Extend selection one cell': 'Ampliar a seleção de uma célula',
'Extend selection one row': 'Ampliar a seleção uma linha',
'Navigation': 'Navegação',
'Focus popup / toolbar': 'Foco popup / barra de ferramentas',
'Return focus to previous position': 'Retornar o foco para a posição anterior',
// Embed.ly
'Embed URL': 'URL de inserção',
'Paste in a URL to embed': 'Colar em url para incorporar',
// Word Paste.
'The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?': 'O conteúdo colado vem de um documento Microsoft Word. Você quer manter o formato ou limpá-lo?',
'Keep': 'Guarda',
'Clean': 'Limpar limpo',
'Word Paste Detected': 'Pasta de palavras detectada',
// Character Counter
'Characters': 'Caracteres',
// More Buttons
'More Text': 'Mais Texto',
'More Paragraph': 'Mais Parágrafo',
'More Rich': 'Mais Rico',
'More Misc': 'Mais Misc'
},
direction: 'ltr'
};
})));
//# sourceMappingURL=pt_pt.js.map
|
Clazz.declarePackage ("JSV.common");
Clazz.load (["JSV.common.Annotation", "$.Coordinate"], "JSV.common.Measurement", null, function () {
c$ = Clazz.decorateAsClass (function () {
this.pt2 = null;
this.value = 0;
Clazz.instantialize (this, arguments);
}, JSV.common, "Measurement", JSV.common.Annotation);
Clazz.prepareFields (c$, function () {
this.pt2 = new JSV.common.Coordinate ();
});
$_M(c$, "setM1",
function (x, y, spec) {
this.setA (x, y, spec, "", false, false, 0, 6);
this.setPt2 (this.getXVal (), this.getYVal ());
return this;
}, "~N,~N,JSV.common.JDXSpectrum");
$_M(c$, "copyM",
function () {
var m = new JSV.common.Measurement ();
m.setA (this.getXVal (), this.getYVal (), this.spec, this.text, false, false, this.offsetX, this.offsetY);
m.setPt2 (this.pt2.getXVal (), this.pt2.getYVal ());
return m;
});
$_M(c$, "setPt2",
function (spec, doSetPt2) {
this.spec = spec;
if (doSetPt2) this.setPt2 (this.getXVal (), this.getYVal ());
return this;
}, "JSV.common.JDXSpectrum,~B");
$_M(c$, "setPt2",
function (x, y) {
this.pt2.setXVal (x);
this.pt2.setYVal (y);
this.value = Math.abs (x - this.getXVal ());
this.text = this.spec.setMeasurementText (this);
}, "~N,~N");
$_M(c$, "getSpectrum",
function () {
return this.spec;
});
$_M(c$, "setValue",
function (value) {
this.value = value;
this.text = this.spec.setMeasurementText (this);
}, "~N");
$_M(c$, "getValue",
function () {
return this.value;
});
$_M(c$, "getXVal2",
function () {
return this.pt2.getXVal ();
});
$_M(c$, "getYVal2",
function () {
return this.pt2.getYVal ();
});
$_V(c$, "addSpecShift",
function (dx) {
this.setXVal (this.getXVal () + dx);
this.pt2.setXVal (this.pt2.getXVal () + dx);
}, "~N");
$_M(c$, "setYVal2",
function (y2) {
this.pt2.setYVal (y2);
}, "~N");
$_M(c$, "overlaps",
function (x1, x2) {
return (Math.min (this.getXVal (), this.getXVal2 ()) < Math.max (x1, x2) && Math.max (this.getXVal (), this.getXVal2 ()) > Math.min (x1, x2));
}, "~N,~N");
$_V(c$, "toString",
function () {
return "[" + this.getXVal () + "," + this.pt2.getXVal () + "]";
});
});
|
module.exports = {
devtool: 'inline-source-map',
bail: true,
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
compact: false,
cacheDirectory: true,
presets: ['es2015']
}
}
]
},
watch: false
};
|
/**
* @output wp-admin/js/user-profile.js
*/
/* global ajaxurl, pwsL10n */
(function($) {
var updateLock = false,
__ = wp.i18n.__,
$pass1Row,
$pass1,
$pass2,
$weakRow,
$weakCheckbox,
$toggleButton,
$submitButtons,
$submitButton,
currentPass;
function generatePassword() {
if ( typeof zxcvbn !== 'function' ) {
setTimeout( generatePassword, 50 );
return;
} else if ( ! $pass1.val() ) {
// zxcvbn loaded before user entered password.
$pass1.val( $pass1.data( 'pw' ) );
$pass1.trigger( 'pwupdate' );
showOrHideWeakPasswordCheckbox();
}
else {
// zxcvbn loaded after the user entered password, check strength.
check_pass_strength();
showOrHideWeakPasswordCheckbox();
}
if ( 1 !== parseInt( $toggleButton.data( 'start-masked' ), 10 ) ) {
$pass1.attr( 'type', 'text' );
} else {
$toggleButton.trigger( 'click' );
}
// Once zxcvbn loads, passwords strength is known.
$( '#pw-weak-text-label' ).text( __( 'Confirm use of weak password' ) );
}
function bindPass1() {
currentPass = $pass1.val();
if ( 1 === parseInt( $pass1.data( 'reveal' ), 10 ) ) {
generatePassword();
}
$pass1.on( 'input' + ' pwupdate', function () {
if ( $pass1.val() === currentPass ) {
return;
}
currentPass = $pass1.val();
$pass1.removeClass( 'short bad good strong' );
showOrHideWeakPasswordCheckbox();
} );
}
function resetToggle( show ) {
$toggleButton
.attr({
'aria-label': show ? __( 'Show password' ) : __( 'Hide password' )
})
.find( '.text' )
.text( show ? __( 'Show' ) : __( 'Hide' ) )
.end()
.find( '.dashicons' )
.removeClass( show ? 'dashicons-hidden' : 'dashicons-visibility' )
.addClass( show ? 'dashicons-visibility' : 'dashicons-hidden' );
}
function bindToggleButton() {
$toggleButton = $pass1Row.find('.wp-hide-pw');
$toggleButton.show().on( 'click', function () {
if ( 'password' === $pass1.attr( 'type' ) ) {
$pass1.attr( 'type', 'text' );
resetToggle( false );
} else {
$pass1.attr( 'type', 'password' );
resetToggle( true );
}
$pass1.focus();
if ( ! _.isUndefined( $pass1[0].setSelectionRange ) ) {
$pass1[0].setSelectionRange( 0, 100 );
}
});
}
function bindPasswordForm() {
var $passwordWrapper,
$generateButton,
$cancelButton;
$pass1Row = $( '.user-pass1-wrap, .user-pass-wrap' );
// Hide the confirm password field when JavaScript support is enabled.
$('.user-pass2-wrap').hide();
$submitButton = $( '#submit, #wp-submit' ).on( 'click', function () {
updateLock = false;
});
$submitButtons = $submitButton.add( ' #createusersub' );
$weakRow = $( '.pw-weak' );
$weakCheckbox = $weakRow.find( '.pw-checkbox' );
$weakCheckbox.change( function() {
$submitButtons.prop( 'disabled', ! $weakCheckbox.prop( 'checked' ) );
} );
$pass1 = $('#pass1');
if ( $pass1.length ) {
bindPass1();
} else {
// Password field for the login form.
$pass1 = $( '#user_pass' );
}
/**
* Fix a LastPass mismatch issue, LastPass only changes pass2.
*
* This fixes the issue by copying any changes from the hidden
* pass2 field to the pass1 field, then running check_pass_strength.
*/
$pass2 = $( '#pass2' ).on( 'input', function () {
if ( $pass2.val().length > 0 ) {
$pass1.val( $pass2.val() );
$pass2.val('');
currentPass = '';
$pass1.trigger( 'pwupdate' );
}
} );
// Disable hidden inputs to prevent autofill and submission.
if ( $pass1.is( ':hidden' ) ) {
$pass1.prop( 'disabled', true );
$pass2.prop( 'disabled', true );
}
$passwordWrapper = $pass1Row.find( '.wp-pwd' );
$generateButton = $pass1Row.find( 'button.wp-generate-pw' );
bindToggleButton();
if ( $generateButton.length ) {
$passwordWrapper.hide();
}
$generateButton.show();
$generateButton.on( 'click', function () {
updateLock = true;
$generateButton.hide();
$passwordWrapper.show();
// Enable the inputs when showing.
$pass1.attr( 'disabled', false );
$pass2.attr( 'disabled', false );
if ( $pass1.val().length === 0 ) {
generatePassword();
}
} );
$cancelButton = $pass1Row.find( 'button.wp-cancel-pw' );
$cancelButton.on( 'click', function () {
updateLock = false;
// Clear any entered password.
$pass1.val( '' );
// Generate a new password.
wp.ajax.post( 'generate-password' )
.done( function( data ) {
$pass1.data( 'pw', data );
} );
$generateButton.show().focus();
$passwordWrapper.hide();
$weakRow.hide( 0, function () {
$weakCheckbox.removeProp( 'checked' );
} );
// Disable the inputs when hiding to prevent autofill and submission.
$pass1.prop( 'disabled', true );
$pass2.prop( 'disabled', true );
resetToggle( false );
if ( $pass1Row.closest( 'form' ).is( '#your-profile' ) ) {
// Clear password field to prevent update.
$pass1.val( '' ).trigger( 'pwupdate' );
$submitButtons.prop( 'disabled', false );
}
} );
$pass1Row.closest( 'form' ).on( 'submit', function () {
updateLock = false;
$pass1.prop( 'disabled', false );
$pass2.prop( 'disabled', false );
$pass2.val( $pass1.val() );
});
}
function check_pass_strength() {
var pass1 = $('#pass1').val(), strength;
$('#pass-strength-result').removeClass('short bad good strong empty');
if ( ! pass1 ) {
$( '#pass-strength-result' ).addClass( 'empty' ).html( ' ' );
return;
}
strength = wp.passwordStrength.meter( pass1, wp.passwordStrength.userInputDisallowedList(), pass1 );
switch ( strength ) {
case -1:
$( '#pass-strength-result' ).addClass( 'bad' ).html( pwsL10n.unknown );
break;
case 2:
$('#pass-strength-result').addClass('bad').html( pwsL10n.bad );
break;
case 3:
$('#pass-strength-result').addClass('good').html( pwsL10n.good );
break;
case 4:
$('#pass-strength-result').addClass('strong').html( pwsL10n.strong );
break;
case 5:
$('#pass-strength-result').addClass('short').html( pwsL10n.mismatch );
break;
default:
$('#pass-strength-result').addClass('short').html( pwsL10n['short'] );
}
}
function showOrHideWeakPasswordCheckbox() {
var passStrength = $('#pass-strength-result')[0];
if ( passStrength.className ) {
$pass1.addClass( passStrength.className );
if ( $( passStrength ).is( '.short, .bad' ) ) {
if ( ! $weakCheckbox.prop( 'checked' ) ) {
$submitButtons.prop( 'disabled', true );
}
$weakRow.show();
} else {
if ( $( passStrength ).is( '.empty' ) ) {
$submitButtons.prop( 'disabled', true );
$weakCheckbox.prop( 'checked', false );
} else {
$submitButtons.prop( 'disabled', false );
}
$weakRow.hide();
}
}
}
$(document).ready( function() {
var $colorpicker, $stylesheet, user_id, current_user_id,
select = $( '#display_name' ),
current_name = select.val(),
greeting = $( '#wp-admin-bar-my-account' ).find( '.display-name' );
$( '#pass1' ).val( '' ).on( 'input' + ' pwupdate', check_pass_strength );
$('#pass-strength-result').show();
$('.color-palette').click( function() {
$(this).siblings('input[name="admin_color"]').prop('checked', true);
});
if ( select.length ) {
$('#first_name, #last_name, #nickname').bind( 'blur.user_profile', function() {
var dub = [],
inputs = {
display_nickname : $('#nickname').val() || '',
display_username : $('#user_login').val() || '',
display_firstname : $('#first_name').val() || '',
display_lastname : $('#last_name').val() || ''
};
if ( inputs.display_firstname && inputs.display_lastname ) {
inputs.display_firstlast = inputs.display_firstname + ' ' + inputs.display_lastname;
inputs.display_lastfirst = inputs.display_lastname + ' ' + inputs.display_firstname;
}
$.each( $('option', select), function( i, el ){
dub.push( el.value );
});
$.each(inputs, function( id, value ) {
if ( ! value ) {
return;
}
var val = value.replace(/<\/?[a-z][^>]*>/gi, '');
if ( inputs[id].length && $.inArray( val, dub ) === -1 ) {
dub.push(val);
$('<option />', {
'text': val
}).appendTo( select );
}
});
});
/**
* Replaces "Howdy, *" in the admin toolbar whenever the display name dropdown is updated for one's own profile.
*/
select.on( 'change', function() {
if ( user_id !== current_user_id ) {
return;
}
var display_name = $.trim( this.value ) || current_name;
greeting.text( display_name );
} );
}
$colorpicker = $( '#color-picker' );
$stylesheet = $( '#colors-css' );
user_id = $( 'input#user_id' ).val();
current_user_id = $( 'input[name="checkuser_id"]' ).val();
$colorpicker.on( 'click.colorpicker', '.color-option', function() {
var colors,
$this = $(this);
if ( $this.hasClass( 'selected' ) ) {
return;
}
$this.siblings( '.selected' ).removeClass( 'selected' );
$this.addClass( 'selected' ).find( 'input[type="radio"]' ).prop( 'checked', true );
// Set color scheme.
if ( user_id === current_user_id ) {
// Load the colors stylesheet.
// The default color scheme won't have one, so we'll need to create an element.
if ( 0 === $stylesheet.length ) {
$stylesheet = $( '<link rel="stylesheet" />' ).appendTo( 'head' );
}
$stylesheet.attr( 'href', $this.children( '.css_url' ).val() );
// Repaint icons.
if ( typeof wp !== 'undefined' && wp.svgPainter ) {
try {
colors = $.parseJSON( $this.children( '.icon_colors' ).val() );
} catch ( error ) {}
if ( colors ) {
wp.svgPainter.setColors( colors );
wp.svgPainter.paint();
}
}
// Update user option.
$.post( ajaxurl, {
action: 'save-user-color-scheme',
color_scheme: $this.children( 'input[name="admin_color"]' ).val(),
nonce: $('#color-nonce').val()
}).done( function( response ) {
if ( response.success ) {
$( 'body' ).removeClass( response.data.previousScheme ).addClass( response.data.currentScheme );
}
});
}
});
bindPasswordForm();
});
$( '#destroy-sessions' ).on( 'click', function( e ) {
var $this = $(this);
wp.ajax.post( 'destroy-sessions', {
nonce: $( '#_wpnonce' ).val(),
user_id: $( '#user_id' ).val()
}).done( function( response ) {
$this.prop( 'disabled', true );
$this.siblings( '.notice' ).remove();
$this.before( '<div class="notice notice-success inline"><p>' + response.message + '</p></div>' );
}).fail( function( response ) {
$this.siblings( '.notice' ).remove();
$this.before( '<div class="notice notice-error inline"><p>' + response.message + '</p></div>' );
});
e.preventDefault();
});
window.generatePassword = generatePassword;
/* Warn the user if password was generated but not saved */
$( window ).on( 'beforeunload', function () {
if ( true === updateLock ) {
return __( 'Your new password has not been saved.' );
}
} );
})(jQuery);
|
/*!
* Copyright (c) Metaways Infosystems GmbH, 2011
* LGPLv3, http://opensource.org/licenses/LGPL-3.0
*/
Ext.ns('MShop.panel.attribute');
// hook text picker into the attribute ItemUi
Ext.ux.ItemRegistry.registerItem('MShop.panel.attribute.ItemUi', 'MShop.panel.attribute.TextItemPickerUi', {
xtype : 'MShop.panel.text.itempickerui',
itemConfig : {
recordName : 'Attribute_List',
idProperty : 'attribute.list.id',
siteidProperty : 'attribute.list.siteid',
listNamePrefix : 'attribute.list.',
listTypeIdProperty : 'attribute.list.type.id',
listTypeLabelProperty : 'attribute.list.type.label',
listTypeControllerName : 'Attribute_List_Type',
listTypeCondition : {
'&&' : [{
'==' : {
'attribute.list.type.domain' : 'text'
}
}]
},
listTypeKey : 'attribute/list/type/text'
},
listConfig : {
domain : 'attribute',
prefix : 'text.'
}
}, 10);
|
'use strict';
var multiplicationOperator = function (a, b) {
return a * b;
};
/**
* Raise value to a positive integer power by repeated squaring.
*
* @param {*} base
* @param {number} power
* @param {function} [mul] - Multiplication function,
* standard multiplication operator by default.
* @param {*} identity - Identity value, used when power == 0.
* If mul is not set, defaults to 1.
* @return {*}
*/
var fastPower = function (base, power, mul, identity) {
if (mul === undefined) {
mul = multiplicationOperator;
identity = 1;
}
if (power < 0 || Math.floor(power) != power) {
throw new Error('Power must be a positive integer or zero.');
}
// If the power is zero, identity value must be given (or set by default).
if (!power) {
if (identity === undefined) {
throw new Error('The power is zero, but identity value not set.');
}
else {
return identity;
}
}
// Iterative form of the algorithm avoids checking the same thing twice.
var result;
var multiplyBy = function (value) {
result = (result === undefined) ? value : mul(result, value);
};
for (var factor = base; power; power >>>= 1, factor = mul(factor, factor)) {
if (power & 1) {
multiplyBy(factor);
}
}
return result;
};
module.exports = fastPower;
|
// Sticky Plugin v1.0.0 for jQuery
// =============
// Author: Anthony Garand
// Improvements by German M. Bravo (Kronuz) and Ruud Kamphuis (ruudk)
// Improvements by Leonardo C. Daronco (daronco)
// Created: 2/14/2011
// Date: 2/12/2012
// Website: http://labs.anthonygarand.com/sticky
// Description: Makes an element on the page stick on the screen as you scroll
// It will only set the 'top' and 'position' of your element, you
// might need to adjust the width in some cases.
(function($) {
var defaults = {
topSpacing: 0,
bottomSpacing: 0,
className: 'is-sticky',
wrapperClassName: 'sticky-wrapper',
center: false,
getWidthFrom: ''
},
$window = $(window),
$document = $(document),
sticked = [],
windowHeight = $window.height(),
scroller = function() {
var scrollTop = $window.scrollTop(),
documentHeight = $document.height(),
dwh = documentHeight - windowHeight,
extra = (scrollTop > dwh) ? dwh - scrollTop : 0;
for (var i = 0; i < sticked.length; i++) {
var s = sticked[i],
elementTop = s.stickyWrapper.offset().top,
etse = elementTop - s.topSpacing - extra;
if (scrollTop <= etse) {
if (s.currentTop !== null) {
s.stickyElement
.css('position', '')
.css('top', '');
s.stickyElement.parent().removeClass(s.className);
s.currentTop = null;
}
}
else {
var newTop = documentHeight - s.stickyElement.outerHeight()
- s.topSpacing - s.bottomSpacing - scrollTop - extra;
if (newTop < 0) {
newTop = newTop + s.topSpacing;
} else {
newTop = s.topSpacing;
}
if (s.currentTop != newTop) {
s.stickyElement
.css('position', 'fixed')
.css('top', newTop);
if (typeof s.getWidthFrom !== 'undefined') {
s.stickyElement.css('width', $(s.getWidthFrom).width());
}
s.stickyElement.parent().addClass(s.className);
s.currentTop = newTop;
}
}
}
},
resizer = function() {
windowHeight = $window.height();
},
methods = {
init: function(options) {
var o = $.extend(defaults, options);
return this.each(function() {
var stickyElement = $(this);
stickyId = stickyElement.attr('id');
wrapper = $('<div></div>')
.attr('id', stickyId + '-sticky-wrapper')
.addClass(o.wrapperClassName);
stickyElement.wrapAll(wrapper);
if (o.center) {
stickyElement.parent().css({width:stickyElement.outerWidth(),marginLeft:"auto",marginRight:"auto"});
}
if (stickyElement.css("float") == "right") {
stickyElement.css({"float":"none"}).parent().css({"float":"right"});
}
var stickyWrapper = stickyElement.parent();
stickyWrapper.css('height', stickyElement.outerHeight());
sticked.push({
topSpacing: o.topSpacing,
bottomSpacing: o.bottomSpacing,
stickyElement: stickyElement,
currentTop: null,
stickyWrapper: stickyWrapper,
className: o.className,
getWidthFrom: o.getWidthFrom
});
});
},
update: scroller
};
// should be more efficient than using $window.scroll(scroller) and $window.resize(resizer):
if (window.addEventListener) {
window.addEventListener('scroll', scroller, false);
window.addEventListener('resize', resizer, false);
} else if (window.attachEvent) {
window.attachEvent('onscroll', scroller);
window.attachEvent('onresize', resizer);
}
$.fn.sticky = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method ) {
return methods.init.apply( this, arguments );
} else {
$.error('Method ' + method + ' does not exist on jQuery.sticky');
}
};
$(function() {
setTimeout(scroller, 0);
});
})(jQuery); |
/*!
* remark (http://getbootstrapadmin.com/remark)
* Copyright 2016 amazingsurge
* Licensed under the Themeforest Standard Licenses
*/
(function(document, window, $) {
'use strict';
var Site = window.Site;
$(document).ready(function($) {
Site.run();
});
// Sparkline Basic
// ---------------
// Pie Chart
$(".sparkline-pie-chart").sparkline([4, 2, 6], {
type: 'pie',
height: '162px',
sliceColors: [$.colors("primary", 500), $.colors("primary", 700), $.colors("primary", 600)]
});
// line chart
$(".sparkline-line-chart").sparkline([1, 3, 4, 2, 3, 6, 5, 3], {
type: 'line',
height: '162px',
width: '200px',
normalRangeMin: 0,
spotRadius: 2,
spotColor: $.colors("red", 600),
highlightSpotColor: $.colors("red", 700),
lineColor: $.colors("red", 500),
highlightLineColor: $.colors("red", 500),
fillColor: $.colors("red", 100)
});
// bar chart
$(".sparkline-bar-chart").sparkline([4, 7, 3, 2, 5, 6, 8, 5, 4, 8], {
type: 'bar',
height: '162px',
barWidth: 10,
barSpacing: 6,
barColor: $.colors("primary", 500),
negBarColor: $.colors("primary", 600)
});
// composite bar chart
$('.sparkline-compositebar-chart').sparkline('html', {
type: 'bar',
height: '162px',
barWidth: 10,
barSpacing: 5,
barColor: $.colors("blue-grey", 300)
});
$('.sparkline-compositebar-chart').sparkline([4, 5, 6, 6, 5, 5, 3, 6, 4, 2], {
composite: true,
fillColor: false,
lineColor: $.colors("purple", 400)
});
$('.sparkline-compositebar-chart').sparkline([1, 4, 5, 2, 3, 5, 6, 1, 3, 6], {
composite: true,
fillColor: false,
lineColor: $.colors("red", 400)
});
// Sparkline Types
// ---------------
// Line charts taking their values from the tag
$('.sparkline-line').sparkline('html', {
height: '32px',
width: '150px',
lineColor: $.colors("red", 600),
fillColor: $.colors("red", 100)
});
// Bar charts using inline values
$('.sparkline-bar').sparkline('html', {
type: 'bar',
height: '32px',
barWidth: 10,
barSpacing: 5,
barColor: $.colors("primary", 500),
negBarColor: $.colors("red", 500),
stackedBarColor: [$.colors("primary", 500), $.colors("red", 500)]
});
// Composite line charts, the second using values supplied via javascript
$('.sparkline-compositeline').sparkline('html', {
height: '32px',
width: '150px',
fillColor: false,
lineColor: $.colors("primary", 500),
spotColor: $.colors("green", 500),
minSpotColor: $.colors("primary", 500),
maxSpotColor: $.colors("green", 500),
changeRangeMin: 0,
chartRangeMax: 10
});
$('.sparkline-compositeline').sparkline([4, 1, 5, 7, 9, 8, 7, 6, 6, 4, 7, 8, 4, 3, 2, 5, 6, 7], {
composite: true,
fillColor: false,
height: '32px',
width: '150px',
lineColor: $.colors("red", 500),
spotColor: $.colors("green", 500),
minSpotColor: $.colors("primary", 500),
maxSpotColor: $.colors("green", 500),
changeRangeMin: 0,
chartRangeMax: 10
});
// Line charts with normal range marker
$('.sparkline-normalline').sparkline('html', {
fillColor: false,
height: '32px',
width: '150px',
lineColor: $.colors("red", 600),
spotColor: $.colors("primary", 500),
minSpotColor: $.colors("primary", 500),
maxSpotColor: $.colors("primary", 500),
normalRangeColor: $.colors("blue-grey", 300),
normalRangeMin: -1,
normalRangeMax: 8
});
// Bar + line composite charts
$('.sparkline-compositebar').sparkline('html', {
type: 'bar',
height: '32px',
barWidth: 10,
barSpacing: 5,
barColor: $.colors("primary", 500)
});
$('.sparkline-compositebar').sparkline([4, 1, 5, 7, 9, 9, 8, 7, 6, 6, 4, 7, 8, 4, 3, 2, 2, 5, 6, 7], {
composite: true,
fillColor: false,
lineColor: $.colors("red", 600),
spotColor: $.colors("primary", 500)
});
// Discrete charts
$('.sparkline-discrete1').sparkline('html', {
type: 'discrete',
height: '32px',
lineColor: $.colors("primary", 500),
xwidth: 36
});
$('.sparkline-discrete2').sparkline('html', {
type: 'discrete',
height: '32px',
lineColor: $.colors("primary", 500),
thresholdColor: $.colors("red", 600),
thresholdValue: 4
});
// Bullet charts
$('.sparkline-bullet').sparkline('html', {
type: 'bullet',
targetColor: $.colors("red", 500),
targetWidth: '2',
performanceColor: $.colors("primary", 600),
rangeColors: [$.colors("primary", 100), $.colors("primary", 200), $.colors("primary", 400)]
});
// Customized line chart
$('.sparkline-linecustom').sparkline('html', {
height: '32px',
width: '150px',
lineColor: $.colors("red", 400),
fillColor: $.colors("blue-grey", 300),
minSpotColor: false,
maxSpotColor: false,
spotColor: $.colors("green", 500),
spotRadius: 2
});
// Tri-state charts using inline values
$('.sparkline-tristate').sparkline('html', {
type: 'tristate',
height: '32px',
barWidth: 10,
barSpacing: 5,
posBarColor: $.colors("primary", 500),
negBarColor: $.colors("blue-grey", 300),
zeroBarColor: $.colors("red", 500)
});
$('.sparkline-tristatecols').sparkline('html', {
type: 'tristate',
height: '32px',
barWidth: 10,
barSpacing: 5,
posBarColor: $.colors("primary", 500),
negBarColor: $.colors("blue-grey", 300),
zeroBarColor: $.colors("red", 500),
colorMap: {
'-4': $.colors("red", 700),
'-2': $.colors("primary", 600),
'2': $.colors("blue-grey", 400)
}
});
// Box plots
$('.sparkline-boxplot').sparkline('html', {
type: 'box',
height: '20px',
width: '68px',
lineColor: $.colors("primary", 700),
boxLineColor: $.colors("primary", 400),
boxFillColor: $.colors("primary", 400),
whiskerColor: $.colors("blue-grey", 500),
// outlierLineColor: $.colors("blue-grey", 300),
// outlierFillColor: false,
medianColor: $.colors("red", 500)
// targetColor: $.colors("green", 500)
});
// Box plots raw
$('.sparkline-boxplotraw').sparkline([1, 3, 5, 8, 10, 15, 18], {
type: 'box',
height: '20px',
width: '78px',
raw: true,
showOutliers: true,
target: 6,
lineColor: $.colors("primary", 700),
boxLineColor: $.colors("primary", 400),
boxFillColor: $.colors("primary", 400),
whiskerColor: $.colors("blue-grey", 500),
outlierLineColor: $.colors("blue-grey", 300),
outlierFillColor: $.colors("blue-grey", 100),
medianColor: $.colors("red", 500),
targetColor: $.colors("green", 500)
});
// Pie charts
$('.sparkline-pie').sparkline('html', {
type: 'pie',
height: '30px',
sliceColors: [$.colors("primary", 500), $.colors("primary", 700), $.colors("primary", 600)]
});
$('.sparkline-pie-1').sparkline('html', {
type: 'pie',
height: '30px',
sliceColors: [$.colors("primary", 500), $.colors("blue-grey", 300)]
});
})(document, window, jQuery);
|
require("should");
var dataUtil = require("../../data-util/garment-purchasing/garment-currency-data-util");
var helper = require("../../helper");
// var validate = require("dl-models").validator.garmentPurchasing.garmentPurchaseOrder;
var moment = require('moment');
var Manager = require("../../../src/managers/garment-purchasing/garment-currency-manager");
var manager = null;
before('#00. connect db', function (done) {
helper.getDb()
.then(db => {
manager = new Manager(db, {
username: 'dev'
});
done();
})
.catch(e => {
done(e);
});
});
var createdData = {};
it("#01. should success when create data csv", function (done) {
dataUtil.getNewDataTest()
.then((data) => {
data.should.instanceof(Array);
data.length.should.not.equal(0);
createdData.data = data;
done();
})
.catch((e) => {
done(e);
});
});
it('#02. should error when insert empty data', function (done) {
var testData = createdData;
testData.data[1][0] = "";
testData.data[1][1] = "";
testData.data[2][0] = "TEST";
testData.data[2][1] = "9,123";
testData.data[3][0] = "TEST";
testData.data[3][1] = "test";
manager.insert(testData)
.then(dataError => {
dataError.should.instanceof(Array);
dataError.length.should.not.equal(0);
done()
})
.catch(e => {
done(e);
});
});
it('#03. should success when insert csv', function (done) {
var dataTest = {};
dataTest.data = [
["Mata Uang", "Kurs"],
["USD", "9999"],
];
dataTest.date = new Date();
manager.insert(dataTest)
.then(result => {
result.should.instanceof(Array);
result.length.should.not.equal(0);
done();
}).catch(e => {
done(e);
});
});
|
import warning from './warning'
import { loopAsync } from './AsyncUtils'
import { matchPattern } from './PatternUtils'
import { createRoutes } from './RouteUtils'
function getChildRoutes(route, location, callback) {
if (route.childRoutes) {
callback(null, route.childRoutes)
} else if (route.getChildRoutes) {
route.getChildRoutes(location, function (error, childRoutes) {
callback(error, !error && createRoutes(childRoutes))
})
} else {
callback()
}
}
function getIndexRoute(route, location, callback) {
if (route.indexRoute) {
callback(null, route.indexRoute)
} else if (route.getIndexRoute) {
route.getIndexRoute(location, function (error, indexRoute) {
callback(error, !error && createRoutes(indexRoute)[0])
})
} else if (route.childRoutes) {
const pathless = route.childRoutes.filter(function (obj) {
return !obj.hasOwnProperty('path')
})
loopAsync(pathless.length, function (index, next, done) {
getIndexRoute(pathless[index], location, function (error, indexRoute) {
if (error || indexRoute) {
const routes = [ pathless[index] ].concat( Array.isArray(indexRoute) ? indexRoute : [ indexRoute ] )
done(error, routes)
} else {
next()
}
})
}, function (err, routes) {
callback(null, routes)
})
} else {
callback()
}
}
function assignParams(params, paramNames, paramValues) {
return paramNames.reduce(function (params, paramName, index) {
const paramValue = paramValues && paramValues[index]
if (Array.isArray(params[paramName])) {
params[paramName].push(paramValue)
} else if (paramName in params) {
params[paramName] = [ params[paramName], paramValue ]
} else {
params[paramName] = paramValue
}
return params
}, params)
}
function createParams(paramNames, paramValues) {
return assignParams({}, paramNames, paramValues)
}
function matchRouteDeep(
route, location, remainingPathname, paramNames, paramValues, callback
) {
let pattern = route.path || ''
if (pattern.charAt(0) === '/') {
remainingPathname = location.pathname
paramNames = []
paramValues = []
}
if (remainingPathname !== null) {
const matched = matchPattern(pattern, remainingPathname)
remainingPathname = matched.remainingPathname
paramNames = [ ...paramNames, ...matched.paramNames ]
paramValues = [ ...paramValues, ...matched.paramValues ]
if (remainingPathname === '' && route.path) {
const match = {
routes: [ route ],
params: createParams(paramNames, paramValues)
}
getIndexRoute(route, location, function (error, indexRoute) {
if (error) {
callback(error)
} else {
if (Array.isArray(indexRoute)) {
warning(
indexRoute.every(route => !route.path),
'Index routes should not have paths'
)
match.routes.push(...indexRoute)
} else if (indexRoute) {
warning(
!indexRoute.path,
'Index routes should not have paths'
)
match.routes.push(indexRoute)
}
callback(null, match)
}
})
return
}
}
if (remainingPathname != null || route.childRoutes) {
// Either a) this route matched at least some of the path or b)
// we don't have to load this route's children asynchronously. In
// either case continue checking for matches in the subtree.
getChildRoutes(route, location, function (error, childRoutes) {
if (error) {
callback(error)
} else if (childRoutes) {
// Check the child routes to see if any of them match.
matchRoutes(childRoutes, location, function (error, match) {
if (error) {
callback(error)
} else if (match) {
// A child route matched! Augment the match and pass it up the stack.
match.routes.unshift(route)
callback(null, match)
} else {
callback()
}
}, remainingPathname, paramNames, paramValues)
} else {
callback()
}
})
} else {
callback()
}
}
/**
* Asynchronously matches the given location to a set of routes and calls
* callback(error, state) when finished. The state object will have the
* following properties:
*
* - routes An array of routes that matched, in hierarchical order
* - params An object of URL parameters
*
* Note: This operation may finish synchronously if no routes have an
* asynchronous getChildRoutes method.
*/
function matchRoutes(
routes, location, callback,
remainingPathname=location.pathname, paramNames=[], paramValues=[]
) {
loopAsync(routes.length, function (index, next, done) {
matchRouteDeep(
routes[index], location, remainingPathname, paramNames, paramValues,
function (error, match) {
if (error || match) {
done(error, match)
} else {
next()
}
}
)
}, callback)
}
export default matchRoutes
|
/*
* @flow
* @lint-ignore-every LINEWRAP1
*/
import {suite, test} from 'flow-dev-tools/src/test/Tester';
export default suite(({addFile, addFiles, addCode}) => [
test('Prevent reposition loops', [
addCode(`
declare class Map<K,V> {
get(k:K): ?V;
set(k:K,v:V): void
}
`).noNewErrors(),
addCode(`
const map1 = new Map();
map1.set('key', map1.get('key'));
`).noNewErrors(),
addCode(`
const map2 = new Map();
const val = map2.get('key');
map2.set('key', val);
`).noNewErrors(),
]),
]);
|
var ZK = require ('../lib/zookeeper');
var assert = require('assert');
var log4js = require('log4js');
var async = require('async');
//
// based on node-leader
// https://github.com/mcavage/node-leader
// callback(error, zookeeperConnection)
//
function startZK(options, callback) {
if(typeof(options) !== 'object')
throw new TypeError('options (Object) required');
if(typeof(options.zookeeper) !== 'string')
throw new TypeError('options.zookeeper (String) required');
if(typeof(options.log4js) !== 'object')
throw new TypeError('options.log4js (Object) required');
if(options.timeout && typeof(options.timeout) !== 'number')
throw new TypeError('options.timeout (Number) required');
if(typeof(callback) !== 'function')
throw new TypeError('callback (Function) required');
var log = options.log4js.getLogger('mkdirp-test');
var zkLogLevel = ZK.ZOO_LOG_LEVEL_WARNING;
if(log.isTraceEnabled())
zkLogLevel = ZK.ZOO_LOG_LEVEL_DEBUG;
var zk = new ZK({
connect: options.zookeeper,
timeout: options.timeout || 1000,
debug_level: zkLogLevel,
host_order_deterministic: false
});
log.debug('connecting to zookeeper');
return zk.connect(function(err) {
if(err)
return callback(err);
log.debug('connected to zookeeper.');
return callback && callback(null, zk);
});
}
if (require.main === module) {
var options = {
zookeeper: 'localhost:2181',
log4js: log4js
};
var PATH = '/mkdirp/test/path/of/death/n/destruction';
var con = null;
startZK(options, function(err, connection) {
if(err) return console.log(err);
con = connection;
return con.mkdirp(PATH, onMkdir);
});
function onMkdir(err, win) {
assert.ifError(err);
// make sure the path now exists :)
con.a_exists(PATH, null, function(rc, error, stat) {
if(rc != 0) {
throw new Error('Zookeeper Error: code='+rc+' '+error);
}
// path already exists, do nothing :)
assert.ok(stat);
return mkDirpAgain();
});
}
// tests that no errors are thrown if you mkdirp a bunch of dirs that exist
function mkDirpAgain(err, win) {
con.mkdirp(PATH, finish);
}
function finish(err) {
assert.ifError(err);
console.log('TEST PASSED!', __filename);
var dirs = [
'/mkdirp/test/path/of/death/n/destruction'
, '/mkdirp/test/path/of/death/n'
, '/mkdirp/test/path/of/death'
, '/mkdirp/test/path/of'
, '/mkdirp/test/path'
, '/mkdirp/test'
, '/mkdirp'
];
// can't easily delete the path, b/c haven't written rm -rf :)
async.series([
function (cb) { con.a_delete_(dirs[0], 0, normalizeCb(cb)); }
, function (cb) { con.a_delete_(dirs[1], 0, normalizeCb(cb)); }
, function (cb) { con.a_delete_(dirs[2], 0, normalizeCb(cb)); }
, function (cb) { con.a_delete_(dirs[3], 0, normalizeCb(cb)); }
, function (cb) { con.a_delete_(dirs[4], 0, normalizeCb(cb)); }
, function (cb) { con.a_delete_(dirs[5], 0, normalizeCb(cb)); }
, function (cb) { con.a_delete_(dirs[6], 0, normalizeCb(cb)); }
], function(err, results) {
console.log('Deleted mkdirp`ed dirs: '+results.length+' of '+dirs.length);
process.exit(0);
});
}
// allows a callback that expects to be called like this:
// cb()
// to instead be called like this:
// cb(rc, error)
// and then have the original callback only be called with an Error, or
// nothing at all if there was no Error.
function normalizeCb(callback) {
return function(rc, error) {
if(!callback) return;
if(rc != 0) {
return callback(new Error('Zookeeper Error: code='+rc+' '+error));
}
return callback(null, true);
};
}
}
|
import React from 'react'
import { Icon, Popup } from 'semantic-ui-react'
const PopupExampleOffset = () => (
<div>
<Popup
trigger={<Icon size='large' name='heart' circular />}
content='Way off to the left'
offset={50}
positioning='left center'
/>
<Popup
trigger={<Icon size='large' name='heart' circular />}
content='As expected this popup is way off to the right'
offset={50}
positioning='right center'
/>
</div>
)
export default PopupExampleOffset
|
/*
* $Id: combinatorics.js,v 0.25 2013/03/11 15:42:14 dankogai Exp dankogai $
*
* Licensed under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* References:
* http://www.ruby-doc.org/core-2.0/Array.html#method-i-combination
* http://www.ruby-doc.org/core-2.0/Array.html#method-i-permutation
* http://en.wikipedia.org/wiki/Factorial_number_system
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.Combinatorics = factory();
}
}(this, function () {
'use strict';
var version = "0.5.0";
/* combinatory arithmetics */
var P = function(m, n) {
var t, p = 1;
if (m < n) {
t = m;
m = n;
n = t;
}
while (n--) p *= m--;
return p;
};
var C = function(m, n) {
return P(m, n) / P(n, n);
};
var factorial = function(n) {
return P(n, n);
};
var factoradic = function(n, d) {
var f = 1;
if (!d) {
for (d = 1; f < n; f *= ++d);
if (f > n) f /= d--;
} else {
f = factorial(d);
}
var result = [0];
for (; d; f /= d--) {
result[d] = Math.floor(n / f);
n %= f;
}
return result;
};
/* common methods */
var addProperties = function(dst, src) {
Object.keys(src).forEach(function(p) {
Object.defineProperty(dst, p, {
value: src[p]
});
});
};
var hideProperty = function(o, p) {
Object.defineProperty(o, p, {
writable: true
});
};
var toArray = function(f) {
var e, result = [];
this.init();
while (e = this.next()) result.push(f ? f(e) : e);
this.init();
return result;
};
var common = {
toArray: toArray,
map: toArray,
forEach: function(f) {
var e;
this.init();
while (e = this.next()) f(e);
this.init();
},
filter: function(f) {
var e, result = [];
this.init();
while (e = this.next()) if (f(e)) result.push(e);
this.init();
return result;
}
};
/* power set */
var power = function(ary, fun) {
if (ary.length > 32) throw new RangeError;
var size = 1 << ary.length,
sizeOf = function() {
return size;
},
that = Object.create(ary.slice(), {
length: {
get: sizeOf
}
});
hideProperty(that, 'index');
addProperties(that, {
valueOf: sizeOf,
init: function() {
that.index = 0;
},
nth: function(n) {
if (n >= size) return;
var i = 0,
result = [];
for (; n; n >>>= 1, i++) if (n & 1) result.push(this[i]);
return result;
},
next: function() {
return this.nth(this.index++);
}
});
addProperties(that, common);
that.init();
return (typeof (fun) === 'function') ? that.map(fun) : that;
};
/* combination */
var nextIndex = function(n) {
var smallest = n & -n,
ripple = n + smallest,
new_smallest = ripple & -ripple,
ones = ((new_smallest / smallest) >> 1) - 1;
return ripple | ones;
};
var combination = function(ary, nelem, fun) {
if (ary.length > 32) throw new RangeError;
if (!nelem) nelem = ary.length;
if (nelem < 1) throw new RangeError;
if (nelem > ary.length) throw new RangeError;
var first = (1 << nelem) - 1,
size = C(ary.length, nelem),
maxIndex = 1 << ary.length,
sizeOf = function() {
return size;
},
that = Object.create(ary.slice(), {
length: {
get: sizeOf
}
});
hideProperty(that, 'index');
addProperties(that, {
valueOf: sizeOf,
init: function() {
this.index = first;
},
next: function() {
if (this.index >= maxIndex) return;
var i = 0,
n = this.index,
result = [];
for (; n; n >>>= 1, i++) if (n & 1) result.push(this[i]);
this.index = nextIndex(this.index);
return result;
}
});
addProperties(that, common);
that.init();
return (typeof (fun) === 'function') ? that.map(fun) : that;
};
/* permutation */
var _permutation = function(ary) {
var that = ary.slice(),
size = factorial(that.length);
that.index = 0;
that.next = function() {
if (this.index >= size) return;
var copy = this.slice(),
digits = factoradic(this.index, this.length),
result = [],
i = this.length - 1;
for (; i >= 0; --i) result.push(copy.splice(digits[i], 1)[0]);
this.index++;
return result;
};
return that;
};
// which is really a permutation of combination
var permutation = function(ary, nelem, fun) {
if (!nelem) nelem = ary.length;
if (nelem < 1) throw new RangeError;
if (nelem > ary.length) throw new RangeError;
var size = P(ary.length, nelem),
sizeOf = function() {
return size;
},
that = Object.create(ary.slice(), {
length: {
get: sizeOf
}
});
hideProperty(that, 'cmb');
hideProperty(that, 'per');
addProperties(that, {
valueOf: function() {
return size;
},
init: function() {
this.cmb = combination(ary, nelem);
this.per = _permutation(this.cmb.next());
},
next: function() {
var result = this.per.next();
if (!result) {
var cmb = this.cmb.next();
if (!cmb) return;
this.per = _permutation(cmb);
return this.next();
}
return result;
}
});
addProperties(that, common);
that.init();
return (typeof (fun) === 'function') ? that.map(fun) : that;
};
var PC = function(m) {
var total = 0;
for (var n = 1; n <= m; n++) {
var p = P(m,n);
total += p;
};
return total;
};
// which is really a permutation of combination
var permutationCombination = function(ary, fun) {
// if (!nelem) nelem = ary.length;
// if (nelem < 1) throw new RangeError;
// if (nelem > ary.length) throw new RangeError;
var size = PC(ary.length),
sizeOf = function() {
return size;
},
that = Object.create(ary.slice(), {
length: {
get: sizeOf
}
});
hideProperty(that, 'cmb');
hideProperty(that, 'per');
hideProperty(that, 'nelem');
addProperties(that, {
valueOf: function() {
return size;
},
init: function() {
this.nelem = 1;
// console.log("Starting nelem: " + this.nelem);
this.cmb = combination(ary, this.nelem);
this.per = _permutation(this.cmb.next());
},
next: function() {
var result = this.per.next();
if (!result) {
var cmb = this.cmb.next();
if (!cmb) {
this.nelem++;
// console.log("increment nelem: " + this.nelem + " vs " + ary.length);
if (this.nelem > ary.length) return;
this.cmb = combination(ary, this.nelem);
cmb = this.cmb.next();
if (!cmb) return;
}
this.per = _permutation(cmb);
return this.next();
}
return result;
}
});
addProperties(that, common);
that.init();
return (typeof (fun) === 'function') ? that.map(fun) : that;
};
/* Cartesian Product */
var arraySlice = Array.prototype.slice;
var cartesianProduct = function() {
if (!arguments.length) throw new RangeError;
var args = arraySlice.call(arguments),
size = args.reduce(function(p, a) {
return p * a.length;
}, 1),
sizeOf = function() {
return size;
},
dim = args.length,
that = Object.create(args, {
length: {
get: sizeOf
}
});
if (!size) throw new RangeError;
hideProperty(that, 'index');
addProperties(that, {
valueOf: sizeOf,
dim: dim,
init: function() {
this.index = 0;
},
get: function() {
if (arguments.length !== this.length) return;
var result = [],
d = 0;
for (; d < dim; d++) {
var i = arguments[d];
if (i >= this[d].length) return;
result.push(this[d][i]);
}
return result;
},
nth: function(n) {
var result = [],
d = 0;
for (; d < dim; d++) {
var l = this[d].length;
var i = n % l;
result.push(this[d][i]);
n -= i;
n /= l;
}
return result;
},
next: function() {
if (this.index >= size) return;
var result = this.nth(this.index);
this.index++;
return result;
}
});
addProperties(that, common);
that.init();
return that;
};
/* baseN */
var baseN = function(ary, nelem, fun) {
if (!nelem) nelem = ary.length;
if (nelem < 1) throw new RangeError;
var base = ary.length,
size = Math.pow(base, nelem);
if (size > Math.pow(2,32)) throw new RangeError;
var sizeOf = function() {
return size;
},
that = Object.create(ary.slice(), {
length: {
get: sizeOf
}
});
hideProperty(that, 'index');
addProperties(that, {
valueOf: sizeOf,
init: function() {
that.index = 0;
},
nth: function(n) {
if (n >= size) return;
var result = [];
for (var i = 0; i < nelem; i++) {
var d = n % base;
result.push(ary[d])
n -= d; n /= base
}
return result;
},
next: function() {
return this.nth(this.index++);
}
});
addProperties(that, common);
that.init();
return (typeof (fun) === 'function') ? that.map(fun) : that;
};
/* export */
var Combinatorics = Object.create(null);
addProperties(Combinatorics, {
C: C,
P: P,
factorial: factorial,
factoradic: factoradic,
cartesianProduct: cartesianProduct,
combination: combination,
permutation: permutation,
permutationCombination: permutationCombination,
power: power,
baseN: baseN,
VERSION: version
});
return Combinatorics;
}));
|
//#include include/takeable.js
var label = "Mailbox Kit";
var version = "1327361898";
var name_single = "Mailbox Kit";
var name_plural = "Mailbox Kits";
var article = "a";
var description = "";
var is_hidden = false;
var has_info = true;
var adjusted_scale = 1;
var stackmax = 1;
var base_cost = 0;
var input_for = [];
var parent_classes = ["mailbox_kit", "takeable"];
var has_instance_props = false;
var classProps = {
"collection_id" : "" // defined by takeable
};
var instancePropsDef = {};
var verbs = {};
verbs.pickup = { // defined by takeable
"name" : "pick up",
"ok_states" : ["in_location"],
"requires_target_pc" : false,
"requires_target_item" : false,
"is_default" : true,
"is_emote" : false,
"sort_on" : 50,
"tooltip" : "Put it in your pack",
"is_drop_target" : false,
"conditions" : function(pc, drop_stack){
return this.takeable_pickup_conditions(pc, drop_stack);
},
"handler" : function(pc, msg, suppress_activity){
return this.takeable_pickup(pc, msg);
}
};
verbs.give = { // defined by takeable
"name" : "give",
"ok_states" : ["in_pack"],
"requires_target_pc" : true,
"requires_target_item" : false,
"is_default" : false,
"is_emote" : false,
"sort_on" : 51,
"tooltip" : "Or, drag item to player",
"is_drop_target" : false,
"conditions" : function(pc, drop_stack){
return this.takeable_give_conditions(pc, drop_stack);
},
"handler" : function(pc, msg, suppress_activity){
return this.takeable_give(pc, msg);
}
};
verbs.drop = { // defined by takeable
"name" : "drop",
"ok_states" : ["in_pack"],
"requires_target_pc" : false,
"requires_target_item" : false,
"is_default" : false,
"is_emote" : false,
"sort_on" : 52,
"tooltip" : "Drop it on the ground",
"is_drop_target" : false,
"conditions" : function(pc, drop_stack){
return this.takeable_drop_conditions(pc, drop_stack);
},
"handler" : function(pc, msg, suppress_activity){
return this.takeable_drop(pc, msg);
}
};
function getDescExtras(pc){
var out = [];
return out;
}
var tags = [
"no_rube",
"metalproduct",
"no_trade"
];
// this is a temporary fix, while the client doesn't load item defs
// from the XML files. we pass this data on login events.
var itemDef = {
label : this.label,
name_plural : this.name_plural,
stackmax : this.stackmax,
is_hidden : this.is_hidden,
has_info : this.has_info,
adjusted_scale : this.adjusted_scale,
asset_swf_v : "\/c2.glitch.bz\/items\/2011-11\/mailbox_kit-1321577014.swf",
admin_props : false,
obey_physics : true,
in_background : false,
in_foreground : false,
has_status : false,
not_selectable : false,
};
if (this.consumable_label_single) itemDef.consumable_label_single = this.consumable_label_single;
if (this.consumable_label_plural) itemDef.consumable_label_plural = this.consumable_label_plural;
itemDef.verbs = {
};
itemDef.hasConditionalVerbs = 1;
itemDef.emote_verbs = {
};
itemDef.hasConditionalEmoteVerbs = 0;
itemDef.tags = [
"no_rube",
"metalproduct",
"no_trade"
];
itemDef.keys_in_location = {
"p" : "pickup"
};
itemDef.keys_in_pack = {
"r" : "drop",
"g" : "give"
};
// generated ok 2012-01-23 15:38:18 by lizg
|
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
'use strict';
var assert = require('assert'),
http = require('http'),
sinon = require('sinon'),
url = require('url');
var error = require('../../error'),
Executor = require('../../http').Executor,
HttpClient = require('../../http').HttpClient,
HttpRequest = require('../../http').Request,
HttpResponse = require('../../http').Response,
buildPath = require('../../http').buildPath,
Capabilities = require('../../lib/capabilities').Capabilities,
Command = require('../../lib/command').Command,
CommandName = require('../../lib/command').Name,
Session = require('../../lib/session').Session,
Server = require('../../lib/test/httpserver').Server,
promise = require('../../lib/promise'),
WebElement = require('../../lib/webdriver').WebElement;
describe('buildPath', function() {
it('properly replaces path segments with command parameters', function() {
var parameters = {'sessionId':'foo', 'url':'http://www.google.com'};
var finalPath = buildPath('/session/:sessionId/url', parameters);
assert.equal(finalPath, '/session/foo/url');
assert.deepEqual(parameters, {'url':'http://www.google.com'});
});
it('handles web element references', function() {
var parameters = {'sessionId':'foo', 'id': WebElement.buildId('bar')};
var finalPath = buildPath(
'/session/:sessionId/element/:id/click', parameters);
assert.equal(finalPath, '/session/foo/element/bar/click');
assert.deepEqual(parameters, {});
});
it('throws if missing a parameter', function() {
assert.throws(
() => buildPath('/session/:sessionId', {}),
function(err) {
return err instanceof error.InvalidArgumentError
&& 'Missing required parameter: sessionId' === err.message;
});
assert.throws(
() => buildPath('/session/:sessionId/element/:id', {'sessionId': 'foo'}),
function(err) {
return err instanceof error.InvalidArgumentError
&& 'Missing required parameter: id' === err.message;
});
});
it('does not match on segments that do not start with a colon', function() {
assert.equal(buildPath('/session/foo:bar/baz', {}), '/session/foo:bar/baz');
});
});
describe('Executor', function() {
let executor;
let client;
let send;
beforeEach(function setUp() {
client = new HttpClient('http://www.example.com');
send = sinon.stub(client, 'send');
executor = new Executor(client);
});
describe('command routing', function() {
it('rejects unrecognized commands', function() {
assert.throws(
() => executor.execute(new Command('fake-name')),
function (err) {
return err instanceof error.UnknownCommandError
&& 'Unrecognized command: fake-name' === err.message;
});
});
it('rejects promise if client fails to send request', function() {
let error = new Error('boom');
send.returns(Promise.reject(error));
return assertFailsToSend(new Command(CommandName.NEW_SESSION))
.then(function(e) {
assert.strictEqual(error, e);
assertSent(
'POST', '/session', {},
[['Accept', 'application/json; charset=utf-8']]);
});
});
it('can execute commands with no URL parameters', function() {
var resp = JSON.stringify({sessionId: 'abc123'});
send.returns(Promise.resolve(new HttpResponse(200, {}, resp)));
let command = new Command(CommandName.NEW_SESSION);
return assertSendsSuccessfully(command).then(function(response) {
assertSent(
'POST', '/session', {},
[['Accept', 'application/json; charset=utf-8']]);
});
});
it('rejects commands missing URL parameters', function() {
let command =
new Command(CommandName.FIND_CHILD_ELEMENT).
setParameter('sessionId', 's123').
// Let this be missing: setParameter('id', {'ELEMENT': 'e456'}).
setParameter('using', 'id').
setParameter('value', 'foo');
assert.throws(
() => executor.execute(command),
function(err) {
return err instanceof error.InvalidArgumentError
&& 'Missing required parameter: id' === err.message;
});
assert.ok(!send.called);
});
it('replaces URL parameters with command parameters', function() {
var command = new Command(CommandName.GET).
setParameter('sessionId', 's123').
setParameter('url', 'http://www.google.com');
send.returns(Promise.resolve(new HttpResponse(200, {}, '')));
return assertSendsSuccessfully(command).then(function(response) {
assertSent(
'POST', '/session/s123/url', {'url': 'http://www.google.com'},
[['Accept', 'application/json; charset=utf-8']]);
});
});
describe('uses correct URL', function() {
beforeEach(() => executor = new Executor(client));
describe('in legacy mode', function() {
test(CommandName.GET_WINDOW_SIZE, {sessionId:'s123'}, false,
'GET', '/session/s123/window/current/size');
test(CommandName.SET_WINDOW_SIZE,
{sessionId:'s123', width: 1, height: 1}, false,
'POST', '/session/s123/window/current/size',
{width: 1, height: 1});
test(CommandName.MAXIMIZE_WINDOW, {sessionId:'s123'}, false,
'POST', '/session/s123/window/current/maximize');
// This is consistent b/w legacy and W3C, just making sure.
test(CommandName.GET,
{sessionId:'s123', url: 'http://www.example.com'}, false,
'POST', '/session/s123/url', {url: 'http://www.example.com'});
});
describe('in W3C mode', function() {
test(CommandName.GET_WINDOW_SIZE,
{sessionId:'s123'}, true,
'GET', '/session/s123/window/size');
test(CommandName.SET_WINDOW_SIZE,
{sessionId:'s123', width: 1, height: 1}, true,
'POST', '/session/s123/window/size', {width: 1, height: 1});
test(CommandName.MAXIMIZE_WINDOW, {sessionId:'s123'}, true,
'POST', '/session/s123/window/maximize');
// This is consistent b/w legacy and W3C, just making sure.
test(CommandName.GET,
{sessionId:'s123', url: 'http://www.example.com'}, true,
'POST', '/session/s123/url', {url: 'http://www.example.com'});
});
function test(command, parameters, w3c,
expectedMethod, expectedUrl, opt_expectedParams) {
it(`command=${command}`, function() {
var resp = JSON.stringify({sessionId: 'abc123'});
send.returns(Promise.resolve(new HttpResponse(200, {}, resp)));
let cmd = new Command(command).setParameters(parameters);
executor.w3c = w3c;
return executor.execute(cmd).then(function() {
assertSent(
expectedMethod, expectedUrl, opt_expectedParams || {},
[['Accept', 'application/json; charset=utf-8']]);
});
});
}
});
});
describe('response parsing', function() {
it('extracts value from JSON response', function() {
var responseObj = {
'status': error.ErrorCode.SUCCESS,
'value': 'http://www.google.com'
};
var command = new Command(CommandName.GET_CURRENT_URL)
.setParameter('sessionId', 's123');
send.returns(Promise.resolve(
new HttpResponse(200, {}, JSON.stringify(responseObj))));
return executor.execute(command).then(function(response) {
assertSent('GET', '/session/s123/url', {},
[['Accept', 'application/json; charset=utf-8']]);
assert.strictEqual(response, 'http://www.google.com');
});
});
describe('extracts Session from NEW_SESSION response', function() {
beforeEach(() => executor = new Executor(client));
const command = new Command(CommandName.NEW_SESSION);
describe('fails if server returns invalid response', function() {
describe('(empty response)', function() {
test(true);
test(false);
function test(w3c) {
it('w3c === ' + w3c, function() {
send.returns(Promise.resolve(new HttpResponse(200, {}, '')));
executor.w3c = w3c;
return executor.execute(command).then(
() => assert.fail('expected to fail'),
(e) => {
if (!e.message.startsWith('Unable to parse')) {
throw e;
}
});
});
}
});
describe('(no session ID)', function() {
test(true);
test(false);
function test(w3c) {
it('w3c === ' + w3c, function() {
let resp = {value:{name: 'Bob'}};
send.returns(Promise.resolve(
new HttpResponse(200, {}, JSON.stringify(resp))));
executor.w3c = w3c;
return executor.execute(command).then(
() => assert.fail('expected to fail'),
(e) => {
if (!e.message.startsWith('Unable to parse')) {
throw e;
}
});
});
}
});
});
it('handles legacy response', function() {
var rawResponse = {sessionId: 's123', status: 0, value: {name: 'Bob'}};
send.returns(Promise.resolve(
new HttpResponse(200, {}, JSON.stringify(rawResponse))));
assert.ok(!executor.w3c);
return executor.execute(command).then(function(response) {
assert.ok(response instanceof Session);
assert.equal(response.getId(), 's123');
let caps = response.getCapabilities();
assert.ok(caps instanceof Capabilities);
assert.equal(caps.get('name'), 'Bob');
assert.ok(!executor.w3c);
});
});
it('auto-upgrades on W3C response', function() {
var rawResponse = {sessionId: 's123', value: {name: 'Bob'}};
send.returns(Promise.resolve(
new HttpResponse(200, {}, JSON.stringify(rawResponse))));
assert.ok(!executor.w3c);
return executor.execute(command).then(function(response) {
assert.ok(response instanceof Session);
assert.equal(response.getId(), 's123');
let caps = response.getCapabilities();
assert.ok(caps instanceof Capabilities);
assert.equal(caps.get('name'), 'Bob');
assert.ok(executor.w3c);
});
});
it('if w3c, does not downgrade on legacy response', function() {
var rawResponse = {sessionId: 's123', status: 0, value: null};
send.returns(Promise.resolve(
new HttpResponse(200, {}, JSON.stringify(rawResponse))));
executor.w3c = true;
return executor.execute(command).then(function(response) {
assert.ok(response instanceof Session);
assert.equal(response.getId(), 's123');
assert.equal(response.getCapabilities().size, 0);
assert.ok(executor.w3c, 'should never downgrade');
});
});
});
it('handles JSON null', function() {
var command = new Command(CommandName.GET_CURRENT_URL)
.setParameter('sessionId', 's123');
send.returns(Promise.resolve(new HttpResponse(200, {}, 'null')));
return executor.execute(command).then(function(response) {
assertSent('GET', '/session/s123/url', {},
[['Accept', 'application/json; charset=utf-8']]);
assert.strictEqual(response, null);
});
});
describe('falsy values', function() {
test(0);
test(false);
test('');
function test(value) {
it(`value=${value}`, function() {
var command = new Command(CommandName.GET_CURRENT_URL)
.setParameter('sessionId', 's123');
send.returns(Promise.resolve(
new HttpResponse(200, {},
JSON.stringify({status: 0, value: value}))));
return executor.execute(command).then(function(response) {
assertSent('GET', '/session/s123/url', {},
[['Accept', 'application/json; charset=utf-8']]);
assert.strictEqual(response, value);
});
});
}
});
it('handles non-object JSON', function() {
var command = new Command(CommandName.GET_CURRENT_URL)
.setParameter('sessionId', 's123');
send.returns(Promise.resolve(new HttpResponse(200, {}, '123')));
return executor.execute(command).then(function(response) {
assertSent('GET', '/session/s123/url', {},
[['Accept', 'application/json; charset=utf-8']]);
assert.strictEqual(response, 123);
});
});
it('returns body text when 2xx but not JSON', function() {
var command = new Command(CommandName.GET_CURRENT_URL)
.setParameter('sessionId', 's123');
send.returns(Promise.resolve(
new HttpResponse(200, {}, 'hello, world\r\ngoodbye, world!')));
return executor.execute(command).then(function(response) {
assertSent('GET', '/session/s123/url', {},
[['Accept', 'application/json; charset=utf-8']]);
assert.strictEqual(response, 'hello, world\ngoodbye, world!');
});
});
it('returns body text when 2xx but invalid JSON', function() {
var command = new Command(CommandName.GET_CURRENT_URL)
.setParameter('sessionId', 's123');
send.returns(Promise.resolve(
new HttpResponse(200, {}, '[')));
return executor.execute(command).then(function(response) {
assertSent('GET', '/session/s123/url', {},
[['Accept', 'application/json; charset=utf-8']]);
assert.strictEqual(response, '[');
});
});
it('returns null if no body text and 2xx', function() {
var command = new Command(CommandName.GET_CURRENT_URL)
.setParameter('sessionId', 's123');
send.returns(Promise.resolve(new HttpResponse(200, {}, '')));
return executor.execute(command).then(function(response) {
assertSent('GET', '/session/s123/url', {},
[['Accept', 'application/json; charset=utf-8']]);
assert.strictEqual(response, null);
});
});
it('returns normalized body text when 2xx but not JSON', function() {
var command = new Command(CommandName.GET_CURRENT_URL)
.setParameter('sessionId', 's123');
send.returns(Promise.resolve(new HttpResponse(200, {}, '\r\n\n\n\r\n')));
return executor.execute(command).then(function(response) {
assertSent('GET', '/session/s123/url', {},
[['Accept', 'application/json; charset=utf-8']]);
assert.strictEqual(response, '\n\n\n\n');
});
});
it('throws UnsupportedOperationError for 404 and body not JSON',
function() {
var command = new Command(CommandName.GET_CURRENT_URL)
.setParameter('sessionId', 's123');
send.returns(Promise.resolve(
new HttpResponse(404, {}, 'hello, world\r\ngoodbye, world!')));
return executor.execute(command)
.then(
() => assert.fail('should have failed'),
checkError(
error.UnsupportedOperationError,
'hello, world\ngoodbye, world!'));
});
it('throws WebDriverError for generic 4xx when body not JSON',
function() {
var command = new Command(CommandName.GET_CURRENT_URL)
.setParameter('sessionId', 's123');
send.returns(Promise.resolve(
new HttpResponse(500, {}, 'hello, world\r\ngoodbye, world!')));
return executor.execute(command)
.then(
() => assert.fail('should have failed'),
checkError(
error.WebDriverError,
'hello, world\ngoodbye, world!'))
.then(function() {
assertSent('GET', '/session/s123/url', {},
[['Accept', 'application/json; charset=utf-8']]);
});
});
});
it('canDefineNewCommands', function() {
executor.defineCommand('greet', 'GET', '/person/:name');
var command = new Command('greet').
setParameter('name', 'Bob');
send.returns(Promise.resolve(new HttpResponse(200, {}, '')));
return assertSendsSuccessfully(command).then(function(response) {
assertSent('GET', '/person/Bob', {},
[['Accept', 'application/json; charset=utf-8']]);
});
});
it('canRedefineStandardCommands', function() {
executor.defineCommand(CommandName.GO_BACK, 'POST', '/custom/back');
var command = new Command(CommandName.GO_BACK).
setParameter('times', 3);
send.returns(Promise.resolve(new HttpResponse(200, {}, '')));
return assertSendsSuccessfully(command).then(function(response) {
assertSent('POST', '/custom/back', {'times': 3},
[['Accept', 'application/json; charset=utf-8']]);
});
});
function entries(map) {
let entries = [];
for (let e of map.entries()) {
entries.push(e);
}
return entries;
}
function checkError(type, message) {
return function(e) {
if (e instanceof type) {
assert.strictEqual(e.message, message);
} else {
throw e;
}
};
}
function assertSent(method, path, data, headers) {
assert.ok(send.calledWith(sinon.match(function(value) {
assert.equal(value.method, method);
assert.equal(value.path, path);
assert.deepEqual(value.data, data);
assert.deepEqual(entries(value.headers), headers);
return true;
})));
}
function assertSendsSuccessfully(command) {
return executor.execute(command).then(function(response) {
return response;
});
}
function assertFailsToSend(command, opt_onError) {
return executor.execute(command).then(
() => {throw Error('should have failed')},
(e) => {return e});
}
});
describe('HttpClient', function() {
this.timeout(4 * 1000);
var server = new Server(function(req, res) {
if (req.method == 'GET' && req.url == '/echo') {
res.writeHead(200, req.headers);
res.end();
} else if (req.method == 'GET' && req.url == '/redirect') {
res.writeHead(303, {'Location': server.url('/hello')});
res.end();
} else if (req.method == 'GET' && req.url == '/hello') {
res.writeHead(200, {'content-type': 'text/plain'});
res.end('hello, world!');
} else if (req.method == 'GET' && req.url == '/badredirect') {
res.writeHead(303, {});
res.end();
} else if (req.method == 'GET' && req.url == '/protected') {
var denyAccess = function() {
res.writeHead(401, {'WWW-Authenticate': 'Basic realm="test"'});
res.end('Access denied');
};
var basicAuthRegExp = /^\s*basic\s+([a-z0-9\-\._~\+\/]+)=*\s*$/i
var auth = req.headers.authorization;
var match = basicAuthRegExp.exec(auth || '');
if (!match) {
denyAccess();
return;
}
var userNameAndPass = new Buffer(match[1], 'base64').toString();
var parts = userNameAndPass.split(':', 2);
if (parts[0] !== 'genie' && parts[1] !== 'bottle') {
denyAccess();
return;
}
res.writeHead(200, {'content-type': 'text/plain'});
res.end('Access granted!');
} else if (req.method == 'GET' && req.url == '/proxy') {
res.writeHead(200, req.headers);
res.end();
} else if (req.method == 'GET' && req.url == '/proxy/redirect') {
res.writeHead(303, {'Location': '/proxy'});
res.end();
} else {
res.writeHead(404, {});
res.end();
}
});
before(function() {
return server.start();
});
after(function() {
return server.stop();
});
it('can send a basic HTTP request', function() {
var request = new HttpRequest('GET', '/echo');
request.headers.set('Foo', 'Bar');
var agent = new http.Agent();
agent.maxSockets = 1; // Only making 1 request.
var client = new HttpClient(server.url(), agent);
return client.send(request).then(function(response) {
assert.equal(200, response.status);
assert.equal(response.headers.get('content-length'), '0');
assert.equal(response.headers.get('connection'), 'keep-alive');
assert.equal(response.headers.get('host'), server.host());
assert.equal(request.headers.get('Foo'), 'Bar');
assert.equal(
request.headers.get('Accept'), 'application/json; charset=utf-8');
});
});
it('can use basic auth', function() {
var parsed = url.parse(server.url());
parsed.auth = 'genie:bottle';
var client = new HttpClient(url.format(parsed));
var request = new HttpRequest('GET', '/protected');
return client.send(request).then(function(response) {
assert.equal(200, response.status);
assert.equal(response.headers.get('content-type'), 'text/plain');
assert.equal(response.body, 'Access granted!');
});
});
it('fails requests missing required basic auth', function() {
var client = new HttpClient(server.url());
var request = new HttpRequest('GET', '/protected');
return client.send(request).then(function(response) {
assert.equal(401, response.status);
assert.equal(response.body, 'Access denied');
});
});
it('automatically follows redirects', function() {
var request = new HttpRequest('GET', '/redirect');
var client = new HttpClient(server.url());
return client.send(request).then(function(response) {
assert.equal(200, response.status);
assert.equal(response.headers.get('content-type'), 'text/plain');
assert.equal(response.body, 'hello, world!');
});
});
it('handles malformed redirect responses', function() {
var request = new HttpRequest('GET', '/badredirect');
var client = new HttpClient(server.url());
return client.send(request).then(assert.fail, function(err) {
assert.ok(/Failed to parse "Location"/.test(err.message),
'Not the expected error: ' + err.message);
});
});
it('proxies requests through the webdriver proxy', function() {
var request = new HttpRequest('GET', '/proxy');
var client = new HttpClient(
'http://another.server.com', undefined, server.url());
return client.send(request).then(function(response) {
assert.equal(200, response.status);
assert.equal(response.headers.get('host'), 'another.server.com');
});
});
it('proxies requests through the webdriver proxy on redirect', function() {
var request = new HttpRequest('GET', '/proxy/redirect');
var client = new HttpClient(
'http://another.server.com', undefined, server.url());
return client.send(request).then(function(response) {
assert.equal(200, response.status);
assert.equal(response.headers.get('host'), 'another.server.com');
});
});
});
|
module.exports=[')',']','}','\u0F3B','\u0F3D','\u169C','\u2046','\u207E','\u208E','\u2309','\u230B','\u232A','\u2769','\u276B','\u276D','\u276F','\u2771','\u2773','\u2775','\u27C6','\u27E7','\u27E9','\u27EB','\u27ED','\u27EF','\u2984','\u2986','\u2988','\u298A','\u298C','\u298E','\u2990','\u2992','\u2994','\u2996','\u2998','\u29D9','\u29DB','\u29FD','\u2E23','\u2E25','\u2E27','\u2E29','\u3009','\u300B','\u300D','\u300F','\u3011','\u3015','\u3017','\u3019','\u301B','\uFE5A','\uFE5C','\uFE5E','\uFF09','\uFF3D','\uFF5D','\uFF60','\uFF63'] |
module.exports = require('./skypager.js')
|
/*
* Copyright (C) 2015 Glyptodon LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* The controller for editing users.
*/
angular.module('manage').controller('manageUserController', ['$scope', '$injector',
function manageUserController($scope, $injector) {
// Required types
var ConnectionGroup = $injector.get('ConnectionGroup');
var PageDefinition = $injector.get('PageDefinition');
var PermissionFlagSet = $injector.get('PermissionFlagSet');
var PermissionSet = $injector.get('PermissionSet');
var User = $injector.get('User');
// Required services
var $location = $injector.get('$location');
var $routeParams = $injector.get('$routeParams');
var $q = $injector.get('$q');
var authenticationService = $injector.get('authenticationService');
var connectionGroupService = $injector.get('connectionGroupService');
var dataSourceService = $injector.get('dataSourceService');
var guacNotification = $injector.get('guacNotification');
var permissionService = $injector.get('permissionService');
var schemaService = $injector.get('schemaService');
var translationStringService = $injector.get('translationStringService');
var userService = $injector.get('userService');
/**
* An action to be provided along with the object sent to showStatus which
* closes the currently-shown status dialog.
*/
var ACKNOWLEDGE_ACTION = {
name : "MANAGE_USER.ACTION_ACKNOWLEDGE",
// Handle action
callback : function acknowledgeCallback() {
guacNotification.showStatus(false);
}
};
/**
* The identifiers of all data sources currently available to the
* authenticated user.
*
* @type String[]
*/
var dataSources = authenticationService.getAvailableDataSources();
/**
* The username of the current, authenticated user.
*
* @type String
*/
var currentUsername = authenticationService.getCurrentUsername();
/**
* The unique identifier of the data source containing the user being
* edited.
*
* @type String
*/
var selectedDataSource = $routeParams.dataSource;
/**
* The username of the user being edited.
*
* @type String
*/
var username = $routeParams.id;
/**
* All user accounts associated with the same username as the account being
* created or edited, as a map of data source identifier to the User object
* within that data source.
*
* @type Object.<String, User>
*/
$scope.users = null;
/**
* The user being modified.
*
* @type User
*/
$scope.user = null;
/**
* All permissions associated with the user being modified.
*
* @type PermissionFlagSet
*/
$scope.permissionFlags = null;
/**
* A map of data source identifiers to the root connection groups within
* thost data sources. As only one data source is applicable to any one
* user being edited/created, this will only contain a single key.
*
* @type Object.<String, ConnectionGroup>
*/
$scope.rootGroups = null;
/**
* A map of data source identifiers to the set of all permissions
* associated with the current user under that data source, or null if the
* user's permissions have not yet been loaded.
*
* @type Object.<String, PermissionSet>
*/
$scope.permissions = null;
/**
* All available user attributes. This is only the set of attribute
* definitions, organized as logical groupings of attributes, not attribute
* values.
*
* @type Form[]
*/
$scope.attributes = null;
/**
* The pages associated with each user account having the given username.
* Each user account will be associated with a particular data source.
*
* @type PageDefinition[]
*/
$scope.accountPages = [];
/**
* Returns whether critical data has completed being loaded.
*
* @returns {Boolean}
* true if enough data has been loaded for the user interface to be
* useful, false otherwise.
*/
$scope.isLoaded = function isLoaded() {
return $scope.users !== null
&& $scope.permissionFlags !== null
&& $scope.rootGroups !== null
&& $scope.permissions !== null
&& $scope.attributes !== null;
};
/**
* Returns whether the user being edited already exists within the data
* source specified.
*
* @param {String} [dataSource]
* The identifier of the data source to check. If omitted, this will
* default to the currently-selected data source.
*
* @returns {Boolean}
* true if the user being edited already exists, false otherwise.
*/
$scope.userExists = function userExists(dataSource) {
// Do not check if users are not yet loaded
if (!$scope.users)
return false;
// Use currently-selected data source if unspecified
dataSource = dataSource || selectedDataSource;
// Account exists only if it was successfully retrieved
return (dataSource in $scope.users);
};
/**
* Returns whether the current user can change attributes associated with
* the user being edited within the given data source.
*
* @param {String} [dataSource]
* The identifier of the data source to check. If omitted, this will
* default to the currently-selected data source.
*
* @returns {Boolean}
* true if the current user can change attributes associated with the
* user being edited, false otherwise.
*/
$scope.canChangeAttributes = function canChangeAttributes(dataSource) {
// Do not check if permissions are not yet loaded
if (!$scope.permissions)
return false;
// Use currently-selected data source if unspecified
dataSource = dataSource || selectedDataSource;
// Attributes can always be set if we are creating the user
if (!$scope.userExists(dataSource))
return true;
// The administrator can always change attributes
if (PermissionSet.hasSystemPermission($scope.permissions[dataSource],
PermissionSet.SystemPermissionType.ADMINISTER))
return true;
// Otherwise, can change attributes if we have permission to update this user
return PermissionSet.hasUserPermission($scope.permissions[dataSource],
PermissionSet.ObjectPermissionType.UPDATE, username);
};
/**
* Returns whether the current user can change permissions of any kind
* which are associated with the user being edited within the given data
* source.
*
* @param {String} [dataSource]
* The identifier of the data source to check. If omitted, this will
* default to the currently-selected data source.
*
* @returns {Boolean}
* true if the current user can grant or revoke permissions of any kind
* which are associated with the user being edited, false otherwise.
*/
$scope.canChangePermissions = function canChangePermissions(dataSource) {
// Do not check if permissions are not yet loaded
if (!$scope.permissions)
return false;
// Use currently-selected data source if unspecified
dataSource = dataSource || selectedDataSource;
// Permissions can always be set if we are creating the user
if (!$scope.userExists(dataSource))
return true;
// The administrator can always modify permissions
if (PermissionSet.hasSystemPermission($scope.permissions[dataSource],
PermissionSet.SystemPermissionType.ADMINISTER))
return true;
// Otherwise, can only modify permissions if we have explicit
// ADMINISTER permission
return PermissionSet.hasUserPermission($scope.permissions[dataSource],
PermissionSet.ObjectPermissionType.ADMINISTER, username);
};
/**
* Returns whether the current user can change the system permissions
* granted to the user being edited within the given data source.
*
* @param {String} [dataSource]
* The identifier of the data source to check. If omitted, this will
* default to the currently-selected data source.
*
* @returns {Boolean}
* true if the current user can grant or revoke system permissions to
* the user being edited, false otherwise.
*/
$scope.canChangeSystemPermissions = function canChangeSystemPermissions(dataSource) {
// Do not check if permissions are not yet loaded
if (!$scope.permissions)
return false;
// Use currently-selected data source if unspecified
dataSource = dataSource || selectedDataSource;
// Only the administrator can modify system permissions
return PermissionSet.hasSystemPermission($scope.permissions[dataSource],
PermissionSet.SystemPermissionType.ADMINISTER);
};
/**
* Returns whether the current user can save the user being edited within
* the given data source. Saving will create or update that user depending
* on whether the user already exists.
*
* @param {String} [dataSource]
* The identifier of the data source to check. If omitted, this will
* default to the currently-selected data source.
*
* @returns {Boolean}
* true if the current user can save changes to the user being edited,
* false otherwise.
*/
$scope.canSaveUser = function canSaveUser(dataSource) {
// Do not check if permissions are not yet loaded
if (!$scope.permissions)
return false;
// Use currently-selected data source if unspecified
dataSource = dataSource || selectedDataSource;
// The administrator can always save users
if (PermissionSet.hasSystemPermission($scope.permissions[dataSource],
PermissionSet.SystemPermissionType.ADMINISTER))
return true;
// If user does not exist, can only save if we have permission to create users
if (!$scope.userExists(dataSource))
return PermissionSet.hasSystemPermission($scope.permissions[dataSource],
PermissionSet.SystemPermissionType.CREATE_USER);
// Otherwise, can only save if we have permission to update this user
return PermissionSet.hasUserPermission($scope.permissions[dataSource],
PermissionSet.ObjectPermissionType.UPDATE, username);
};
/**
* Returns whether the current user can delete the user being edited from
* the given data source.
*
* @param {String} [dataSource]
* The identifier of the data source to check. If omitted, this will
* default to the currently-selected data source.
*
* @returns {Boolean}
* true if the current user can delete the user being edited, false
* otherwise.
*/
$scope.canDeleteUser = function canDeleteUser(dataSource) {
// Do not check if permissions are not yet loaded
if (!$scope.permissions)
return false;
// Use currently-selected data source if unspecified
dataSource = dataSource || selectedDataSource;
// Can't delete what doesn't exist
if (!$scope.userExists(dataSource))
return false;
// The administrator can always delete users
if (PermissionSet.hasSystemPermission($scope.permissions[dataSource],
PermissionSet.SystemPermissionType.ADMINISTER))
return true;
// Otherwise, require explicit DELETE permission on the user
return PermissionSet.hasUserPermission($scope.permissions[dataSource],
PermissionSet.ObjectPermissionType.DELETE, username);
};
/**
* Returns whether the user being edited within the given data source is
* read-only, and thus cannot be modified by the current user.
*
* @param {String} [dataSource]
* The identifier of the data source to check. If omitted, this will
* default to the currently-selected data source.
*
* @returns {Boolean}
* true if the user being edited is actually read-only and cannot be
* edited at all, false otherwise.
*/
$scope.isReadOnly = function isReadOnly(dataSource) {
// Use currently-selected data source if unspecified
dataSource = dataSource || selectedDataSource;
// User is read-only if they cannot be saved
return !$scope.canSaveUser(dataSource);
};
// Update visible account pages whenever available users/permissions changes
$scope.$watchGroup(['users', 'permissions'], function updateAccountPages() {
// Generate pages for each applicable data source
$scope.accountPages = [];
angular.forEach(dataSources, function addAccountPage(dataSource) {
// Determine whether data source contains this user
var linked = $scope.userExists(dataSource);
var readOnly = $scope.isReadOnly(dataSource);
// Account is not relevant if it does not exist and cannot be
// created
if (!linked && readOnly)
return;
// Determine class name based on read-only / linked status
var className;
if (readOnly) className = 'read-only';
else if (linked) className = 'linked';
else className = 'unlinked';
// Add page entry
$scope.accountPages.push(new PageDefinition({
name : translationStringService.canonicalize('DATA_SOURCE_' + dataSource) + '.NAME',
url : '/manage/' + encodeURIComponent(dataSource) + '/users/' + encodeURIComponent(username),
className : className
}));
});
});
// Pull user attribute schema
schemaService.getUserAttributes(selectedDataSource).success(function attributesReceived(attributes) {
$scope.attributes = attributes;
});
// Pull user data
dataSourceService.apply(userService.getUser, dataSources, username)
.then(function usersReceived(users) {
// Get user for currently-selected data source
$scope.users = users;
$scope.user = users[selectedDataSource];
// Create skeleton user if user does not exist
if (!$scope.user)
$scope.user = new User({
'username' : username
});
});
// Pull user permissions
permissionService.getPermissions(selectedDataSource, username).success(function gotPermissions(permissions) {
$scope.permissionFlags = PermissionFlagSet.fromPermissionSet(permissions);
})
// If permissions cannot be retrieved, use empty permissions
.error(function permissionRetrievalFailed() {
$scope.permissionFlags = new PermissionFlagSet();
});
// Retrieve all connections for which we have ADMINISTER permission
dataSourceService.apply(
connectionGroupService.getConnectionGroupTree,
[selectedDataSource],
ConnectionGroup.ROOT_IDENTIFIER,
[PermissionSet.ObjectPermissionType.ADMINISTER]
)
.then(function connectionGroupReceived(rootGroups) {
$scope.rootGroups = rootGroups;
});
// Query the user's permissions for the current user
dataSourceService.apply(
permissionService.getPermissions,
dataSources,
currentUsername
)
.then(function permissionsReceived(permissions) {
$scope.permissions = permissions;
});
/**
* Available system permission types, as translation string / internal
* value pairs.
*
* @type Object[]
*/
$scope.systemPermissionTypes = [
{
label: "MANAGE_USER.FIELD_HEADER_ADMINISTER_SYSTEM",
value: PermissionSet.SystemPermissionType.ADMINISTER
},
{
label: "MANAGE_USER.FIELD_HEADER_CREATE_NEW_USERS",
value: PermissionSet.SystemPermissionType.CREATE_USER
},
{
label: "MANAGE_USER.FIELD_HEADER_CREATE_NEW_CONNECTIONS",
value: PermissionSet.SystemPermissionType.CREATE_CONNECTION
},
{
label: "MANAGE_USER.FIELD_HEADER_CREATE_NEW_CONNECTION_GROUPS",
value: PermissionSet.SystemPermissionType.CREATE_CONNECTION_GROUP
}
];
/**
* The set of permissions that will be added to the user when the user is
* saved. Permissions will only be present in this set if they are
* manually added, and not later manually removed before saving.
*
* @type PermissionSet
*/
var permissionsAdded = new PermissionSet();
/**
* The set of permissions that will be removed from the user when the user
* is saved. Permissions will only be present in this set if they are
* manually removed, and not later manually added before saving.
*
* @type PermissionSet
*/
var permissionsRemoved = new PermissionSet();
/**
* Updates the permissionsAdded and permissionsRemoved permission sets to
* reflect the addition of the given system permission.
*
* @param {String} type
* The system permission to add, as defined by
* PermissionSet.SystemPermissionType.
*/
var addSystemPermission = function addSystemPermission(type) {
// If permission was previously removed, simply un-remove it
if (PermissionSet.hasSystemPermission(permissionsRemoved, type))
PermissionSet.removeSystemPermission(permissionsRemoved, type);
// Otherwise, explicitly add the permission
else
PermissionSet.addSystemPermission(permissionsAdded, type);
};
/**
* Updates the permissionsAdded and permissionsRemoved permission sets to
* reflect the removal of the given system permission.
*
* @param {String} type
* The system permission to remove, as defined by
* PermissionSet.SystemPermissionType.
*/
var removeSystemPermission = function removeSystemPermission(type) {
// If permission was previously added, simply un-add it
if (PermissionSet.hasSystemPermission(permissionsAdded, type))
PermissionSet.removeSystemPermission(permissionsAdded, type);
// Otherwise, explicitly remove the permission
else
PermissionSet.addSystemPermission(permissionsRemoved, type);
};
/**
* Notifies the controller that a change has been made to the given
* system permission for the user being edited.
*
* @param {String} type
* The system permission that was changed, as defined by
* PermissionSet.SystemPermissionType.
*/
$scope.systemPermissionChanged = function systemPermissionChanged(type) {
// Determine current permission setting
var value = $scope.permissionFlags.systemPermissions[type];
// Add/remove permission depending on flag state
if (value)
addSystemPermission(type);
else
removeSystemPermission(type);
};
/**
* Updates the permissionsAdded and permissionsRemoved permission sets to
* reflect the addition of the given user permission.
*
* @param {String} type
* The user permission to add, as defined by
* PermissionSet.ObjectPermissionType.
*
* @param {String} identifier
* The identifier of the user affected by the permission being added.
*/
var addUserPermission = function addUserPermission(type, identifier) {
// If permission was previously removed, simply un-remove it
if (PermissionSet.hasUserPermission(permissionsRemoved, type, identifier))
PermissionSet.removeUserPermission(permissionsRemoved, type, identifier);
// Otherwise, explicitly add the permission
else
PermissionSet.addUserPermission(permissionsAdded, type, identifier);
};
/**
* Updates the permissionsAdded and permissionsRemoved permission sets to
* reflect the removal of the given user permission.
*
* @param {String} type
* The user permission to remove, as defined by
* PermissionSet.ObjectPermissionType.
*
* @param {String} identifier
* The identifier of the user affected by the permission being removed.
*/
var removeUserPermission = function removeUserPermission(type, identifier) {
// If permission was previously added, simply un-add it
if (PermissionSet.hasUserPermission(permissionsAdded, type, identifier))
PermissionSet.removeUserPermission(permissionsAdded, type, identifier);
// Otherwise, explicitly remove the permission
else
PermissionSet.addUserPermission(permissionsRemoved, type, identifier);
};
/**
* Notifies the controller that a change has been made to the given user
* permission for the user being edited.
*
* @param {String} type
* The user permission that was changed, as defined by
* PermissionSet.ObjectPermissionType.
*
* @param {String} identifier
* The identifier of the user affected by the changed permission.
*/
$scope.userPermissionChanged = function userPermissionChanged(type, identifier) {
// Determine current permission setting
var value = $scope.permissionFlags.userPermissions[type][identifier];
// Add/remove permission depending on flag state
if (value)
addUserPermission(type, identifier);
else
removeUserPermission(type, identifier);
};
/**
* Updates the permissionsAdded and permissionsRemoved permission sets to
* reflect the addition of the given connection permission.
*
* @param {String} identifier
* The identifier of the connection to add READ permission for.
*/
var addConnectionPermission = function addConnectionPermission(identifier) {
// If permission was previously removed, simply un-remove it
if (PermissionSet.hasConnectionPermission(permissionsRemoved, PermissionSet.ObjectPermissionType.READ, identifier))
PermissionSet.removeConnectionPermission(permissionsRemoved, PermissionSet.ObjectPermissionType.READ, identifier);
// Otherwise, explicitly add the permission
else
PermissionSet.addConnectionPermission(permissionsAdded, PermissionSet.ObjectPermissionType.READ, identifier);
};
/**
* Updates the permissionsAdded and permissionsRemoved permission sets to
* reflect the removal of the given connection permission.
*
* @param {String} identifier
* The identifier of the connection to remove READ permission for.
*/
var removeConnectionPermission = function removeConnectionPermission(identifier) {
// If permission was previously added, simply un-add it
if (PermissionSet.hasConnectionPermission(permissionsAdded, PermissionSet.ObjectPermissionType.READ, identifier))
PermissionSet.removeConnectionPermission(permissionsAdded, PermissionSet.ObjectPermissionType.READ, identifier);
// Otherwise, explicitly remove the permission
else
PermissionSet.addConnectionPermission(permissionsRemoved, PermissionSet.ObjectPermissionType.READ, identifier);
};
/**
* Updates the permissionsAdded and permissionsRemoved permission sets to
* reflect the addition of the given connection group permission.
*
* @param {String} identifier
* The identifier of the connection group to add READ permission for.
*/
var addConnectionGroupPermission = function addConnectionGroupPermission(identifier) {
// If permission was previously removed, simply un-remove it
if (PermissionSet.hasConnectionGroupPermission(permissionsRemoved, PermissionSet.ObjectPermissionType.READ, identifier))
PermissionSet.removeConnectionGroupPermission(permissionsRemoved, PermissionSet.ObjectPermissionType.READ, identifier);
// Otherwise, explicitly add the permission
else
PermissionSet.addConnectionGroupPermission(permissionsAdded, PermissionSet.ObjectPermissionType.READ, identifier);
};
/**
* Updates the permissionsAdded and permissionsRemoved permission sets to
* reflect the removal of the given connection permission.
*
* @param {String} identifier
* The identifier of the connection to remove READ permission for.
*/
var removeConnectionGroupPermission = function removeConnectionGroupPermission(identifier) {
// If permission was previously added, simply un-add it
if (PermissionSet.hasConnectionGroupPermission(permissionsAdded, PermissionSet.ObjectPermissionType.READ, identifier))
PermissionSet.removeConnectionGroupPermission(permissionsAdded, PermissionSet.ObjectPermissionType.READ, identifier);
// Otherwise, explicitly remove the permission
else
PermissionSet.addConnectionGroupPermission(permissionsRemoved, PermissionSet.ObjectPermissionType.READ, identifier);
};
// Expose permission query and modification functions to group list template
$scope.groupListContext = {
/**
* Returns the PermissionFlagSet that contains the current state of
* granted permissions.
*
* @returns {PermissionFlagSet}
* The PermissionFlagSet describing the current state of granted
* permissions for the user being edited.
*/
getPermissionFlags : function getPermissionFlags() {
return $scope.permissionFlags;
},
/**
* Notifies the controller that a change has been made to the given
* connection permission for the user being edited. This only applies
* to READ permissions.
*
* @param {String} identifier
* The identifier of the connection affected by the changed
* permission.
*/
connectionPermissionChanged : function connectionPermissionChanged(identifier) {
// Determine current permission setting
var value = $scope.permissionFlags.connectionPermissions.READ[identifier];
// Add/remove permission depending on flag state
if (value)
addConnectionPermission(identifier);
else
removeConnectionPermission(identifier);
},
/**
* Notifies the controller that a change has been made to the given
* connection group permission for the user being edited. This only
* applies to READ permissions.
*
* @param {String} identifier
* The identifier of the connection group affected by the changed
* permission.
*/
connectionGroupPermissionChanged : function connectionGroupPermissionChanged(identifier) {
// Determine current permission setting
var value = $scope.permissionFlags.connectionGroupPermissions.READ[identifier];
// Add/remove permission depending on flag state
if (value)
addConnectionGroupPermission(identifier);
else
removeConnectionGroupPermission(identifier);
}
};
/**
* Cancels all pending edits, returning to the management page.
*/
$scope.cancel = function cancel() {
$location.path('/settings/users');
};
/**
* Saves the user, updating the existing user only.
*/
$scope.saveUser = function saveUser() {
// Verify passwords match
if ($scope.passwordMatch !== $scope.user.password) {
guacNotification.showStatus({
'className' : 'error',
'title' : 'MANAGE_USER.DIALOG_HEADER_ERROR',
'text' : 'MANAGE_USER.ERROR_PASSWORD_MISMATCH',
'actions' : [ ACKNOWLEDGE_ACTION ]
});
return;
}
// Save or create the user, depending on whether the user exists
var saveUserPromise;
if ($scope.userExists(selectedDataSource))
saveUserPromise = userService.saveUser(selectedDataSource, $scope.user);
else
saveUserPromise = userService.createUser(selectedDataSource, $scope.user);
saveUserPromise.success(function savedUser() {
// Upon success, save any changed permissions
permissionService.patchPermissions(selectedDataSource, $scope.user.username, permissionsAdded, permissionsRemoved)
.success(function patchedUserPermissions() {
$location.path('/settings/users');
})
// Notify of any errors
.error(function userPermissionsPatchFailed(error) {
guacNotification.showStatus({
'className' : 'error',
'title' : 'MANAGE_USER.DIALOG_HEADER_ERROR',
'text' : error.message,
'actions' : [ ACKNOWLEDGE_ACTION ]
});
});
})
// Notify of any errors
.error(function userSaveFailed(error) {
guacNotification.showStatus({
'className' : 'error',
'title' : 'MANAGE_USER.DIALOG_HEADER_ERROR',
'text' : error.message,
'actions' : [ ACKNOWLEDGE_ACTION ]
});
});
};
/**
* An action to be provided along with the object sent to showStatus which
* immediately deletes the current user.
*/
var DELETE_ACTION = {
name : "MANAGE_USER.ACTION_DELETE",
className : "danger",
// Handle action
callback : function deleteCallback() {
deleteUserImmediately();
guacNotification.showStatus(false);
}
};
/**
* An action to be provided along with the object sent to showStatus which
* closes the currently-shown status dialog.
*/
var CANCEL_ACTION = {
name : "MANAGE_USER.ACTION_CANCEL",
// Handle action
callback : function cancelCallback() {
guacNotification.showStatus(false);
}
};
/**
* Immediately deletes the current user, without prompting the user for
* confirmation.
*/
var deleteUserImmediately = function deleteUserImmediately() {
// Delete the user
userService.deleteUser(selectedDataSource, $scope.user)
.success(function deletedUser() {
$location.path('/settings/users');
})
// Notify of any errors
.error(function userDeletionFailed(error) {
guacNotification.showStatus({
'className' : 'error',
'title' : 'MANAGE_USER.DIALOG_HEADER_ERROR',
'text' : error.message,
'actions' : [ ACKNOWLEDGE_ACTION ]
});
});
};
/**
* Deletes the user, prompting the user first to confirm that deletion is
* desired.
*/
$scope.deleteUser = function deleteUser() {
// Confirm deletion request
guacNotification.showStatus({
'title' : 'MANAGE_USER.DIALOG_HEADER_CONFIRM_DELETE',
'text' : 'MANAGE_USER.TEXT_CONFIRM_DELETE',
'actions' : [ DELETE_ACTION, CANCEL_ACTION]
});
};
}]);
|
var connect = require('connect')
var app = connect()
app.use(function(req,res,next){
res.writeHead(200)
res.end(JSON.stringify({"web":{"test":"web"}}))
})
app.listen(62626)
console.log('ready')
setTimeout(process.exit,3000)
|
const KEYWORDS = [
"as", // for exports
"in",
"of",
"if",
"for",
"while",
"finally",
"var",
"new",
"function",
"do",
"return",
"void",
"else",
"break",
"catch",
"instanceof",
"with",
"throw",
"case",
"default",
"try",
"switch",
"continue",
"typeof",
"delete",
"let",
"yield",
"const",
"class",
// JS handles these with a special rule
// "get",
// "set",
"debugger",
"async",
"await",
"static",
"import",
"from",
"export",
"extends"
];
const LITERALS = [
"true",
"false",
"null",
"undefined",
"NaN",
"Infinity"
];
const TYPES = [
"Intl",
"DataView",
"Number",
"Math",
"Date",
"String",
"RegExp",
"Object",
"Function",
"Boolean",
"Error",
"Symbol",
"Set",
"Map",
"WeakSet",
"WeakMap",
"Proxy",
"Reflect",
"JSON",
"Promise",
"Float64Array",
"Int16Array",
"Int32Array",
"Int8Array",
"Uint16Array",
"Uint32Array",
"Float32Array",
"Array",
"Uint8Array",
"Uint8ClampedArray",
"ArrayBuffer",
"BigInt64Array",
"BigUint64Array",
"BigInt"
];
const ERROR_TYPES = [
"EvalError",
"InternalError",
"RangeError",
"ReferenceError",
"SyntaxError",
"TypeError",
"URIError"
];
const BUILT_IN_GLOBALS = [
"setInterval",
"setTimeout",
"clearInterval",
"clearTimeout",
"require",
"exports",
"eval",
"isFinite",
"isNaN",
"parseFloat",
"parseInt",
"decodeURI",
"decodeURIComponent",
"encodeURI",
"encodeURIComponent",
"escape",
"unescape"
];
const BUILT_IN_VARIABLES = [
"arguments",
"this",
"super",
"console",
"window",
"document",
"localStorage",
"module",
"global" // Node.js
];
const BUILT_INS = [].concat(
BUILT_IN_GLOBALS,
BUILT_IN_VARIABLES,
TYPES,
ERROR_TYPES
);
/*
Language: CoffeeScript
Author: Dmytrii Nagirniak <dnagir@gmail.com>
Contributors: Oleg Efimov <efimovov@gmail.com>, Cédric Néhémie <cedric.nehemie@gmail.com>
Description: CoffeeScript is a programming language that transcompiles to JavaScript. For info about language see http://coffeescript.org/
Category: common, scripting
Website: https://coffeescript.org
*/
/** @type LanguageFn */
function coffeescript(hljs) {
const COFFEE_BUILT_INS = [
'npm',
'print'
];
const COFFEE_LITERALS = [
'yes',
'no',
'on',
'off'
];
const COFFEE_KEYWORDS = [
'then',
'unless',
'until',
'loop',
'by',
'when',
'and',
'or',
'is',
'isnt',
'not'
];
const NOT_VALID_KEYWORDS = [
"var",
"const",
"let",
"function",
"static"
];
const excluding = (list) =>
(kw) => !list.includes(kw);
const KEYWORDS$1 = {
keyword: KEYWORDS.concat(COFFEE_KEYWORDS).filter(excluding(NOT_VALID_KEYWORDS)),
literal: LITERALS.concat(COFFEE_LITERALS),
built_in: BUILT_INS.concat(COFFEE_BUILT_INS)
};
const JS_IDENT_RE = '[A-Za-z$_][0-9A-Za-z$_]*';
const SUBST = {
className: 'subst',
begin: /#\{/,
end: /\}/,
keywords: KEYWORDS$1
};
const EXPRESSIONS = [
hljs.BINARY_NUMBER_MODE,
hljs.inherit(hljs.C_NUMBER_MODE, {
starts: {
end: '(\\s*/)?',
relevance: 0
}
}), // a number tries to eat the following slash to prevent treating it as a regexp
{
className: 'string',
variants: [
{
begin: /'''/,
end: /'''/,
contains: [hljs.BACKSLASH_ESCAPE]
},
{
begin: /'/,
end: /'/,
contains: [hljs.BACKSLASH_ESCAPE]
},
{
begin: /"""/,
end: /"""/,
contains: [
hljs.BACKSLASH_ESCAPE,
SUBST
]
},
{
begin: /"/,
end: /"/,
contains: [
hljs.BACKSLASH_ESCAPE,
SUBST
]
}
]
},
{
className: 'regexp',
variants: [
{
begin: '///',
end: '///',
contains: [
SUBST,
hljs.HASH_COMMENT_MODE
]
},
{
begin: '//[gim]{0,3}(?=\\W)',
relevance: 0
},
{
// regex can't start with space to parse x / 2 / 3 as two divisions
// regex can't start with *, and it supports an "illegal" in the main mode
begin: /\/(?![ *]).*?(?![\\]).\/[gim]{0,3}(?=\W)/
}
]
},
{
begin: '@' + JS_IDENT_RE // relevance booster
},
{
subLanguage: 'javascript',
excludeBegin: true,
excludeEnd: true,
variants: [
{
begin: '```',
end: '```'
},
{
begin: '`',
end: '`'
}
]
}
];
SUBST.contains = EXPRESSIONS;
const TITLE = hljs.inherit(hljs.TITLE_MODE, {
begin: JS_IDENT_RE
});
const POSSIBLE_PARAMS_RE = '(\\(.*\\)\\s*)?\\B[-=]>';
const PARAMS = {
className: 'params',
begin: '\\([^\\(]',
returnBegin: true,
/* We need another contained nameless mode to not have every nested
pair of parens to be called "params" */
contains: [{
begin: /\(/,
end: /\)/,
keywords: KEYWORDS$1,
contains: ['self'].concat(EXPRESSIONS)
}]
};
return {
name: 'CoffeeScript',
aliases: [
'coffee',
'cson',
'iced'
],
keywords: KEYWORDS$1,
illegal: /\/\*/,
contains: EXPRESSIONS.concat([
hljs.COMMENT('###', '###'),
hljs.HASH_COMMENT_MODE,
{
className: 'function',
begin: '^\\s*' + JS_IDENT_RE + '\\s*=\\s*' + POSSIBLE_PARAMS_RE,
end: '[-=]>',
returnBegin: true,
contains: [
TITLE,
PARAMS
]
},
{
// anonymous function start
begin: /[:\(,=]\s*/,
relevance: 0,
contains: [{
className: 'function',
begin: POSSIBLE_PARAMS_RE,
end: '[-=]>',
returnBegin: true,
contains: [PARAMS]
}]
},
{
className: 'class',
beginKeywords: 'class',
end: '$',
illegal: /[:="\[\]]/,
contains: [
{
beginKeywords: 'extends',
endsWithParent: true,
illegal: /[:="\[\]]/,
contains: [TITLE]
},
TITLE
]
},
{
begin: JS_IDENT_RE + ':',
end: ':',
returnBegin: true,
returnEnd: true,
relevance: 0
}
])
};
}
module.exports = coffeescript;
|
var currentBoard = function() {
return Boards.findOne(Router.current().params.boardId);
}
var widgetTitles = {
filter: 'filter-cards',
background: 'change-background'
};
Template.boardWidgets.helpers({
currentWidget: function() {
return Session.get('currentWidget') + 'Widget';
},
currentWidgetTitle: function() {
return TAPi18n.__(widgetTitles[Session.get('currentWidget')]);
}
});
Template.addMemberPopup.helpers({
isBoardMember: function() {
var user = Users.findOne(this._id);
return user && user.isBoardMember();
}
});
Template.backgroundWidget.helpers({
backgroundColors: function() {
return DefaultBoardBackgroundColors;
}
});
Template.memberPopup.helpers({
user: function() {
return Users.findOne(this.userId);
},
memberType: function() {
var type = Users.findOne(this.userId).isBoardAdmin() ? 'admin' : 'normal';
return TAPi18n.__(type).toLowerCase();
}
});
Template.removeMemberPopup.helpers({
user: function() {
return Users.findOne(this.userId)
},
board: function() {
return currentBoard();
}
});
Template.changePermissionsPopup.helpers({
isAdmin: function() {
return this.user.isBoardAdmin();
},
isLastAdmin: function() {
if (! this.user.isBoardAdmin())
return false;
var nbAdmins = _.where(currentBoard().members, { isAdmin: true }).length;
return nbAdmins === 1;
}
});
|
window.onload = function() {
var artwork = document.getElementById("j5-artwork");
if (!artwork) {
return;
}
var original = artwork.firstElementChild;
var payload = artwork.lastElementChild;
var audio = document.createElement("audio");
var sequence = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];
var pressed = [];
payload.srcset = "img/trick-or-treat.png";
payload.classList.add("j5");
if (!artwork) {
return;
}
(function() {
var types = [
"webm",
"mp4",
];
types.forEach(function(type) {
var file = "audio/j5." + type;
var source = document.createElement("source");
source.src = file;
source.type = "audio/" + type;
audio.appendChild(source);
});
window.jaudio = audio;
}());
document.addEventListener("keyup", function(event) {
event.preventDefault();
if (sequence.length > pressed.length) {
pressed.push(event.keyCode);
timeout(1000, reset);
}
if (sequence.length === pressed.length) {
if (isKonami()) {
swap(payload);
} else {
reset();
}
}
}, false);
function isKonami() {
return sequence.toString() === pressed.toString();
}
function reset() {
pressed.length = 0;
}
function swap(show) {
var hide = show === original ? payload : original;
hide.classList.remove("vanishIn");
hide.classList.add("vanishOut");
show.classList.remove("vanishOut");
show.classList.add("vanishIn");
if (show === payload) {
timeout(250, function() {
audio.onended = function() {
reset();
swap(original);
};
console.log(audio);
audio.play();
});
}
}
function timeout(time, callback) {
if (timeout.current) {
clearTimeout(timeout.current);
}
timeout.current = setTimeout(callback, time);
}
};
|
import createRound from '../internal/createRound';
/**
* Calculates `n` rounded up to `precision`.
*
* @static
* @memberOf _
* @category Math
* @param {number} n The number to round up.
* @param {number} [precision=0] The precision to round up to.
* @returns {number} Returns the rounded up number.
* @example
*
* _.ceil(4.006);
* // => 5
*
* _.ceil(6.004, 2);
* // => 6.01
*
* _.ceil(6040, -2);
* // => 6100
*/
var ceil = createRound('ceil');
export default ceil; |
var ChannelModule = require("./module");
var Poll = require("../poll").Poll;
const TYPE_NEW_POLL = {
title: "string",
timeout: "number,optional",
obscured: "boolean",
opts: "array"
};
const TYPE_VOTE = {
option: "number"
};
function PollModule(channel) {
ChannelModule.apply(this, arguments);
this.poll = null;
if (this.channel.modules.chat) {
this.channel.modules.chat.registerCommand("poll", this.handlePollCmd.bind(this, false));
this.channel.modules.chat.registerCommand("hpoll", this.handlePollCmd.bind(this, true));
}
}
PollModule.prototype = Object.create(ChannelModule.prototype);
PollModule.prototype.unload = function () {
if (this.poll && this.poll.timer) {
clearTimeout(this.poll.timer);
}
};
PollModule.prototype.load = function (data) {
if ("poll" in data) {
if (data.poll !== null) {
this.poll = new Poll(data.poll.initiator, "", [], data.poll.obscured);
this.poll.title = data.poll.title;
this.poll.options = data.poll.options;
this.poll.counts = data.poll.counts;
this.poll.votes = data.poll.votes;
}
}
};
PollModule.prototype.save = function (data) {
if (this.poll === null) {
data.poll = null;
return;
}
data.poll = {
title: this.poll.title,
initiator: this.poll.initiator,
options: this.poll.options,
counts: this.poll.counts,
votes: this.poll.votes,
obscured: this.poll.obscured
};
};
PollModule.prototype.onUserPostJoin = function (user) {
this.sendPoll([user]);
user.socket.typecheckedOn("newPoll", TYPE_NEW_POLL, this.handleNewPoll.bind(this, user));
user.socket.typecheckedOn("vote", TYPE_VOTE, this.handleVote.bind(this, user));
user.socket.on("closePoll", this.handleClosePoll.bind(this, user));
};
PollModule.prototype.onUserPart = function(user) {
if (this.poll) {
this.poll.unvote(user.realip);
this.sendPollUpdate(this.channel.users);
}
};
PollModule.prototype.sendPoll = function (users) {
if (!this.poll) {
return;
}
var obscured = this.poll.packUpdate(false);
var unobscured = this.poll.packUpdate(true);
var perms = this.channel.modules.permissions;
users.forEach(function (u) {
u.socket.emit("closePoll");
if (perms.canViewHiddenPoll(u)) {
u.socket.emit("newPoll", unobscured);
} else {
u.socket.emit("newPoll", obscured);
}
});
};
PollModule.prototype.sendPollUpdate = function (users) {
if (!this.poll) {
return;
}
var obscured = this.poll.packUpdate(false);
var unobscured = this.poll.packUpdate(true);
var perms = this.channel.modules.permissions;
users.forEach(function (u) {
if (perms.canViewHiddenPoll(u)) {
u.socket.emit("updatePoll", unobscured);
} else {
u.socket.emit("updatePoll", obscured);
}
});
};
PollModule.prototype.handleNewPoll = function (user, data) {
if (!this.channel.modules.permissions.canControlPoll(user)) {
return;
}
var title = data.title.substring(0, 255);
var opts = data.opts.map(function (x) { return (""+x).substring(0, 255); });
var obscured = data.obscured;
var poll = new Poll(user.getName(), title, opts, obscured);
var self = this;
if (data.hasOwnProperty("timeout") && !isNaN(data.timeout) && data.timeout > 0) {
poll.timer = setTimeout(function () {
if (self.poll === poll) {
self.handleClosePoll({
getName: function () { return "[poll timer]" },
effectiveRank: 255
});
}
}, data.timeout * 1000);
}
this.poll = poll;
this.sendPoll(this.channel.users);
this.channel.logger.log("[poll] " + user.getName() + " opened poll: '" + poll.title + "'");
};
PollModule.prototype.handleVote = function (user, data) {
if (!this.channel.modules.permissions.canVote(user)) {
return;
}
if (this.poll) {
this.poll.vote(user.realip, data.option);
this.sendPollUpdate(this.channel.users);
}
};
PollModule.prototype.handleClosePoll = function (user) {
if (!this.channel.modules.permissions.canControlPoll(user)) {
return;
}
if (this.poll) {
if (this.poll.obscured) {
this.poll.obscured = false;
this.channel.broadcastAll("updatePoll", this.poll.packUpdate(true));
}
if (this.poll.timer) {
clearTimeout(this.poll.timer);
}
this.channel.broadcastAll("closePoll");
this.channel.logger.log("[poll] " + user.getName() + " closed the active poll");
this.poll = null;
}
};
PollModule.prototype.handlePollCmd = function (obscured, user, msg, meta) {
if (!this.channel.modules.permissions.canControlPoll(user)) {
return;
}
msg = msg.replace(/^\/h?poll/, "");
var args = msg.split(",");
var title = args.shift();
var poll = new Poll(user.getName(), title, args, obscured);
this.poll = poll;
this.sendPoll(this.channel.users);
this.channel.logger.log("[poll] " + user.getName() + " opened poll: '" + poll.title + "'");
};
module.exports = PollModule;
|
const {createAddColumnMigration} = require('../../utils');
module.exports = createAddColumnMigration('members_stripe_customers_subscriptions', 'cancellation_reason', {
type: 'string',
maxlength: 500,
nullable: true
});
|
var error = require('./error');
function flattenShallow(array) {
if (!array || !array.reduce) { return array; }
return array.reduce(function(a, b) {
var aIsArray = Array.isArray(a);
var bIsArray = Array.isArray(b);
if (aIsArray && bIsArray ) {
return a.concat(b);
}
if (aIsArray) {
a.push(b);
return a;
}
if (bIsArray) {
return [a].concat(b);
}
return [a, b];
});
}
function isFlat(array) {
if (!array) { return false; }
for (var i = 0; i < array.length; ++i) {
if (Array.isArray(array[i])) {
return false;
}
}
return true;
}
exports.flatten = function() {
var result = exports.argsToArray.apply(null, arguments);
while (!isFlat(result)) {
result = flattenShallow(result);
}
return result;
};
exports.argsToArray = function(args) {
return Array.prototype.slice.call(args, 0);
};
exports.numbers = function() {
var possibleNumbers = this.flatten.apply(null, arguments);
return possibleNumbers.filter(function(el) {
return typeof el === 'number';
});
};
exports.cleanFloat = function(number) {
var power = 1e14;
return Math.round(number * power) / power;
};
exports.parseBool = function(bool) {
if (typeof bool === 'boolean') {
return bool;
}
if (bool instanceof Error) {
return bool;
}
if (typeof bool === 'number') {
return bool !== 0;
}
if (typeof bool === 'string') {
var up = bool.toUpperCase();
if (up === 'TRUE') {
return true;
}
if (up === 'FALSE') {
return false;
}
}
if (bool instanceof Date && !isNaN(bool)) {
return true;
}
return error.value;
};
exports.parseNumber = function(string) {
if (string === undefined || string === '') {
return error.value;
}
if (!isNaN(string)) {
return parseFloat(string);
}
return error.value;
};
exports.parseNumberArray = function(arr) {
var len;
if (!arr || (len = arr.length) === 0) {
return error.value;
}
var parsed;
while (len--) {
parsed = exports.parseNumber(arr[len]);
if (parsed === error.value) {
return parsed;
}
arr[len] = parsed;
}
return arr;
};
exports.parseMatrix = function(matrix) {
var n;
if (!matrix || (n = matrix.length) === 0) {
return error.value;
}
var pnarr;
for (var i = 0; i < matrix.length; i++) {
pnarr = exports.parseNumberArray(matrix[i]);
matrix[i] = pnarr;
if (pnarr instanceof Error) {
return pnarr;
}
}
return matrix;
};
var d1900 = new Date(1900, 0, 1);
exports.parseDate = function(date) {
if (!isNaN(date)) {
if (date instanceof Date) {
return new Date(date);
}
var d = parseInt(date, 10);
if (d < 0) {
return error.num;
}
if (d <= 60) {
return new Date(d1900.getTime() + (d - 1) * 86400000);
}
return new Date(d1900.getTime() + (d - 2) * 86400000);
}
if (typeof date === 'string') {
date = new Date(date);
if (!isNaN(date)) {
return date;
}
}
return error.value;
};
exports.parseDateArray = function(arr) {
var len = arr.length;
var parsed;
while (len--) {
parsed = this.parseDate(arr[len]);
if (parsed === error.value) {
return parsed;
}
arr[len] = parsed;
}
return arr;
};
exports.anyIsError = function() {
var n = arguments.length;
while (n--) {
if (arguments[n] instanceof Error) {
return true;
}
}
return false;
};
exports.arrayValuesToNumbers = function(arr) {
var n = arr.length;
var el;
while (n--) {
el = arr[n];
if (typeof el === 'number') {
continue;
}
if (el === true) {
arr[n] = 1;
continue;
}
if (el === false) {
arr[n] = 0;
continue;
}
if (typeof el === 'string') {
var number = this.parseNumber(el);
if (number instanceof Error) {
arr[n] = 0;
} else {
arr[n] = number;
}
}
}
return arr;
};
exports.rest = function(array, idx) {
idx = idx || 1;
if (!array || typeof array.slice !== 'function') {
return array;
}
return array.slice(idx);
};
exports.initial = function(array, idx) {
idx = idx || 1;
if (!array || typeof array.slice !== 'function') {
return array;
}
return array.slice(0, array.length - idx);
}; |
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'clipboard', 'pl', {
copy: 'Kopiuj',
copyError: 'Ustawienia bezpieczeństwa Twojej przeglądarki nie pozwalają na automatyczne kopiowanie tekstu. Użyj skrótu klawiszowego Ctrl/Cmd+C.',
cut: 'Wytnij',
cutError: 'Ustawienia bezpieczeństwa Twojej przeglądarki nie pozwalają na automatyczne wycinanie tekstu. Użyj skrótu klawiszowego Ctrl/Cmd+X.',
paste: 'Wklej',
pasteArea: 'Obszar wklejania',
pasteMsg: 'Wklej tekst w poniższym polu, używając skrótu klawiaturowego (<STRONG>Ctrl/Cmd+V</STRONG>), i kliknij <STRONG>OK</STRONG>.',
securityMsg: 'Zabezpieczenia przeglądarki uniemożliwiają wklejenie danych bezpośrednio do edytora. Proszę ponownie wkleić dane w tym oknie.',
title: 'Wklej'
} );
|
/**
* @author mrdoob / http://mrdoob.com/
*/
Sidebar.Settings = function ( editor ) {
var config = editor.config;
var signals = editor.signals;
var strings = editor.strings;
var container = new UI.Panel();
container.setBorderTop( '0' );
container.setPaddingTop( '20px' );
container.setPaddingBottom( '20px' );
// language
var options = {
en: 'English',
zh: '中文'
};
var languageRow = new UI.Row();
var language = new UI.Select().setWidth( '150px' );
language.setOptions( options );
if ( config.getKey( 'language' ) !== undefined ) {
language.setValue( config.getKey( 'language' ) );
}
language.onChange( function () {
var value = this.getValue();
editor.config.setKey( 'language', value );
} );
languageRow.add( new UI.Text( strings.getKey( 'sidebar/settings/language' ) ).setWidth( '90px' ) );
languageRow.add( language );
container.add( languageRow );
// theme
var options = {
'css/light.css': strings.getKey( 'sidebar/settings/theme/light' ),
'css/dark.css': strings.getKey( 'sidebar/settings/theme/dark' )
};
var themeRow = new UI.Row();
var theme = new UI.Select().setWidth( '150px' );
theme.setOptions( options );
if ( config.getKey( 'theme' ) !== undefined ) {
theme.setValue( config.getKey( 'theme' ) );
}
theme.onChange( function () {
var value = this.getValue();
editor.setTheme( value );
editor.config.setKey( 'theme', value );
} );
themeRow.add( new UI.Text( strings.getKey( 'sidebar/settings/theme' ) ).setWidth( '90px' ) );
themeRow.add( theme );
container.add( themeRow );
container.add( new Sidebar.Settings.Shortcuts( editor ) );
container.add( new Sidebar.Settings.Viewport( editor ) );
return container;
};
|
tinyMCE.addI18n('no.advhr_dlg',{
width:"Bredde",
size:"Høyde",
noshade:"Ingen skygge"
});
|
import Ember from 'ember';
const a = Ember.A;
export default Ember.Route.extend({
model() {
return {
items: a(['Uno', 'Dos', 'Tres', 'Cuatro', 'Cinco'])
};
},
actions: {
update(newOrder, draggedModel) {
this.set('currentModel.items', a(newOrder));
this.set('currentModel.dragged', draggedModel);
}
}
});
|
module.exports={title:"Databricks",slug:"databricks",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Databricks</title><path d="'+this.path+'"/></svg>'},path:"M.95 14.184L12 20.403l9.919-5.55v2.21L12 22.662l-10.484-5.96-.565.308v.77L12 24l11.05-6.218v-4.317l-.515-.309L12 19.118l-9.867-5.653v-2.21L12 16.805l11.05-6.218V6.32l-.515-.308L12 11.974 2.647 6.681 12 1.388l7.76 4.368.668-.411v-.566L12 0 .95 6.27v.72L12 13.207l9.919-5.55v2.26L12 15.52 1.516 9.56l-.565.308Z",source:"https://www.databricks.com/",hex:"FF3621",guidelines:"https://brand.databricks.com/Styleguide/Guide/",license:void 0}; |
/****************************************************************************
Copyright (c) 2011 Gordon P. Hemsley
http://gphemsley.org/
Copyright (c) 2010-2013 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
cc.TIFFReader = cc.Class.extend({
_littleEndian: false,
_tiffData: null,
_fileDirectories: null,
ctor: function () {
this._fileDirectories = [];
},
getUint8: function (offset) {
return this._tiffData[offset];
},
getUint16: function (offset) {
if (this._littleEndian)
return (this._tiffData[offset + 1] << 8) | (this._tiffData[offset]);
else
return (this._tiffData[offset] << 8) | (this._tiffData[offset + 1]);
},
getUint32: function (offset) {
var a = this._tiffData;
if (this._littleEndian)
return (a[offset + 3] << 24) | (a[offset + 2] << 16) | (a[offset + 1] << 8) | (a[offset]);
else
return (a[offset] << 24) | (a[offset + 1] << 16) | (a[offset + 2] << 8) | (a[offset + 3]);
},
checkLittleEndian: function () {
var BOM = this.getUint16(0);
if (BOM === 0x4949) {
this.littleEndian = true;
} else if (BOM === 0x4D4D) {
this.littleEndian = false;
} else {
console.log(BOM);
throw TypeError("Invalid byte order value.");
}
return this.littleEndian;
},
hasTowel: function () {
// Check for towel.
if (this.getUint16(2) !== 42) {
throw RangeError("You forgot your towel!");
return false;
}
return true;
},
getFieldTypeName: function (fieldType) {
var typeNames = this.fieldTypeNames;
if (fieldType in typeNames) {
return typeNames[fieldType];
}
return null;
},
getFieldTagName: function (fieldTag) {
var tagNames = this.fieldTagNames;
if (fieldTag in tagNames) {
return tagNames[fieldTag];
} else {
console.log("Unknown Field Tag:", fieldTag);
return "Tag" + fieldTag;
}
},
getFieldTypeLength: function (fieldTypeName) {
if (['BYTE', 'ASCII', 'SBYTE', 'UNDEFINED'].indexOf(fieldTypeName) !== -1) {
return 1;
} else if (['SHORT', 'SSHORT'].indexOf(fieldTypeName) !== -1) {
return 2;
} else if (['LONG', 'SLONG', 'FLOAT'].indexOf(fieldTypeName) !== -1) {
return 4;
} else if (['RATIONAL', 'SRATIONAL', 'DOUBLE'].indexOf(fieldTypeName) !== -1) {
return 8;
}
return null;
},
getFieldValues: function (fieldTagName, fieldTypeName, typeCount, valueOffset) {
var fieldValues = [];
var fieldTypeLength = this.getFieldTypeLength(fieldTypeName);
var fieldValueSize = fieldTypeLength * typeCount;
if (fieldValueSize <= 4) {
// The value is stored at the big end of the valueOffset.
if (this.littleEndian === false)
fieldValues.push(valueOffset >>> ((4 - fieldTypeLength) * 8));
else
fieldValues.push(valueOffset);
} else {
for (var i = 0; i < typeCount; i++) {
var indexOffset = fieldTypeLength * i;
if (fieldTypeLength >= 8) {
if (['RATIONAL', 'SRATIONAL'].indexOf(fieldTypeName) !== -1) {
// Numerator
fieldValues.push(this.getUint32(valueOffset + indexOffset));
// Denominator
fieldValues.push(this.getUint32(valueOffset + indexOffset + 4));
} else {
cc.log("Can't handle this field type or size");
}
} else {
fieldValues.push(this.getBytes(fieldTypeLength, valueOffset + indexOffset));
}
}
}
if (fieldTypeName === 'ASCII') {
fieldValues.forEach(function (e, i, a) {
a[i] = String.fromCharCode(e);
});
}
return fieldValues;
},
getBytes: function (numBytes, offset) {
if (numBytes <= 0) {
cc.log("No bytes requested");
} else if (numBytes <= 1) {
return this.getUint8(offset);
} else if (numBytes <= 2) {
return this.getUint16(offset);
} else if (numBytes <= 3) {
return this.getUint32(offset) >>> 8;
} else if (numBytes <= 4) {
return this.getUint32(offset);
} else {
cc.log("Too many bytes requested");
}
},
getBits: function (numBits, byteOffset, bitOffset) {
bitOffset = bitOffset || 0;
var extraBytes = Math.floor(bitOffset / 8);
var newByteOffset = byteOffset + extraBytes;
var totalBits = bitOffset + numBits;
var shiftRight = 32 - numBits;
var shiftLeft,rawBits;
if (totalBits <= 0) {
console.log("No bits requested");
} else if (totalBits <= 8) {
shiftLeft = 24 + bitOffset;
rawBits = this.getUint8(newByteOffset);
} else if (totalBits <= 16) {
shiftLeft = 16 + bitOffset;
rawBits = this.getUint16(newByteOffset);
} else if (totalBits <= 32) {
shiftLeft = bitOffset;
rawBits = this.getUint32(newByteOffset);
} else {
console.log( "Too many bits requested" );
}
return {
'bits': ((rawBits << shiftLeft) >>> shiftRight),
'byteOffset': newByteOffset + Math.floor(totalBits / 8),
'bitOffset': totalBits % 8
};
},
parseFileDirectory: function (byteOffset) {
var numDirEntries = this.getUint16(byteOffset);
var tiffFields = [];
for (var i = byteOffset + 2, entryCount = 0; entryCount < numDirEntries; i += 12, entryCount++) {
var fieldTag = this.getUint16(i);
var fieldType = this.getUint16(i + 2);
var typeCount = this.getUint32(i + 4);
var valueOffset = this.getUint32(i + 8);
var fieldTagName = this.getFieldTagName(fieldTag);
var fieldTypeName = this.getFieldTypeName(fieldType);
var fieldValues = this.getFieldValues(fieldTagName, fieldTypeName, typeCount, valueOffset);
tiffFields[fieldTagName] = { type: fieldTypeName, values: fieldValues };
}
this.fileDirectories.push(tiffFields);
var nextIFDByteOffset = this.getUint32(i);
if (nextIFDByteOffset !== 0x00000000) {
this.parseFileDirectory(nextIFDByteOffset);
}
},
clampColorSample: function(colorSample, bitsPerSample) {
var multiplier = Math.pow(2, 8 - bitsPerSample);
return Math.floor((colorSample * multiplier) + (multiplier - 1));
},
parseTIFF: function (tiffData, canvas) {
canvas = canvas || document.createElement('canvas');
this._tiffData = tiffData;
this.canvas = canvas;
this.checkLittleEndian();
if (!this.hasTowel()) {
return;
}
var firstIFDByteOffset = this.getUint32(4);
this.fileDirectories = [];
this.parseFileDirectory(firstIFDByteOffset);
var fileDirectory = this.fileDirectories[0];
var imageWidth = fileDirectory['ImageWidth'].values[0];
var imageLength = fileDirectory['ImageLength'].values[0];
this.canvas.width = imageWidth;
this.canvas.height = imageLength;
var strips = [];
var compression = (fileDirectory['Compression']) ? fileDirectory['Compression'].values[0] : 1;
var samplesPerPixel = fileDirectory['SamplesPerPixel'].values[0];
var sampleProperties = [];
var bitsPerPixel = 0;
var hasBytesPerPixel = false;
fileDirectory['BitsPerSample'].values.forEach(function (bitsPerSample, i, bitsPerSampleValues) {
sampleProperties[i] = {
'bitsPerSample': bitsPerSample,
'hasBytesPerSample': false,
'bytesPerSample': undefined
};
if ((bitsPerSample % 8) === 0) {
sampleProperties[i].hasBytesPerSample = true;
sampleProperties[i].bytesPerSample = bitsPerSample / 8;
}
bitsPerPixel += bitsPerSample;
}, this);
if ((bitsPerPixel % 8) === 0) {
hasBytesPerPixel = true;
var bytesPerPixel = bitsPerPixel / 8;
}
var stripOffsetValues = fileDirectory['StripOffsets'].values;
var numStripOffsetValues = stripOffsetValues.length;
// StripByteCounts is supposed to be required, but see if we can recover anyway.
if (fileDirectory['StripByteCounts']) {
var stripByteCountValues = fileDirectory['StripByteCounts'].values;
} else {
cc.log("Missing StripByteCounts!");
// Infer StripByteCounts, if possible.
if (numStripOffsetValues === 1) {
var stripByteCountValues = [Math.ceil((imageWidth * imageLength * bitsPerPixel) / 8)];
} else {
throw Error("Cannot recover from missing StripByteCounts");
}
}
// Loop through strips and decompress as necessary.
for (var i = 0; i < numStripOffsetValues; i++) {
var stripOffset = stripOffsetValues[i];
strips[i] = [];
var stripByteCount = stripByteCountValues[i];
// Loop through pixels.
for (var byteOffset = 0, bitOffset = 0, jIncrement = 1, getHeader = true, pixel = [], numBytes = 0, sample = 0, currentSample = 0;
byteOffset < stripByteCount; byteOffset += jIncrement) {
// Decompress strip.
switch (compression) {
// Uncompressed
case 1:
// Loop through samples (sub-pixels).
for (var m = 0, pixel = []; m < samplesPerPixel; m++) {
if (sampleProperties[m].hasBytesPerSample) {
// XXX: This is wrong!
var sampleOffset = sampleProperties[m].bytesPerSample * m;
pixel.push(this.getBytes(sampleProperties[m].bytesPerSample, stripOffset + byteOffset + sampleOffset));
} else {
var sampleInfo = this.getBits(sampleProperties[m].bitsPerSample, stripOffset + byteOffset, bitOffset);
pixel.push(sampleInfo.bits);
byteOffset = sampleInfo.byteOffset - stripOffset;
bitOffset = sampleInfo.bitOffset;
throw RangeError("Cannot handle sub-byte bits per sample");
}
}
strips[i].push(pixel);
if (hasBytesPerPixel) {
jIncrement = bytesPerPixel;
} else {
jIncrement = 0;
throw RangeError("Cannot handle sub-byte bits per pixel");
}
break;
// CITT Group 3 1-Dimensional Modified Huffman run-length encoding
case 2:
// XXX: Use PDF.js code?
break;
// Group 3 Fax
case 3:
// XXX: Use PDF.js code?
break;
// Group 4 Fax
case 4:
// XXX: Use PDF.js code?
break;
// LZW
case 5:
// XXX: Use PDF.js code?
break;
// Old-style JPEG (TIFF 6.0)
case 6:
// XXX: Use PDF.js code?
break;
// New-style JPEG (TIFF Specification Supplement 2)
case 7:
// XXX: Use PDF.js code?
break;
// PackBits
case 32773:
// Are we ready for a new block?
if (getHeader) {
getHeader = false;
var blockLength = 1;
var iterations = 1;
// The header byte is signed.
var header = this.getInt8(stripOffset + byteOffset);
if ((header >= 0) && (header <= 127)) { // Normal pixels.
blockLength = header + 1;
} else if ((header >= -127) && (header <= -1)) { // Collapsed pixels.
iterations = -header + 1;
} else /*if (header === -128)*/ { // Placeholder byte?
getHeader = true;
}
} else {
var currentByte = this.getUint8(stripOffset + byteOffset);
// Duplicate bytes, if necessary.
for (var m = 0; m < iterations; m++) {
if (sampleProperties[sample].hasBytesPerSample) {
// We're reading one byte at a time, so we need to handle multi-byte samples.
currentSample = (currentSample << (8 * numBytes)) | currentByte;
numBytes++;
// Is our sample complete?
if (numBytes === sampleProperties[sample].bytesPerSample) {
pixel.push(currentSample);
currentSample = numBytes = 0;
sample++;
}
} else {
throw RangeError("Cannot handle sub-byte bits per sample");
}
// Is our pixel complete?
if (sample === samplesPerPixel) {
strips[i].push(pixel);
pixel = [];
sample = 0;
}
}
blockLength--;
// Is our block complete?
if (blockLength === 0) {
getHeader = true;
}
}
jIncrement = 1;
break;
// Unknown compression algorithm
default:
// Do not attempt to parse the image data.
break;
}
}
}
if (canvas.getContext) {
var ctx = this.canvas.getContext("2d");
// Set a default fill style.
ctx.fillStyle = "rgba(255, 255, 255, 0)";
// If RowsPerStrip is missing, the whole image is in one strip.
var rowsPerStrip = fileDirectory['RowsPerStrip'] ? fileDirectory['RowsPerStrip'].values[0] : imageLength;
var numStrips = strips.length;
var imageLengthModRowsPerStrip = imageLength % rowsPerStrip;
var rowsInLastStrip = (imageLengthModRowsPerStrip === 0) ? rowsPerStrip : imageLengthModRowsPerStrip;
var numRowsInStrip = rowsPerStrip;
var numRowsInPreviousStrip = 0;
var photometricInterpretation = fileDirectory['PhotometricInterpretation'].values[0];
var extraSamplesValues = [];
var numExtraSamples = 0;
if (fileDirectory['ExtraSamples']) {
extraSamplesValues = fileDirectory['ExtraSamples'].values;
numExtraSamples = extraSamplesValues.length;
}
if (fileDirectory['ColorMap']) {
var colorMapValues = fileDirectory['ColorMap'].values;
var colorMapSampleSize = Math.pow(2, sampleProperties[0].bitsPerSample);
}
// Loop through the strips in the image.
for (var i = 0; i < numStrips; i++) {
// The last strip may be short.
if ((i + 1) === numStrips) {
numRowsInStrip = rowsInLastStrip;
}
var numPixels = strips[i].length;
var yPadding = numRowsInPreviousStrip * i;
// Loop through the rows in the strip.
for (var y = 0, j = 0; y < numRowsInStrip, j < numPixels; y++) {
// Loop through the pixels in the row.
for (var x = 0; x < imageWidth; x++, j++) {
var pixelSamples = strips[i][j];
var red = 0;
var green = 0;
var blue = 0;
var opacity = 1.0;
if (numExtraSamples > 0) {
for (var k = 0; k < numExtraSamples; k++) {
if (extraSamplesValues[k] === 1 || extraSamplesValues[k] === 2) {
// Clamp opacity to the range [0,1].
opacity = pixelSamples[3 + k] / 256;
break;
}
}
}
switch (photometricInterpretation) {
// Bilevel or Grayscale
// WhiteIsZero
case 0:
if (sampleProperties[0].hasBytesPerSample) {
var invertValue = Math.pow(0x10, sampleProperties[0].bytesPerSample * 2);
}
// Invert samples.
pixelSamples.forEach(function (sample, index, samples) {
samples[index] = invertValue - sample;
});
// Bilevel or Grayscale
// BlackIsZero
case 1:
red = green = blue = this.clampColorSample(pixelSamples[0], sampleProperties[0].bitsPerSample);
break;
// RGB Full Color
case 2:
red = this.clampColorSample(pixelSamples[0], sampleProperties[0].bitsPerSample);
green = this.clampColorSample(pixelSamples[1], sampleProperties[1].bitsPerSample);
blue = this.clampColorSample(pixelSamples[2], sampleProperties[2].bitsPerSample);
break;
// RGB Color Palette
case 3:
if (colorMapValues === undefined) {
throw Error("Palette image missing color map");
}
var colorMapIndex = pixelSamples[0];
red = this.clampColorSample(colorMapValues[colorMapIndex], 16);
green = this.clampColorSample(colorMapValues[colorMapSampleSize + colorMapIndex], 16);
blue = this.clampColorSample(colorMapValues[(2 * colorMapSampleSize) + colorMapIndex], 16);
break;
// Unknown Photometric Interpretation
default:
throw RangeError('Unknown Photometric Interpretation:', photometricInterpretation);
break;
}
ctx.fillStyle = "rgba(" + red + ", " + green + ", " + blue + ", " + opacity + ")";
ctx.fillRect(x, yPadding + y, 1, 1);
}
}
numRowsInPreviousStrip = numRowsInStrip;
}
}
return this.canvas;
},
// See: http://www.digitizationguidelines.gov/guidelines/TIFF_Metadata_Final.pdf
// See: http://www.digitalpreservation.gov/formats/content/tiff_tags.shtml
fieldTagNames: {
// TIFF Baseline
0x013B: 'Artist',
0x0102: 'BitsPerSample',
0x0109: 'CellLength',
0x0108: 'CellWidth',
0x0140: 'ColorMap',
0x0103: 'Compression',
0x8298: 'Copyright',
0x0132: 'DateTime',
0x0152: 'ExtraSamples',
0x010A: 'FillOrder',
0x0121: 'FreeByteCounts',
0x0120: 'FreeOffsets',
0x0123: 'GrayResponseCurve',
0x0122: 'GrayResponseUnit',
0x013C: 'HostComputer',
0x010E: 'ImageDescription',
0x0101: 'ImageLength',
0x0100: 'ImageWidth',
0x010F: 'Make',
0x0119: 'MaxSampleValue',
0x0118: 'MinSampleValue',
0x0110: 'Model',
0x00FE: 'NewSubfileType',
0x0112: 'Orientation',
0x0106: 'PhotometricInterpretation',
0x011C: 'PlanarConfiguration',
0x0128: 'ResolutionUnit',
0x0116: 'RowsPerStrip',
0x0115: 'SamplesPerPixel',
0x0131: 'Software',
0x0117: 'StripByteCounts',
0x0111: 'StripOffsets',
0x00FF: 'SubfileType',
0x0107: 'Threshholding',
0x011A: 'XResolution',
0x011B: 'YResolution',
// TIFF Extended
0x0146: 'BadFaxLines',
0x0147: 'CleanFaxData',
0x0157: 'ClipPath',
0x0148: 'ConsecutiveBadFaxLines',
0x01B1: 'Decode',
0x01B2: 'DefaultImageColor',
0x010D: 'DocumentName',
0x0150: 'DotRange',
0x0141: 'HalftoneHints',
0x015A: 'Indexed',
0x015B: 'JPEGTables',
0x011D: 'PageName',
0x0129: 'PageNumber',
0x013D: 'Predictor',
0x013F: 'PrimaryChromaticities',
0x0214: 'ReferenceBlackWhite',
0x0153: 'SampleFormat',
0x022F: 'StripRowCounts',
0x014A: 'SubIFDs',
0x0124: 'T4Options',
0x0125: 'T6Options',
0x0145: 'TileByteCounts',
0x0143: 'TileLength',
0x0144: 'TileOffsets',
0x0142: 'TileWidth',
0x012D: 'TransferFunction',
0x013E: 'WhitePoint',
0x0158: 'XClipPathUnits',
0x011E: 'XPosition',
0x0211: 'YCbCrCoefficients',
0x0213: 'YCbCrPositioning',
0x0212: 'YCbCrSubSampling',
0x0159: 'YClipPathUnits',
0x011F: 'YPosition',
// EXIF
0x9202: 'ApertureValue',
0xA001: 'ColorSpace',
0x9004: 'DateTimeDigitized',
0x9003: 'DateTimeOriginal',
0x8769: 'Exif IFD',
0x9000: 'ExifVersion',
0x829A: 'ExposureTime',
0xA300: 'FileSource',
0x9209: 'Flash',
0xA000: 'FlashpixVersion',
0x829D: 'FNumber',
0xA420: 'ImageUniqueID',
0x9208: 'LightSource',
0x927C: 'MakerNote',
0x9201: 'ShutterSpeedValue',
0x9286: 'UserComment',
// IPTC
0x83BB: 'IPTC',
// ICC
0x8773: 'ICC Profile',
// XMP
0x02BC: 'XMP',
// GDAL
0xA480: 'GDAL_METADATA',
0xA481: 'GDAL_NODATA',
// Photoshop
0x8649: 'Photoshop'
},
fieldTypeNames: {
0x0001: 'BYTE',
0x0002: 'ASCII',
0x0003: 'SHORT',
0x0004: 'LONG',
0x0005: 'RATIONAL',
0x0006: 'SBYTE',
0x0007: 'UNDEFINED',
0x0008: 'SSHORT',
0x0009: 'SLONG',
0x000A: 'SRATIONAL',
0x000B: 'FLOAT',
0x000C: 'DOUBLE'
}
});
cc.TIFFReader.__instance = null;
cc.TIFFReader.getInstance = function () {
if (!cc.TIFFReader.__instance)
cc.TIFFReader.__instance = new cc.TIFFReader();
return cc.TIFFReader.__instance;
};
|
module.exports={title:"Crystal",slug:"crystal",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Crystal</title><path d="'+this.path+'"/></svg>'},path:"M23.964 15.266l-8.687 8.669c-.034.035-.086.052-.121.035L3.29 20.79c-.052-.017-.087-.052-.087-.086L.007 8.856c-.018-.053 0-.087.035-.122L8.728.065c.035-.035.087-.052.121-.035l11.866 3.18c.052.017.087.052.087.086l3.18 11.848c.034.053.016.087-.018.122zm-11.64-9.433L.667 8.943c-.017 0-.035.034-.017.052l8.53 8.512c.017.017.052.017.052-.017l3.127-11.64c.017 0-.018-.035-.035-.017Z",source:"https://crystal-lang.org/media/",hex:"000000",guidelines:void 0,license:void 0}; |
angular.module('ui.bootstrap.position', [])
/**
* A set of utility methods that can be use to retrieve position of DOM elements.
* It is meant to be used where we need to absolute-position DOM elements in
* relation to other, existing elements (this is the case for tooltips, popovers,
* typeahead suggestions etc.).
*/
.factory('$position', ['$document', '$window', function ($document, $window) {
var mouseX, mouseY;
$document.bind('mousemove', function mouseMoved(event) {
mouseX = event.pageX;
mouseY = event.pageY;
});
function getStyle(el, cssprop) {
if (el.currentStyle) { //IE
return el.currentStyle[cssprop];
} else if ($window.getComputedStyle) {
return $window.getComputedStyle(el)[cssprop];
}
// finally try and get inline style
return el.style[cssprop];
}
/**
* Checks if a given element is statically positioned
* @param element - raw DOM element
*/
function isStaticPositioned(element) {
return (getStyle(element, "position") || 'static' ) === 'static';
}
/**
* returns the closest, non-statically positioned parentOffset of a given element
* @param element
*/
var parentOffsetEl = function (element) {
var docDomEl = $document[0];
var offsetParent = element.offsetParent || docDomEl;
while (offsetParent && offsetParent !== docDomEl && isStaticPositioned(offsetParent) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docDomEl;
};
return {
/**
* Provides read-only equivalent of jQuery's position function:
* http://api.jquery.com/position/
*/
position: function (element) {
var elBCR = this.offset(element);
var offsetParentBCR = { top: 0, left: 0 };
var offsetParentEl = parentOffsetEl(element[0]);
if (offsetParentEl != $document[0]) {
offsetParentBCR = this.offset(angular.element(offsetParentEl));
offsetParentBCR.top += offsetParentEl.clientTop;
offsetParentBCR.left += offsetParentEl.clientLeft;
}
return {
width: element.prop('offsetWidth'),
height: element.prop('offsetHeight'),
top: elBCR.top - offsetParentBCR.top,
left: elBCR.left - offsetParentBCR.left
};
},
/**
* Provides read-only equivalent of jQuery's offset function:
* http://api.jquery.com/offset/
*/
offset: function (element) {
var boundingClientRect = element[0].getBoundingClientRect();
return {
width: element.prop('offsetWidth'),
height: element.prop('offsetHeight'),
top: boundingClientRect.top + ($window.pageYOffset || $document[0].body.scrollTop),
left: boundingClientRect.left + ($window.pageXOffset || $document[0].body.scrollLeft)
};
},
/**
* Provides the coordinates of the mouse
*/
mouse: function () {
return {x: mouseX, y: mouseY};
}
};
}]);
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
(function(global) {
global.ng = global.ng || {};
global.ng.common = global.ng.common || {};
global.ng.common.locales = global.ng.common.locales || {};
const u = undefined;
function plural(n) {
let i = Math.floor(Math.abs(n));
if (i === 0 || i === 1) return 1;
return 5;
}
global.ng.common.locales['fr-mq'] = [
'fr-MQ',
[['AM', 'PM'], u, u],
u,
[
['D', 'L', 'M', 'M', 'J', 'V', 'S'], ['dim.', 'lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.'],
['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'],
['di', 'lu', 'ma', 'me', 'je', 've', 'sa']
],
u,
[
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
[
'janv.', 'févr.', 'mars', 'avr.', 'mai', 'juin', 'juil.', 'août', 'sept.', 'oct.', 'nov.',
'déc.'
],
[
'janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre',
'octobre', 'novembre', 'décembre'
]
],
u,
[['av. J.-C.', 'ap. J.-C.'], u, ['avant Jésus-Christ', 'après Jésus-Christ']],
1,
[6, 0],
['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE d MMMM y'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'],
['{1} {0}', '{1} \'à\' {0}', u, u],
[',', '\u202f', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0 %', '#,##0.00 ¤', '#E0'],
'EUR',
'€',
'euro',
{
'ARS': ['$AR', '$'],
'AUD': ['$AU', '$'],
'BEF': ['FB'],
'BMD': ['$BM', '$'],
'BND': ['$BN', '$'],
'BZD': ['$BZ', '$'],
'CAD': ['$CA', '$'],
'CLP': ['$CL', '$'],
'CNY': [u, '¥'],
'COP': ['$CO', '$'],
'CYP': ['£CY'],
'EGP': [u, '£E'],
'FJD': ['$FJ', '$'],
'FKP': ['£FK', '£'],
'FRF': ['F'],
'GBP': ['£GB', '£'],
'GIP': ['£GI', '£'],
'HKD': [u, '$'],
'IEP': ['£IE'],
'ILP': ['£IL'],
'ITL': ['₤IT'],
'JPY': [u, '¥'],
'KMF': [u, 'FC'],
'LBP': ['£LB', '£L'],
'MTP': ['£MT'],
'MXN': ['$MX', '$'],
'NAD': ['$NA', '$'],
'NIO': [u, '$C'],
'NZD': ['$NZ', '$'],
'RHD': ['$RH'],
'RON': [u, 'L'],
'RWF': [u, 'FR'],
'SBD': ['$SB', '$'],
'SGD': ['$SG', '$'],
'SRD': ['$SR', '$'],
'TOP': [u, '$T'],
'TTD': ['$TT', '$'],
'TWD': [u, 'NT$'],
'USD': ['$US', '$'],
'UYU': ['$UY', '$'],
'WST': ['$WS'],
'XCD': [u, '$'],
'XPF': ['FCFP'],
'ZMW': [u, 'Kw']
},
'ltr',
plural,
[
[
['minuit', 'midi', 'mat.', 'ap.m.', 'soir', 'nuit'], u,
['minuit', 'midi', 'du matin', 'de l’après-midi', 'du soir', 'du matin']
],
[
['minuit', 'midi', 'mat.', 'ap.m.', 'soir', 'nuit'], u,
['minuit', 'midi', 'matin', 'après-midi', 'soir', 'nuit']
],
[
'00:00', '12:00', ['04:00', '12:00'], ['12:00', '18:00'], ['18:00', '24:00'],
['00:00', '04:00']
]
]
];
})(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global ||
typeof window !== 'undefined' && window);
|
/**
* @file 命令相关配置项目,用来配置命令执行前或者执行后的动作
* @author mengke01(kekee000@gmail.com)
*/
define(
function (require) {
// 支持历史记录的命令列表
var supportHistory = {
alignshapes: true,
verticalalignshapes: true,
horizontalalignshapes: true,
joinshapes: true,
intersectshapes: true,
tangencyshapes: true,
splitshapes: true,
removeshapes: true,
reversepoints: true,
topshape: true,
bottomshape: true,
upshape: true,
downshape: true,
cutshapes: true,
pasteshapes: true,
addshapes: true,
rotateleft: true,
rotateright: true,
flipshapes: true,
mirrorshapes: true
};
return {
history: supportHistory
};
}
);
|
import { settings } from '../../../settings';
settings.addGroup('Webdav Integration', function() {
this.add('Webdav_Integration_Enabled', false, {
type: 'boolean',
public: true,
});
});
|
var key_2_s = function( p ) {
var x = 20;
p.setup = function() {
p.createCanvas(100, 100);
p.strokeWeight(4);
}
p.draw = function() {
p.background(204);
if (p.keyIsPressed == true) { // If the key is pressed
x++; // add 1 to x
}
p.line(x, 20, x-60, 80);
}
};
var key_2 = new p5(key_2_s, 'key_2'); |
import Vue from 'vue';
const manager = new Vue({
data() {
return {
current: null
};
}
});
export default manager;
|
import { useMemo } from 'react';
import { DropTargetMonitorImpl } from '../../internals';
import { useDragDropManager } from '../useDragDropManager';
export function useDropTargetMonitor() {
var manager = useDragDropManager();
return useMemo(function () {
return new DropTargetMonitorImpl(manager);
}, [manager]);
} |
"use strict";
module.exports = require("./is-implemented")()
? Math.sinh
: require("./shim");
|
// Load modules
var Http = require('http');
var Stream = require('stream');
var Bluebird = require('bluebird');
var Boom = require('boom');
var Code = require('code');
var Hapi = require('..');
var Hoek = require('hoek');
var Lab = require('lab');
// Declare internals
var internals = {};
// Test shortcuts
var lab = exports.lab = Lab.script();
var describe = lab.describe;
var it = lab.it;
var expect = Code.expect;
describe('Reply', function () {
it('throws when reply called twice', function (done) {
var handler = function (request, reply) {
reply('ok'); return reply('not ok');
};
var server = new Hapi.Server({ debug: false });
server.connection();
server.route({ method: 'GET', path: '/', handler: handler });
server.inject('/', function (res) {
expect(res.statusCode).to.equal(500);
done();
});
});
it('redirects from handler', function (done) {
var handler = function (request, reply) {
return reply.redirect('/elsewhere');
};
var server = new Hapi.Server();
server.connection();
server.route({ method: 'GET', path: '/', handler: handler });
server.inject('/', function (res) {
expect(res.statusCode).to.equal(302);
expect(res.headers.location).to.equal('/elsewhere');
done();
});
});
describe('interface()', function () {
it('uses reply(null, result) for result', function (done) {
var handler = function (request, reply) {
return reply(null, 'steve');
};
var server = new Hapi.Server();
server.connection();
server.route({ method: 'GET', path: '/', handler: handler });
server.inject('/', function (res) {
expect(res.statusCode).to.equal(200);
expect(res.result).to.equal('steve');
done();
});
});
it('uses reply(null, err) for err', function (done) {
var handler = function (request, reply) {
return reply(null, Boom.badRequest());
};
var server = new Hapi.Server();
server.connection();
server.route({ method: 'GET', path: '/', handler: handler });
server.inject('/', function (res) {
expect(res.statusCode).to.equal(400);
done();
});
});
it('ignores result when err provided in reply(err, result)', function (done) {
var handler = function (request, reply) {
return reply(Boom.badRequest(), 'steve');
};
var server = new Hapi.Server();
server.connection();
server.route({ method: 'GET', path: '/', handler: handler });
server.inject('/', function (res) {
expect(res.statusCode).to.equal(400);
done();
});
});
it('skips decorations on minimal server', function (done) {
var handler = function (request, reply) {
return reply(reply.view === undefined);
};
var server = new Hapi.Server({ minimal: true });
server.connection();
server.route({ method: 'GET', path: '/', handler: handler });
server.inject('/', function (res) {
expect(res.result).to.equal(true);
done();
});
});
});
describe('response()', function () {
it('returns null', function (done) {
var handler = function (request, reply) {
return reply(null, null);
};
var server = new Hapi.Server();
server.connection();
server.route({ method: 'GET', path: '/', handler: handler });
server.inject('/', function (res) {
expect(res.statusCode).to.equal(200);
expect(res.result).to.equal(null);
expect(res.payload).to.equal('');
expect(res.headers['content-type']).to.not.exist();
done();
});
});
it('returns a buffer reply', function (done) {
var handler = function (request, reply) {
return reply(new Buffer('Tada1')).code(299);
};
var server = new Hapi.Server();
server.connection();
server.route({ method: 'GET', path: '/', config: { handler: handler } });
server.inject('/', function (res) {
expect(res.statusCode).to.equal(299);
expect(res.result).to.equal('Tada1');
expect(res.headers['content-type']).to.equal('application/octet-stream');
done();
});
});
it('returns an object response', function (done) {
var handler = function (request, reply) {
return reply({ a: 1, b: 2 });
};
var server = new Hapi.Server();
server.connection();
server.route({ method: 'GET', path: '/', handler: handler });
server.inject('/', function (res) {
expect(res.payload).to.equal('{\"a\":1,\"b\":2}');
expect(res.headers['content-length']).to.equal(13);
done();
});
});
it('returns false', function (done) {
var handler = function (request, reply) {
return reply(false);
};
var server = new Hapi.Server();
server.connection();
server.route({ method: 'GET', path: '/', handler: handler });
server.inject('/', function (res) {
expect(res.payload).to.equal('false');
done();
});
});
it('returns an error reply', function (done) {
var handler = function (request, reply) {
return reply(new Error('boom'));
};
var server = new Hapi.Server({ debug: false });
server.connection();
server.route({ method: 'GET', path: '/', handler: handler });
server.inject('/', function (res) {
expect(res.statusCode).to.equal(500);
expect(res.result).to.exist();
done();
});
});
it('returns an empty reply', function (done) {
var handler = function (request, reply) {
return reply().code(299);
};
var server = new Hapi.Server();
server.connection({ routes: { cors: { credentials: true } } });
server.route({ method: 'GET', path: '/', handler: handler });
server.inject('/', function (res) {
expect(res.statusCode).to.equal(299);
expect(res.result).to.equal(null);
expect(res.headers['access-control-allow-credentials']).to.equal('true');
done();
});
});
it('returns a stream reply', function (done) {
var TestStream = function () {
Stream.Readable.call(this);
};
Hoek.inherits(TestStream, Stream.Readable);
TestStream.prototype._read = function (size) {
if (this.isDone) {
return;
}
this.isDone = true;
this.push('x');
this.push('y');
this.push(null);
};
var handler = function (request, reply) {
return reply(new TestStream()).ttl(2000);
};
var server = new Hapi.Server();
server.connection({ routes: { cors: { origin: ['test.example.com'] } } });
server.route({ method: 'GET', path: '/stream', config: { handler: handler, cache: { expiresIn: 9999 } } });
server.inject('/stream', function (res) {
expect(res.result).to.equal('xy');
expect(res.statusCode).to.equal(200);
expect(res.headers['cache-control']).to.equal('max-age=2, must-revalidate');
expect(res.headers['access-control-allow-origin']).to.equal('test.example.com');
server.inject({ method: 'HEAD', url: '/stream' }, function (res) {
expect(res.result).to.equal('');
expect(res.statusCode).to.equal(200);
expect(res.headers['cache-control']).to.equal('max-age=2, must-revalidate');
expect(res.headers['access-control-allow-origin']).to.equal('test.example.com');
done();
});
});
});
it('errors on non-readable stream reply', function (done) {
var streamHandler = function (request, reply) {
var stream = new Stream();
stream.writable = true;
reply(stream);
};
var writableHandler = function (request, reply) {
var writable = new Stream.Writable();
writable._write = function () {};
reply(writable);
};
var server = new Hapi.Server({ debug: false });
server.connection();
server.route({ method: 'GET', path: '/stream', handler: streamHandler });
server.route({ method: 'GET', path: '/writable', handler: writableHandler });
var requestError;
server.on('request-error', function (request, err) {
requestError = err;
});
server.start(function () {
server.inject('/stream', function (res) {
expect(res.statusCode).to.equal(500);
expect(requestError).to.exist();
expect(requestError.message).to.equal('Stream must have a streams2 readable interface');
requestError = undefined;
server.inject('/writable', function (res) {
expect(res.statusCode).to.equal(500);
expect(requestError).to.exist();
expect(requestError.message).to.equal('Stream must have a streams2 readable interface');
done();
});
});
});
});
it('errors on an http client stream reply', function (done) {
var handler = function (request, reply) {
reply('just a string');
};
var streamHandler = function (request, reply) {
reply(Http.get(request.server.info + '/'));
};
var server = new Hapi.Server({ debug: false });
server.connection();
server.route({ method: 'GET', path: '/', handler: handler });
server.route({ method: 'GET', path: '/stream', handler: streamHandler });
server.start(function () {
server.inject('/stream', function (res) {
expect(res.statusCode).to.equal(500);
done();
});
});
});
it('errors on objectMode stream reply', function (done) {
var TestStream = function () {
Stream.Readable.call(this, { objectMode: true });
};
Hoek.inherits(TestStream, Stream.Readable);
TestStream.prototype._read = function (size) {
if (this.isDone) {
return;
}
this.isDone = true;
this.push({ x: 1 });
this.push({ y: 1 });
this.push(null);
};
var handler = function (request, reply) {
return reply(new TestStream());
};
var server = new Hapi.Server({ debug: false });
server.connection();
server.route({ method: 'GET', path: '/', handler: handler });
server.inject('/', function (res) {
expect(res.statusCode).to.equal(500);
done();
});
});
describe('promises', function () {
it('returns a stream', function (done) {
var TestStream = function () {
Stream.Readable.call(this);
this.statusCode = 200;
};
Hoek.inherits(TestStream, Stream.Readable);
TestStream.prototype._read = function (size) {
if (this.isDone) {
return;
}
this.isDone = true;
this.push('x');
this.push('y');
this.push(null);
};
var handler = function (request, reply) {
return reply(Bluebird.resolve(new TestStream())).ttl(2000).code(299);
};
var server = new Hapi.Server({ debug: false });
server.connection({ routes: { cors: { origin: ['test.example.com'] } } });
server.route({ method: 'GET', path: '/stream', config: { handler: handler, cache: { expiresIn: 9999 } } });
server.inject('/stream', function (res) {
expect(res.result).to.equal('xy');
expect(res.statusCode).to.equal(299);
expect(res.headers['cache-control']).to.equal('max-age=2, must-revalidate');
expect(res.headers['access-control-allow-origin']).to.equal('test.example.com');
done();
});
});
it('returns a buffer', function (done) {
var handler = function (request, reply) {
return reply(Bluebird.resolve(new Buffer('buffer content'))).code(299).type('something/special');
};
var server = new Hapi.Server();
server.connection();
server.route({ method: 'GET', path: '/', handler: handler });
server.inject('/', function (res) {
expect(res.statusCode).to.equal(299);
expect(res.result.toString()).to.equal('buffer content');
expect(res.headers['content-type']).to.equal('something/special');
done();
});
});
});
});
describe('hold()', function () {
it('undo scheduled next tick in reply interface', function (done) {
var server = new Hapi.Server();
server.connection();
var handler = function (request, reply) {
return reply('123').hold().send();
};
server.route({ method: 'GET', path: '/domain', handler: handler });
server.inject('/domain', function (res) {
expect(res.result).to.equal('123');
done();
});
});
it('sends reply after timed handler', function (done) {
var server = new Hapi.Server();
server.connection();
var handler = function (request, reply) {
var response = reply('123').hold();
setTimeout(function () {
response.send();
}, 10);
};
server.route({ method: 'GET', path: '/domain', handler: handler });
server.inject('/domain', function (res) {
expect(res.result).to.equal('123');
done();
});
});
});
describe('close()', function () {
it('returns a reply with manual end', function (done) {
var handler = function (request, reply) {
request.raw.res.end();
return reply.close({ end: false });
};
var server = new Hapi.Server();
server.connection();
server.route({ method: 'GET', path: '/', config: { handler: handler } });
server.inject('/', function (res) {
expect(res.result).to.equal('');
done();
});
});
it('returns a reply with auto end', function (done) {
var handler = function (request, reply) {
return reply.close();
};
var server = new Hapi.Server();
server.connection();
server.route({ method: 'GET', path: '/', config: { handler: handler } });
server.inject('/', function (res) {
expect(res.result).to.equal('');
done();
});
});
});
describe('continue()', function () {
it('sets empty reply on continue in handler', function (done) {
var handler = function (request, reply) {
return reply.continue();
};
var server = new Hapi.Server();
server.connection();
server.route({ method: 'GET', path: '/', config: { handler: handler } });
server.inject('/', function (res) {
expect(res.statusCode).to.equal(200);
expect(res.result).to.equal(null);
expect(res.payload).to.equal('');
done();
});
});
it('sets empty reply on continue in prerequisite', function (done) {
var pre1 = function (request, reply) {
return reply.continue();
};
var pre2 = function (request, reply) {
return reply.continue();
};
var pre3 = function (request, reply) {
return reply({
m1: request.pre.m1,
m2: request.pre.m2
});
};
var handler = function (request, reply) {
return reply(request.pre.m3);
};
var server = new Hapi.Server();
server.connection();
server.route({
method: 'GET',
path: '/',
config: {
pre: [
{ method: pre1, assign: 'm1' },
{ method: pre2, assign: 'm2' },
{ method: pre3, assign: 'm3' }
],
handler: handler
}
});
server.inject('/', function (res) {
expect(res.statusCode).to.equal(200);
expect(res.result).to.deep.equal({
m1: null,
m2: null
});
expect(res.payload).to.equal('{"m1":null,"m2":null}');
done();
});
});
});
});
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {PriorityLevel} from './SchedulerPriorities';
import {enableProfiling} from './SchedulerFeatureFlags';
import {NoPriority} from './SchedulerPriorities';
let runIdCounter: number = 0;
let mainThreadIdCounter: number = 0;
const profilingStateSize = 4;
export const sharedProfilingBuffer = enableProfiling
? // $FlowFixMe Flow doesn't know about SharedArrayBuffer
typeof SharedArrayBuffer === 'function'
? new SharedArrayBuffer(profilingStateSize * Int32Array.BYTES_PER_ELEMENT)
: // $FlowFixMe Flow doesn't know about ArrayBuffer
typeof ArrayBuffer === 'function'
? new ArrayBuffer(profilingStateSize * Int32Array.BYTES_PER_ELEMENT)
: null // Don't crash the init path on IE9
: null;
const profilingState =
enableProfiling && sharedProfilingBuffer !== null
? new Int32Array(sharedProfilingBuffer)
: []; // We can't read this but it helps save bytes for null checks
const PRIORITY = 0;
const CURRENT_TASK_ID = 1;
const CURRENT_RUN_ID = 2;
const QUEUE_SIZE = 3;
if (enableProfiling) {
profilingState[PRIORITY] = NoPriority;
// This is maintained with a counter, because the size of the priority queue
// array might include canceled tasks.
profilingState[QUEUE_SIZE] = 0;
profilingState[CURRENT_TASK_ID] = 0;
}
// Bytes per element is 4
const INITIAL_EVENT_LOG_SIZE = 131072;
const MAX_EVENT_LOG_SIZE = 524288; // Equivalent to 2 megabytes
let eventLogSize = 0;
let eventLogBuffer = null;
let eventLog = null;
let eventLogIndex = 0;
const TaskStartEvent = 1;
const TaskCompleteEvent = 2;
const TaskErrorEvent = 3;
const TaskCancelEvent = 4;
const TaskRunEvent = 5;
const TaskYieldEvent = 6;
const SchedulerSuspendEvent = 7;
const SchedulerResumeEvent = 8;
function logEvent(entries) {
if (eventLog !== null) {
const offset = eventLogIndex;
eventLogIndex += entries.length;
if (eventLogIndex + 1 > eventLogSize) {
eventLogSize *= 2;
if (eventLogSize > MAX_EVENT_LOG_SIZE) {
// Using console['error'] to evade Babel and ESLint
console['error'](
"Scheduler Profiling: Event log exceeded maximum size. Don't " +
'forget to call `stopLoggingProfilingEvents()`.',
);
stopLoggingProfilingEvents();
return;
}
const newEventLog = new Int32Array(eventLogSize * 4);
newEventLog.set(eventLog);
eventLogBuffer = newEventLog.buffer;
eventLog = newEventLog;
}
eventLog.set(entries, offset);
}
}
export function startLoggingProfilingEvents(): void {
eventLogSize = INITIAL_EVENT_LOG_SIZE;
eventLogBuffer = new ArrayBuffer(eventLogSize * 4);
eventLog = new Int32Array(eventLogBuffer);
eventLogIndex = 0;
}
export function stopLoggingProfilingEvents(): ArrayBuffer | null {
const buffer = eventLogBuffer;
eventLogSize = 0;
eventLogBuffer = null;
eventLog = null;
eventLogIndex = 0;
return buffer;
}
export function markTaskStart(
task: {
id: number,
priorityLevel: PriorityLevel,
...
},
ms: number,
) {
if (enableProfiling) {
profilingState[QUEUE_SIZE]++;
if (eventLog !== null) {
// performance.now returns a float, representing milliseconds. When the
// event is logged, it's coerced to an int. Convert to microseconds to
// maintain extra degrees of precision.
logEvent([TaskStartEvent, ms * 1000, task.id, task.priorityLevel]);
}
}
}
export function markTaskCompleted(
task: {
id: number,
priorityLevel: PriorityLevel,
...
},
ms: number,
) {
if (enableProfiling) {
profilingState[PRIORITY] = NoPriority;
profilingState[CURRENT_TASK_ID] = 0;
profilingState[QUEUE_SIZE]--;
if (eventLog !== null) {
logEvent([TaskCompleteEvent, ms * 1000, task.id]);
}
}
}
export function markTaskCanceled(
task: {
id: number,
priorityLevel: PriorityLevel,
...
},
ms: number,
) {
if (enableProfiling) {
profilingState[QUEUE_SIZE]--;
if (eventLog !== null) {
logEvent([TaskCancelEvent, ms * 1000, task.id]);
}
}
}
export function markTaskErrored(
task: {
id: number,
priorityLevel: PriorityLevel,
...
},
ms: number,
) {
if (enableProfiling) {
profilingState[PRIORITY] = NoPriority;
profilingState[CURRENT_TASK_ID] = 0;
profilingState[QUEUE_SIZE]--;
if (eventLog !== null) {
logEvent([TaskErrorEvent, ms * 1000, task.id]);
}
}
}
export function markTaskRun(
task: {
id: number,
priorityLevel: PriorityLevel,
...
},
ms: number,
) {
if (enableProfiling) {
runIdCounter++;
profilingState[PRIORITY] = task.priorityLevel;
profilingState[CURRENT_TASK_ID] = task.id;
profilingState[CURRENT_RUN_ID] = runIdCounter;
if (eventLog !== null) {
logEvent([TaskRunEvent, ms * 1000, task.id, runIdCounter]);
}
}
}
export function markTaskYield(task: {id: number, ...}, ms: number) {
if (enableProfiling) {
profilingState[PRIORITY] = NoPriority;
profilingState[CURRENT_TASK_ID] = 0;
profilingState[CURRENT_RUN_ID] = 0;
if (eventLog !== null) {
logEvent([TaskYieldEvent, ms * 1000, task.id, runIdCounter]);
}
}
}
export function markSchedulerSuspended(ms: number) {
if (enableProfiling) {
mainThreadIdCounter++;
if (eventLog !== null) {
logEvent([SchedulerSuspendEvent, ms * 1000, mainThreadIdCounter]);
}
}
}
export function markSchedulerUnsuspended(ms: number) {
if (enableProfiling) {
if (eventLog !== null) {
logEvent([SchedulerResumeEvent, ms * 1000, mainThreadIdCounter]);
}
}
}
|
'use strict';
const stringUtil = require('ember-cli-string-utils');
module.exports = {
description: 'Generates an Ember application with a module unification layout.',
filesToRemove: [],
locals(options) {
let entity = options.entity;
let rawName = entity.name;
let name = stringUtil.dasherize(rawName);
let namespace = stringUtil.classify(rawName);
return {
name,
modulePrefix: name,
namespace,
emberCLIVersion: require('../../package').version,
yarn: options.yarn,
welcome: options.welcome,
};
},
fileMapTokens(options) {
return {
__component__() { return options.locals.component; },
};
},
};
|
// @noflow
var x: string = 123;
|
/*
Language: VBScript in HTML
Requires: xml.js, vbscript.js
Author: Ivan Sagalaev <maniac@softwaremaniacs.org>
Description: "Bridge" language defining fragments of VBScript in HTML within <% .. %>
Website: https://en.wikipedia.org/wiki/VBScript
Category: scripting
*/
function vbscriptHtml(hljs) {
return {
name: 'VBScript in HTML',
subLanguage: 'xml',
contains: [
{
begin: '<%',
end: '%>',
subLanguage: 'vbscript'
}
]
};
}
module.exports = vbscriptHtml;
|
const path = require('path');
module.exports = {
entry: {
client1: './src/client1.js',
client2: './src/client2.js',
client3: './src/client3.js',
client4: './src/client4.js'
},
output: {
path: path.resolve(__dirname, '../public'),
filename: '[name].bundle.js'
}
};
|
// 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.
// Copyright 2007 Google Inc. All Rights Reserved.
/**
* @fileoverview DOM pattern to match a tag and all of its children.
*
*/
goog.provide('goog.dom.pattern.Repeat');
goog.require('goog.dom.NodeType');
goog.require('goog.dom.pattern.AbstractPattern');
goog.require('goog.dom.pattern.MatchType');
/**
* Pattern object that matches a repetition of another pattern.
* @param {goog.dom.pattern.AbstractPattern} pattern The pattern to
* repetitively match.
* @param {number} opt_minimum The minimum number of times to match. Defaults
* to 0.
* @param {number} opt_maximum The maximum number of times to match. Defaults
* to unlimited.
* @constructor
* @extends {goog.dom.pattern.AbstractPattern}
*/
goog.dom.pattern.Repeat = function(pattern,
opt_minimum,
opt_maximum) {
this.pattern_ = pattern;
this.minimum_ = opt_minimum || 0;
this.maximum_ = opt_maximum || null;
this.matches = [];
};
goog.inherits(goog.dom.pattern.Repeat, goog.dom.pattern.AbstractPattern);
/**
* Pattern to repetitively match.
*
* @type {goog.dom.pattern.AbstractPattern}
* @private
*/
goog.dom.pattern.Repeat.prototype.pattern_;
/**
* Minimum number of times to match the pattern.
*
* @private
*/
goog.dom.pattern.Repeat.prototype.minimum_ = 0;
/**
* Optional maximum number of times to match the pattern. A {@code null} value
* will be treated as infinity.
*
* @type {number?}
* @private
*/
goog.dom.pattern.Repeat.prototype.maximum_ = 0;
/**
* Number of times the pattern has matched.
*
* @type {number}
*/
goog.dom.pattern.Repeat.prototype.count = 0;
/**
* Whether the pattern has recently matched or failed to match and will need to
* be reset when starting a new round of matches.
*
* @type {boolean}
* @private
*/
goog.dom.pattern.Repeat.prototype.needsReset_ = false;
/**
* The matched nodes.
*
* @type {Array.<Node>}
*/
goog.dom.pattern.Repeat.prototype.matches;
/**
* Test whether the given token continues a repeated series of matches of the
* pattern given in the constructor.
*
* @param {Node} token Token to match against.
* @param {goog.dom.TagWalkType} type The type of token.
* @return {goog.dom.pattern.MatchType} <code>MATCH</code> if the pattern
* matches, <code>BACKTRACK_MATCH</code> if the pattern does not match
* but already had accumulated matches, <code>MATCHING</code> if the pattern
* starts a match, and <code>NO_MATCH</code> if the pattern does not match.
*/
goog.dom.pattern.Repeat.prototype.matchToken = function(token, type) {
// Reset if we're starting a new match
if (this.needsReset_) {
this.reset();
}
// If the option is set, ignore any whitespace only text nodes
if (token.nodeType == goog.dom.NodeType.TEXT &&
token.nodeValue.match(/^\s+$/)) {
return goog.dom.pattern.MatchType.MATCHING;
}
switch (this.pattern_.matchToken(token, type)) {
case goog.dom.pattern.MatchType.MATCH:
// Record the first token we match.
if (this.count == 0) {
this.matchedNode = token;
}
// Mark the match
this.count++;
// Add to the list
this.matches.push(this.pattern_.matchedNode);
// Check if this match hits our maximum
if (this.maximum_ !== null && this.count == this.maximum_) {
this.needsReset_ = true;
return goog.dom.pattern.MatchType.MATCH;
} else {
return goog.dom.pattern.MatchType.MATCHING;
}
case goog.dom.pattern.MatchType.MATCHING:
// This can happen when our child pattern is a sequence or a repetition.
return goog.dom.pattern.MatchType.MATCHING;
case goog.dom.pattern.MatchType.BACKTRACK_MATCH:
// This happens if our child pattern is repetitive too.
// TODO: Backtrack further if necessary.
this.count++;
if (this.currentPosition_ == this.patterns_.length) {
this.needsReset_ = true;
return goog.dom.pattern.MatchType.BACKTRACK_MATCH;
} else {
// Retry the same token on the next iteration of the child pattern.
return this.matchToken(token, type);
}
default:
this.needsReset_ = true;
if (this.count >= this.minimum_) {
return goog.dom.pattern.MatchType.BACKTRACK_MATCH;
} else {
return goog.dom.pattern.MatchType.NO_MATCH;
}
}
};
/**
* Reset any internal state this pattern keeps.
*/
goog.dom.pattern.Repeat.prototype.reset = function() {
this.pattern_.reset();
this.count = 0;
this.needsReset_ = false;
this.matches.length = 0;
};
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'format', 'ko', {
label: '포맷',
panelTitle: '포맷',
tag_address: 'Address',
tag_div: 'Normal (DIV)', // MISSING
tag_h1: 'Heading 1',
tag_h2: 'Heading 2',
tag_h3: 'Heading 3',
tag_h4: 'Heading 4',
tag_h5: 'Heading 5',
tag_h6: 'Heading 6',
tag_p: 'Normal',
tag_pre: 'Formatted'
});
|
/**
@module dbUpdate
@class dbUpdate
@toc
1. sessId
*/
'use strict';
var Q = require('q');
var lodash = require('lodash');
var dependency =require('../../../dependency.js');
var pathParts =dependency.buildPaths(__dirname, {});
// var StringMod =require(pathParts.services+'string/string.js');
var MongoDBMod =require(pathParts.services+'mongodb/mongodb.js');
var self;
var defaults = {
};
/**
DbUpdate module constructor
@class DbUpdate
@constructor
@param options {Object} constructor options
**/
function DbUpdate(options){
this.opts = lodash.merge({}, defaults, options||{});
self = this;
}
/**
@toc 1.
@method sessId
@param {Object} data
@param {Object} params
@return {Object} (via Promise)
@param {Number} code
@param {String} msg
@param {Array} results
**/
DbUpdate.prototype.sessId = function(db, data, params) {
var deferred = Q.defer();
var ret ={code:0, msg:'DbUpdate.sessId ', results:false};
db.user.find({}, {sess_id:1}).toArray(function(err, records) {
var promises =[], deferreds =[];
var ii, counter;
for(ii =0; ii<records.length; ii++) {
//need closure inside for loop
(function(ii) {
deferreds[ii] =Q.defer();
promises[ii] =deferreds[ii].promise;
//if session id is a string, convert it to an array and re-save
if(typeof(records[ii].sess_id) =='string') {
db.user.update({_id: MongoDBMod.makeIds({'id': records[ii]._id}) }, {$set: {sess_id: [ records[ii].sess_id ] } }, function(err, valid) {
if(err) {
ret.msg +='Error: '+err;
deferreds[ii].reject(ret);
}
else if(!valid) {
ret.msg +='Invalid ';
deferreds[ii].reject(ret);
}
else {
deferreds[ii].resolve({});
}
});
}
else {
deferreds[ii].resolve({});
}
})(ii);
}
//once have updated all users, resolve
Q.all(promises).then(function(ret1) {
deferred.resolve(ret);
}, function(err) {
deferred.resolve(ret);
});
});
return deferred.promise;
};
/**
Module exports
@method exports
@return {DbUpdate} DbUpdate constructor
**/
module.exports = new DbUpdate({}); |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'image', 'he', {
alertUrl: 'יש להקליד את כתובת התמונה',
alt: 'טקסט חלופי',
border: 'מסגרת',
btnUpload: 'שליחה לשרת',
button2Img: 'האם להפוך את תמונת הכפתור לתמונה פשוטה?',
hSpace: 'מרווח אופקי',
img2Button: 'האם להפוך את התמונה לכפתור תמונה?',
infoTab: 'מידע על התמונה',
linkTab: 'קישור',
lockRatio: 'נעילת היחס',
menu: 'תכונות התמונה',
resetSize: 'איפוס הגודל',
title: 'מאפייני התמונה',
titleButton: 'מאפיני כפתור תמונה',
upload: 'העלאה',
urlMissing: 'כתובת התמונה חסרה.',
vSpace: 'מרווח אנכי',
validateBorder: 'שדה המסגרת חייב להיות מספר שלם.',
validateHSpace: 'שדה המרווח האופקי חייב להיות מספר שלם.',
validateVSpace: 'שדה המרווח האנכי חייב להיות מספר שלם.'
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:f253cdd70d6409cfd55dbf57f6304532b6af981d266164254fd41de91a500998
size 2723
|
/*
* This file has been generated to support Visual Studio IntelliSense.
* You should not use this file at runtime inside the browser--it is only
* intended to be used only for design-time IntelliSense. Please use the
* standard jQuery library for all production use.
*
* Comment version: 1.6.1
*/
/*!
* jQuery JavaScript Library v1.6.1
* http://jquery.com/
*
* Distributed in whole under the terms of the MIT
*
* Copyright 2010, John Resig
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2010, The Dojo Foundation
* Released under the MIT and BSD Licenses.
*/
(function ( window, undefined ) {
var jQuery = function( selector, context ) {
/// <summary>
/// 1: Accepts a string containing a CSS selector which is then used to match a set of elements.
/// 1.1 - $(selector, context)
/// 1.2 - $(element)
/// 1.3 - $(elementArray)
/// 1.4 - $(jQuery object)
/// 1.5 - $()
/// 2: Creates DOM elements on the fly from the provided string of raw HTML.
/// 2.1 - $(html, ownerDocument)
/// 2.2 - $(html, props)
/// 3: Binds a function to be executed when the DOM has finished loading.
/// 3.1 - $(callback)
/// </summary>
/// <param name="selector" type="String">
/// A string containing a selector expression
/// </param>
/// <param name="context" type="jQuery">
/// A DOM Element, Document, or jQuery to use as context
/// </param>
/// <returns type="jQuery" />
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
};
jQuery.Deferred = function( func ) {
var deferred = jQuery._Deferred(),
failDeferred = jQuery._Deferred(),
promise;
// Add errorDeferred methods, then and promise
jQuery.extend( deferred, {
then: function( doneCallbacks, failCallbacks ) {
deferred.done( doneCallbacks ).fail( failCallbacks );
return this;
},
always: function() {
return deferred.done.apply( deferred, arguments ).fail.apply( this, arguments );
},
fail: failDeferred.done,
rejectWith: failDeferred.resolveWith,
reject: failDeferred.resolve,
isRejected: failDeferred.isResolved,
pipe: function( fnDone, fnFail ) {
return jQuery.Deferred(function( newDefer ) {
jQuery.each( {
done: [ fnDone, "resolve" ],
fail: [ fnFail, "reject" ]
}, function( handler, data ) {
var fn = data[ 0 ],
action = data[ 1 ],
returned;
if ( jQuery.isFunction( fn ) ) {
deferred[ handler ](function() {
returned = fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise().then( newDefer.resolve, newDefer.reject );
} else {
newDefer[ action ]( returned );
}
});
} else {
deferred[ handler ]( newDefer[ action ] );
}
});
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
if ( obj == null ) {
if ( promise ) {
return promise;
}
promise = obj = {};
}
var i = promiseMethods.length;
while( i-- ) {
obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ];
}
return obj;
}
});
// Make sure only one callback list will be used
deferred.done( failDeferred.cancel ).fail( deferred.cancel );
// Unexpose cancel
delete deferred.cancel;
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
return deferred;
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !this.preventDefault ) {
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 );
}
// timeStamp is buggy for some events on Firefox(#3843)
// So we won't rely on the native value
this.timeStamp = jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
jQuery._Deferred = function() {
var // callbacks list
callbacks = [],
// stored [ context , args ]
fired,
// to avoid firing when already doing so
firing,
// flag to know if the deferred has been cancelled
cancelled,
// the deferred itself
deferred = {
// done( f1, f2, ...)
done: function() {
if ( !cancelled ) {
var args = arguments,
i,
length,
elem,
type,
_fired;
if ( fired ) {
_fired = fired;
fired = 0;
}
for ( i = 0, length = args.length; i < length; i++ ) {
elem = args[ i ];
type = jQuery.type( elem );
if ( type === "array" ) {
deferred.done.apply( deferred, elem );
} else if ( type === "function" ) {
callbacks.push( elem );
}
}
if ( _fired ) {
deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] );
}
}
return this;
},
// resolve with given context and args
resolveWith: function( context, args ) {
if ( !cancelled && !fired && !firing ) {
// make sure args are available (#8421)
args = args || [];
firing = 1;
try {
while( callbacks[ 0 ] ) {
callbacks.shift().apply( context, args );
}
}
finally {
fired = [ context, args ];
firing = 0;
}
}
return this;
},
// resolve with this as context and given arguments
resolve: function() {
deferred.resolveWith( this, arguments );
return this;
},
// Has this deferred been resolved?
isResolved: function() {
return !!( firing || fired );
},
// Cancel
cancel: function() {
cancelled = 1;
callbacks = [];
return this;
}
};
return deferred;
};
jQuery._data = function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
};
jQuery._mark = function( elem, type ) {
if ( elem ) {
type = (type || "fx") + "mark";
jQuery.data( elem, type, (jQuery.data(elem,type,undefined,true) || 0) + 1, true );
}
};
jQuery._unmark = function( force, elem, type ) {
if ( force !== true ) {
type = elem;
elem = force;
force = false;
}
if ( elem ) {
type = type || "fx";
var key = type + "mark",
count = force ? 0 : ( (jQuery.data( elem, key, undefined, true) || 1 ) - 1 );
if ( count ) {
jQuery.data( elem, key, count, true );
} else {
jQuery.removeData( elem, key, true );
handleQueueMarkDefer( elem, type, "mark" );
}
}
};
jQuery.acceptData = function( elem ) {
if ( elem.nodeName ) {
var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
if ( match ) {
return !(match === true || elem.getAttribute("classid") !== match);
}
}
return true;
};
jQuery.access = function( elems, key, value, exec, fn, pass ) {
var length = elems.length;
// Setting many attributes
if ( typeof key === "object" ) {
for ( var k in key ) {
jQuery.access( elems, k, key[k], exec, fn, value );
}
return elems;
}
// Setting one attribute
if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = !pass && exec && jQuery.isFunction(value);
for ( var i = 0; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
return elems;
}
// Getting an attribute
return length ? fn( elems[0], key ) : undefined;
};
jQuery.active = 0;
jQuery.ajax = function( url, options ) {
/// <summary>
/// Perform an asynchronous HTTP (Ajax) request.
/// 1 - jQuery.ajax(url, settings)
/// 2 - jQuery.ajax(settings)
/// </summary>
/// <param name="url" type="String">
/// A string containing the URL to which the request is sent.
/// </param>
/// <param name="options" type="Object">
/// A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) below for a complete list of all settings.
/// </param>
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events
// It's the callbackContext if one was provided in the options
// and if it's a DOM node or a jQuery collection
globalEventContext = callbackContext !== s &&
( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
jQuery( callbackContext ) : jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery._Deferred(),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// ifModified key
ifModifiedKey,
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// Response headers
responseHeadersString,
responseHeaders,
// transport
transport,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// The jqXHR state
state = 0,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Fake xhr
jqXHR = {
readyState: 0,
// Caches the header
setRequestHeader: function( name, value ) {
if ( !state ) {
var lname = name.toLowerCase();
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match === undefined ? null : match;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Cancel the request
abort: function( statusText ) {
statusText = statusText || "abort";
if ( transport ) {
transport.abort( statusText );
}
done( 0, statusText );
return this;
}
};
// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done( status, statusText, responses, headers ) {
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status ? 4 : 0;
var isSuccess,
success,
error,
response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
lastModified,
etag;
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
jQuery.lastModified[ ifModifiedKey ] = lastModified;
}
if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
jQuery.etag[ ifModifiedKey ] = etag;
}
}
// If not modified
if ( status === 304 ) {
statusText = "notmodified";
isSuccess = true;
// If we have data
} else {
try {
success = ajaxConvert( s, response );
statusText = "success";
isSuccess = true;
} catch(e) {
// We have a parsererror
statusText = "parsererror";
error = e;
}
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if( !statusText || status ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = statusText;
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
// Attach deferreds
deferred.promise( jqXHR );
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.done;
// Status-dependent callbacks
jqXHR.statusCode = function( map ) {
if ( map ) {
var tmp;
if ( state < 2 ) {
for( tmp in map ) {
statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
} else {
tmp = map[ jqXHR.status ];
jqXHR.then( tmp, tmp );
}
}
return this;
};
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// We also use the url parameter if available
s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
// Determine if a cross-domain request is in order
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefiler, stop there
if ( state === 2 ) {
return false;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
}
// Get ifModifiedKey before adding the anti-cache parameter
ifModifiedKey = s.url;
// Add anti-cache in url if needed
if ( s.cache === false ) {
var ts = jQuery.now(),
// try replacing _= if it is there
ret = s.url.replace( rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end
s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url;
if ( jQuery.lastModified[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
}
if ( jQuery.etag[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
}
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already
jqXHR.abort();
return false;
}
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout( function(){
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch (e) {
// Propagate exception as error if not done
if ( status < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
jQuery.error( e );
}
}
}
return jqXHR;
};
jQuery.ajaxPrefilter = function( dataTypeExpression, func ) {
/// <summary>
/// Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax().
/// </summary>
/// <param name="dataTypeExpression" type="String">
/// An optional string containing one or more space-separated dataTypes
/// </param>
/// <param name="func" type="Function">
/// A handler to set default values for future Ajax requests.
/// </param>
/// <returns type="undefined" />
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
if ( jQuery.isFunction( func ) ) {
var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
i = 0,
length = dataTypes.length,
dataType,
list,
placeBefore;
// For each dataType in the dataTypeExpression
for(; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
jQuery.ajaxSettings = { "url": 'http://localhost:25813/',
"isLocal": false,
"global": true,
"type": 'GET',
"contentType": 'application/x-www-form-urlencoded',
"processData": true,
"async": true,
"accepts": {},
"contents": {},
"responseFields": {},
"converters": {},
"jsonp": 'callback' };
jQuery.ajaxSetup = function ( target, settings ) {
/// <summary>
/// Set default values for future Ajax requests.
/// </summary>
/// <param name="target" type="Object">
/// A set of key/value pairs that configure the default Ajax request. All options are optional.
/// </param>
if ( !settings ) {
// Only one parameter, we extend ajaxSettings
settings = target;
target = jQuery.extend( true, jQuery.ajaxSettings, settings );
} else {
// target was provided, we extend into it
jQuery.extend( true, target, jQuery.ajaxSettings, settings );
}
// Flatten fields we don't want deep extended
for( var field in { context: 1, url: 1 } ) {
if ( field in settings ) {
target[ field ] = settings[ field ];
} else if( field in jQuery.ajaxSettings ) {
target[ field ] = jQuery.ajaxSettings[ field ];
}
}
return target;
};
jQuery.ajaxTransport = function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
if ( jQuery.isFunction( func ) ) {
var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
i = 0,
length = dataTypes.length,
dataType,
list,
placeBefore;
// For each dataType in the dataTypeExpression
for(; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
jQuery.attr = function( elem, name, value, pass ) {
var nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return undefined;
}
if ( pass && name in jQuery.attrFn ) {
return jQuery( elem )[ name ]( value );
}
// Fallback to prop when attributes are not supported
if ( !("getAttribute" in elem) ) {
return jQuery.prop( elem, name, value );
}
var ret, hooks,
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// Normalize the name if needed
name = notxml && jQuery.attrFix[ name ] || name;
hooks = jQuery.attrHooks[ name ];
if ( !hooks ) {
// Use boolHook for boolean attributes
if ( rboolean.test( name ) &&
(typeof value === "boolean" || value === undefined || value.toLowerCase() === name.toLowerCase()) ) {
hooks = boolHook;
// Use formHook for forms and if the name contains certain characters
} else if ( formHook && (jQuery.nodeName( elem, "form" ) || rinvalidChar.test( name )) ) {
hooks = formHook;
}
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return undefined;
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, "" + value );
return value;
}
} else if ( hooks && "get" in hooks && notxml ) {
return hooks.get( elem, name );
} else {
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
};
jQuery.attrFix = { "tabindex": 'tabIndex' };
jQuery.attrFn = { "val": true,
"css": true,
"html": true,
"text": true,
"data": true,
"width": true,
"height": true,
"offset": true,
"blur": true,
"focus": true,
"focusin": true,
"focusout": true,
"load": true,
"resize": true,
"scroll": true,
"unload": true,
"click": true,
"dblclick": true,
"mousedown": true,
"mouseup": true,
"mousemove": true,
"mouseover": true,
"mouseout": true,
"mouseenter": true,
"mouseleave": true,
"change": true,
"select": true,
"submit": true,
"keydown": true,
"keypress": true,
"keyup": true,
"error": true };
jQuery.attrHooks = { "type": {},
"tabIndex": {},
"value": {} };
jQuery.bindReady = function() {
if ( readyList ) {
return;
}
readyList = jQuery._Deferred();
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
return setTimeout( jQuery.ready, 1 );
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
};
jQuery.boxModel = true;
jQuery.browser = { "msie": true,
"version": '9.0' };
jQuery.buildFragment = function( args, nodes, scripts ) {
var fragment, cacheable, cacheresults,
doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document &&
args[0].charAt(0) === "<" && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {
cacheable = true;
cacheresults = jQuery.fragments[ args[0] ];
if ( cacheresults && cacheresults !== 1 ) {
fragment = cacheresults;
}
}
if ( !fragment ) {
fragment = doc.createDocumentFragment();
jQuery.clean( args, doc, fragment, scripts );
}
if ( cacheable ) {
jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.cache = {};
jQuery.camelCase = function( string ) {
return string.replace( rdashAlpha, fcamelCase );
};
jQuery.clean = function( elems, context, fragment, scripts ) {
var checkScriptType;
context = context || document;
// !context.createElement fails in IE with an error but returns typeof 'object'
if ( typeof context.createElement === "undefined" ) {
context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
}
var ret = [], j;
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else {
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Trim whitespace, otherwise indexOf won't work as expected
var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(),
wrap = wrapMap[ tag ] || wrapMap._default,
depth = wrap[0],
div = context.createElement("div");
// Go to html and back, then peel off extra wrappers
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
var hasBody = rtbody.test(elem),
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
}
}
// Resets defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
var len;
if ( !jQuery.support.appendChecked ) {
if ( elem[0] && typeof (len = elem.length) === "number" ) {
for ( j = 0; j < len; j++ ) {
findInputs( elem[j] );
}
} else {
findInputs( elem );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
ret = jQuery.merge( ret, elem );
}
}
if ( fragment ) {
checkScriptType = function( elem ) {
return !elem.type || rscriptType.test( elem.type );
};
for ( i = 0; ret[i]; i++ ) {
if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
} else {
if ( ret[i].nodeType === 1 ) {
var jsTags = jQuery.grep( ret[i].getElementsByTagName( "script" ), checkScriptType );
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
}
fragment.appendChild( ret[i] );
}
}
}
return ret;
};
jQuery.cleanData = function( elems ) {
var data, id, cache = jQuery.cache, internalKey = jQuery.expando, special = jQuery.event.special,
deleteExpando = jQuery.support.deleteExpando;
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
continue;
}
id = elem[ jQuery.expando ];
if ( id ) {
data = cache[ id ] && cache[ id ][ internalKey ];
if ( data && data.events ) {
for ( var type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
// Null the DOM reference to avoid IE6/7/8 leak (#7054)
if ( data.handle ) {
data.handle.elem = null;
}
}
if ( deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
}
delete cache[ id ];
}
}
};
jQuery.clone = function( elem, dataAndEvents, deepDataAndEvents ) {
var clone = elem.cloneNode(true),
srcElements,
destElements,
i;
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes( elem, clone );
// Using Sizzle here is crazy slow, so we use getElementsByTagName
// instead
srcElements = getAll( elem );
destElements = getAll( clone );
// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for ( i = 0; srcElements[i]; ++i ) {
cloneFixAttributes( srcElements[i], destElements[i] );
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
cloneCopyEvent( elem, clone );
if ( deepDataAndEvents ) {
srcElements = getAll( elem );
destElements = getAll( clone );
for ( i = 0; srcElements[i]; ++i ) {
cloneCopyEvent( srcElements[i], destElements[i] );
}
}
}
// Return the cloned set
return clone;
};
jQuery.contains = function( a, b ) {
/// <summary>
/// Check to see if a DOM node is within another DOM node.
/// </summary>
/// <param name="a" domElement="true">
/// The DOM element that may contain the other element.
/// </param>
/// <param name="b" domElement="true">
/// The DOM node that may be contained by the other element.
/// </param>
/// <returns type="Boolean" />
return a !== b && (a.contains ? a.contains(b) : true);
};
jQuery.css = function( elem, name, extra ) {
var ret, hooks;
// Make sure that we're working with the right name
name = jQuery.camelCase( name );
hooks = jQuery.cssHooks[ name ];
name = jQuery.cssProps[ name ] || name;
// cssFloat needs a special treatment
if ( name === "cssFloat" ) {
name = "float";
}
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
return ret;
// Otherwise, if a way to get the computed value exists, use that
} else if ( curCSS ) {
return curCSS( elem, name );
}
};
jQuery.cssHooks = { "opacity": {},
"height": {},
"width": {} };
jQuery.cssNumber = { "zIndex": true,
"fontWeight": true,
"opacity": true,
"zoom": true,
"lineHeight": true,
"widows": true,
"orphans": true };
jQuery.cssProps = { "float": 'cssFloat' };
jQuery.curCSS = function( elem, name, extra ) {
var ret, hooks;
// Make sure that we're working with the right name
name = jQuery.camelCase( name );
hooks = jQuery.cssHooks[ name ];
name = jQuery.cssProps[ name ] || name;
// cssFloat needs a special treatment
if ( name === "cssFloat" ) {
name = "float";
}
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
return ret;
// Otherwise, if a way to get the computed value exists, use that
} else if ( curCSS ) {
return curCSS( elem, name );
}
};
jQuery.data = function( elem, name, data, pvt /* Internal Use Only */ ) {
/// <summary>
/// 1: Store arbitrary data associated with the specified element. Returns the value that was set.
/// 1.1 - jQuery.data(element, key, value)
/// 2: Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element.
/// 2.1 - jQuery.data(element, key)
/// 2.2 - jQuery.data(element)
/// </summary>
/// <param name="elem" domElement="true">
/// The DOM element to associate with the data.
/// </param>
/// <param name="name" type="String">
/// A string naming the piece of data to set.
/// </param>
/// <param name="data" type="Object">
/// The new data value.
/// </param>
/// <returns type="Object" />
if ( !jQuery.acceptData( elem ) ) {
return;
}
var internalKey = jQuery.expando, getByName = typeof name === "string", thisCache,
// 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[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando;
// 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 || (pvt && id && !cache[ id ][ internalKey ])) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ jQuery.expando ] = id = ++jQuery.uuid;
} else {
id = jQuery.expando;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery
// metadata on plain JS objects when the object is serialized using
// JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name);
} else {
cache[ id ] = jQuery.extend(cache[ id ], name);
}
}
thisCache = cache[ id ];
// Internal jQuery data is stored in a separate object inside the object's data
// cache in order to avoid key collisions between internal data and user-defined
// data
if ( pvt ) {
if ( !thisCache[ internalKey ] ) {
thisCache[ internalKey ] = {};
}
thisCache = thisCache[ internalKey ];
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should
// not attempt to inspect the internal events object using jQuery.data, as this
// internal data object is undocumented and subject to change.
if ( name === "events" && !thisCache[name] ) {
return thisCache[ internalKey ] && thisCache[ internalKey ].events;
}
return getByName ? thisCache[ jQuery.camelCase( name ) ] : thisCache;
};
jQuery.dequeue = function( elem, type ) {
/// <summary>
/// Execute the next function on the queue for the matched element.
/// </summary>
/// <param name="elem" domElement="true">
/// A DOM element from which to remove and execute a queued function.
/// </param>
/// <param name="type" type="String">
/// A string containing the name of the queue. Defaults to fx, the standard effects queue.
/// </param>
/// <returns type="jQuery" />
type = type || "fx";
var queue = jQuery.queue( elem, type ),
fn = queue.shift(),
defer;
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift("inprogress");
}
fn.call(elem, function() {
jQuery.dequeue(elem, type);
});
}
if ( !queue.length ) {
jQuery.removeData( elem, type + "queue", true );
handleQueueMarkDefer( elem, type, "queue" );
}
};
jQuery.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;
};
jQuery.each = function( object, callback, args ) {
/// <summary>
/// A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.
/// </summary>
/// <param name="object" type="Object">
/// The object or array to iterate over.
/// </param>
/// <param name="callback" type="Function">
/// The function that will be executed on every object.
/// </param>
/// <returns type="Object" />
var name, i = 0,
length = object.length,
isObj = length === undefined || jQuery.isFunction( object );
if ( args ) {
if ( isObj ) {
for ( name in object ) {
if ( callback.apply( object[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( object[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
break;
}
}
}
}
return object;
};
jQuery.easing = {};
jQuery.error = function( msg ) {
/// <summary>
/// Takes a string and throws an exception containing it.
/// </summary>
/// <param name="msg" type="String">
/// The message to send out.
/// </param>
throw msg;
};
jQuery.etag = {};
jQuery.event = { "global": {},
"customEvent": {},
"props": ['altKey','attrChange','attrName','bubbles','button','cancelable','charCode','clientX','clientY','ctrlKey','currentTarget','data','detail','eventPhase','fromElement','handler','keyCode','layerX','layerY','metaKey','newValue','offsetX','offsetY','pageX','pageY','prevValue','relatedNode','relatedTarget','screenX','screenY','shiftKey','srcElement','target','toElement','view','wheelDelta','which'],
"guid": 100000000,
"special": {},
"triggered": };
jQuery.expr = { "order": ['ID','CLASS','NAME','TAG'],
"match": {},
"leftMatch": {},
"attrMap": {},
"attrHandle": {},
"relative": {},
"find": {},
"preFilter": {},
"filters": {},
"setFilters": {},
"filter": {},
":": {} };
jQuery.extend = function() {
/// <summary>
/// Merge the contents of two or more objects together into the first object.
/// 1 - jQuery.extend(target, object1, objectN)
/// 2 - jQuery.extend(deep, target, object1, objectN)
/// </summary>
/// <param name="" type="Boolean">
/// If true, the merge becomes recursive (aka. deep copy).
/// </param>
/// <param name="" type="Object">
/// The object to extend. It will receive the new properties.
/// </param>
/// <param name="" type="Object">
/// An object containing additional properties to merge in.
/// </param>
/// <param name="" type="Object">
/// Additional objects containing properties to merge in.
/// </param>
/// <returns type="Object" />
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.filter = function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
};
jQuery.find = function( query, context, extra, seed ) {
context = context || document;
// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if ( !seed && !Sizzle.isXML(context) ) {
// See if we find a selector to speed up
var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
// Speed-up: Sizzle("TAG")
if ( match[1] ) {
return makeArray( context.getElementsByTagName( query ), extra );
// Speed-up: Sizzle(".CLASS")
} else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
return makeArray( context.getElementsByClassName( match[2] ), extra );
}
}
if ( context.nodeType === 9 ) {
// Speed-up: Sizzle("body")
// The body element only exists once, optimize finding it
if ( query === "body" && context.body ) {
return makeArray( [ context.body ], extra );
// Speed-up: Sizzle("#ID")
} else if ( match && match[3] ) {
var elem = context.getElementById( match[3] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id === match[3] ) {
return makeArray( [ elem ], extra );
}
} else {
return makeArray( [], extra );
}
}
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(qsaError) {}
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
var oldContext = context,
old = context.getAttribute( "id" ),
nid = old || id,
hasParent = context.parentNode,
relativeHierarchySelector = /^\s*[+~]/.test( query );
if ( !old ) {
context.setAttribute( "id", nid );
} else {
nid = nid.replace( /'/g, "\\$&" );
}
if ( relativeHierarchySelector && hasParent ) {
context = context.parentNode;
}
try {
if ( !relativeHierarchySelector || hasParent ) {
return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
}
} catch(pseudoError) {
} finally {
if ( !old ) {
oldContext.removeAttribute( "id" );
}
}
}
}
return oldSizzle(query, context, extra, seed);
};
jQuery.fn = { "selector": '',
"jquery": '1.6.1',
"length": 0 };
jQuery.fragments = {};
jQuery.fx = function( elem, options, prop ) {
this.options = options;
this.elem = elem;
this.prop = prop;
options.orig = options.orig || {};
};
jQuery.get = function( url, data, callback, type ) {
/// <summary>
/// Load data from the server using a HTTP GET request.
/// </summary>
/// <param name="url" type="String">
/// A string containing the URL to which the request is sent.
/// </param>
/// <param name="data" type="String">
/// A map or string that is sent to the server with the request.
/// </param>
/// <param name="callback" type="Function">
/// A callback function that is executed if the request succeeds.
/// </param>
/// <param name="type" type="String">
/// The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).
/// </param>
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
jQuery.getJSON = function( url, data, callback ) {
/// <summary>
/// Load JSON-encoded data from the server using a GET HTTP request.
/// </summary>
/// <param name="url" type="String">
/// A string containing the URL to which the request is sent.
/// </param>
/// <param name="data" type="Object">
/// A map or string that is sent to the server with the request.
/// </param>
/// <param name="callback" type="Function">
/// A callback function that is executed if the request succeeds.
/// </param>
return jQuery.get( url, data, callback, "json" );
};
jQuery.getScript = function( url, callback ) {
/// <summary>
/// Load a JavaScript file from the server using a GET HTTP request, then execute it.
/// </summary>
/// <param name="url" type="String">
/// A string containing the URL to which the request is sent.
/// </param>
/// <param name="callback" type="Function">
/// A callback function that is executed if the request succeeds.
/// </param>
/// <returns type="XMLHttpRequest" />
return jQuery.get( url, undefined, callback, "script" );
};
jQuery.globalEval = function( data ) {
/// <summary>
/// Execute some JavaScript code globally.
/// </summary>
/// <param name="data" type="String">
/// The JavaScript code to execute.
/// </param>
if ( data && rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
};
jQuery.grep = function( elems, callback, inv ) {
/// <summary>
/// Finds the elements of an array which satisfy a filter function. The original array is not affected.
/// </summary>
/// <param name="elems" type="Array">
/// The array to search through.
/// </param>
/// <param name="callback" type="Function">
/// The function to process each item against. The first argument to the function is the item, and the second argument is the index. The function should return a Boolean value. this will be the global window object.
/// </param>
/// <param name="inv" type="Boolean">
/// If "invert" is false, or not provided, then the function returns an array consisting of all elements for which "callback" returns true. If "invert" is true, then the function returns an array consisting of all elements for which "callback" returns false.
/// </param>
/// <returns type="Array" />
var ret = [], retVal;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0, length = elems.length; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
};
jQuery.guid = 1;
jQuery.hasData = function( elem ) {
/// <summary>
/// Determine whether an element has any jQuery data associated with it.
/// </summary>
/// <param name="elem" domElement="true">
/// A DOM element to be checked for data.
/// </param>
/// <returns type="Boolean" />
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
};
jQuery.holdReady = function( hold ) {
/// <summary>
/// Holds or releases the execution of jQuery's ready event.
/// </summary>
/// <param name="hold" type="Boolean">
/// Indicates whether the ready hold is being requested or released
/// </param>
/// <returns type="Boolean" />
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
};
jQuery.inArray = function( elem, array ) {
/// <summary>
/// Search for a specified value within an array and return its index (or -1 if not found).
/// </summary>
/// <param name="elem" type="Object">
/// The value to search for.
/// </param>
/// <param name="array" type="Array">
/// An array through which to search.
/// </param>
/// <returns type="Number" />
if ( indexOf ) {
return indexOf.call( array, elem );
}
for ( var i = 0, length = array.length; i < length; i++ ) {
if ( array[ i ] === elem ) {
return i;
}
}
return -1;
};
jQuery.isEmptyObject = function( obj ) {
/// <summary>
/// Check to see if an object is empty (contains no properties).
/// </summary>
/// <param name="obj" type="Object">
/// The object that will be checked to see if it's empty.
/// </param>
/// <returns type="Boolean" />
for ( var name in obj ) {
return false;
}
return true;
};
jQuery.isFunction = function( obj ) {
/// <summary>
/// Determine if the argument passed is a Javascript function object.
/// </summary>
/// <param name="obj" type="Object">
/// Object to test whether or not it is a function.
/// </param>
/// <returns type="boolean" />
return jQuery.type(obj) === "function";
};
jQuery.isNaN = function( obj ) {
return obj == null || !rdigit.test( obj ) || isNaN( obj );
};
jQuery.isPlainObject = function( obj ) {
/// <summary>
/// Check to see if an object is a plain object (created using "{}" or "new Object").
/// </summary>
/// <param name="obj" type="Object">
/// The object that will be checked to see if it's a plain object.
/// </param>
/// <returns type="Boolean" />
// 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;
}
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
};
jQuery.isReady = true;
jQuery.isWindow = function( obj ) {
/// <summary>
/// Determine whether the argument is a window.
/// </summary>
/// <param name="obj" type="Object">
/// Object to test whether or not it is a window.
/// </param>
/// <returns type="boolean" />
return obj && typeof obj === "object" && "setInterval" in obj;
};
jQuery.isXMLDoc = function( elem ) {
/// <summary>
/// Check to see if a DOM node is within an XML document (or is an XML document).
/// </summary>
/// <param name="elem" domElement="true">
/// The DOM node that will be checked to see if it's in an XML document.
/// </param>
/// <returns type="Boolean" />
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
jQuery.lastModified = {};
jQuery.makeArray = function( array, results ) {
/// <summary>
/// Convert an array-like object into a true JavaScript array.
/// </summary>
/// <param name="array" type="Object">
/// Any object to turn into a native Array.
/// </param>
/// <returns type="Array" />
var ret = results || [];
if ( array != null ) {
// The window, strings (and functions) also have 'length'
// The extra typeof function check is to prevent crashes
// in Safari 2 (See: #3039)
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
var type = jQuery.type( array );
if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
push.call( ret, array );
} else {
jQuery.merge( ret, array );
}
}
return ret;
};
jQuery.map = function( elems, callback, arg ) {
/// <summary>
/// Translate all items in an array or object to new array of items.
/// 1 - jQuery.map(array, callback(elementOfArray, indexInArray))
/// 2 - jQuery.map(arrayOrObject, callback( value, indexOrKey ))
/// </summary>
/// <param name="elems" type="Array">
/// The Array to translate.
/// </param>
/// <param name="callback" type="Function">
/// The function to process each item against. The first argument to the function is the array item, the second argument is the index in array The function can return any value. Within the function, this refers to the global (window) object.
/// </param>
/// <returns type="Array" />
var value, key, ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return ret.concat.apply( [], ret );
};
jQuery.merge = function( first, second ) {
/// <summary>
/// Merge the contents of two arrays together into the first array.
/// </summary>
/// <param name="first" type="Array">
/// The first array to merge, the elements of second added.
/// </param>
/// <param name="second" type="Array">
/// The second array to merge into the first, unaltered.
/// </param>
/// <returns type="Array" />
var i = first.length,
j = 0;
if ( typeof second.length === "number" ) {
for ( var l = second.length; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
};
jQuery.noConflict = function( deep ) {
/// <summary>
/// Relinquish jQuery's control of the $ variable.
/// </summary>
/// <param name="deep" type="Boolean">
/// A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself).
/// </param>
/// <returns type="Object" />
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
};
jQuery.noData = { "embed": true,
"object": 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000',
"applet": true };
jQuery.nodeName = function( elem, name ) {
return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
};
jQuery.noop = function() {
/// <summary>
/// An empty function.
/// </summary>
/// <returns type="Function" />
};
jQuery.now = function() {
/// <summary>
/// Return a number representing the current time.
/// </summary>
/// <returns type="Number" />
return (new Date()).getTime();
};
jQuery.nth = function( cur, result, dir, elem ) {
result = result || 1;
var num = 0;
for ( ; cur; cur = cur[dir] ) {
if ( cur.nodeType === 1 && ++num === result ) {
break;
}
}
return cur;
};
jQuery.offset = {};
jQuery.param = function( a, traditional ) {
/// <summary>
/// Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.
/// 1 - jQuery.param(obj)
/// 2 - jQuery.param(obj, traditional)
/// </summary>
/// <param name="a" type="Object">
/// An array or object to serialize.
/// </param>
/// <param name="traditional" type="Boolean">
/// A Boolean indicating whether to perform a traditional "shallow" serialization.
/// </param>
/// <returns type="String" />
var s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : value;
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( var prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
jQuery.parseJSON = function( data ) {
/// <summary>
/// Takes a well-formed JSON string and returns the resulting JavaScript object.
/// </summary>
/// <param name="data" type="String">
/// The JSON string to parse.
/// </param>
/// <returns type="Object" />
if ( typeof data !== "string" || !data ) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return (new Function( "return " + data ))();
}
jQuery.error( "Invalid JSON: " + data );
};
jQuery.parseXML = function( data , xml , tmp ) {
/// <summary>
/// Parses a string into an XML document.
/// </summary>
/// <param name="data" type="String">
/// a well-formed XML string to be parsed
/// </param>
/// <returns type="XMLDocument" />
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 );
}
tmp = xml.documentElement;
if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
};
jQuery.post = function( url, data, callback, type ) {
/// <summary>
/// Load data from the server using a HTTP POST request.
/// </summary>
/// <param name="url" type="String">
/// A string containing the URL to which the request is sent.
/// </param>
/// <param name="data" type="String">
/// A map or string that is sent to the server with the request.
/// </param>
/// <param name="callback" type="Function">
/// A callback function that is executed if the request succeeds.
/// </param>
/// <param name="type" type="String">
/// The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).
/// </param>
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
jQuery.prop = function( elem, name, value ) {
var nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return undefined;
}
var ret, hooks,
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// Try to normalize/fix the name
name = notxml && jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return (elem[ name ] = value);
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== undefined ) {
return ret;
} else {
return elem[ name ];
}
}
};
jQuery.propFix = { "tabindex": 'tabIndex',
"readonly": 'readOnly',
"for": 'htmlFor',
"class": 'className',
"maxlength": 'maxLength',
"cellspacing": 'cellSpacing',
"cellpadding": 'cellPadding',
"rowspan": 'rowSpan',
"colspan": 'colSpan',
"usemap": 'useMap',
"frameborder": 'frameBorder',
"contenteditable": 'contentEditable' };
jQuery.propHooks = { "selected": {} };
jQuery.proxy = function( fn, context ) {
/// <summary>
/// Takes a function and returns a new one that will always have a particular context.
/// 1 - jQuery.proxy(function, context)
/// 2 - jQuery.proxy(context, name)
/// </summary>
/// <param name="fn" type="Function">
/// The function whose context will be changed.
/// </param>
/// <param name="context" type="Object">
/// The object to which the context (this) of the function should be set.
/// </param>
/// <returns type="Function" />
if ( typeof context === "string" ) {
var tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
var args = slice.call( arguments, 2 ),
proxy = function() {
return fn.apply( context, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
return proxy;
};
jQuery.queue = function( elem, type, data ) {
/// <summary>
/// 1: Show the queue of functions to be executed on the matched element.
/// 1.1 - jQuery.queue(element, queueName)
/// 2: Manipulate the queue of functions to be executed on the matched element.
/// 2.1 - jQuery.queue(element, queueName, newQueue)
/// 2.2 - jQuery.queue(element, queueName, callback())
/// </summary>
/// <param name="elem" domElement="true">
/// A DOM element where the array of queued functions is attached.
/// </param>
/// <param name="type" type="String">
/// A string containing the name of the queue. Defaults to fx, the standard effects queue.
/// </param>
/// <param name="data" type="Array">
/// An array of functions to replace the current queue contents.
/// </param>
/// <returns type="jQuery" />
if ( elem ) {
type = (type || "fx") + "queue";
var q = jQuery.data( elem, type, undefined, true );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !q || jQuery.isArray(data) ) {
q = jQuery.data( elem, type, jQuery.makeArray(data), true );
} else {
q.push( data );
}
}
return q || [];
}
};
jQuery.ready = function( wait ) {
// Either a released hold or an DOMready/load event and not yet ready
if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger( "ready" ).unbind( "ready" );
}
}
};
jQuery.readyWait = 0;
jQuery.removeAttr = function( elem, name ) {
var propName;
if ( elem.nodeType === 1 ) {
name = jQuery.attrFix[ name ] || name;
if ( jQuery.support.getSetAttribute ) {
// Use removeAttribute in browsers that support it
elem.removeAttribute( name );
} else {
jQuery.attr( elem, name, "" );
elem.removeAttributeNode( elem.getAttributeNode( name ) );
}
// Set corresponding property to false for boolean attributes
if ( rboolean.test( name ) && (propName = jQuery.propFix[ name ] || name) in elem ) {
elem[ propName ] = false;
}
}
};
jQuery.removeData = function( elem, name, pvt /* Internal Use Only */ ) {
/// <summary>
/// Remove a previously-stored piece of data.
/// </summary>
/// <param name="elem" domElement="true">
/// A DOM element from which to remove data.
/// </param>
/// <param name="name" type="String">
/// A string naming the piece of data to remove.
/// </param>
/// <returns type="jQuery" />
if ( !jQuery.acceptData( elem ) ) {
return;
}
var internalKey = jQuery.expando, isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
// See jQuery.data for more information
id = isNode ? elem[ 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 ) {
var thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ];
if ( thisCache ) {
delete thisCache[ name ];
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !isEmptyDataObject(thisCache) ) {
return;
}
}
}
// See jQuery.data for more information
if ( pvt ) {
delete cache[ id ][ internalKey ];
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject(cache[ id ]) ) {
return;
}
}
var internalCache = cache[ id ][ internalKey ];
// Browsers that fail expando deletion also refuse to delete expandos on
// the window, but it will allow it on all other JS objects; other browsers
// don't care
if ( jQuery.support.deleteExpando || cache != window ) {
delete cache[ id ];
} else {
cache[ id ] = null;
}
// We destroyed the entire user cache at once because it's faster than
// iterating through each key, but we need to continue to persist internal
// data if it existed
if ( internalCache ) {
cache[ id ] = {};
// TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery
// metadata on plain JS objects when the object is serialized using
// JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
cache[ id ][ internalKey ] = internalCache;
// Otherwise, we need to eliminate the expando on the node to avoid
// false lookups in the cache for entries that no longer exist
} else if ( isNode ) {
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( jQuery.support.deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
} else {
elem[ jQuery.expando ] = null;
}
}
};
jQuery.removeEvent = function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
};
jQuery.sibling = function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
};
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;
// Queueing
opt.old = opt.complete;
opt.complete = function( noUnmark ) {
if ( opt.queue !== false ) {
jQuery.dequeue( this );
} else if ( noUnmark !== false ) {
jQuery._unmark( this );
}
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
};
return opt;
};
jQuery.style = function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, origName = jQuery.camelCase( name ),
style = elem.style, hooks = jQuery.cssHooks[ origName ];
name = jQuery.cssProps[ origName ] || origName;
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// Make sure that NaN and null values aren't set. See: #7116
if ( type === "number" && isNaN( value ) || value == null ) {
return;
}
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && rrelNum.test( value ) ) {
value = +value.replace( rrelNumFilter, "" ) + parseFloat( jQuery.css( elem, name ) );
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
};
jQuery.sub = function() {
/// <summary>
/// Creates a new copy of jQuery whose properties and methods can be modified without affecting the original jQuery object.
/// </summary>
/// <returns type="jQuery" />
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
};
jQuery.support = { "leadingWhitespace": true,
"tbody": true,
"htmlSerialize": true,
"style": true,
"hrefNormalized": true,
"opacity": true,
"cssFloat": true,
"checkOn": true,
"optSelected": false,
"getSetAttribute": true,
"submitBubbles": true,
"changeBubbles": true,
"focusinBubbles": true,
"deleteExpando": true,
"noCloneEvent": true,
"inlineBlockNeedsLayout": false,
"shrinkWrapBlocks": false,
"reliableMarginRight": true,
"noCloneChecked": false,
"optDisabled": true,
"radioValue": false,
"checkClone": ,
"appendChecked": true,
"boxModel": true,
"reliableHiddenOffsets": true,
"ajax": true,
"cors": false };
jQuery.swap = function( elem, options, callback ) {
var old = {};
// Remember the old values, and insert the new ones
for ( var name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
callback.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
};
jQuery.text = function( elems ) {
var ret = "", elem;
for ( var i = 0; elems[i]; i++ ) {
elem = elems[i];
// Get the text from text nodes and CDATA nodes
if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
ret += elem.nodeValue;
// Traverse everything else, except comment nodes
} else if ( elem.nodeType !== 8 ) {
ret += Sizzle.getText( elem.childNodes );
}
}
return ret;
};
jQuery.trim = function( text ) {
/// <summary>
/// Remove the whitespace from the beginning and end of a string.
/// </summary>
/// <param name="text" type="String">
/// The string to trim.
/// </param>
/// <returns type="String" />
return text == null ?
"" :
trim.call( text );
};
jQuery.type = function( obj ) {
/// <summary>
/// Determine the internal JavaScript [[Class]] of an object.
/// </summary>
/// <param name="obj" type="Object">
/// Object to get the internal JavaScript [[Class]] of.
/// </param>
/// <returns type="String" />
return obj == null ?
String( obj ) :
class2type[ toString.call(obj) ] || "object";
};
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = rwebkit.exec( ua ) ||
ropera.exec( ua ) ||
rmsie.exec( ua ) ||
ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
[];
return { browser: match[1] || "", version: match[2] || "0" };
};
jQuery.unique = function( results ) {
/// <summary>
/// Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers.
/// </summary>
/// <param name="results" type="Array">
/// The Array of DOM elements.
/// </param>
/// <returns type="Array" />
if ( sortOrder ) {
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( var i = 1; i < results.length; i++ ) {
if ( results[i] === results[ i - 1 ] ) {
results.splice( i--, 1 );
}
}
}
}
return results;
};
jQuery.uuid = 0;
jQuery.valHooks = { "option": {},
"select": {},
"radio": {},
"checkbox": {} };
jQuery.when = function( firstParam ) {
/// <summary>
/// Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.
/// </summary>
/// <param name="firstParam" type="Deferred">
/// One or more Deferred objects, or plain JavaScript objects.
/// </param>
/// <returns type="Promise" />
var args = arguments,
i = 0,
length = args.length,
count = length,
deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ?
firstParam :
jQuery.Deferred();
function resolveFunc( i ) {
return function( value ) {
args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
if ( !( --count ) ) {
// Strange bug in FF4:
// Values changed onto the arguments object sometimes end up as undefined values
// outside the $.when method. Cloning the object into a fresh array solves the issue
deferred.resolveWith( deferred, sliceDeferred.call( args, 0 ) );
}
};
}
if ( length > 1 ) {
for( ; i < length; i++ ) {
if ( args[ i ] && jQuery.isFunction( args[ i ].promise ) ) {
args[ i ].promise().then( resolveFunc(i), deferred.reject );
} else {
--count;
}
}
if ( !count ) {
deferred.resolveWith( deferred, args );
}
} else if ( deferred !== firstParam ) {
deferred.resolveWith( deferred, length ? [ firstParam ] : [] );
}
return deferred.promise();
};
jQuery.Event.prototype.isDefaultPrevented = function returnFalse() {
/// <summary>
/// Returns whether event.preventDefault() was ever called on this event object.
/// </summary>
/// <returns type="Boolean" />
return false;
};
jQuery.Event.prototype.isImmediatePropagationStopped = function returnFalse() {
/// <summary>
/// Returns whether event.stopImmediatePropagation() was ever called on this event object.
/// </summary>
/// <returns type="Boolean" />
return false;
};
jQuery.Event.prototype.isPropagationStopped = function returnFalse() {
/// <summary>
/// Returns whether event.stopPropagation() was ever called on this event object.
/// </summary>
/// <returns type="Boolean" />
return false;
};
jQuery.Event.prototype.preventDefault = function() {
/// <summary>
/// If this method is called, the default action of the event will not be triggered.
/// </summary>
/// <returns type="undefined" />
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
};
jQuery.Event.prototype.stopImmediatePropagation = function() {
/// <summary>
/// Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.
/// </summary>
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
};
jQuery.Event.prototype.stopPropagation = function() {
/// <summary>
/// Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
/// </summary>
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
};
jQuery.prototype._toggle = function( fn ) {
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
};
jQuery.prototype.add = function( selector, context ) {
/// <summary>
/// Add elements to the set of matched elements.
/// 1 - add(selector)
/// 2 - add(elements)
/// 3 - add(html)
/// 4 - add(selector, context)
/// </summary>
/// <param name="selector" type="String">
/// A string representing a selector expression to find additional elements to add to the set of matched elements.
/// </param>
/// <param name="context" domElement="true">
/// The point in the document at which the selector should begin matching; similar to the context argument of the $(selector, context) method.
/// </param>
/// <returns type="jQuery" />
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
};
jQuery.prototype.addClass = function( value ) {
/// <summary>
/// Adds the specified class(es) to each of the set of matched elements.
/// 1 - addClass(className)
/// 2 - addClass(function(index, currentClass))
/// </summary>
/// <param name="value" type="String">
/// One or more class names to be added to the class attribute of each matched element.
/// </param>
/// <returns type="jQuery" />
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this);
self.addClass( value.call(this, i, self.attr("class") || "") );
});
}
if ( value && typeof value === "string" ) {
var classNames = (value || "").split( rspace );
for ( var i = 0, l = this.length; i < l; i++ ) {
var elem = this[i];
if ( elem.nodeType === 1 ) {
if ( !elem.className ) {
elem.className = value;
} else {
var className = " " + elem.className + " ",
setClass = elem.className;
for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) {
setClass += " " + classNames[c];
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
};
jQuery.prototype.after = function() {
/// <summary>
/// Insert content, specified by the parameter, after each element in the set of matched elements.
/// 1 - after(content, content)
/// 2 - after(function(index))
/// </summary>
/// <param name="" type="jQuery">
/// HTML string, DOM element, or jQuery object to insert after each element in the set of matched elements.
/// </param>
/// <param name="" type="jQuery">
/// One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert after each element in the set of matched elements.
/// </param>
/// <returns type="jQuery" />
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
} else if ( arguments.length ) {
var set = this.pushStack( this, "after", arguments );
set.push.apply( set, jQuery(arguments[0]).toArray() );
return set;
}
};
jQuery.prototype.ajaxComplete = function( f ){
/// <summary>
/// Register a handler to be called when Ajax requests complete. This is an Ajax Event.
/// </summary>
/// <param name="f" type="Function">
/// The function to be invoked.
/// </param>
/// <returns type="jQuery" />
return this.bind( o, f );
};
jQuery.prototype.ajaxError = function( f ){
/// <summary>
/// Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event.
/// </summary>
/// <param name="f" type="Function">
/// The function to be invoked.
/// </param>
/// <returns type="jQuery" />
return this.bind( o, f );
};
jQuery.prototype.ajaxSend = function( f ){
/// <summary>
/// Attach a function to be executed before an Ajax request is sent. This is an Ajax Event.
/// </summary>
/// <param name="f" type="Function">
/// The function to be invoked.
/// </param>
/// <returns type="jQuery" />
return this.bind( o, f );
};
jQuery.prototype.ajaxStart = function( f ){
/// <summary>
/// Register a handler to be called when the first Ajax request begins. This is an Ajax Event.
/// </summary>
/// <param name="f" type="Function">
/// The function to be invoked.
/// </param>
/// <returns type="jQuery" />
return this.bind( o, f );
};
jQuery.prototype.ajaxStop = function( f ){
/// <summary>
/// Register a handler to be called when all Ajax requests have completed. This is an Ajax Event.
/// </summary>
/// <param name="f" type="Function">
/// The function to be invoked.
/// </param>
/// <returns type="jQuery" />
return this.bind( o, f );
};
jQuery.prototype.ajaxSuccess = function( f ){
/// <summary>
/// Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event.
/// </summary>
/// <param name="f" type="Function">
/// The function to be invoked.
/// </param>
/// <returns type="jQuery" />
return this.bind( o, f );
};
jQuery.prototype.andSelf = function() {
/// <summary>
/// Add the previous set of elements on the stack to the current set.
/// </summary>
/// <returns type="jQuery" />
return this.add( this.prevObject );
};
jQuery.prototype.animate = function( prop, speed, easing, callback ) {
/// <summary>
/// Perform a custom animation of a set of CSS properties.
/// 1 - animate(properties, duration, easing, complete)
/// 2 - animate(properties, options)
/// </summary>
/// <param name="prop" type="Object">
/// A map of CSS properties that the animation will move toward.
/// </param>
/// <param name="speed" type="Number">
/// A string or number determining how long the animation will run.
/// </param>
/// <param name="easing" type="String">
/// A string indicating which easing function to use for the transition.
/// </param>
/// <param name="callback" type="Function">
/// A function to call once the animation is complete.
/// </param>
/// <returns type="jQuery" />
var optall = jQuery.speed(speed, easing, callback);
if ( jQuery.isEmptyObject( prop ) ) {
return this.each( optall.complete, [ false ] );
}
// Do not change referenced properties as per-property easing will be lost
prop = jQuery.extend( {}, prop );
return this[ optall.queue === false ? "each" : "queue" ](function() {
// XXX 'this' does not always have a nodeName when running the
// test suite
if ( optall.queue === false ) {
jQuery._mark( this );
}
var opt = jQuery.extend( {}, optall ),
isElement = this.nodeType === 1,
hidden = isElement && jQuery(this).is(":hidden"),
name, val, p,
display, e,
parts, start, end, unit;
// will store per property easing and be used to determine when an animation is complete
opt.animatedProperties = {};
for ( p in prop ) {
// property name normalization
name = jQuery.camelCase( p );
if ( p !== name ) {
prop[ name ] = prop[ p ];
delete prop[ p ];
}
val = prop[ name ];
// easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default)
if ( jQuery.isArray( val ) ) {
opt.animatedProperties[ name ] = val[ 1 ];
val = prop[ name ] = val[ 0 ];
} else {
opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing';
}
if ( val === "hide" && hidden || val === "show" && !hidden ) {
return opt.complete.call( this );
}
if ( isElement && ( name === "height" || name === "width" ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height
// animated
if ( jQuery.css( this, "display" ) === "inline" &&
jQuery.css( this, "float" ) === "none" ) {
if ( !jQuery.support.inlineBlockNeedsLayout ) {
this.style.display = "inline-block";
} else {
display = defaultDisplay( this.nodeName );
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( display === "inline" ) {
this.style.display = "inline-block";
} else {
this.style.display = "inline";
this.style.zoom = 1;
}
}
}
}
}
if ( opt.overflow != null ) {
this.style.overflow = "hidden";
}
for ( p in prop ) {
e = new jQuery.fx( this, opt, p );
val = prop[ p ];
if ( rfxtypes.test(val) ) {
e[ val === "toggle" ? hidden ? "show" : "hide" : val ]();
} else {
parts = rfxnum.exec( val );
start = e.cur();
if ( parts ) {
end = parseFloat( parts[2] );
unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" ) {
jQuery.style( this, p, (end || 1) + unit);
start = ((end || 1) / e.cur()) * start;
jQuery.style( this, p, start + unit);
}
// If a +=/-= token was provided, we're doing a relative animation
if ( parts[1] ) {
end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start;
}
e.custom( start, end, unit );
} else {
e.custom( start, val, "" );
}
}
}
// For JS strict compliance
return true;
});
};
jQuery.prototype.append = function() {
/// <summary>
/// Insert content, specified by the parameter, to the end of each element in the set of matched elements.
/// 1 - append(content, content)
/// 2 - append(function(index, html))
/// </summary>
/// <param name="" type="jQuery">
/// DOM element, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.
/// </param>
/// <param name="" type="jQuery">
/// One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.
/// </param>
/// <returns type="jQuery" />
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.appendChild( elem );
}
});
};
jQuery.prototype.appendTo = function( selector ) {
/// <summary>
/// Insert every element in the set of matched elements to the end of the target.
/// </summary>
/// <param name="selector" type="jQuery">
/// A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter.
/// </param>
/// <returns type="jQuery" />
var ret = [],
insert = jQuery( selector ),
parent = this.length === 1 && this[0].parentNode;
if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = (i > 0 ? this.clone(true) : this).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
jQuery.prototype.attr = function( name, value ) {
/// <summary>
/// 1: Get the value of an attribute for the first element in the set of matched elements.
/// 1.1 - attr(attributeName)
/// 2: Set one or more attributes for the set of matched elements.
/// 2.1 - attr(attributeName, value)
/// 2.2 - attr(map)
/// 2.3 - attr(attributeName, function(index, attr))
/// </summary>
/// <param name="name" type="String">
/// The name of the attribute to set.
/// </param>
/// <param name="value" type="Number">
/// A value to set for the attribute.
/// </param>
/// <returns type="jQuery" />
return jQuery.access( this, name, value, true, jQuery.attr );
};
jQuery.prototype.before = function() {
/// <summary>
/// Insert content, specified by the parameter, before each element in the set of matched elements.
/// 1 - before(content, content)
/// 2 - before(function)
/// </summary>
/// <param name="" type="jQuery">
/// HTML string, DOM element, or jQuery object to insert before each element in the set of matched elements.
/// </param>
/// <param name="" type="jQuery">
/// One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert before each element in the set of matched elements.
/// </param>
/// <returns type="jQuery" />
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
} else if ( arguments.length ) {
var set = jQuery(arguments[0]);
set.push.apply( set, this.toArray() );
return this.pushStack( set, "before", arguments );
}
};
jQuery.prototype.bind = function( type, data, fn ) {
/// <summary>
/// Attach a handler to an event for the elements.
/// 1 - bind(eventType, eventData, handler(eventObject))
/// 2 - bind(eventType, eventData, false)
/// 3 - bind(events)
/// </summary>
/// <param name="type" type="String">
/// A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names.
/// </param>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
var handler;
// Handle object literals
if ( typeof type === "object" ) {
for ( var key in type ) {
this[ name ](key, data, type[key], fn);
}
return this;
}
if ( arguments.length === 2 || data === false ) {
fn = data;
data = undefined;
}
if ( name === "one" ) {
handler = function( event ) {
jQuery( this ).unbind( event, handler );
return fn.apply( this, arguments );
};
handler.guid = fn.guid || jQuery.guid++;
} else {
handler = fn;
}
if ( type === "unload" && name !== "one" ) {
this.one( type, data, fn );
} else {
for ( var i = 0, l = this.length; i < l; i++ ) {
jQuery.event.add( this[i], type, handler, data );
}
}
return this;
};
jQuery.prototype.blur = function( data, fn ) {
/// <summary>
/// Bind an event handler to the "blur" JavaScript event, or trigger that event on an element.
/// 1 - blur(handler(eventObject))
/// 2 - blur(eventData, handler(eventObject))
/// 3 - blur()
/// </summary>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
jQuery.prototype.change = function( data, fn ) {
/// <summary>
/// Bind an event handler to the "change" JavaScript event, or trigger that event on an element.
/// 1 - change(handler(eventObject))
/// 2 - change(eventData, handler(eventObject))
/// 3 - change()
/// </summary>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
jQuery.prototype.children = function( until, selector ) {
/// <summary>
/// Get the children of each element in the set of matched elements, optionally filtered by a selector.
/// </summary>
/// <param name="until" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="jQuery" />
var ret = jQuery.map( this, fn, until ),
// The variable 'args' was introduced in
// https://github.com/jquery/jquery/commit/52a0238
// to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
// http://code.google.com/p/v8/issues/detail?id=1050
args = slice.call(arguments);
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, args.join(",") );
};
jQuery.prototype.clearQueue = function( type ) {
/// <summary>
/// Remove from the queue all items that have not yet been run.
/// </summary>
/// <param name="type" type="String">
/// A string containing the name of the queue. Defaults to fx, the standard effects queue.
/// </param>
/// <returns type="jQuery" />
return this.queue( type || "fx", [] );
};
jQuery.prototype.click = function( data, fn ) {
/// <summary>
/// Bind an event handler to the "click" JavaScript event, or trigger that event on an element.
/// 1 - click(handler(eventObject))
/// 2 - click(eventData, handler(eventObject))
/// 3 - click()
/// </summary>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
jQuery.prototype.clone = function( dataAndEvents, deepDataAndEvents ) {
/// <summary>
/// Create a deep copy of the set of matched elements.
/// 1 - clone(withDataAndEvents)
/// 2 - clone(withDataAndEvents, deepWithDataAndEvents)
/// </summary>
/// <param name="dataAndEvents" type="Boolean">
/// A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false. *For 1.5.0 the default value is incorrectly true. This will be changed back to false in 1.5.1 and up.
/// </param>
/// <param name="deepDataAndEvents" type="Boolean">
/// A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to false).
/// </param>
/// <returns type="jQuery" />
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
};
jQuery.prototype.closest = function( selectors, context ) {
/// <summary>
/// 1: Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.
/// 1.1 - closest(selector)
/// 1.2 - closest(selector, context)
/// 1.3 - closest(jQuery object)
/// 1.4 - closest(element)
/// 2: Gets an array of all the elements and selectors matched against the current element up through the DOM tree.
/// 2.1 - closest(selectors, context)
/// </summary>
/// <param name="selectors" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <param name="context" domElement="true">
/// A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead.
/// </param>
/// <returns type="jQuery" />
var ret = [], i, l, cur = this[0];
// Array
if ( jQuery.isArray( selectors ) ) {
var match, selector,
matches = {},
level = 1;
if ( cur && selectors.length ) {
for ( i = 0, l = selectors.length; i < l; i++ ) {
selector = selectors[i];
if ( !matches[ selector ] ) {
matches[ selector ] = POS.test( selector ) ?
jQuery( selector, context || this.context ) :
selector;
}
}
while ( cur && cur.ownerDocument && cur !== context ) {
for ( selector in matches ) {
match = matches[ selector ];
if ( match.jquery ? match.index( cur ) > -1 : jQuery( cur ).is( match ) ) {
ret.push({ selector: selector, elem: cur, level: level });
}
}
cur = cur.parentNode;
level++;
}
}
return ret;
}
// String
var pos = POS.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( i = 0, l = this.length; i < l; i++ ) {
cur = this[i];
while ( cur ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
} else {
cur = cur.parentNode;
if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) {
break;
}
}
}
}
ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
return this.pushStack( ret, "closest", selectors );
};
jQuery.prototype.constructor = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
};
jQuery.prototype.contents = function( until, selector ) {
/// <summary>
/// Get the children of each element in the set of matched elements, including text and comment nodes.
/// </summary>
/// <returns type="jQuery" />
var ret = jQuery.map( this, fn, until ),
// The variable 'args' was introduced in
// https://github.com/jquery/jquery/commit/52a0238
// to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
// http://code.google.com/p/v8/issues/detail?id=1050
args = slice.call(arguments);
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, args.join(",") );
};
jQuery.prototype.css = function( name, value ) {
/// <summary>
/// 1: Get the value of a style property for the first element in the set of matched elements.
/// 1.1 - css(propertyName)
/// 2: Set one or more CSS properties for the set of matched elements.
/// 2.1 - css(propertyName, value)
/// 2.2 - css(propertyName, function(index, value))
/// 2.3 - css(map)
/// </summary>
/// <param name="name" type="String">
/// A CSS property name.
/// </param>
/// <param name="value" type="Number">
/// A value to set for the property.
/// </param>
/// <returns type="jQuery" />
// Setting 'undefined' is a no-op
if ( arguments.length === 2 && value === undefined ) {
return this;
}
return jQuery.access( this, name, value, true, function( elem, name, value ) {
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
});
};
jQuery.prototype.data = function( key, value ) {
/// <summary>
/// 1: Store arbitrary data associated with the matched elements.
/// 1.1 - data(key, value)
/// 1.2 - data(obj)
/// 2: Returns value at named data store for the first element in the jQuery collection, as set by data(name, value).
/// 2.1 - data(key)
/// 2.2 - data()
/// </summary>
/// <param name="key" type="String">
/// A string naming the piece of data to set.
/// </param>
/// <param name="value" type="Object">
/// The new data value; it can be any Javascript type including Array or Object.
/// </param>
/// <returns type="jQuery" />
var data = null;
if ( typeof key === "undefined" ) {
if ( this.length ) {
data = jQuery.data( this[0] );
if ( this[0].nodeType === 1 ) {
var attr = this[0].attributes, name;
for ( var i = 0, l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.substring(5) );
dataAttr( this[0], name, data[ name ] );
}
}
}
}
return data;
} else if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
var parts = key.split(".");
parts[1] = parts[1] ? "." + parts[1] : "";
if ( value === undefined ) {
data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
// Try to fetch any internally stored data first
if ( data === undefined && this.length ) {
data = jQuery.data( this[0], key );
data = dataAttr( this[0], key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
} else {
return this.each(function() {
var $this = jQuery( this ),
args = [ parts[0], value ];
$this.triggerHandler( "setData" + parts[1] + "!", args );
jQuery.data( this, key, value );
$this.triggerHandler( "changeData" + parts[1] + "!", args );
});
}
};
jQuery.prototype.dblclick = function( data, fn ) {
/// <summary>
/// Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element.
/// 1 - dblclick(handler(eventObject))
/// 2 - dblclick(eventData, handler(eventObject))
/// 3 - dblclick()
/// </summary>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
jQuery.prototype.delay = function( time, type ) {
/// <summary>
/// Set a timer to delay execution of subsequent items in the queue.
/// </summary>
/// <param name="time" type="Number">
/// An integer indicating the number of milliseconds to delay execution of the next item in the queue.
/// </param>
/// <param name="type" type="String">
/// A string containing the name of the queue. Defaults to fx, the standard effects queue.
/// </param>
/// <returns type="jQuery" />
time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
type = type || "fx";
return this.queue( type, function() {
var elem = this;
setTimeout(function() {
jQuery.dequeue( elem, type );
}, time );
});
};
jQuery.prototype.delegate = function( selector, types, data, fn ) {
/// <summary>
/// Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.
/// 1 - delegate(selector, eventType, handler)
/// 2 - delegate(selector, eventType, eventData, handler)
/// 3 - delegate(selector, events)
/// </summary>
/// <param name="selector" type="String">
/// A selector to filter the elements that trigger the event.
/// </param>
/// <param name="types" type="String">
/// A string containing one or more space-separated JavaScript event types, such as "click" or "keydown," or custom event names.
/// </param>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute at the time the event is triggered.
/// </param>
/// <returns type="jQuery" />
return this.live( types, data, fn, selector );
};
jQuery.prototype.dequeue = function( type ) {
/// <summary>
/// Execute the next function on the queue for the matched elements.
/// </summary>
/// <param name="type" type="String">
/// A string containing the name of the queue. Defaults to fx, the standard effects queue.
/// </param>
/// <returns type="jQuery" />
return this.each(function() {
jQuery.dequeue( this, type );
});
};
jQuery.prototype.detach = function( selector ) {
/// <summary>
/// Remove the set of matched elements from the DOM.
/// </summary>
/// <param name="selector" type="String">
/// A selector expression that filters the set of matched elements to be removed.
/// </param>
/// <returns type="jQuery" />
return this.remove( selector, true );
};
jQuery.prototype.die = function( types, data, fn, origSelector /* Internal Use Only */ ) {
/// <summary>
/// 1: Remove all event handlers previously attached using .live() from the elements.
/// 1.1 - die()
/// 2: Remove an event handler previously attached using .live() from the elements.
/// 2.1 - die(eventType, handler)
/// 2.2 - die(eventTypes)
/// </summary>
/// <param name="types" type="String">
/// A string containing a JavaScript event type, such as click or keydown.
/// </param>
/// <param name="data" type="String">
/// The function that is no longer to be executed.
/// </param>
/// <returns type="jQuery" />
var type, i = 0, match, namespaces, preType,
selector = origSelector || this.selector,
context = origSelector ? this : jQuery( this.context );
if ( typeof types === "object" && !types.preventDefault ) {
for ( var key in types ) {
context[ name ]( key, data, types[key], selector );
}
return this;
}
if ( name === "die" && !types &&
origSelector && origSelector.charAt(0) === "." ) {
context.unbind( origSelector );
return this;
}
if ( data === false || jQuery.isFunction( data ) ) {
fn = data || returnFalse;
data = undefined;
}
types = (types || "").split(" ");
while ( (type = types[ i++ ]) != null ) {
match = rnamespaces.exec( type );
namespaces = "";
if ( match ) {
namespaces = match[0];
type = type.replace( rnamespaces, "" );
}
if ( type === "hover" ) {
types.push( "mouseenter" + namespaces, "mouseleave" + namespaces );
continue;
}
preType = type;
if ( liveMap[ type ] ) {
types.push( liveMap[ type ] + namespaces );
type = type + namespaces;
} else {
type = (liveMap[ type ] || type) + namespaces;
}
if ( name === "live" ) {
// bind live handler
for ( var j = 0, l = context.length; j < l; j++ ) {
jQuery.event.add( context[j], "live." + liveConvert( type, selector ),
{ data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } );
}
} else {
// unbind live handler
context.unbind( "live." + liveConvert( type, selector ), fn );
}
}
return this;
};
jQuery.prototype.domManip = function( args, table, callback ) {
var results, first, fragment, parent,
value = args[0],
scripts = [];
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback, true );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call(this, i, table ? self.html() : undefined);
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
parent = value && value.parentNode;
// If we're in a fragment, just use that instead of building a new one
if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
results = { fragment: parent };
} else {
results = jQuery.buildFragment( args, this, scripts );
}
fragment = results.fragment;
if ( fragment.childNodes.length === 1 ) {
first = fragment = fragment.firstChild;
} else {
first = fragment.firstChild;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) {
callback.call(
table ?
root(this[i], first) :
this[i],
// Make sure that we do not leak memory by inadvertently discarding
// the original fragment (which might have attached data) instead of
// using it; in addition, use the original fragment object for the last
// item instead of first because it can end up being emptied incorrectly
// in certain situations (Bug #8070).
// Fragments from the fragment cache must always be cloned and never used
// in place.
results.cacheable || (l > 1 && i < lastIndex) ?
jQuery.clone( fragment, true, true ) :
fragment
);
}
}
if ( scripts.length ) {
jQuery.each( scripts, evalScript );
}
}
return this;
};
jQuery.prototype.each = function( callback, args ) {
/// <summary>
/// Iterate over a jQuery object, executing a function for each matched element.
/// </summary>
/// <param name="callback" type="Function">
/// A function to execute for each matched element.
/// </param>
/// <returns type="jQuery" />
return jQuery.each( this, callback, args );
};
jQuery.prototype.empty = function() {
/// <summary>
/// Remove all child nodes of the set of matched elements from the DOM.
/// </summary>
/// <returns type="jQuery" />
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
return this;
};
jQuery.prototype.end = function() {
/// <summary>
/// End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.
/// </summary>
/// <returns type="jQuery" />
return this.prevObject || this.constructor(null);
};
jQuery.prototype.eq = function( i ) {
/// <summary>
/// Reduce the set of matched elements to the one at the specified index.
/// 1 - eq(index)
/// 2 - eq(-index)
/// </summary>
/// <param name="i" type="Number">
/// An integer indicating the 0-based position of the element.
/// </param>
/// <returns type="jQuery" />
return i === -1 ?
this.slice( i ) :
this.slice( i, +i + 1 );
};
jQuery.prototype.error = function( data, fn ) {
/// <summary>
/// Bind an event handler to the "error" JavaScript event.
/// 1 - error(handler(eventObject))
/// 2 - error(eventData, handler(eventObject))
/// </summary>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
jQuery.prototype.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.prototype.fadeIn = function( speed, easing, callback ) {
/// <summary>
/// Display the matched elements by fading them to opaque.
/// 1 - fadeIn(duration, callback)
/// 2 - fadeIn(duration, easing, callback)
/// </summary>
/// <param name="speed" type="Number">
/// A string or number determining how long the animation will run.
/// </param>
/// <param name="easing" type="String">
/// A string indicating which easing function to use for the transition.
/// </param>
/// <param name="callback" type="Function">
/// A function to call once the animation is complete.
/// </param>
/// <returns type="jQuery" />
return this.animate( props, speed, easing, callback );
};
jQuery.prototype.fadeOut = function( speed, easing, callback ) {
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// 1 - fadeOut(duration, callback)
/// 2 - fadeOut(duration, easing, callback)
/// </summary>
/// <param name="speed" type="Number">
/// A string or number determining how long the animation will run.
/// </param>
/// <param name="easing" type="String">
/// A string indicating which easing function to use for the transition.
/// </param>
/// <param name="callback" type="Function">
/// A function to call once the animation is complete.
/// </param>
/// <returns type="jQuery" />
return this.animate( props, speed, easing, callback );
};
jQuery.prototype.fadeTo = function( speed, to, easing, callback ) {
/// <summary>
/// Adjust the opacity of the matched elements.
/// 1 - fadeTo(duration, opacity, callback)
/// 2 - fadeTo(duration, opacity, easing, callback)
/// </summary>
/// <param name="speed" type="Number">
/// A string or number determining how long the animation will run.
/// </param>
/// <param name="to" type="Number">
/// A number between 0 and 1 denoting the target opacity.
/// </param>
/// <param name="easing" type="String">
/// A string indicating which easing function to use for the transition.
/// </param>
/// <param name="callback" type="Function">
/// A function to call once the animation is complete.
/// </param>
/// <returns type="jQuery" />
return this.filter(":hidden").css("opacity", 0).show().end()
.animate({opacity: to}, speed, easing, callback);
};
jQuery.prototype.fadeToggle = function( speed, easing, callback ) {
/// <summary>
/// Display or hide the matched elements by animating their opacity.
/// </summary>
/// <param name="speed" type="Number">
/// A string or number determining how long the animation will run.
/// </param>
/// <param name="easing" type="String">
/// A string indicating which easing function to use for the transition.
/// </param>
/// <param name="callback" type="Function">
/// A function to call once the animation is complete.
/// </param>
/// <returns type="jQuery" />
return this.animate( props, speed, easing, callback );
};
jQuery.prototype.filter = function( selector ) {
/// <summary>
/// Reduce the set of matched elements to those that match the selector or pass the function's test.
/// 1 - filter(selector)
/// 2 - filter(function(index))
/// 3 - filter(element)
/// 4 - filter(jQuery object)
/// </summary>
/// <param name="selector" type="String">
/// A string containing a selector expression to match the current set of elements against.
/// </param>
/// <returns type="jQuery" />
return this.pushStack( winnow(this, selector, true), "filter", selector );
};
jQuery.prototype.find = function( selector ) {
/// <summary>
/// Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
/// 1 - find(selector)
/// 2 - find(jQuery object)
/// 3 - find(element)
/// </summary>
/// <param name="selector" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="jQuery" />
var self = this,
i, l;
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
});
}
var ret = this.pushStack( "", "find", selector ),
length, n, r;
for ( i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
if ( i > 0 ) {
// Make sure that the results are unique
for ( n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
};
jQuery.prototype.first = function() {
/// <summary>
/// Reduce the set of matched elements to the first in the set.
/// </summary>
/// <returns type="jQuery" />
return this.eq( 0 );
};
jQuery.prototype.focus = function( data, fn ) {
/// <summary>
/// Bind an event handler to the "focus" JavaScript event, or trigger that event on an element.
/// 1 - focus(handler(eventObject))
/// 2 - focus(eventData, handler(eventObject))
/// 3 - focus()
/// </summary>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
jQuery.prototype.focusin = function( data, fn ) {
/// <summary>
/// Bind an event handler to the "focusin" JavaScript event.
/// 1 - focusin(handler(eventObject))
/// 2 - focusin(eventData, handler(eventObject))
/// </summary>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
jQuery.prototype.focusout = function( data, fn ) {
/// <summary>
/// Bind an event handler to the "focusout" JavaScript event.
/// 1 - focusout(handler(eventObject))
/// 2 - focusout(eventData, handler(eventObject))
/// </summary>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
jQuery.prototype.get = function( num ) {
/// <summary>
/// Retrieve the DOM elements matched by the jQuery object.
/// </summary>
/// <param name="num" type="Number">
/// A zero-based integer indicating which element to retrieve.
/// </param>
/// <returns type="Array" />
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
};
jQuery.prototype.has = function( target ) {
/// <summary>
/// Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.
/// 1 - has(selector)
/// 2 - has(contained)
/// </summary>
/// <param name="target" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="jQuery" />
var targets = jQuery( target );
return this.filter(function() {
for ( var i = 0, l = targets.length; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
};
jQuery.prototype.hasClass = function( selector ) {
/// <summary>
/// Determine whether any of the matched elements are assigned the given class.
/// </summary>
/// <param name="selector" type="String">
/// The class name to search for.
/// </param>
/// <returns type="Boolean" />
var className = " " + selector + " ";
for ( var i = 0, l = this.length; i < l; i++ ) {
if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
return true;
}
}
return false;
};
jQuery.prototype.height = function( size ) {
/// <summary>
/// 1: Get the current computed height for the first element in the set of matched elements.
/// 1.1 - height()
/// 2: Set the CSS height of every matched element.
/// 2.1 - height(value)
/// 2.2 - height(function(index, height))
/// </summary>
/// <param name="size" type="Number">
/// An integer representing the number of pixels, or an integer with an optional unit of measure appended (as a string).
/// </param>
/// <returns type="jQuery" />
// Get window width or height
var elem = this[0];
if ( !elem ) {
return size == null ? null : this;
}
if ( jQuery.isFunction( size ) ) {
return this.each(function( i ) {
var self = jQuery( this );
self[ type ]( size.call( this, i, self[ type ]() ) );
});
}
if ( jQuery.isWindow( elem ) ) {
// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
// 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
var docElemProp = elem.document.documentElement[ "client" + name ];
return elem.document.compatMode === "CSS1Compat" && docElemProp ||
elem.document.body[ "client" + name ] || docElemProp;
// Get document width or height
} else if ( elem.nodeType === 9 ) {
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
return Math.max(
elem.documentElement["client" + name],
elem.body["scroll" + name], elem.documentElement["scroll" + name],
elem.body["offset" + name], elem.documentElement["offset" + name]
);
// Get or set width or height on the element
} else if ( size === undefined ) {
var orig = jQuery.css( elem, type ),
ret = parseFloat( orig );
return jQuery.isNaN( ret ) ? orig : ret;
// Set the width or height on the element (default to pixels if value is unitless)
} else {
return this.css( type, typeof size === "string" ? size : size + "px" );
}
};
jQuery.prototype.hide = function( speed, easing, callback ) {
/// <summary>
/// Hide the matched elements.
/// 1 - hide()
/// 2 - hide(duration, callback)
/// 3 - hide(duration, easing, callback)
/// </summary>
/// <param name="speed" type="Number">
/// A string or number determining how long the animation will run.
/// </param>
/// <param name="easing" type="String">
/// A string indicating which easing function to use for the transition.
/// </param>
/// <param name="callback" type="Function">
/// A function to call once the animation is complete.
/// </param>
/// <returns type="jQuery" />
if ( speed || speed === 0 ) {
return this.animate( genFx("hide", 3), speed, easing, callback);
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
if ( this[i].style ) {
var display = jQuery.css( this[i], "display" );
if ( display !== "none" && !jQuery._data( this[i], "olddisplay" ) ) {
jQuery._data( this[i], "olddisplay", display );
}
}
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
if ( this[i].style ) {
this[i].style.display = "none";
}
}
return this;
}
};
jQuery.prototype.hover = function( fnOver, fnOut ) {
/// <summary>
/// 1: Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.
/// 1.1 - hover(handlerIn(eventObject), handlerOut(eventObject))
/// 2: Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements.
/// 2.1 - hover(handlerInOut(eventObject))
/// </summary>
/// <param name="fnOver" type="Function">
/// A function to execute when the mouse pointer enters the element.
/// </param>
/// <param name="fnOut" type="Function">
/// A function to execute when the mouse pointer leaves the element.
/// </param>
/// <returns type="jQuery" />
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
};
jQuery.prototype.html = function( value ) {
/// <summary>
/// 1: Get the HTML contents of the first element in the set of matched elements.
/// 1.1 - html()
/// 2: Set the HTML contents of each element in the set of matched elements.
/// 2.1 - html(htmlString)
/// 2.2 - html(function(index, oldhtml))
/// </summary>
/// <param name="value" type="String">
/// A string of HTML to set as the content of each matched element.
/// </param>
/// <returns type="jQuery" />
if ( value === undefined ) {
return this[0] && this[0].nodeType === 1 ?
this[0].innerHTML.replace(rinlinejQuery, "") :
null;
// See if we can take a shortcut and just use innerHTML
} else if ( typeof value === "string" && !rnocache.test( value ) &&
(jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
!wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
value = value.replace(rxhtmlTag, "<$1></$2>");
try {
for ( var i = 0, l = this.length; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
if ( this[i].nodeType === 1 ) {
jQuery.cleanData( this[i].getElementsByTagName("*") );
this[i].innerHTML = value;
}
}
// If using innerHTML throws an exception, use the fallback method
} catch(e) {
this.empty().append( value );
}
} else if ( jQuery.isFunction( value ) ) {
this.each(function(i){
var self = jQuery( this );
self.html( value.call(this, i, self.html()) );
});
} else {
this.empty().append( value );
}
return this;
};
jQuery.prototype.index = function( elem ) {
/// <summary>
/// Search for a given element from among the matched elements.
/// 1 - index()
/// 2 - index(selector)
/// 3 - index(element)
/// </summary>
/// <param name="elem" type="String">
/// A selector representing a jQuery collection in which to look for an element.
/// </param>
/// <returns type="Number" />
if ( !elem || typeof elem === "string" ) {
return jQuery.inArray( this[0],
// If it receives a string, the selector is used
// If it receives nothing, the siblings are used
elem ? jQuery( elem ) : this.parent().children() );
}
// 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 );
};
jQuery.prototype.init = function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), or $(undefined)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// The body element only exists once, optimize finding it
if ( selector === "body" && !context && document.body ) {
this.context = document;
this[0] = document.body;
this.selector = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
// Are we dealing with HTML string or an ID?
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = quickExpr.exec( selector );
}
// Verify a match, and that no context was specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = (context ? context.ownerDocument || context : document);
// If a single string is passed in and it's a single tag
// just do a createElement and skip the rest
ret = rsingleTag.exec( selector );
if ( ret ) {
if ( jQuery.isPlainObject( context ) ) {
selector = [ document.createElement( ret[1] ) ];
jQuery.fn.attr.call( selector, context, true );
} else {
selector = [ doc.createElement( ret[1] ) ];
}
} else {
ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes;
}
return jQuery.merge( this, selector );
// HANDLE: $("#id")
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return (context || rootjQuery).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if (selector.selector !== undefined) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
};
jQuery.prototype.innerHeight = function() {
/// <summary>
/// Get the current computed height for the first element in the set of matched elements, including padding but not border.
/// </summary>
/// <returns type="Number" />
return this[0] ?
parseFloat( jQuery.css( this[0], type, "padding" ) ) :
null;
};
jQuery.prototype.innerWidth = function() {
/// <summary>
/// Get the current computed width for the first element in the set of matched elements, including padding but not border.
/// </summary>
/// <returns type="Number" />
return this[0] ?
parseFloat( jQuery.css( this[0], type, "padding" ) ) :
null;
};
jQuery.prototype.insertAfter = function( selector ) {
/// <summary>
/// Insert every element in the set of matched elements after the target.
/// </summary>
/// <param name="selector" type="jQuery">
/// A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter.
/// </param>
/// <returns type="jQuery" />
var ret = [],
insert = jQuery( selector ),
parent = this.length === 1 && this[0].parentNode;
if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = (i > 0 ? this.clone(true) : this).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
jQuery.prototype.insertBefore = function( selector ) {
/// <summary>
/// Insert every element in the set of matched elements before the target.
/// </summary>
/// <param name="selector" type="jQuery">
/// A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter.
/// </param>
/// <returns type="jQuery" />
var ret = [],
insert = jQuery( selector ),
parent = this.length === 1 && this[0].parentNode;
if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = (i > 0 ? this.clone(true) : this).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
jQuery.prototype.is = function( selector ) {
/// <summary>
/// Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
/// 1 - is(selector)
/// 2 - is(function(index))
/// 3 - is(jQuery object)
/// 4 - is(element)
/// </summary>
/// <param name="selector" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="Boolean" />
return !!selector && ( typeof selector === "string" ?
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
};
jQuery.prototype.keydown = function( data, fn ) {
/// <summary>
/// Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element.
/// 1 - keydown(handler(eventObject))
/// 2 - keydown(eventData, handler(eventObject))
/// 3 - keydown()
/// </summary>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
jQuery.prototype.keypress = function( data, fn ) {
/// <summary>
/// Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element.
/// 1 - keypress(handler(eventObject))
/// 2 - keypress(eventData, handler(eventObject))
/// 3 - keypress()
/// </summary>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
jQuery.prototype.keyup = function( data, fn ) {
/// <summary>
/// Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element.
/// 1 - keyup(handler(eventObject))
/// 2 - keyup(eventData, handler(eventObject))
/// 3 - keyup()
/// </summary>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
jQuery.prototype.last = function() {
/// <summary>
/// Reduce the set of matched elements to the final one in the set.
/// </summary>
/// <returns type="jQuery" />
return this.eq( -1 );
};
jQuery.prototype.length = 0;
jQuery.prototype.live = function( types, data, fn, origSelector /* Internal Use Only */ ) {
/// <summary>
/// Attach a handler to the event for all elements which match the current selector, now and in the future.
/// 1 - live(eventType, handler)
/// 2 - live(eventType, eventData, handler)
/// 3 - live(events)
/// </summary>
/// <param name="types" type="String">
/// A string containing a JavaScript event type, such as "click" or "keydown." As of jQuery 1.4 the string can contain multiple, space-separated event types or custom event names, as well.
/// </param>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute at the time the event is triggered.
/// </param>
/// <returns type="jQuery" />
var type, i = 0, match, namespaces, preType,
selector = origSelector || this.selector,
context = origSelector ? this : jQuery( this.context );
if ( typeof types === "object" && !types.preventDefault ) {
for ( var key in types ) {
context[ name ]( key, data, types[key], selector );
}
return this;
}
if ( name === "die" && !types &&
origSelector && origSelector.charAt(0) === "." ) {
context.unbind( origSelector );
return this;
}
if ( data === false || jQuery.isFunction( data ) ) {
fn = data || returnFalse;
data = undefined;
}
types = (types || "").split(" ");
while ( (type = types[ i++ ]) != null ) {
match = rnamespaces.exec( type );
namespaces = "";
if ( match ) {
namespaces = match[0];
type = type.replace( rnamespaces, "" );
}
if ( type === "hover" ) {
types.push( "mouseenter" + namespaces, "mouseleave" + namespaces );
continue;
}
preType = type;
if ( liveMap[ type ] ) {
types.push( liveMap[ type ] + namespaces );
type = type + namespaces;
} else {
type = (liveMap[ type ] || type) + namespaces;
}
if ( name === "live" ) {
// bind live handler
for ( var j = 0, l = context.length; j < l; j++ ) {
jQuery.event.add( context[j], "live." + liveConvert( type, selector ),
{ data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } );
}
} else {
// unbind live handler
context.unbind( "live." + liveConvert( type, selector ), fn );
}
}
return this;
};
jQuery.prototype.load = function( url, params, callback ) {
/// <summary>
/// 1: Bind an event handler to the "load" JavaScript event.
/// 1.1 - load(handler(eventObject))
/// 1.2 - load(eventData, handler(eventObject))
/// 2: Load data from the server and place the returned HTML into the matched element.
/// 2.1 - load(url, data, complete(responseText, textStatus, XMLHttpRequest))
/// </summary>
/// <param name="url" type="String">
/// A string containing the URL to which the request is sent.
/// </param>
/// <param name="params" type="String">
/// A map or string that is sent to the server with the request.
/// </param>
/// <param name="callback" type="Function">
/// A callback function that is executed when the request completes.
/// </param>
/// <returns type="jQuery" />
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
// Don't do a request if no elements are being requested
} else if ( !this.length ) {
return this;
}
var off = url.indexOf( " " );
if ( off >= 0 ) {
var selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// Default to a GET request
var type = "GET";
// If the second parameter was provided
if ( params ) {
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( typeof params === "object" ) {
params = jQuery.param( params, jQuery.ajaxSettings.traditional );
type = "POST";
}
}
var self = this;
// Request the remote document
jQuery.ajax({
url: url,
type: type,
dataType: "html",
data: params,
// Complete callback (responseText is used internally)
complete: function( jqXHR, status, responseText ) {
// Store the response as specified by the jqXHR object
responseText = jqXHR.responseText;
// If successful, inject the HTML into all the matched elements
if ( jqXHR.isResolved() ) {
// #4825: Get the actual response in case
// a dataFilter is present in ajaxSettings
jqXHR.done(function( r ) {
responseText = r;
});
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(responseText.replace(rscript, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
responseText );
}
if ( callback ) {
self.each( callback, [ responseText, status, jqXHR ] );
}
}
});
return this;
};
jQuery.prototype.map = function( callback ) {
/// <summary>
/// Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.
/// </summary>
/// <param name="callback" type="Function">
/// A function object that will be invoked for each element in the current set.
/// </param>
/// <returns type="jQuery" />
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
};
jQuery.prototype.mousedown = function( data, fn ) {
/// <summary>
/// Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element.
/// 1 - mousedown(handler(eventObject))
/// 2 - mousedown(eventData, handler(eventObject))
/// 3 - mousedown()
/// </summary>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
jQuery.prototype.mouseenter = function( data, fn ) {
/// <summary>
/// Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.
/// 1 - mouseenter(handler(eventObject))
/// 2 - mouseenter(eventData, handler(eventObject))
/// 3 - mouseenter()
/// </summary>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
jQuery.prototype.mouseleave = function( data, fn ) {
/// <summary>
/// Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element.
/// 1 - mouseleave(handler(eventObject))
/// 2 - mouseleave(eventData, handler(eventObject))
/// 3 - mouseleave()
/// </summary>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
jQuery.prototype.mousemove = function( data, fn ) {
/// <summary>
/// Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element.
/// 1 - mousemove(handler(eventObject))
/// 2 - mousemove(eventData, handler(eventObject))
/// 3 - mousemove()
/// </summary>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
jQuery.prototype.mouseout = function( data, fn ) {
/// <summary>
/// Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element.
/// 1 - mouseout(handler(eventObject))
/// 2 - mouseout(eventData, handler(eventObject))
/// 3 - mouseout()
/// </summary>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
jQuery.prototype.mouseover = function( data, fn ) {
/// <summary>
/// Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.
/// 1 - mouseover(handler(eventObject))
/// 2 - mouseover(eventData, handler(eventObject))
/// 3 - mouseover()
/// </summary>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
jQuery.prototype.mouseup = function( data, fn ) {
/// <summary>
/// Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element.
/// 1 - mouseup(handler(eventObject))
/// 2 - mouseup(eventData, handler(eventObject))
/// 3 - mouseup()
/// </summary>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
jQuery.prototype.next = function( until, selector ) {
/// <summary>
/// Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
/// </summary>
/// <param name="until" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="jQuery" />
var ret = jQuery.map( this, fn, until ),
// The variable 'args' was introduced in
// https://github.com/jquery/jquery/commit/52a0238
// to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
// http://code.google.com/p/v8/issues/detail?id=1050
args = slice.call(arguments);
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, args.join(",") );
};
jQuery.prototype.nextAll = function( until, selector ) {
/// <summary>
/// Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.
/// </summary>
/// <param name="until" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="jQuery" />
var ret = jQuery.map( this, fn, until ),
// The variable 'args' was introduced in
// https://github.com/jquery/jquery/commit/52a0238
// to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
// http://code.google.com/p/v8/issues/detail?id=1050
args = slice.call(arguments);
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, args.join(",") );
};
jQuery.prototype.nextUntil = function( until, selector ) {
/// <summary>
/// Get all following siblings of each element up to but not including the element matched by the selector.
/// </summary>
/// <param name="until" type="String">
/// A string containing a selector expression to indicate where to stop matching following sibling elements.
/// </param>
/// <returns type="jQuery" />
var ret = jQuery.map( this, fn, until ),
// The variable 'args' was introduced in
// https://github.com/jquery/jquery/commit/52a0238
// to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
// http://code.google.com/p/v8/issues/detail?id=1050
args = slice.call(arguments);
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, args.join(",") );
};
jQuery.prototype.not = function( selector ) {
/// <summary>
/// Remove elements from the set of matched elements.
/// 1 - not(selector)
/// 2 - not(elements)
/// 3 - not(function(index))
/// </summary>
/// <param name="selector" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="jQuery" />
return this.pushStack( winnow(this, selector, false), "not", selector);
};
jQuery.prototype.offset = function( options ) {
/// <summary>
/// 1: Get the current coordinates of the first element in the set of matched elements, relative to the document.
/// 1.1 - offset()
/// 2: Set the current coordinates of every element in the set of matched elements, relative to the document.
/// 2.1 - offset(coordinates)
/// 2.2 - offset(function(index, coords))
/// </summary>
/// <param name="options" type="Object">
/// An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements.
/// </param>
/// <returns type="jQuery" />
var elem = this[0], box;
if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
if ( !elem || !elem.ownerDocument ) {
return null;
}
if ( elem === elem.ownerDocument.body ) {
return jQuery.offset.bodyOffset( elem );
}
try {
box = elem.getBoundingClientRect();
} catch(e) {}
var doc = elem.ownerDocument,
docElem = doc.documentElement;
// Make sure we're not dealing with a disconnected DOM node
if ( !box || !jQuery.contains( docElem, elem ) ) {
return box ? { top: box.top, left: box.left } : { top: 0, left: 0 };
}
var body = doc.body,
win = getWindow(doc),
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop,
scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft,
top = box.top + scrollTop - clientTop,
left = box.left + scrollLeft - clientLeft;
return { top: top, left: left };
};
jQuery.prototype.offsetParent = function() {
/// <summary>
/// Get the closest ancestor element that is positioned.
/// </summary>
/// <returns type="jQuery" />
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent;
});
};
jQuery.prototype.one = function( type, data, fn ) {
/// <summary>
/// Attach a handler to an event for the elements. The handler is executed at most once per element.
/// </summary>
/// <param name="type" type="String">
/// A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names.
/// </param>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute at the time the event is triggered.
/// </param>
/// <returns type="jQuery" />
var handler;
// Handle object literals
if ( typeof type === "object" ) {
for ( var key in type ) {
this[ name ](key, data, type[key], fn);
}
return this;
}
if ( arguments.length === 2 || data === false ) {
fn = data;
data = undefined;
}
if ( name === "one" ) {
handler = function( event ) {
jQuery( this ).unbind( event, handler );
return fn.apply( this, arguments );
};
handler.guid = fn.guid || jQuery.guid++;
} else {
handler = fn;
}
if ( type === "unload" && name !== "one" ) {
this.one( type, data, fn );
} else {
for ( var i = 0, l = this.length; i < l; i++ ) {
jQuery.event.add( this[i], type, handler, data );
}
}
return this;
};
jQuery.prototype.outerHeight = function( margin ) {
/// <summary>
/// Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin.
/// </summary>
/// <param name="margin" type="Boolean">
/// A Boolean indicating whether to include the element's margin in the calculation.
/// </param>
/// <returns type="Number" />
return this[0] ?
parseFloat( jQuery.css( this[0], type, margin ? "margin" : "border" ) ) :
null;
};
jQuery.prototype.outerWidth = function( margin ) {
/// <summary>
/// Get the current computed width for the first element in the set of matched elements, including padding and border.
/// </summary>
/// <param name="margin" type="Boolean">
/// A Boolean indicating whether to include the element's margin in the calculation.
/// </param>
/// <returns type="Number" />
return this[0] ?
parseFloat( jQuery.css( this[0], type, margin ? "margin" : "border" ) ) :
null;
};
jQuery.prototype.parent = function( until, selector ) {
/// <summary>
/// Get the parent of each element in the current set of matched elements, optionally filtered by a selector.
/// </summary>
/// <param name="until" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="jQuery" />
var ret = jQuery.map( this, fn, until ),
// The variable 'args' was introduced in
// https://github.com/jquery/jquery/commit/52a0238
// to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
// http://code.google.com/p/v8/issues/detail?id=1050
args = slice.call(arguments);
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, args.join(",") );
};
jQuery.prototype.parents = function( until, selector ) {
/// <summary>
/// Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.
/// </summary>
/// <param name="until" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="jQuery" />
var ret = jQuery.map( this, fn, until ),
// The variable 'args' was introduced in
// https://github.com/jquery/jquery/commit/52a0238
// to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
// http://code.google.com/p/v8/issues/detail?id=1050
args = slice.call(arguments);
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, args.join(",") );
};
jQuery.prototype.parentsUntil = function( until, selector ) {
/// <summary>
/// Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector.
/// </summary>
/// <param name="until" type="String">
/// A string containing a selector expression to indicate where to stop matching ancestor elements.
/// </param>
/// <returns type="jQuery" />
var ret = jQuery.map( this, fn, until ),
// The variable 'args' was introduced in
// https://github.com/jquery/jquery/commit/52a0238
// to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
// http://code.google.com/p/v8/issues/detail?id=1050
args = slice.call(arguments);
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, args.join(",") );
};
jQuery.prototype.position = function() {
/// <summary>
/// Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.
/// </summary>
/// <returns type="Object" />
if ( !this[0] ) {
return null;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
};
jQuery.prototype.prepend = function() {
/// <summary>
/// Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.
/// 1 - prepend(content, content)
/// 2 - prepend(function(index, html))
/// </summary>
/// <param name="" type="jQuery">
/// DOM element, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements.
/// </param>
/// <param name="" type="jQuery">
/// One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the beginning of each element in the set of matched elements.
/// </param>
/// <returns type="jQuery" />
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.insertBefore( elem, this.firstChild );
}
});
};
jQuery.prototype.prependTo = function( selector ) {
/// <summary>
/// Insert every element in the set of matched elements to the beginning of the target.
/// </summary>
/// <param name="selector" type="jQuery">
/// A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter.
/// </param>
/// <returns type="jQuery" />
var ret = [],
insert = jQuery( selector ),
parent = this.length === 1 && this[0].parentNode;
if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = (i > 0 ? this.clone(true) : this).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
jQuery.prototype.prev = function( until, selector ) {
/// <summary>
/// Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.
/// </summary>
/// <param name="until" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="jQuery" />
var ret = jQuery.map( this, fn, until ),
// The variable 'args' was introduced in
// https://github.com/jquery/jquery/commit/52a0238
// to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
// http://code.google.com/p/v8/issues/detail?id=1050
args = slice.call(arguments);
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, args.join(",") );
};
jQuery.prototype.prevAll = function( until, selector ) {
/// <summary>
/// Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector.
/// </summary>
/// <param name="until" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="jQuery" />
var ret = jQuery.map( this, fn, until ),
// The variable 'args' was introduced in
// https://github.com/jquery/jquery/commit/52a0238
// to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
// http://code.google.com/p/v8/issues/detail?id=1050
args = slice.call(arguments);
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, args.join(",") );
};
jQuery.prototype.prevUntil = function( until, selector ) {
/// <summary>
/// Get all preceding siblings of each element up to but not including the element matched by the selector.
/// </summary>
/// <param name="until" type="String">
/// A string containing a selector expression to indicate where to stop matching preceding sibling elements.
/// </param>
/// <returns type="jQuery" />
var ret = jQuery.map( this, fn, until ),
// The variable 'args' was introduced in
// https://github.com/jquery/jquery/commit/52a0238
// to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
// http://code.google.com/p/v8/issues/detail?id=1050
args = slice.call(arguments);
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, args.join(",") );
};
jQuery.prototype.promise = function( type, object ) {
/// <summary>
/// Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished.
/// </summary>
/// <param name="type" type="String">
/// The type of queue that needs to be observed.
/// </param>
/// <param name="object" type="Object">
/// Object onto which the promise methods have to be attached
/// </param>
/// <returns type="Promise" />
if ( typeof type !== "string" ) {
object = type;
type = undefined;
}
type = type || "fx";
var defer = jQuery.Deferred(),
elements = this,
i = elements.length,
count = 1,
deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark",
tmp;
function resolve() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
}
while( i-- ) {
if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) ||
( jQuery.data( elements[ i ], queueDataKey, undefined, true ) ||
jQuery.data( elements[ i ], markDataKey, undefined, true ) ) &&
jQuery.data( elements[ i ], deferDataKey, jQuery._Deferred(), true ) )) {
count++;
tmp.done( resolve );
}
}
resolve();
return defer.promise();
};
jQuery.prototype.prop = function( name, value ) {
/// <summary>
/// 1: Get the value of a property for the first element in the set of matched elements.
/// 1.1 - prop(propertyName)
/// 2: Set one or more properties for the set of matched elements.
/// 2.1 - prop(propertyName, value)
/// 2.2 - prop(map)
/// 2.3 - prop(propertyName, function(index, oldPropertyValue))
/// </summary>
/// <param name="name" type="String">
/// The name of the property to set.
/// </param>
/// <param name="value" type="Boolean">
/// A value to set for the property.
/// </param>
/// <returns type="jQuery" />
return jQuery.access( this, name, value, true, jQuery.prop );
};
jQuery.prototype.pushStack = function( elems, name, selector ) {
/// <summary>
/// Add a collection of DOM elements onto the jQuery stack.
/// 1 - pushStack(elements)
/// 2 - pushStack(elements, name, arguments)
/// </summary>
/// <param name="elems" type="Array">
/// An array of elements to push onto the stack and make into a new jQuery object.
/// </param>
/// <param name="name" type="String">
/// The name of a jQuery method that generated the array of elements.
/// </param>
/// <param name="selector" type="Array">
/// The arguments that were passed in to the jQuery method (for serialization).
/// </param>
/// <returns type="jQuery" />
// Build a new jQuery matched element set
var ret = this.constructor();
if ( jQuery.isArray( elems ) ) {
push.apply( ret, elems );
} else {
jQuery.merge( ret, elems );
}
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + (this.selector ? " " : "") + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
};
jQuery.prototype.queue = function( type, data ) {
/// <summary>
/// 1: Show the queue of functions to be executed on the matched elements.
/// 1.1 - queue(queueName)
/// 2: Manipulate the queue of functions to be executed on the matched elements.
/// 2.1 - queue(queueName, newQueue)
/// 2.2 - queue(queueName, callback( next ))
/// </summary>
/// <param name="type" type="String">
/// A string containing the name of the queue. Defaults to fx, the standard effects queue.
/// </param>
/// <param name="data" type="Array">
/// An array of functions to replace the current queue contents.
/// </param>
/// <returns type="jQuery" />
if ( typeof type !== "string" ) {
data = type;
type = "fx";
}
if ( data === undefined ) {
return jQuery.queue( this[0], type );
}
return this.each(function() {
var queue = jQuery.queue( this, type, data );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
};
jQuery.prototype.ready = function( fn ) {
/// <summary>
/// Specify a function to execute when the DOM is fully loaded.
/// </summary>
/// <param name="fn" type="Function">
/// A function to execute after the DOM is ready.
/// </param>
/// <returns type="jQuery" />
// Attach the listeners
jQuery.bindReady();
// Add the callback
readyList.done( fn );
return this;
};
jQuery.prototype.remove = function( selector, keepData ) {
/// <summary>
/// Remove the set of matched elements from the DOM.
/// </summary>
/// <param name="selector" type="String">
/// A selector expression that filters the set of matched elements to be removed.
/// </param>
/// <returns type="jQuery" />
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
};
jQuery.prototype.removeAttr = function( name ) {
/// <summary>
/// Remove an attribute from each element in the set of matched elements.
/// </summary>
/// <param name="name" type="String">
/// An attribute to remove.
/// </param>
/// <returns type="jQuery" />
return this.each(function() {
jQuery.removeAttr( this, name );
});
};
jQuery.prototype.removeClass = function( value ) {
/// <summary>
/// Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
/// 1 - removeClass(className)
/// 2 - removeClass(function(index, class))
/// </summary>
/// <param name="value" type="String">
/// One or more space-separated classes to be removed from the class attribute of each matched element.
/// </param>
/// <returns type="jQuery" />
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
self.removeClass( value.call(this, i, self.attr("class")) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
var classNames = (value || "").split( rspace );
for ( var i = 0, l = this.length; i < l; i++ ) {
var elem = this[i];
if ( elem.nodeType === 1 && elem.className ) {
if ( value ) {
var className = (" " + elem.className + " ").replace(rclass, " ");
for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
className = className.replace(" " + classNames[c] + " ", " ");
}
elem.className = jQuery.trim( className );
} else {
elem.className = "";
}
}
}
}
return this;
};
jQuery.prototype.removeData = function( key ) {
/// <summary>
/// Remove a previously-stored piece of data.
/// </summary>
/// <param name="key" type="String">
/// A string naming the piece of data to delete.
/// </param>
/// <returns type="jQuery" />
return this.each(function() {
jQuery.removeData( this, key );
});
};
jQuery.prototype.removeProp = function( name ) {
/// <summary>
/// Remove a property for the set of matched elements.
/// </summary>
/// <param name="name" type="String">
/// The name of the property to set.
/// </param>
/// <param name="" type="Boolean">
/// A value to set for the property.
/// </param>
/// <returns type="jQuery" />
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 ) {}
});
};
jQuery.prototype.replaceAll = function( selector ) {
/// <summary>
/// Replace each target element with the set of matched elements.
/// </summary>
/// <param name="selector" type="String">
/// A selector expression indicating which element(s) to replace.
/// </param>
/// <returns type="jQuery" />
var ret = [],
insert = jQuery( selector ),
parent = this.length === 1 && this[0].parentNode;
if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = (i > 0 ? this.clone(true) : this).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
jQuery.prototype.replaceWith = function( value ) {
/// <summary>
/// Replace each element in the set of matched elements with the provided new content.
/// 1 - replaceWith(newContent)
/// 2 - replaceWith(function)
/// </summary>
/// <param name="value" type="jQuery">
/// The content to insert. May be an HTML string, DOM element, or jQuery object.
/// </param>
/// <returns type="jQuery" />
if ( this[0] && this[0].parentNode ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
} else {
return this.length ?
this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
this;
}
};
jQuery.prototype.resize = function( data, fn ) {
/// <summary>
/// Bind an event handler to the "resize" JavaScript event, or trigger that event on an element.
/// 1 - resize(handler(eventObject))
/// 2 - resize(eventData, handler(eventObject))
/// 3 - resize()
/// </summary>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
jQuery.prototype.scroll = function( data, fn ) {
/// <summary>
/// Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element.
/// 1 - scroll(handler(eventObject))
/// 2 - scroll(eventData, handler(eventObject))
/// 3 - scroll()
/// </summary>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
jQuery.prototype.scrollLeft = function( val ) {
/// <summary>
/// 1: Get the current horizontal position of the scroll bar for the first element in the set of matched elements.
/// 1.1 - scrollLeft()
/// 2: Set the current horizontal position of the scroll bar for each of the set of matched elements.
/// 2.1 - scrollLeft(value)
/// </summary>
/// <param name="val" type="Number">
/// An integer indicating the new position to set the scroll bar to.
/// </param>
/// <returns type="jQuery" />
var elem, win;
if ( val === undefined ) {
elem = this[ 0 ];
if ( !elem ) {
return null;
}
win = getWindow( elem );
// Return the scroll offset
return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] :
jQuery.support.boxModel && win.document.documentElement[ method ] ||
win.document.body[ method ] :
elem[ method ];
}
// Set the scroll offset
return this.each(function() {
win = getWindow( this );
if ( win ) {
win.scrollTo(
!i ? val : jQuery( win ).scrollLeft(),
i ? val : jQuery( win ).scrollTop()
);
} else {
this[ method ] = val;
}
});
};
jQuery.prototype.scrollTop = function( val ) {
/// <summary>
/// 1: Get the current vertical position of the scroll bar for the first element in the set of matched elements.
/// 1.1 - scrollTop()
/// 2: Set the current vertical position of the scroll bar for each of the set of matched elements.
/// 2.1 - scrollTop(value)
/// </summary>
/// <param name="val" type="Number">
/// An integer indicating the new position to set the scroll bar to.
/// </param>
/// <returns type="jQuery" />
var elem, win;
if ( val === undefined ) {
elem = this[ 0 ];
if ( !elem ) {
return null;
}
win = getWindow( elem );
// Return the scroll offset
return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] :
jQuery.support.boxModel && win.document.documentElement[ method ] ||
win.document.body[ method ] :
elem[ method ];
}
// Set the scroll offset
return this.each(function() {
win = getWindow( this );
if ( win ) {
win.scrollTo(
!i ? val : jQuery( win ).scrollLeft(),
i ? val : jQuery( win ).scrollTop()
);
} else {
this[ method ] = val;
}
});
};
jQuery.prototype.select = function( data, fn ) {
/// <summary>
/// Bind an event handler to the "select" JavaScript event, or trigger that event on an element.
/// 1 - select(handler(eventObject))
/// 2 - select(eventData, handler(eventObject))
/// 3 - select()
/// </summary>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
jQuery.prototype.serialize = function() {
/// <summary>
/// Encode a set of form elements as a string for submission.
/// </summary>
/// <returns type="String" />
return jQuery.param( this.serializeArray() );
};
jQuery.prototype.serializeArray = function() {
/// <summary>
/// Encode a set of form elements as an array of names and values.
/// </summary>
/// <returns type="Array" />
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
};
jQuery.prototype.show = function( speed, easing, callback ) {
/// <summary>
/// Display the matched elements.
/// 1 - show()
/// 2 - show(duration, callback)
/// 3 - show(duration, easing, callback)
/// </summary>
/// <param name="speed" type="Number">
/// A string or number determining how long the animation will run.
/// </param>
/// <param name="easing" type="String">
/// A string indicating which easing function to use for the transition.
/// </param>
/// <param name="callback" type="Function">
/// A function to call once the animation is complete.
/// </param>
/// <returns type="jQuery" />
var elem, display;
if ( speed || speed === 0 ) {
return this.animate( genFx("show", 3), speed, easing, callback);
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
elem = this[i];
if ( elem.style ) {
display = elem.style.display;
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !jQuery._data(elem, "olddisplay") && display === "none" ) {
display = elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( display === "" && jQuery.css( elem, "display" ) === "none" ) {
jQuery._data(elem, "olddisplay", defaultDisplay(elem.nodeName));
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
elem = this[i];
if ( elem.style ) {
display = elem.style.display;
if ( display === "" || display === "none" ) {
elem.style.display = jQuery._data(elem, "olddisplay") || "";
}
}
}
return this;
}
};
jQuery.prototype.siblings = function( until, selector ) {
/// <summary>
/// Get the siblings of each element in the set of matched elements, optionally filtered by a selector.
/// </summary>
/// <param name="until" type="String">
/// A string containing a selector expression to match elements against.
/// </param>
/// <returns type="jQuery" />
var ret = jQuery.map( this, fn, until ),
// The variable 'args' was introduced in
// https://github.com/jquery/jquery/commit/52a0238
// to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
// http://code.google.com/p/v8/issues/detail?id=1050
args = slice.call(arguments);
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, args.join(",") );
};
jQuery.prototype.size = function() {
/// <summary>
/// Return the number of elements in the jQuery object.
/// </summary>
/// <returns type="Number" />
return this.length;
};
jQuery.prototype.slice = function() {
/// <summary>
/// Reduce the set of matched elements to a subset specified by a range of indices.
/// </summary>
/// <param name="" type="Number">
/// An integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set.
/// </param>
/// <param name="" type="Number">
/// An integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from the end of the set. If omitted, the range continues until the end of the set.
/// </param>
/// <returns type="jQuery" />
return this.pushStack( slice.apply( this, arguments ),
"slice", slice.call(arguments).join(",") );
};
jQuery.prototype.slideDown = function( speed, easing, callback ) {
/// <summary>
/// Display the matched elements with a sliding motion.
/// 1 - slideDown(duration, callback)
/// 2 - slideDown(duration, easing, callback)
/// </summary>
/// <param name="speed" type="Number">
/// A string or number determining how long the animation will run.
/// </param>
/// <param name="easing" type="String">
/// A string indicating which easing function to use for the transition.
/// </param>
/// <param name="callback" type="Function">
/// A function to call once the animation is complete.
/// </param>
/// <returns type="jQuery" />
return this.animate( props, speed, easing, callback );
};
jQuery.prototype.slideToggle = function( speed, easing, callback ) {
/// <summary>
/// Display or hide the matched elements with a sliding motion.
/// 1 - slideToggle(duration, callback)
/// 2 - slideToggle(duration, easing, callback)
/// </summary>
/// <param name="speed" type="Number">
/// A string or number determining how long the animation will run.
/// </param>
/// <param name="easing" type="String">
/// A string indicating which easing function to use for the transition.
/// </param>
/// <param name="callback" type="Function">
/// A function to call once the animation is complete.
/// </param>
/// <returns type="jQuery" />
return this.animate( props, speed, easing, callback );
};
jQuery.prototype.slideUp = function( speed, easing, callback ) {
/// <summary>
/// Hide the matched elements with a sliding motion.
/// 1 - slideUp(duration, callback)
/// 2 - slideUp(duration, easing, callback)
/// </summary>
/// <param name="speed" type="Number">
/// A string or number determining how long the animation will run.
/// </param>
/// <param name="easing" type="String">
/// A string indicating which easing function to use for the transition.
/// </param>
/// <param name="callback" type="Function">
/// A function to call once the animation is complete.
/// </param>
/// <returns type="jQuery" />
return this.animate( props, speed, easing, callback );
};
jQuery.prototype.stop = function( clearQueue, gotoEnd ) {
/// <summary>
/// Stop the currently-running animation on the matched elements.
/// </summary>
/// <param name="clearQueue" type="Boolean">
/// A Boolean indicating whether to remove queued animation as well. Defaults to false.
/// </param>
/// <param name="gotoEnd" type="Boolean">
/// A Boolean indicating whether to complete the current animation immediately. Defaults to false.
/// </param>
/// <returns type="jQuery" />
if ( clearQueue ) {
this.queue([]);
}
this.each(function() {
var timers = jQuery.timers,
i = timers.length;
// clear marker counters if we know they won't be
if ( !gotoEnd ) {
jQuery._unmark( true, this );
}
while ( i-- ) {
if ( timers[i].elem === this ) {
if (gotoEnd) {
// force the next step to be the last
timers[i](true);
}
timers.splice(i, 1);
}
}
});
// start the next in the queue if the last step wasn't forced
if ( !gotoEnd ) {
this.dequeue();
}
return this;
};
jQuery.prototype.submit = function( data, fn ) {
/// <summary>
/// Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.
/// 1 - submit(handler(eventObject))
/// 2 - submit(eventData, handler(eventObject))
/// 3 - submit()
/// </summary>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
jQuery.prototype.text = function( text ) {
/// <summary>
/// 1: Get the combined text contents of each element in the set of matched elements, including their descendants.
/// 1.1 - text()
/// 2: Set the content of each element in the set of matched elements to the specified text.
/// 2.1 - text(textString)
/// 2.2 - text(function(index, text))
/// </summary>
/// <param name="text" type="String">
/// A string of text to set as the content of each matched element.
/// </param>
/// <returns type="jQuery" />
if ( jQuery.isFunction(text) ) {
return this.each(function(i) {
var self = jQuery( this );
self.text( text.call(this, i, self.text()) );
});
}
if ( typeof text !== "object" && text !== undefined ) {
return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
}
return jQuery.text( this );
};
jQuery.prototype.toArray = function() {
/// <summary>
/// Retrieve all the DOM elements contained in the jQuery set, as an array.
/// </summary>
/// <returns type="Array" />
return slice.call( this, 0 );
};
jQuery.prototype.toggle = function( fn, fn2, callback ) {
/// <summary>
/// 1: Bind two or more handlers to the matched elements, to be executed on alternate clicks.
/// 1.1 - toggle(handler(eventObject), handler(eventObject), handler(eventObject))
/// 2: Display or hide the matched elements.
/// 2.1 - toggle(duration, callback)
/// 2.2 - toggle(duration, easing, callback)
/// 2.3 - toggle(showOrHide)
/// </summary>
/// <param name="fn" type="Function">
/// A function to execute every even time the element is clicked.
/// </param>
/// <param name="fn2" type="Function">
/// A function to execute every odd time the element is clicked.
/// </param>
/// <param name="callback" type="Function">
/// Additional handlers to cycle through after clicks.
/// </param>
/// <returns type="jQuery" />
var bool = typeof fn === "boolean";
if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) {
this._toggle.apply( this, arguments );
} else if ( fn == null || bool ) {
this.each(function() {
var state = bool ? fn : jQuery(this).is(":hidden");
jQuery(this)[ state ? "show" : "hide" ]();
});
} else {
this.animate(genFx("toggle", 3), fn, fn2, callback);
}
return this;
};
jQuery.prototype.toggleClass = function( value, stateVal ) {
/// <summary>
/// Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.
/// 1 - toggleClass(className)
/// 2 - toggleClass(className, switch)
/// 3 - toggleClass(function(index, class), switch)
/// </summary>
/// <param name="value" type="String">
/// One or more class names (separated by spaces) to be toggled for each element in the matched set.
/// </param>
/// <param name="stateVal" type="Boolean">
/// A boolean value to determine whether the class should be added or removed.
/// </param>
/// <returns type="jQuery" />
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this);
self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( rspace );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space seperated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
};
jQuery.prototype.trigger = function( type, data ) {
/// <summary>
/// Execute all handlers and behaviors attached to the matched elements for the given event type.
/// 1 - trigger(eventType, extraParameters)
/// 2 - trigger(event)
/// </summary>
/// <param name="type" type="String">
/// A string containing a JavaScript event type, such as click or submit.
/// </param>
/// <param name="data" type="Array">
/// An array of additional parameters to pass along to the event handler.
/// </param>
/// <returns type="jQuery" />
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
};
jQuery.prototype.triggerHandler = function( type, data ) {
/// <summary>
/// Execute all handlers attached to an element for an event.
/// </summary>
/// <param name="type" type="String">
/// A string containing a JavaScript event type, such as click or submit.
/// </param>
/// <param name="data" type="Array">
/// An array of additional parameters to pass along to the event handler.
/// </param>
/// <returns type="Object" />
if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true );
}
};
jQuery.prototype.unbind = function( type, fn ) {
/// <summary>
/// Remove a previously-attached event handler from the elements.
/// 1 - unbind(eventType, handler(eventObject))
/// 2 - unbind(eventType, false)
/// 3 - unbind(event)
/// </summary>
/// <param name="type" type="String">
/// A string containing a JavaScript event type, such as click or submit.
/// </param>
/// <param name="fn" type="Function">
/// The function that is to be no longer executed.
/// </param>
/// <returns type="jQuery" />
// Handle object literals
if ( typeof type === "object" && !type.preventDefault ) {
for ( var key in type ) {
this.unbind(key, type[key]);
}
} else {
for ( var i = 0, l = this.length; i < l; i++ ) {
jQuery.event.remove( this[i], type, fn );
}
}
return this;
};
jQuery.prototype.undelegate = function( selector, types, fn ) {
/// <summary>
/// Remove a handler from the event for all elements which match the current selector, now or in the future, based upon a specific set of root elements.
/// 1 - undelegate()
/// 2 - undelegate(selector, eventType)
/// 3 - undelegate(selector, eventType, handler)
/// 4 - undelegate(selector, events)
/// 5 - undelegate(namespace)
/// </summary>
/// <param name="selector" type="String">
/// A selector which will be used to filter the event results.
/// </param>
/// <param name="types" type="String">
/// A string containing a JavaScript event type, such as "click" or "keydown"
/// </param>
/// <param name="fn" type="Function">
/// A function to execute at the time the event is triggered.
/// </param>
/// <returns type="jQuery" />
if ( arguments.length === 0 ) {
return this.unbind( "live" );
} else {
return this.die( types, null, fn, selector );
}
};
jQuery.prototype.unload = function( data, fn ) {
/// <summary>
/// Bind an event handler to the "unload" JavaScript event.
/// 1 - unload(handler(eventObject))
/// 2 - unload(eventData, handler(eventObject))
/// </summary>
/// <param name="data" type="Object">
/// A map of data that will be passed to the event handler.
/// </param>
/// <param name="fn" type="Function">
/// A function to execute each time the event is triggered.
/// </param>
/// <returns type="jQuery" />
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
jQuery.prototype.unwrap = function() {
/// <summary>
/// Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.
/// </summary>
/// <returns type="jQuery" />
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
};
jQuery.prototype.val = function( value ) {
/// <summary>
/// 1: Get the current value of the first element in the set of matched elements.
/// 1.1 - val()
/// 2: Set the value of each element in the set of matched elements.
/// 2.1 - val(value)
/// 2.2 - val(function(index, value))
/// </summary>
/// <param name="value" type="String">
/// A string of text or an array of strings corresponding to the value of each matched element to set as selected/checked.
/// </param>
/// <returns type="jQuery" />
var hooks, ret,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
return (elem.value || "").replace(rreturn, "");
}
return undefined;
}
var isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var self = jQuery(this), val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
};
jQuery.prototype.width = function( size ) {
/// <summary>
/// 1: Get the current computed width for the first element in the set of matched elements.
/// 1.1 - width()
/// 2: Set the CSS width of each element in the set of matched elements.
/// 2.1 - width(value)
/// 2.2 - width(function(index, width))
/// </summary>
/// <param name="size" type="Number">
/// An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string).
/// </param>
/// <returns type="jQuery" />
// Get window width or height
var elem = this[0];
if ( !elem ) {
return size == null ? null : this;
}
if ( jQuery.isFunction( size ) ) {
return this.each(function( i ) {
var self = jQuery( this );
self[ type ]( size.call( this, i, self[ type ]() ) );
});
}
if ( jQuery.isWindow( elem ) ) {
// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
// 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
var docElemProp = elem.document.documentElement[ "client" + name ];
return elem.document.compatMode === "CSS1Compat" && docElemProp ||
elem.document.body[ "client" + name ] || docElemProp;
// Get document width or height
} else if ( elem.nodeType === 9 ) {
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
return Math.max(
elem.documentElement["client" + name],
elem.body["scroll" + name], elem.documentElement["scroll" + name],
elem.body["offset" + name], elem.documentElement["offset" + name]
);
// Get or set width or height on the element
} else if ( size === undefined ) {
var orig = jQuery.css( elem, type ),
ret = parseFloat( orig );
return jQuery.isNaN( ret ) ? orig : ret;
// Set the width or height on the element (default to pixels if value is unitless)
} else {
return this.css( type, typeof size === "string" ? size : size + "px" );
}
};
jQuery.prototype.wrap = function( html ) {
/// <summary>
/// Wrap an HTML structure around each element in the set of matched elements.
/// 1 - wrap(wrappingElement)
/// 2 - wrap(function(index))
/// </summary>
/// <param name="html" type="jQuery">
/// An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the matched elements.
/// </param>
/// <returns type="jQuery" />
return this.each(function() {
jQuery( this ).wrapAll( html );
});
};
jQuery.prototype.wrapAll = function( html ) {
/// <summary>
/// Wrap an HTML structure around all elements in the set of matched elements.
/// </summary>
/// <param name="html" type="jQuery">
/// An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the matched elements.
/// </param>
/// <returns type="jQuery" />
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;
};
jQuery.prototype.wrapInner = function( html ) {
/// <summary>
/// Wrap an HTML structure around the content of each element in the set of matched elements.
/// 1 - wrapInner(wrappingElement)
/// 2 - wrapInner(wrappingFunction)
/// </summary>
/// <param name="html" type="String">
/// An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the content of the matched elements.
/// </param>
/// <returns type="jQuery" />
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 );
}
});
};
jQuery.fn = jQuery.prototype;
jQuery.fn.init.prototype = jQuery.fn;
window.jQuery = window.$ = jQuery;
})(window); |
/*! Raven.js 3.23.1 (84edddc) | github.com/getsentry/raven-js */
/*
* Includes TraceKit
* https://github.com/getsentry/TraceKit
*
* Copyright 2018 Matt Robenolt and other contributors
* Released under the BSD license
* https://github.com/getsentry/raven-js/blob/master/LICENSE
*
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g=(g.Raven||(g.Raven = {}));g=(g.Plugins||(g.Plugins = {}));g.Angular = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
/**
* Angular.js plugin
*
* Provides an $exceptionHandler for Angular.js
*/
var wrappedCallback = _dereq_(2).wrappedCallback;
// See https://github.com/angular/angular.js/blob/v1.4.7/src/minErr.js
var angularPattern = /^\[((?:[$a-zA-Z0-9]+:)?(?:[$a-zA-Z0-9]+))\] (.*?)\n?(\S+)$/;
var moduleName = 'ngRaven';
function angularPlugin(Raven, angular) {
angular = angular || window.angular;
if (!angular) return;
function RavenProvider() {
this.$get = [
'$window',
function($window) {
return Raven;
}
];
}
function ExceptionHandlerProvider($provide) {
$provide.decorator('$exceptionHandler', ['Raven', '$delegate', exceptionHandler]);
}
function exceptionHandler(R, $delegate) {
return function(ex, cause) {
R.captureException(ex, {
extra: {cause: cause}
});
$delegate(ex, cause);
};
}
angular
.module(moduleName, [])
.provider('Raven', RavenProvider)
.config(['$provide', ExceptionHandlerProvider]);
Raven.setDataCallback(
wrappedCallback(function(data) {
return angularPlugin._normalizeData(data);
})
);
}
angularPlugin._normalizeData = function(data) {
// We only care about mutating an exception
var exception = data.exception;
if (exception) {
exception = exception.values[0];
var matches = angularPattern.exec(exception.value);
if (matches) {
// This type now becomes something like: $rootScope:inprog
exception.type = matches[1];
exception.value = matches[2];
data.message = exception.type + ': ' + exception.value;
// auto set a new tag specifically for the angular error url
data.extra.angularDocs = matches[3].substr(0, 250);
}
}
return data;
};
angularPlugin.moduleName = moduleName;
module.exports = angularPlugin;
},{"2":2}],2:[function(_dereq_,module,exports){
(function (global){
var _window =
typeof window !== 'undefined'
? window
: typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function isObject(what) {
return typeof what === 'object' && what !== null;
}
// Yanked from https://git.io/vS8DV re-used under CC0
// with some tiny modifications
function isError(value) {
switch ({}.toString.call(value)) {
case '[object Error]':
return true;
case '[object Exception]':
return true;
case '[object DOMException]':
return true;
default:
return value instanceof Error;
}
}
function isErrorEvent(value) {
return supportsErrorEvent() && {}.toString.call(value) === '[object ErrorEvent]';
}
function isUndefined(what) {
return what === void 0;
}
function isFunction(what) {
return typeof what === 'function';
}
function isPlainObject(what) {
return Object.prototype.toString.call(what) === '[object Object]';
}
function isString(what) {
return Object.prototype.toString.call(what) === '[object String]';
}
function isArray(what) {
return Object.prototype.toString.call(what) === '[object Array]';
}
function isEmptyObject(what) {
if (!isPlainObject(what)) return false;
for (var _ in what) {
if (what.hasOwnProperty(_)) {
return false;
}
}
return true;
}
function supportsErrorEvent() {
try {
new ErrorEvent(''); // eslint-disable-line no-new
return true;
} catch (e) {
return false;
}
}
function supportsFetch() {
if (!('fetch' in _window)) return false;
try {
new Headers(); // eslint-disable-line no-new
new Request(''); // eslint-disable-line no-new
new Response(); // eslint-disable-line no-new
return true;
} catch (e) {
return false;
}
}
// Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default
// https://caniuse.com/#feat=referrer-policy
// It doesn't. And it throw exception instead of ignoring this parameter...
// REF: https://github.com/getsentry/raven-js/issues/1233
function supportsReferrerPolicy() {
if (!supportsFetch()) return false;
try {
// eslint-disable-next-line no-new
new Request('pickleRick', {
referrerPolicy: 'origin'
});
return true;
} catch (e) {
return false;
}
}
function supportsPromiseRejectionEvent() {
return typeof PromiseRejectionEvent === 'function';
}
function wrappedCallback(callback) {
function dataCallback(data, original) {
var normalizedData = callback(data) || data;
if (original) {
return original(normalizedData) || normalizedData;
}
return normalizedData;
}
return dataCallback;
}
function each(obj, callback) {
var i, j;
if (isUndefined(obj.length)) {
for (i in obj) {
if (hasKey(obj, i)) {
callback.call(null, i, obj[i]);
}
}
} else {
j = obj.length;
if (j) {
for (i = 0; i < j; i++) {
callback.call(null, i, obj[i]);
}
}
}
}
function objectMerge(obj1, obj2) {
if (!obj2) {
return obj1;
}
each(obj2, function(key, value) {
obj1[key] = value;
});
return obj1;
}
/**
* This function is only used for react-native.
* react-native freezes object that have already been sent over the
* js bridge. We need this function in order to check if the object is frozen.
* So it's ok that objectFrozen returns false if Object.isFrozen is not
* supported because it's not relevant for other "platforms". See related issue:
* https://github.com/getsentry/react-native-sentry/issues/57
*/
function objectFrozen(obj) {
if (!Object.isFrozen) {
return false;
}
return Object.isFrozen(obj);
}
function truncate(str, max) {
return !max || str.length <= max ? str : str.substr(0, max) + '\u2026';
}
/**
* hasKey, a better form of hasOwnProperty
* Example: hasKey(MainHostObject, property) === true/false
*
* @param {Object} host object to check property
* @param {string} key to check
*/
function hasKey(object, key) {
return Object.prototype.hasOwnProperty.call(object, key);
}
function joinRegExp(patterns) {
// Combine an array of regular expressions and strings into one large regexp
// Be mad.
var sources = [],
i = 0,
len = patterns.length,
pattern;
for (; i < len; i++) {
pattern = patterns[i];
if (isString(pattern)) {
// If it's a string, we need to escape it
// Taken from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
sources.push(pattern.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1'));
} else if (pattern && pattern.source) {
// If it's a regexp already, we want to extract the source
sources.push(pattern.source);
}
// Intentionally skip other cases
}
return new RegExp(sources.join('|'), 'i');
}
function urlencode(o) {
var pairs = [];
each(o, function(key, value) {
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
});
return pairs.join('&');
}
// borrowed from https://tools.ietf.org/html/rfc3986#appendix-B
// intentionally using regex and not <a/> href parsing trick because React Native and other
// environments where DOM might not be available
function parseUrl(url) {
if (typeof url !== 'string') return {};
var match = url.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);
// coerce to undefined values to empty string so we don't get 'undefined'
var query = match[6] || '';
var fragment = match[8] || '';
return {
protocol: match[2],
host: match[4],
path: match[5],
relative: match[5] + query + fragment // everything minus origin
};
}
function uuid4() {
var crypto = _window.crypto || _window.msCrypto;
if (!isUndefined(crypto) && crypto.getRandomValues) {
// Use window.crypto API if available
// eslint-disable-next-line no-undef
var arr = new Uint16Array(8);
crypto.getRandomValues(arr);
// set 4 in byte 7
arr[3] = (arr[3] & 0xfff) | 0x4000;
// set 2 most significant bits of byte 9 to '10'
arr[4] = (arr[4] & 0x3fff) | 0x8000;
var pad = function(num) {
var v = num.toString(16);
while (v.length < 4) {
v = '0' + v;
}
return v;
};
return (
pad(arr[0]) +
pad(arr[1]) +
pad(arr[2]) +
pad(arr[3]) +
pad(arr[4]) +
pad(arr[5]) +
pad(arr[6]) +
pad(arr[7])
);
} else {
// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523
return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (Math.random() * 16) | 0,
v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
}
/**
* Given a child DOM element, returns a query-selector statement describing that
* and its ancestors
* e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]
* @param elem
* @returns {string}
*/
function htmlTreeAsString(elem) {
/* eslint no-extra-parens:0*/
var MAX_TRAVERSE_HEIGHT = 5,
MAX_OUTPUT_LEN = 80,
out = [],
height = 0,
len = 0,
separator = ' > ',
sepLength = separator.length,
nextStr;
while (elem && height++ < MAX_TRAVERSE_HEIGHT) {
nextStr = htmlElementAsString(elem);
// bail out if
// - nextStr is the 'html' element
// - the length of the string that would be created exceeds MAX_OUTPUT_LEN
// (ignore this limit if we are on the first iteration)
if (
nextStr === 'html' ||
(height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)
) {
break;
}
out.push(nextStr);
len += nextStr.length;
elem = elem.parentNode;
}
return out.reverse().join(separator);
}
/**
* Returns a simple, query-selector representation of a DOM element
* e.g. [HTMLElement] => input#foo.btn[name=baz]
* @param HTMLElement
* @returns {string}
*/
function htmlElementAsString(elem) {
var out = [],
className,
classes,
key,
attr,
i;
if (!elem || !elem.tagName) {
return '';
}
out.push(elem.tagName.toLowerCase());
if (elem.id) {
out.push('#' + elem.id);
}
className = elem.className;
if (className && isString(className)) {
classes = className.split(/\s+/);
for (i = 0; i < classes.length; i++) {
out.push('.' + classes[i]);
}
}
var attrWhitelist = ['type', 'name', 'title', 'alt'];
for (i = 0; i < attrWhitelist.length; i++) {
key = attrWhitelist[i];
attr = elem.getAttribute(key);
if (attr) {
out.push('[' + key + '="' + attr + '"]');
}
}
return out.join('');
}
/**
* Returns true if either a OR b is truthy, but not both
*/
function isOnlyOneTruthy(a, b) {
return !!(!!a ^ !!b);
}
/**
* Returns true if both parameters are undefined
*/
function isBothUndefined(a, b) {
return isUndefined(a) && isUndefined(b);
}
/**
* Returns true if the two input exception interfaces have the same content
*/
function isSameException(ex1, ex2) {
if (isOnlyOneTruthy(ex1, ex2)) return false;
ex1 = ex1.values[0];
ex2 = ex2.values[0];
if (ex1.type !== ex2.type || ex1.value !== ex2.value) return false;
// in case both stacktraces are undefined, we can't decide so default to false
if (isBothUndefined(ex1.stacktrace, ex2.stacktrace)) return false;
return isSameStacktrace(ex1.stacktrace, ex2.stacktrace);
}
/**
* Returns true if the two input stack trace interfaces have the same content
*/
function isSameStacktrace(stack1, stack2) {
if (isOnlyOneTruthy(stack1, stack2)) return false;
var frames1 = stack1.frames;
var frames2 = stack2.frames;
// Exit early if frame count differs
if (frames1.length !== frames2.length) return false;
// Iterate through every frame; bail out if anything differs
var a, b;
for (var i = 0; i < frames1.length; i++) {
a = frames1[i];
b = frames2[i];
if (
a.filename !== b.filename ||
a.lineno !== b.lineno ||
a.colno !== b.colno ||
a['function'] !== b['function']
)
return false;
}
return true;
}
/**
* Polyfill a method
* @param obj object e.g. `document`
* @param name method name present on object e.g. `addEventListener`
* @param replacement replacement function
* @param track {optional} record instrumentation to an array
*/
function fill(obj, name, replacement, track) {
var orig = obj[name];
obj[name] = replacement(orig);
obj[name].__raven__ = true;
obj[name].__orig__ = orig;
if (track) {
track.push([obj, name, orig]);
}
}
/**
* Join values in array
* @param input array of values to be joined together
* @param delimiter string to be placed in-between values
* @returns {string}
*/
function safeJoin(input, delimiter) {
if (!isArray(input)) return '';
var output = [];
for (var i = 0; i < input.length; i++) {
try {
output.push(String(input[i]));
} catch (e) {
output.push('[value cannot be serialized]');
}
}
return output.join(delimiter);
}
module.exports = {
isObject: isObject,
isError: isError,
isErrorEvent: isErrorEvent,
isUndefined: isUndefined,
isFunction: isFunction,
isPlainObject: isPlainObject,
isString: isString,
isArray: isArray,
isEmptyObject: isEmptyObject,
supportsErrorEvent: supportsErrorEvent,
supportsFetch: supportsFetch,
supportsReferrerPolicy: supportsReferrerPolicy,
supportsPromiseRejectionEvent: supportsPromiseRejectionEvent,
wrappedCallback: wrappedCallback,
each: each,
objectMerge: objectMerge,
truncate: truncate,
objectFrozen: objectFrozen,
hasKey: hasKey,
joinRegExp: joinRegExp,
urlencode: urlencode,
uuid4: uuid4,
htmlTreeAsString: htmlTreeAsString,
htmlElementAsString: htmlElementAsString,
isSameException: isSameException,
isSameStacktrace: isSameStacktrace,
parseUrl: parseUrl,
fill: fill,
safeJoin: safeJoin
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}]},{},[1])(1)
}); |
/**
* Copyright 2013-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.
*
* @noflow
* @providesModule ReactNativeStack-dev
*/
"use strict";
var invariant = require("fbjs/lib/invariant");
require("InitializeCore");
var warning = require("fbjs/lib/warning"), RCTEventEmitter = require("RCTEventEmitter"), emptyFunction = require("fbjs/lib/emptyFunction"), UIManager = require("UIManager"), React = require("react"), ExecutionEnvironment = require("fbjs/lib/ExecutionEnvironment"), performanceNow = require("fbjs/lib/performanceNow"), emptyObject = require("fbjs/lib/emptyObject"), checkPropTypes = require("prop-types/checkPropTypes"), shallowEqual = require("fbjs/lib/shallowEqual"), deepDiffer = require("deepDiffer"), flattenStyle = require("flattenStyle"), TextInputState = require("TextInputState"), deepFreezeAndThrowOnMutationInDev = require("deepFreezeAndThrowOnMutationInDev"), instanceCache = {}, instanceProps = {};
function getRenderedHostOrTextFromComponent(component) {
for (var rendered; rendered = component._renderedComponent; ) component = rendered;
return component;
}
function precacheNode(inst, tag) {
var nativeInst = getRenderedHostOrTextFromComponent(inst);
instanceCache[tag] = nativeInst;
}
function precacheFiberNode(hostInst, tag) {
instanceCache[tag] = hostInst;
}
function uncacheNode(inst) {
var tag = inst._rootNodeID;
tag && delete instanceCache[tag];
}
function uncacheFiberNode(tag) {
delete instanceCache[tag], delete instanceProps[tag];
}
function getInstanceFromTag(tag) {
return instanceCache[tag] || null;
}
function getTagFromInstance(inst) {
var tag = "number" != typeof inst.tag ? inst._rootNodeID : inst.stateNode._nativeTag;
return invariant(tag, "All native instances should have a tag."), tag;
}
function getFiberCurrentPropsFromNode(stateNode) {
return instanceProps[stateNode._nativeTag] || null;
}
function updateFiberProps(tag, props) {
instanceProps[tag] = props;
}
var ReactNativeComponentTree = {
getClosestInstanceFromNode: getInstanceFromTag,
getInstanceFromNode: getInstanceFromTag,
getNodeFromInstance: getTagFromInstance,
precacheFiberNode: precacheFiberNode,
precacheNode: precacheNode,
uncacheFiberNode: uncacheFiberNode,
uncacheNode: uncacheNode,
getFiberCurrentPropsFromNode: getFiberCurrentPropsFromNode,
updateFiberProps: updateFiberProps
}, ReactNativeComponentTree_1 = ReactNativeComponentTree, eventPluginOrder = null, namesToPlugins = {};
function recomputePluginOrdering() {
if (eventPluginOrder) for (var pluginName in namesToPlugins) {
var pluginModule = namesToPlugins[pluginName], pluginIndex = eventPluginOrder.indexOf(pluginName);
if (invariant(pluginIndex > -1, "EventPluginRegistry: Cannot inject event plugins that do not exist in " + "the plugin ordering, `%s`.", pluginName),
!EventPluginRegistry.plugins[pluginIndex]) {
invariant(pluginModule.extractEvents, "EventPluginRegistry: Event plugins must implement an `extractEvents` " + "method, but `%s` does not.", pluginName),
EventPluginRegistry.plugins[pluginIndex] = pluginModule;
var publishedEvents = pluginModule.eventTypes;
for (var eventName in publishedEvents) invariant(publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName), "EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.", eventName, pluginName);
}
}
}
function publishEventForPlugin(dispatchConfig, pluginModule, eventName) {
invariant(!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName), "EventPluginHub: More than one plugin attempted to publish the same " + "event name, `%s`.", eventName),
EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig;
var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;
if (phasedRegistrationNames) {
for (var phaseName in phasedRegistrationNames) if (phasedRegistrationNames.hasOwnProperty(phaseName)) {
var phasedRegistrationName = phasedRegistrationNames[phaseName];
publishRegistrationName(phasedRegistrationName, pluginModule, eventName);
}
return !0;
}
return !!dispatchConfig.registrationName && (publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName),
!0);
}
function publishRegistrationName(registrationName, pluginModule, eventName) {
invariant(!EventPluginRegistry.registrationNameModules[registrationName], "EventPluginHub: More than one plugin attempted to publish the same " + "registration name, `%s`.", registrationName),
EventPluginRegistry.registrationNameModules[registrationName] = pluginModule, EventPluginRegistry.registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies;
var lowerCasedName = registrationName.toLowerCase();
EventPluginRegistry.possibleRegistrationNames[lowerCasedName] = registrationName,
"onDoubleClick" === registrationName && (EventPluginRegistry.possibleRegistrationNames.ondblclick = registrationName);
}
var EventPluginRegistry = {
plugins: [],
eventNameDispatchConfigs: {},
registrationNameModules: {},
registrationNameDependencies: {},
possibleRegistrationNames: {},
injectEventPluginOrder: function(injectedEventPluginOrder) {
invariant(!eventPluginOrder, "EventPluginRegistry: Cannot inject event plugin ordering more than " + "once. You are likely trying to load more than one copy of React."),
eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder), recomputePluginOrdering();
},
injectEventPluginsByName: function(injectedNamesToPlugins) {
var isOrderingDirty = !1;
for (var pluginName in injectedNamesToPlugins) if (injectedNamesToPlugins.hasOwnProperty(pluginName)) {
var pluginModule = injectedNamesToPlugins[pluginName];
namesToPlugins.hasOwnProperty(pluginName) && namesToPlugins[pluginName] === pluginModule || (invariant(!namesToPlugins[pluginName], "EventPluginRegistry: Cannot inject two different event plugins " + "using the same name, `%s`.", pluginName),
namesToPlugins[pluginName] = pluginModule, isOrderingDirty = !0);
}
isOrderingDirty && recomputePluginOrdering();
}
}, EventPluginRegistry_1 = EventPluginRegistry, caughtError = null, invokeGuardedCallback = function(name, func, context, a, b, c, d, e, f) {
var funcArgs = Array.prototype.slice.call(arguments, 3);
try {
func.apply(context, funcArgs);
} catch (error) {
return error;
}
return null;
};
if ("undefined" != typeof window && "function" == typeof window.dispatchEvent && "undefined" != typeof document && "function" == typeof document.createEvent) {
var fakeNode = document.createElement("react"), depth = 0;
invokeGuardedCallback = function(name, func, context, a, b, c, d, e, f) {
depth++;
var thisDepth = depth, funcArgs = Array.prototype.slice.call(arguments, 3), boundFunc = function() {
func.apply(context, funcArgs);
}, fakeEventError = null, onFakeEventError = function(event) {
depth === thisDepth && (fakeEventError = event.error);
}, evtType = "react-" + (name || "invokeguardedcallback") + "-" + depth;
window.addEventListener("error", onFakeEventError), fakeNode.addEventListener(evtType, boundFunc, !1);
var evt = document.createEvent("Event");
return evt.initEvent(evtType, !1, !1), fakeNode.dispatchEvent(evt), fakeNode.removeEventListener(evtType, boundFunc, !1),
window.removeEventListener("error", onFakeEventError), depth--, fakeEventError;
};
}
var rethrowCaughtError = function() {
if (caughtError) {
var error = caughtError;
throw caughtError = null, error;
}
}, ReactErrorUtils = {
injection: {
injectErrorUtils: function(injectedErrorUtils) {
invariant("function" == typeof injectedErrorUtils.invokeGuardedCallback, "Injected invokeGuardedCallback() must be a function."),
invokeGuardedCallback = injectedErrorUtils.invokeGuardedCallback;
}
},
invokeGuardedCallback: function(name, func, context, a, b, c, d, e, f) {
return invokeGuardedCallback.apply(this, arguments);
},
invokeGuardedCallbackAndCatchFirstError: function(name, func, context, a, b, c, d, e, f) {
var error = ReactErrorUtils.invokeGuardedCallback.apply(this, arguments);
null !== error && null === caughtError && (caughtError = error);
},
rethrowCaughtError: function() {
return rethrowCaughtError.apply(this, arguments);
}
}, ReactErrorUtils_1 = ReactErrorUtils, ComponentTree, injection = {
injectComponentTree: function(Injected) {
ComponentTree = Injected, warning(Injected && Injected.getNodeFromInstance && Injected.getInstanceFromNode, "EventPluginUtils.injection.injectComponentTree(...): Injected " + "module is missing getNodeFromInstance or getInstanceFromNode.");
}
};
function isEndish(topLevelType) {
return "topMouseUp" === topLevelType || "topTouchEnd" === topLevelType || "topTouchCancel" === topLevelType;
}
function isMoveish(topLevelType) {
return "topMouseMove" === topLevelType || "topTouchMove" === topLevelType;
}
function isStartish(topLevelType) {
return "topMouseDown" === topLevelType || "topTouchStart" === topLevelType;
}
var validateEventDispatches;
validateEventDispatches = function(event) {
var dispatchListeners = event._dispatchListeners, dispatchInstances = event._dispatchInstances, listenersIsArr = Array.isArray(dispatchListeners), listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0, instancesIsArr = Array.isArray(dispatchInstances), instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0;
warning(instancesIsArr === listenersIsArr && instancesLen === listenersLen, "EventPluginUtils: Invalid `event`.");
};
function executeDispatch(event, simulated, listener, inst) {
var type = event.type || "unknown-event";
event.currentTarget = EventPluginUtils.getNodeFromInstance(inst), ReactErrorUtils_1.invokeGuardedCallbackAndCatchFirstError(type, listener, void 0, event),
event.currentTarget = null;
}
function executeDispatchesInOrder(event, simulated) {
var dispatchListeners = event._dispatchListeners, dispatchInstances = event._dispatchInstances;
if (validateEventDispatches(event), Array.isArray(dispatchListeners)) for (var i = 0; i < dispatchListeners.length && !event.isPropagationStopped(); i++) executeDispatch(event, simulated, dispatchListeners[i], dispatchInstances[i]); else dispatchListeners && executeDispatch(event, simulated, dispatchListeners, dispatchInstances);
event._dispatchListeners = null, event._dispatchInstances = null;
}
function executeDispatchesInOrderStopAtTrueImpl(event) {
var dispatchListeners = event._dispatchListeners, dispatchInstances = event._dispatchInstances;
if (validateEventDispatches(event), Array.isArray(dispatchListeners)) {
for (var i = 0; i < dispatchListeners.length && !event.isPropagationStopped(); i++) if (dispatchListeners[i](event, dispatchInstances[i])) return dispatchInstances[i];
} else if (dispatchListeners && dispatchListeners(event, dispatchInstances)) return dispatchInstances;
return null;
}
function executeDispatchesInOrderStopAtTrue(event) {
var ret = executeDispatchesInOrderStopAtTrueImpl(event);
return event._dispatchInstances = null, event._dispatchListeners = null, ret;
}
function executeDirectDispatch(event) {
validateEventDispatches(event);
var dispatchListener = event._dispatchListeners, dispatchInstance = event._dispatchInstances;
invariant(!Array.isArray(dispatchListener), "executeDirectDispatch(...): Invalid `event`."),
event.currentTarget = dispatchListener ? EventPluginUtils.getNodeFromInstance(dispatchInstance) : null;
var res = dispatchListener ? dispatchListener(event) : null;
return event.currentTarget = null, event._dispatchListeners = null, event._dispatchInstances = null,
res;
}
function hasDispatches(event) {
return !!event._dispatchListeners;
}
var EventPluginUtils = {
isEndish: isEndish,
isMoveish: isMoveish,
isStartish: isStartish,
executeDirectDispatch: executeDirectDispatch,
executeDispatchesInOrder: executeDispatchesInOrder,
executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue,
hasDispatches: hasDispatches,
getFiberCurrentPropsFromNode: function(node) {
return ComponentTree.getFiberCurrentPropsFromNode(node);
},
getInstanceFromNode: function(node) {
return ComponentTree.getInstanceFromNode(node);
},
getNodeFromInstance: function(node) {
return ComponentTree.getNodeFromInstance(node);
},
injection: injection
}, EventPluginUtils_1 = EventPluginUtils;
function accumulateInto(current, next) {
return invariant(null != next, "accumulateInto(...): Accumulated items must not be null or undefined."),
null == current ? next : Array.isArray(current) ? Array.isArray(next) ? (current.push.apply(current, next),
current) : (current.push(next), current) : Array.isArray(next) ? [ current ].concat(next) : [ current, next ];
}
var accumulateInto_1 = accumulateInto;
function forEachAccumulated(arr, cb, scope) {
Array.isArray(arr) ? arr.forEach(cb, scope) : arr && cb.call(scope, arr);
}
var forEachAccumulated_1 = forEachAccumulated, eventQueue = null, executeDispatchesAndRelease = function(event, simulated) {
event && (EventPluginUtils_1.executeDispatchesInOrder(event, simulated), event.isPersistent() || event.constructor.release(event));
}, executeDispatchesAndReleaseSimulated = function(e) {
return executeDispatchesAndRelease(e, !0);
}, executeDispatchesAndReleaseTopLevel = function(e) {
return executeDispatchesAndRelease(e, !1);
};
function isInteractive(tag) {
return "button" === tag || "input" === tag || "select" === tag || "textarea" === tag;
}
function shouldPreventMouseEvent(name, type, props) {
switch (name) {
case "onClick":
case "onClickCapture":
case "onDoubleClick":
case "onDoubleClickCapture":
case "onMouseDown":
case "onMouseDownCapture":
case "onMouseMove":
case "onMouseMoveCapture":
case "onMouseUp":
case "onMouseUpCapture":
return !(!props.disabled || !isInteractive(type));
default:
return !1;
}
}
var EventPluginHub = {
injection: {
injectEventPluginOrder: EventPluginRegistry_1.injectEventPluginOrder,
injectEventPluginsByName: EventPluginRegistry_1.injectEventPluginsByName
},
getListener: function(inst, registrationName) {
var listener;
if ("number" == typeof inst.tag) {
var stateNode = inst.stateNode;
if (!stateNode) return null;
var props = EventPluginUtils_1.getFiberCurrentPropsFromNode(stateNode);
if (!props) return null;
if (listener = props[registrationName], shouldPreventMouseEvent(registrationName, inst.type, props)) return null;
} else {
var currentElement = inst._currentElement;
if ("string" == typeof currentElement || "number" == typeof currentElement) return null;
if (!inst._rootNodeID) return null;
var _props = currentElement.props;
if (listener = _props[registrationName], shouldPreventMouseEvent(registrationName, currentElement.type, _props)) return null;
}
return invariant(!listener || "function" == typeof listener, "Expected %s listener to be a function, instead got type %s", registrationName, typeof listener),
listener;
},
extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
for (var events, plugins = EventPluginRegistry_1.plugins, i = 0; i < plugins.length; i++) {
var possiblePlugin = plugins[i];
if (possiblePlugin) {
var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget);
extractedEvents && (events = accumulateInto_1(events, extractedEvents));
}
}
return events;
},
enqueueEvents: function(events) {
events && (eventQueue = accumulateInto_1(eventQueue, events));
},
processEventQueue: function(simulated) {
var processingEventQueue = eventQueue;
eventQueue = null, simulated ? forEachAccumulated_1(processingEventQueue, executeDispatchesAndReleaseSimulated) : forEachAccumulated_1(processingEventQueue, executeDispatchesAndReleaseTopLevel),
invariant(!eventQueue, "processEventQueue(): Additional events were enqueued while processing " + "an event queue. Support for this has not yet been implemented."),
ReactErrorUtils_1.rethrowCaughtError();
}
}, EventPluginHub_1 = EventPluginHub, ReactTypeOfWork = {
IndeterminateComponent: 0,
FunctionalComponent: 1,
ClassComponent: 2,
HostRoot: 3,
HostPortal: 4,
HostComponent: 5,
HostText: 6,
CoroutineComponent: 7,
CoroutineHandlerPhase: 8,
YieldComponent: 9,
Fragment: 10
}, HostComponent = ReactTypeOfWork.HostComponent;
function getParent(inst) {
if (void 0 !== inst._hostParent) return inst._hostParent;
if ("number" == typeof inst.tag) {
do {
inst = inst.return;
} while (inst && inst.tag !== HostComponent);
if (inst) return inst;
}
return null;
}
function getLowestCommonAncestor(instA, instB) {
for (var depthA = 0, tempA = instA; tempA; tempA = getParent(tempA)) depthA++;
for (var depthB = 0, tempB = instB; tempB; tempB = getParent(tempB)) depthB++;
for (;depthA - depthB > 0; ) instA = getParent(instA), depthA--;
for (;depthB - depthA > 0; ) instB = getParent(instB), depthB--;
for (var depth = depthA; depth--; ) {
if (instA === instB || instA === instB.alternate) return instA;
instA = getParent(instA), instB = getParent(instB);
}
return null;
}
function isAncestor(instA, instB) {
for (;instB; ) {
if (instA === instB || instA === instB.alternate) return !0;
instB = getParent(instB);
}
return !1;
}
function getParentInstance(inst) {
return getParent(inst);
}
function traverseTwoPhase(inst, fn, arg) {
for (var path = []; inst; ) path.push(inst), inst = getParent(inst);
var i;
for (i = path.length; i-- > 0; ) fn(path[i], "captured", arg);
for (i = 0; i < path.length; i++) fn(path[i], "bubbled", arg);
}
function traverseEnterLeave(from, to, fn, argFrom, argTo) {
for (var common = from && to ? getLowestCommonAncestor(from, to) : null, pathFrom = []; from && from !== common; ) pathFrom.push(from),
from = getParent(from);
for (var pathTo = []; to && to !== common; ) pathTo.push(to), to = getParent(to);
var i;
for (i = 0; i < pathFrom.length; i++) fn(pathFrom[i], "bubbled", argFrom);
for (i = pathTo.length; i-- > 0; ) fn(pathTo[i], "captured", argTo);
}
var ReactTreeTraversal = {
isAncestor: isAncestor,
getLowestCommonAncestor: getLowestCommonAncestor,
getParentInstance: getParentInstance,
traverseTwoPhase: traverseTwoPhase,
traverseEnterLeave: traverseEnterLeave
}, getListener = EventPluginHub_1.getListener;
function listenerAtPhase(inst, event, propagationPhase) {
var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];
return getListener(inst, registrationName);
}
function accumulateDirectionalDispatches(inst, phase, event) {
warning(inst, "Dispatching inst must not be null");
var listener = listenerAtPhase(inst, event, phase);
listener && (event._dispatchListeners = accumulateInto_1(event._dispatchListeners, listener),
event._dispatchInstances = accumulateInto_1(event._dispatchInstances, inst));
}
function accumulateTwoPhaseDispatchesSingle(event) {
event && event.dispatchConfig.phasedRegistrationNames && ReactTreeTraversal.traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
}
function accumulateTwoPhaseDispatchesSingleSkipTarget(event) {
if (event && event.dispatchConfig.phasedRegistrationNames) {
var targetInst = event._targetInst, parentInst = targetInst ? ReactTreeTraversal.getParentInstance(targetInst) : null;
ReactTreeTraversal.traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event);
}
}
function accumulateDispatches(inst, ignoredDirection, event) {
if (inst && event && event.dispatchConfig.registrationName) {
var registrationName = event.dispatchConfig.registrationName, listener = getListener(inst, registrationName);
listener && (event._dispatchListeners = accumulateInto_1(event._dispatchListeners, listener),
event._dispatchInstances = accumulateInto_1(event._dispatchInstances, inst));
}
}
function accumulateDirectDispatchesSingle(event) {
event && event.dispatchConfig.registrationName && accumulateDispatches(event._targetInst, null, event);
}
function accumulateTwoPhaseDispatches(events) {
forEachAccumulated_1(events, accumulateTwoPhaseDispatchesSingle);
}
function accumulateTwoPhaseDispatchesSkipTarget(events) {
forEachAccumulated_1(events, accumulateTwoPhaseDispatchesSingleSkipTarget);
}
function accumulateEnterLeaveDispatches(leave, enter, from, to) {
ReactTreeTraversal.traverseEnterLeave(from, to, accumulateDispatches, leave, enter);
}
function accumulateDirectDispatches(events) {
forEachAccumulated_1(events, accumulateDirectDispatchesSingle);
}
var EventPropagators = {
accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches,
accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget,
accumulateDirectDispatches: accumulateDirectDispatches,
accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches
}, EventPropagators_1 = EventPropagators, oneArgumentPooler = function(copyFieldsFrom) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
return Klass.call(instance, copyFieldsFrom), instance;
}
return new Klass(copyFieldsFrom);
}, twoArgumentPooler = function(a1, a2) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
return Klass.call(instance, a1, a2), instance;
}
return new Klass(a1, a2);
}, threeArgumentPooler = function(a1, a2, a3) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
return Klass.call(instance, a1, a2, a3), instance;
}
return new Klass(a1, a2, a3);
}, fourArgumentPooler = function(a1, a2, a3, a4) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
return Klass.call(instance, a1, a2, a3, a4), instance;
}
return new Klass(a1, a2, a3, a4);
}, standardReleaser = function(instance) {
var Klass = this;
invariant(instance instanceof Klass, "Trying to release an instance into a pool of a different type."),
instance.destructor(), Klass.instancePool.length < Klass.poolSize && Klass.instancePool.push(instance);
}, DEFAULT_POOL_SIZE = 10, DEFAULT_POOLER = oneArgumentPooler, addPoolingTo = function(CopyConstructor, pooler) {
var NewKlass = CopyConstructor;
return NewKlass.instancePool = [], NewKlass.getPooled = pooler || DEFAULT_POOLER,
NewKlass.poolSize || (NewKlass.poolSize = DEFAULT_POOL_SIZE), NewKlass.release = standardReleaser,
NewKlass;
}, PooledClass = {
addPoolingTo: addPoolingTo,
oneArgumentPooler: oneArgumentPooler,
twoArgumentPooler: twoArgumentPooler,
threeArgumentPooler: threeArgumentPooler,
fourArgumentPooler: fourArgumentPooler
}, PooledClass_1 = PooledClass, didWarnForAddedNewProperty = !1, isProxySupported = "function" == typeof Proxy, shouldBeReleasedProperties = [ "dispatchConfig", "_targetInst", "nativeEvent", "isDefaultPrevented", "isPropagationStopped", "_dispatchListeners", "_dispatchInstances" ], EventInterface = {
type: null,
target: null,
currentTarget: emptyFunction.thatReturnsNull,
eventPhase: null,
bubbles: null,
cancelable: null,
timeStamp: function(event) {
return event.timeStamp || Date.now();
},
defaultPrevented: null,
isTrusted: null
};
function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {
delete this.nativeEvent, delete this.preventDefault, delete this.stopPropagation,
this.dispatchConfig = dispatchConfig, this._targetInst = targetInst, this.nativeEvent = nativeEvent;
var Interface = this.constructor.Interface;
for (var propName in Interface) if (Interface.hasOwnProperty(propName)) {
delete this[propName];
var normalize = Interface[propName];
normalize ? this[propName] = normalize(nativeEvent) : "target" === propName ? this.target = nativeEventTarget : this[propName] = nativeEvent[propName];
}
var defaultPrevented = null != nativeEvent.defaultPrevented ? nativeEvent.defaultPrevented : !1 === nativeEvent.returnValue;
return this.isDefaultPrevented = defaultPrevented ? emptyFunction.thatReturnsTrue : emptyFunction.thatReturnsFalse,
this.isPropagationStopped = emptyFunction.thatReturnsFalse, this;
}
Object.assign(SyntheticEvent.prototype, {
preventDefault: function() {
this.defaultPrevented = !0;
var event = this.nativeEvent;
event && (event.preventDefault ? event.preventDefault() : "unknown" != typeof event.returnValue && (event.returnValue = !1),
this.isDefaultPrevented = emptyFunction.thatReturnsTrue);
},
stopPropagation: function() {
var event = this.nativeEvent;
event && (event.stopPropagation ? event.stopPropagation() : "unknown" != typeof event.cancelBubble && (event.cancelBubble = !0),
this.isPropagationStopped = emptyFunction.thatReturnsTrue);
},
persist: function() {
this.isPersistent = emptyFunction.thatReturnsTrue;
},
isPersistent: emptyFunction.thatReturnsFalse,
destructor: function() {
var Interface = this.constructor.Interface;
for (var propName in Interface) Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));
for (var i = 0; i < shouldBeReleasedProperties.length; i++) this[shouldBeReleasedProperties[i]] = null;
Object.defineProperty(this, "nativeEvent", getPooledWarningPropertyDefinition("nativeEvent", null)),
Object.defineProperty(this, "preventDefault", getPooledWarningPropertyDefinition("preventDefault", emptyFunction)),
Object.defineProperty(this, "stopPropagation", getPooledWarningPropertyDefinition("stopPropagation", emptyFunction));
}
}), SyntheticEvent.Interface = EventInterface, SyntheticEvent.augmentClass = function(Class, Interface) {
var Super = this, E = function() {};
E.prototype = Super.prototype;
var prototype = new E();
Object.assign(prototype, Class.prototype), Class.prototype = prototype, Class.prototype.constructor = Class,
Class.Interface = Object.assign({}, Super.Interface, Interface), Class.augmentClass = Super.augmentClass,
PooledClass_1.addPoolingTo(Class, PooledClass_1.fourArgumentPooler);
}, isProxySupported && (SyntheticEvent = new Proxy(SyntheticEvent, {
construct: function(target, args) {
return this.apply(target, Object.create(target.prototype), args);
},
apply: function(constructor, that, args) {
return new Proxy(constructor.apply(that, args), {
set: function(target, prop, value) {
return "isPersistent" === prop || target.constructor.Interface.hasOwnProperty(prop) || -1 !== shouldBeReleasedProperties.indexOf(prop) || (warning(didWarnForAddedNewProperty || target.isPersistent(), "This synthetic event is reused for performance reasons. If you're " + "seeing this, you're adding a new property in the synthetic event object. " + "The property is never released. See " + "https://fb.me/react-event-pooling for more information."),
didWarnForAddedNewProperty = !0), target[prop] = value, !0;
}
});
}
})), PooledClass_1.addPoolingTo(SyntheticEvent, PooledClass_1.fourArgumentPooler);
var SyntheticEvent_1 = SyntheticEvent;
function getPooledWarningPropertyDefinition(propName, getVal) {
var isFunction = "function" == typeof getVal;
return {
configurable: !0,
set: set,
get: get
};
function set(val) {
return warn(isFunction ? "setting the method" : "setting the property", "This is effectively a no-op"),
val;
}
function get() {
return warn(isFunction ? "accessing the method" : "accessing the property", isFunction ? "This is a no-op function" : "This is set to null"),
getVal;
}
function warn(action, result) {
warning(!1, "This synthetic event is reused for performance reasons. If you're seeing this, " + "you're %s `%s` on a released/nullified synthetic event. %s. " + "If you must keep the original synthetic event around, use event.persist(). " + "See https://fb.me/react-event-pooling for more information.", action, propName, result);
}
}
var _extends = Object.assign || function(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]);
}
return target;
}, customBubblingEventTypes = UIManager.customBubblingEventTypes, customDirectEventTypes = UIManager.customDirectEventTypes, allTypesByEventName = {};
for (var bubblingTypeName in customBubblingEventTypes) allTypesByEventName[bubblingTypeName] = customBubblingEventTypes[bubblingTypeName];
for (var directTypeName in customDirectEventTypes) warning(!customBubblingEventTypes[directTypeName], "Event cannot be both direct and bubbling: %s", directTypeName),
allTypesByEventName[directTypeName] = customDirectEventTypes[directTypeName];
var ReactNativeBridgeEventPlugin = {
eventTypes: _extends({}, customBubblingEventTypes, customDirectEventTypes),
extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var bubbleDispatchConfig = customBubblingEventTypes[topLevelType], directDispatchConfig = customDirectEventTypes[topLevelType], event = SyntheticEvent_1.getPooled(bubbleDispatchConfig || directDispatchConfig, targetInst, nativeEvent, nativeEventTarget);
if (bubbleDispatchConfig) EventPropagators_1.accumulateTwoPhaseDispatches(event); else {
if (!directDispatchConfig) return null;
EventPropagators_1.accumulateDirectDispatches(event);
}
return event;
}
}, ReactNativeBridgeEventPlugin_1 = ReactNativeBridgeEventPlugin;
function runEventQueueInBatch(events) {
EventPluginHub_1.enqueueEvents(events), EventPluginHub_1.processEventQueue(!1);
}
var ReactEventEmitterMixin = {
handleTopLevel: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
runEventQueueInBatch(EventPluginHub_1.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget));
}
}, ReactEventEmitterMixin_1 = ReactEventEmitterMixin, INITIAL_TAG_COUNT = 1, ReactNativeTagHandles = {
tagsStartAt: INITIAL_TAG_COUNT,
tagCount: INITIAL_TAG_COUNT,
allocateTag: function() {
for (;this.reactTagIsNativeTopRootID(ReactNativeTagHandles.tagCount); ) ReactNativeTagHandles.tagCount++;
var tag = ReactNativeTagHandles.tagCount;
return ReactNativeTagHandles.tagCount++, tag;
},
assertRootTag: function(tag) {
invariant(this.reactTagIsNativeTopRootID(tag), "Expect a native root tag, instead got %s", tag);
},
reactTagIsNativeTopRootID: function(reactTag) {
return reactTag % 10 == 1;
}
}, ReactNativeTagHandles_1 = ReactNativeTagHandles, fiberHostComponent = null, ReactControlledComponentInjection = {
injectFiberControlledHostComponent: function(hostComponentImpl) {
fiberHostComponent = hostComponentImpl;
}
}, restoreTarget = null, restoreQueue = null;
function restoreStateOfTarget(target) {
var internalInstance = EventPluginUtils_1.getInstanceFromNode(target);
if (internalInstance) {
if ("number" == typeof internalInstance.tag) {
invariant(fiberHostComponent && "function" == typeof fiberHostComponent.restoreControlledState, "Fiber needs to be injected to handle a fiber target for controlled " + "events.");
var props = EventPluginUtils_1.getFiberCurrentPropsFromNode(internalInstance.stateNode);
return void fiberHostComponent.restoreControlledState(internalInstance.stateNode, internalInstance.type, props);
}
invariant("function" == typeof internalInstance.restoreControlledState, "The internal instance must be a React host component."),
internalInstance.restoreControlledState();
}
}
var ReactControlledComponent = {
injection: ReactControlledComponentInjection,
enqueueStateRestore: function(target) {
restoreTarget ? restoreQueue ? restoreQueue.push(target) : restoreQueue = [ target ] : restoreTarget = target;
},
restoreStateIfNeeded: function() {
if (restoreTarget) {
var target = restoreTarget, queuedTargets = restoreQueue;
if (restoreTarget = null, restoreQueue = null, restoreStateOfTarget(target), queuedTargets) for (var i = 0; i < queuedTargets.length; i++) restoreStateOfTarget(queuedTargets[i]);
}
}
}, ReactControlledComponent_1 = ReactControlledComponent, stackBatchedUpdates = function(fn, a, b, c, d, e) {
return fn(a, b, c, d, e);
}, fiberBatchedUpdates = function(fn, bookkeeping) {
return fn(bookkeeping);
};
function performFiberBatchedUpdates(fn, bookkeeping) {
return fiberBatchedUpdates(fn, bookkeeping);
}
function batchedUpdates(fn, bookkeeping) {
return stackBatchedUpdates(performFiberBatchedUpdates, fn, bookkeeping);
}
var isNestingBatched = !1;
function batchedUpdatesWithControlledComponents(fn, bookkeeping) {
if (isNestingBatched) return batchedUpdates(fn, bookkeeping);
isNestingBatched = !0;
try {
return batchedUpdates(fn, bookkeeping);
} finally {
isNestingBatched = !1, ReactControlledComponent_1.restoreStateIfNeeded();
}
}
var ReactGenericBatchingInjection = {
injectStackBatchedUpdates: function(_batchedUpdates) {
stackBatchedUpdates = _batchedUpdates;
},
injectFiberBatchedUpdates: function(_batchedUpdates) {
fiberBatchedUpdates = _batchedUpdates;
}
}, ReactGenericBatching = {
batchedUpdates: batchedUpdatesWithControlledComponents,
injection: ReactGenericBatchingInjection
}, ReactGenericBatching_1 = ReactGenericBatching, _extends$1 = Object.assign || function(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]);
}
return target;
}, EMPTY_NATIVE_EVENT = {}, touchSubsequence = function(touches, indices) {
for (var ret = [], i = 0; i < indices.length; i++) ret.push(touches[indices[i]]);
return ret;
}, removeTouchesAtIndices = function(touches, indices) {
for (var rippedOut = [], temp = touches, i = 0; i < indices.length; i++) {
var index = indices[i];
rippedOut.push(touches[index]), temp[index] = null;
}
for (var fillAt = 0, j = 0; j < temp.length; j++) {
var cur = temp[j];
null !== cur && (temp[fillAt++] = cur);
}
return temp.length = fillAt, rippedOut;
}, ReactNativeEventEmitter = _extends$1({}, ReactEventEmitterMixin_1, {
registrationNames: EventPluginRegistry_1.registrationNameModules,
getListener: EventPluginHub_1.getListener,
_receiveRootNodeIDEvent: function(rootNodeID, topLevelType, nativeEventParam) {
var nativeEvent = nativeEventParam || EMPTY_NATIVE_EVENT, inst = ReactNativeComponentTree_1.getInstanceFromNode(rootNodeID);
ReactGenericBatching_1.batchedUpdates(function() {
ReactNativeEventEmitter.handleTopLevel(topLevelType, inst, nativeEvent, nativeEvent.target);
});
},
receiveEvent: function(tag, topLevelType, nativeEventParam) {
var rootNodeID = tag;
ReactNativeEventEmitter._receiveRootNodeIDEvent(rootNodeID, topLevelType, nativeEventParam);
},
receiveTouches: function(eventTopLevelType, touches, changedIndices) {
for (var changedTouches = "topTouchEnd" === eventTopLevelType || "topTouchCancel" === eventTopLevelType ? removeTouchesAtIndices(touches, changedIndices) : touchSubsequence(touches, changedIndices), jj = 0; jj < changedTouches.length; jj++) {
var touch = changedTouches[jj];
touch.changedTouches = changedTouches, touch.touches = touches;
var nativeEvent = touch, rootNodeID = null, target = nativeEvent.target;
null !== target && void 0 !== target && (target < ReactNativeTagHandles_1.tagsStartAt ? warning(!1, "A view is reporting that a touch occurred on tag zero.") : rootNodeID = target),
ReactNativeEventEmitter._receiveRootNodeIDEvent(rootNodeID, eventTopLevelType, nativeEvent);
}
}
}), ReactNativeEventEmitter_1 = ReactNativeEventEmitter, ReactNativeEventPluginOrder = [ "ResponderEventPlugin", "ReactNativeBridgeEventPlugin" ], ReactNativeEventPluginOrder_1 = ReactNativeEventPluginOrder, ReactNativeGlobalResponderHandler = {
onChange: function(from, to, blockNativeResponder) {
if (null !== to) {
var tag = "number" != typeof to.tag ? to._rootNodeID : to.stateNode._nativeTag;
UIManager.setJSResponder(tag, blockNativeResponder);
} else UIManager.clearJSResponder();
}
}, ReactNativeGlobalResponderHandler_1 = ReactNativeGlobalResponderHandler, ResponderEventInterface = {
touchHistory: function(nativeEvent) {
return null;
}
};
function ResponderSyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent_1.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent_1.augmentClass(ResponderSyntheticEvent, ResponderEventInterface);
var ResponderSyntheticEvent_1 = ResponderSyntheticEvent, isEndish$2 = EventPluginUtils_1.isEndish, isMoveish$2 = EventPluginUtils_1.isMoveish, isStartish$2 = EventPluginUtils_1.isStartish, MAX_TOUCH_BANK = 20, touchBank = [], touchHistory = {
touchBank: touchBank,
numberActiveTouches: 0,
indexOfSingleActiveTouch: -1,
mostRecentTimeStamp: 0
};
function timestampForTouch(touch) {
return touch.timeStamp || touch.timestamp;
}
function createTouchRecord(touch) {
return {
touchActive: !0,
startPageX: touch.pageX,
startPageY: touch.pageY,
startTimeStamp: timestampForTouch(touch),
currentPageX: touch.pageX,
currentPageY: touch.pageY,
currentTimeStamp: timestampForTouch(touch),
previousPageX: touch.pageX,
previousPageY: touch.pageY,
previousTimeStamp: timestampForTouch(touch)
};
}
function resetTouchRecord(touchRecord, touch) {
touchRecord.touchActive = !0, touchRecord.startPageX = touch.pageX, touchRecord.startPageY = touch.pageY,
touchRecord.startTimeStamp = timestampForTouch(touch), touchRecord.currentPageX = touch.pageX,
touchRecord.currentPageY = touch.pageY, touchRecord.currentTimeStamp = timestampForTouch(touch),
touchRecord.previousPageX = touch.pageX, touchRecord.previousPageY = touch.pageY,
touchRecord.previousTimeStamp = timestampForTouch(touch);
}
function getTouchIdentifier(_ref) {
var identifier = _ref.identifier;
return invariant(null != identifier, "Touch object is missing identifier."), warning(identifier <= MAX_TOUCH_BANK, "Touch identifier %s is greater than maximum supported %s which causes " + "performance issues backfilling array locations for all of the indices.", identifier, MAX_TOUCH_BANK),
identifier;
}
function recordTouchStart(touch) {
var identifier = getTouchIdentifier(touch), touchRecord = touchBank[identifier];
touchRecord ? resetTouchRecord(touchRecord, touch) : touchBank[identifier] = createTouchRecord(touch),
touchHistory.mostRecentTimeStamp = timestampForTouch(touch);
}
function recordTouchMove(touch) {
var touchRecord = touchBank[getTouchIdentifier(touch)];
touchRecord ? (touchRecord.touchActive = !0, touchRecord.previousPageX = touchRecord.currentPageX,
touchRecord.previousPageY = touchRecord.currentPageY, touchRecord.previousTimeStamp = touchRecord.currentTimeStamp,
touchRecord.currentPageX = touch.pageX, touchRecord.currentPageY = touch.pageY,
touchRecord.currentTimeStamp = timestampForTouch(touch), touchHistory.mostRecentTimeStamp = timestampForTouch(touch)) : console.error("Cannot record touch move without a touch start.\n" + "Touch Move: %s\n", "Touch Bank: %s", printTouch(touch), printTouchBank());
}
function recordTouchEnd(touch) {
var touchRecord = touchBank[getTouchIdentifier(touch)];
touchRecord ? (touchRecord.touchActive = !1, touchRecord.previousPageX = touchRecord.currentPageX,
touchRecord.previousPageY = touchRecord.currentPageY, touchRecord.previousTimeStamp = touchRecord.currentTimeStamp,
touchRecord.currentPageX = touch.pageX, touchRecord.currentPageY = touch.pageY,
touchRecord.currentTimeStamp = timestampForTouch(touch), touchHistory.mostRecentTimeStamp = timestampForTouch(touch)) : console.error("Cannot record touch end without a touch start.\n" + "Touch End: %s\n", "Touch Bank: %s", printTouch(touch), printTouchBank());
}
function printTouch(touch) {
return JSON.stringify({
identifier: touch.identifier,
pageX: touch.pageX,
pageY: touch.pageY,
timestamp: timestampForTouch(touch)
});
}
function printTouchBank() {
var printed = JSON.stringify(touchBank.slice(0, MAX_TOUCH_BANK));
return touchBank.length > MAX_TOUCH_BANK && (printed += " (original size: " + touchBank.length + ")"),
printed;
}
var ResponderTouchHistoryStore = {
recordTouchTrack: function(topLevelType, nativeEvent) {
if (isMoveish$2(topLevelType)) nativeEvent.changedTouches.forEach(recordTouchMove); else if (isStartish$2(topLevelType)) nativeEvent.changedTouches.forEach(recordTouchStart),
touchHistory.numberActiveTouches = nativeEvent.touches.length, 1 === touchHistory.numberActiveTouches && (touchHistory.indexOfSingleActiveTouch = nativeEvent.touches[0].identifier); else if (isEndish$2(topLevelType) && (nativeEvent.changedTouches.forEach(recordTouchEnd),
touchHistory.numberActiveTouches = nativeEvent.touches.length, 1 === touchHistory.numberActiveTouches)) {
for (var i = 0; i < touchBank.length; i++) {
var touchTrackToCheck = touchBank[i];
if (null != touchTrackToCheck && touchTrackToCheck.touchActive) {
touchHistory.indexOfSingleActiveTouch = i;
break;
}
}
var activeRecord = touchBank[touchHistory.indexOfSingleActiveTouch];
warning(null != activeRecord && activeRecord.touchActive, "Cannot find single active touch.");
}
},
touchHistory: touchHistory
}, ResponderTouchHistoryStore_1 = ResponderTouchHistoryStore;
function accumulate(current, next) {
return invariant(null != next, "accumulate(...): Accumulated items must be not be null or undefined."),
null == current ? next : Array.isArray(current) ? current.concat(next) : Array.isArray(next) ? [ current ].concat(next) : [ current, next ];
}
var accumulate_1 = accumulate, isStartish$1 = EventPluginUtils_1.isStartish, isMoveish$1 = EventPluginUtils_1.isMoveish, isEndish$1 = EventPluginUtils_1.isEndish, executeDirectDispatch$1 = EventPluginUtils_1.executeDirectDispatch, hasDispatches$1 = EventPluginUtils_1.hasDispatches, executeDispatchesInOrderStopAtTrue$1 = EventPluginUtils_1.executeDispatchesInOrderStopAtTrue, responderInst = null, trackedTouchCount = 0, previousActiveTouches = 0, changeResponder = function(nextResponderInst, blockHostResponder) {
var oldResponderInst = responderInst;
responderInst = nextResponderInst, null !== ResponderEventPlugin.GlobalResponderHandler && ResponderEventPlugin.GlobalResponderHandler.onChange(oldResponderInst, nextResponderInst, blockHostResponder);
}, eventTypes = {
startShouldSetResponder: {
phasedRegistrationNames: {
bubbled: "onStartShouldSetResponder",
captured: "onStartShouldSetResponderCapture"
}
},
scrollShouldSetResponder: {
phasedRegistrationNames: {
bubbled: "onScrollShouldSetResponder",
captured: "onScrollShouldSetResponderCapture"
}
},
selectionChangeShouldSetResponder: {
phasedRegistrationNames: {
bubbled: "onSelectionChangeShouldSetResponder",
captured: "onSelectionChangeShouldSetResponderCapture"
}
},
moveShouldSetResponder: {
phasedRegistrationNames: {
bubbled: "onMoveShouldSetResponder",
captured: "onMoveShouldSetResponderCapture"
}
},
responderStart: {
registrationName: "onResponderStart"
},
responderMove: {
registrationName: "onResponderMove"
},
responderEnd: {
registrationName: "onResponderEnd"
},
responderRelease: {
registrationName: "onResponderRelease"
},
responderTerminationRequest: {
registrationName: "onResponderTerminationRequest"
},
responderGrant: {
registrationName: "onResponderGrant"
},
responderReject: {
registrationName: "onResponderReject"
},
responderTerminate: {
registrationName: "onResponderTerminate"
}
};
function setResponderAndExtractTransfer(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var shouldSetEventType = isStartish$1(topLevelType) ? eventTypes.startShouldSetResponder : isMoveish$1(topLevelType) ? eventTypes.moveShouldSetResponder : "topSelectionChange" === topLevelType ? eventTypes.selectionChangeShouldSetResponder : eventTypes.scrollShouldSetResponder, bubbleShouldSetFrom = responderInst ? ReactTreeTraversal.getLowestCommonAncestor(responderInst, targetInst) : targetInst, skipOverBubbleShouldSetFrom = bubbleShouldSetFrom === responderInst, shouldSetEvent = ResponderSyntheticEvent_1.getPooled(shouldSetEventType, bubbleShouldSetFrom, nativeEvent, nativeEventTarget);
shouldSetEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, skipOverBubbleShouldSetFrom ? EventPropagators_1.accumulateTwoPhaseDispatchesSkipTarget(shouldSetEvent) : EventPropagators_1.accumulateTwoPhaseDispatches(shouldSetEvent);
var wantsResponderInst = executeDispatchesInOrderStopAtTrue$1(shouldSetEvent);
if (shouldSetEvent.isPersistent() || shouldSetEvent.constructor.release(shouldSetEvent),
!wantsResponderInst || wantsResponderInst === responderInst) return null;
var extracted, grantEvent = ResponderSyntheticEvent_1.getPooled(eventTypes.responderGrant, wantsResponderInst, nativeEvent, nativeEventTarget);
grantEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, EventPropagators_1.accumulateDirectDispatches(grantEvent);
var blockHostResponder = !0 === executeDirectDispatch$1(grantEvent);
if (responderInst) {
var terminationRequestEvent = ResponderSyntheticEvent_1.getPooled(eventTypes.responderTerminationRequest, responderInst, nativeEvent, nativeEventTarget);
terminationRequestEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory,
EventPropagators_1.accumulateDirectDispatches(terminationRequestEvent);
var shouldSwitch = !hasDispatches$1(terminationRequestEvent) || executeDirectDispatch$1(terminationRequestEvent);
if (terminationRequestEvent.isPersistent() || terminationRequestEvent.constructor.release(terminationRequestEvent),
shouldSwitch) {
var terminateEvent = ResponderSyntheticEvent_1.getPooled(eventTypes.responderTerminate, responderInst, nativeEvent, nativeEventTarget);
terminateEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, EventPropagators_1.accumulateDirectDispatches(terminateEvent),
extracted = accumulate_1(extracted, [ grantEvent, terminateEvent ]), changeResponder(wantsResponderInst, blockHostResponder);
} else {
var rejectEvent = ResponderSyntheticEvent_1.getPooled(eventTypes.responderReject, wantsResponderInst, nativeEvent, nativeEventTarget);
rejectEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, EventPropagators_1.accumulateDirectDispatches(rejectEvent),
extracted = accumulate_1(extracted, rejectEvent);
}
} else extracted = accumulate_1(extracted, grantEvent), changeResponder(wantsResponderInst, blockHostResponder);
return extracted;
}
function canTriggerTransfer(topLevelType, topLevelInst, nativeEvent) {
return topLevelInst && ("topScroll" === topLevelType && !nativeEvent.responderIgnoreScroll || trackedTouchCount > 0 && "topSelectionChange" === topLevelType || isStartish$1(topLevelType) || isMoveish$1(topLevelType));
}
function noResponderTouches(nativeEvent) {
var touches = nativeEvent.touches;
if (!touches || 0 === touches.length) return !0;
for (var i = 0; i < touches.length; i++) {
var activeTouch = touches[i], target = activeTouch.target;
if (null !== target && void 0 !== target && 0 !== target) {
var targetInst = EventPluginUtils_1.getInstanceFromNode(target);
if (ReactTreeTraversal.isAncestor(responderInst, targetInst)) return !1;
}
}
return !0;
}
var ResponderEventPlugin = {
_getResponder: function() {
return responderInst;
},
eventTypes: eventTypes,
extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
if (isStartish$1(topLevelType)) trackedTouchCount += 1; else if (isEndish$1(topLevelType)) {
if (!(trackedTouchCount >= 0)) return console.error("Ended a touch event which was not counted in `trackedTouchCount`."),
null;
trackedTouchCount -= 1;
}
ResponderTouchHistoryStore_1.recordTouchTrack(topLevelType, nativeEvent);
var extracted = canTriggerTransfer(topLevelType, targetInst, nativeEvent) ? setResponderAndExtractTransfer(topLevelType, targetInst, nativeEvent, nativeEventTarget) : null, isResponderTouchStart = responderInst && isStartish$1(topLevelType), isResponderTouchMove = responderInst && isMoveish$1(topLevelType), isResponderTouchEnd = responderInst && isEndish$1(topLevelType), incrementalTouch = isResponderTouchStart ? eventTypes.responderStart : isResponderTouchMove ? eventTypes.responderMove : isResponderTouchEnd ? eventTypes.responderEnd : null;
if (incrementalTouch) {
var gesture = ResponderSyntheticEvent_1.getPooled(incrementalTouch, responderInst, nativeEvent, nativeEventTarget);
gesture.touchHistory = ResponderTouchHistoryStore_1.touchHistory, EventPropagators_1.accumulateDirectDispatches(gesture),
extracted = accumulate_1(extracted, gesture);
}
var isResponderTerminate = responderInst && "topTouchCancel" === topLevelType, isResponderRelease = responderInst && !isResponderTerminate && isEndish$1(topLevelType) && noResponderTouches(nativeEvent), finalTouch = isResponderTerminate ? eventTypes.responderTerminate : isResponderRelease ? eventTypes.responderRelease : null;
if (finalTouch) {
var finalEvent = ResponderSyntheticEvent_1.getPooled(finalTouch, responderInst, nativeEvent, nativeEventTarget);
finalEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory, EventPropagators_1.accumulateDirectDispatches(finalEvent),
extracted = accumulate_1(extracted, finalEvent), changeResponder(null);
}
var numberActiveTouches = ResponderTouchHistoryStore_1.touchHistory.numberActiveTouches;
return ResponderEventPlugin.GlobalInteractionHandler && numberActiveTouches !== previousActiveTouches && ResponderEventPlugin.GlobalInteractionHandler.onChange(numberActiveTouches),
previousActiveTouches = numberActiveTouches, extracted;
},
GlobalResponderHandler: null,
GlobalInteractionHandler: null,
injection: {
injectGlobalResponderHandler: function(GlobalResponderHandler) {
ResponderEventPlugin.GlobalResponderHandler = GlobalResponderHandler;
},
injectGlobalInteractionHandler: function(GlobalInteractionHandler) {
ResponderEventPlugin.GlobalInteractionHandler = GlobalInteractionHandler;
}
}
}, ResponderEventPlugin_1 = ResponderEventPlugin;
function inject() {
RCTEventEmitter.register(ReactNativeEventEmitter_1), EventPluginHub_1.injection.injectEventPluginOrder(ReactNativeEventPluginOrder_1),
EventPluginUtils_1.injection.injectComponentTree(ReactNativeComponentTree_1), ResponderEventPlugin_1.injection.injectGlobalResponderHandler(ReactNativeGlobalResponderHandler_1),
EventPluginHub_1.injection.injectEventPluginsByName({
ResponderEventPlugin: ResponderEventPlugin_1,
ReactNativeBridgeEventPlugin: ReactNativeBridgeEventPlugin_1
});
}
var ReactNativeInjection = {
inject: inject
}, ReactInvalidSetStateWarningHook = {}, processingChildContext = !1, warnInvalidSetState = function() {
warning(!processingChildContext, "setState(...): Cannot call setState() inside getChildContext()");
};
ReactInvalidSetStateWarningHook = {
onBeginProcessingChildContext: function() {
processingChildContext = !0;
},
onEndProcessingChildContext: function() {
processingChildContext = !1;
},
onSetState: function() {
warnInvalidSetState();
}
};
var ReactInvalidSetStateWarningHook_1 = ReactInvalidSetStateWarningHook, ReactHostOperationHistoryHook = null, history = [];
ReactHostOperationHistoryHook = {
onHostOperation: function(operation) {
history.push(operation);
},
clearHistory: function() {
ReactHostOperationHistoryHook._preventClearing || (history = []);
},
getHistory: function() {
return history;
}
};
var ReactHostOperationHistoryHook_1 = ReactHostOperationHistoryHook, ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, ReactGlobalSharedState = {
ReactCurrentOwner: ReactInternals.ReactCurrentOwner
};
Object.assign(ReactGlobalSharedState, {
ReactComponentTreeHook: ReactInternals.ReactComponentTreeHook,
ReactDebugCurrentFrame: ReactInternals.ReactDebugCurrentFrame
});
var ReactGlobalSharedState_1 = ReactGlobalSharedState, ReactComponentTreeHook = ReactGlobalSharedState_1.ReactComponentTreeHook, ReactDebugTool$1 = null, hooks = [], didHookThrowForEvent = {}, callHook = function(event, fn, context, arg1, arg2, arg3, arg4, arg5) {
try {
fn.call(context, arg1, arg2, arg3, arg4, arg5);
} catch (e) {
warning(didHookThrowForEvent[event], "Exception thrown by hook while handling %s: %s", event, e + "\n" + e.stack),
didHookThrowForEvent[event] = !0;
}
}, emitEvent = function(event, arg1, arg2, arg3, arg4, arg5) {
for (var i = 0; i < hooks.length; i++) {
var hook = hooks[i], fn = hook[event];
fn && callHook(event, fn, hook, arg1, arg2, arg3, arg4, arg5);
}
}, isProfiling = !1, flushHistory = [], lifeCycleTimerStack = [], currentFlushNesting = 0, currentFlushMeasurements = [], currentFlushStartTime = 0, currentTimerDebugID = null, currentTimerStartTime = 0, currentTimerNestedFlushDuration = 0, currentTimerType = null, lifeCycleTimerHasWarned = !1, clearHistory = function() {
ReactComponentTreeHook.purgeUnmountedComponents(), ReactHostOperationHistoryHook_1.clearHistory();
}, getTreeSnapshot = function(registeredIDs) {
return registeredIDs.reduce(function(tree, id) {
var ownerID = ReactComponentTreeHook.getOwnerID(id), parentID = ReactComponentTreeHook.getParentID(id);
return tree[id] = {
displayName: ReactComponentTreeHook.getDisplayName(id),
text: ReactComponentTreeHook.getText(id),
updateCount: ReactComponentTreeHook.getUpdateCount(id),
childIDs: ReactComponentTreeHook.getChildIDs(id),
ownerID: ownerID || parentID && ReactComponentTreeHook.getOwnerID(parentID) || 0,
parentID: parentID
}, tree;
}, {});
}, resetMeasurements = function() {
var previousStartTime = currentFlushStartTime, previousMeasurements = currentFlushMeasurements, previousOperations = ReactHostOperationHistoryHook_1.getHistory();
if (0 === currentFlushNesting) return currentFlushStartTime = 0, currentFlushMeasurements = [],
void clearHistory();
if (previousMeasurements.length || previousOperations.length) {
var registeredIDs = ReactComponentTreeHook.getRegisteredIDs();
flushHistory.push({
duration: performanceNow() - previousStartTime,
measurements: previousMeasurements || [],
operations: previousOperations || [],
treeSnapshot: getTreeSnapshot(registeredIDs)
});
}
clearHistory(), currentFlushStartTime = performanceNow(), currentFlushMeasurements = [];
}, checkDebugID = function(debugID) {
arguments.length > 1 && void 0 !== arguments[1] && arguments[1] && 0 === debugID || debugID || warning(!1, "ReactDebugTool: debugID may not be empty.");
}, beginLifeCycleTimer = function(debugID, timerType) {
0 !== currentFlushNesting && (currentTimerType && !lifeCycleTimerHasWarned && (warning(!1, "There is an internal error in the React performance measurement code." + "\n\nDid not expect %s timer to start while %s timer is still in " + "progress for %s instance.", timerType, currentTimerType || "no", debugID === currentTimerDebugID ? "the same" : "another"),
lifeCycleTimerHasWarned = !0), currentTimerStartTime = performanceNow(), currentTimerNestedFlushDuration = 0,
currentTimerDebugID = debugID, currentTimerType = timerType);
}, endLifeCycleTimer = function(debugID, timerType) {
0 !== currentFlushNesting && (currentTimerType === timerType || lifeCycleTimerHasWarned || (warning(!1, "There is an internal error in the React performance measurement code. " + "We did not expect %s timer to stop while %s timer is still in " + "progress for %s instance. Please report this as a bug in React.", timerType, currentTimerType || "no", debugID === currentTimerDebugID ? "the same" : "another"),
lifeCycleTimerHasWarned = !0), isProfiling && currentFlushMeasurements.push({
timerType: timerType,
instanceID: debugID,
duration: performanceNow() - currentTimerStartTime - currentTimerNestedFlushDuration
}), currentTimerStartTime = 0, currentTimerNestedFlushDuration = 0, currentTimerDebugID = null,
currentTimerType = null);
}, pauseCurrentLifeCycleTimer = function() {
var currentTimer = {
startTime: currentTimerStartTime,
nestedFlushStartTime: performanceNow(),
debugID: currentTimerDebugID,
timerType: currentTimerType
};
lifeCycleTimerStack.push(currentTimer), currentTimerStartTime = 0, currentTimerNestedFlushDuration = 0,
currentTimerDebugID = null, currentTimerType = null;
}, resumeCurrentLifeCycleTimer = function() {
var _lifeCycleTimerStack$ = lifeCycleTimerStack.pop(), startTime = _lifeCycleTimerStack$.startTime, nestedFlushStartTime = _lifeCycleTimerStack$.nestedFlushStartTime, debugID = _lifeCycleTimerStack$.debugID, timerType = _lifeCycleTimerStack$.timerType, nestedFlushDuration = performanceNow() - nestedFlushStartTime;
currentTimerStartTime = startTime, currentTimerNestedFlushDuration += nestedFlushDuration,
currentTimerDebugID = debugID, currentTimerType = timerType;
}, lastMarkTimeStamp = 0, canUsePerformanceMeasure = "undefined" != typeof performance && "function" == typeof performance.mark && "function" == typeof performance.clearMarks && "function" == typeof performance.measure && "function" == typeof performance.clearMeasures, shouldMark = function(debugID) {
if (!isProfiling || !canUsePerformanceMeasure) return !1;
var element = ReactComponentTreeHook.getElement(debugID);
return null != element && "object" == typeof element && !("string" == typeof element.type);
}, markBegin = function(debugID, markType) {
if (shouldMark(debugID)) {
var markName = debugID + "::" + markType;
lastMarkTimeStamp = performanceNow(), performance.mark(markName);
}
}, markEnd = function(debugID, markType) {
if (shouldMark(debugID)) {
var markName = debugID + "::" + markType, displayName = ReactComponentTreeHook.getDisplayName(debugID) || "Unknown";
if (performanceNow() - lastMarkTimeStamp > .1) {
var measurementName = displayName + " [" + markType + "]";
performance.measure(measurementName, markName);
}
performance.clearMarks(markName), measurementName && performance.clearMeasures(measurementName);
}
};
ReactDebugTool$1 = {
addHook: function(hook) {
hooks.push(hook);
},
removeHook: function(hook) {
for (var i = 0; i < hooks.length; i++) hooks[i] === hook && (hooks.splice(i, 1),
i--);
},
isProfiling: function() {
return isProfiling;
},
beginProfiling: function() {
isProfiling || (isProfiling = !0, flushHistory.length = 0, resetMeasurements(),
ReactDebugTool$1.addHook(ReactHostOperationHistoryHook_1));
},
endProfiling: function() {
isProfiling && (isProfiling = !1, resetMeasurements(), ReactDebugTool$1.removeHook(ReactHostOperationHistoryHook_1));
},
getFlushHistory: function() {
return flushHistory;
},
onBeginFlush: function() {
currentFlushNesting++, resetMeasurements(), pauseCurrentLifeCycleTimer(), emitEvent("onBeginFlush");
},
onEndFlush: function() {
resetMeasurements(), currentFlushNesting--, resumeCurrentLifeCycleTimer(), emitEvent("onEndFlush");
},
onBeginLifeCycleTimer: function(debugID, timerType) {
checkDebugID(debugID), emitEvent("onBeginLifeCycleTimer", debugID, timerType), markBegin(debugID, timerType),
beginLifeCycleTimer(debugID, timerType);
},
onEndLifeCycleTimer: function(debugID, timerType) {
checkDebugID(debugID), endLifeCycleTimer(debugID, timerType), markEnd(debugID, timerType),
emitEvent("onEndLifeCycleTimer", debugID, timerType);
},
onBeginProcessingChildContext: function() {
emitEvent("onBeginProcessingChildContext");
},
onEndProcessingChildContext: function() {
emitEvent("onEndProcessingChildContext");
},
onHostOperation: function(operation) {
checkDebugID(operation.instanceID), emitEvent("onHostOperation", operation);
},
onSetState: function() {
emitEvent("onSetState");
},
onSetChildren: function(debugID, childDebugIDs) {
checkDebugID(debugID), childDebugIDs.forEach(checkDebugID), emitEvent("onSetChildren", debugID, childDebugIDs);
},
onBeforeMountComponent: function(debugID, element, parentDebugID) {
checkDebugID(debugID), checkDebugID(parentDebugID, !0), emitEvent("onBeforeMountComponent", debugID, element, parentDebugID),
markBegin(debugID, "mount");
},
onMountComponent: function(debugID) {
checkDebugID(debugID), markEnd(debugID, "mount"), emitEvent("onMountComponent", debugID);
},
onBeforeUpdateComponent: function(debugID, element) {
checkDebugID(debugID), emitEvent("onBeforeUpdateComponent", debugID, element), markBegin(debugID, "update");
},
onUpdateComponent: function(debugID) {
checkDebugID(debugID), markEnd(debugID, "update"), emitEvent("onUpdateComponent", debugID);
},
onBeforeUnmountComponent: function(debugID) {
checkDebugID(debugID), emitEvent("onBeforeUnmountComponent", debugID), markBegin(debugID, "unmount");
},
onUnmountComponent: function(debugID) {
checkDebugID(debugID), markEnd(debugID, "unmount"), emitEvent("onUnmountComponent", debugID);
},
onTestEvent: function() {
emitEvent("onTestEvent");
}
}, ReactDebugTool$1.addHook(ReactInvalidSetStateWarningHook_1), ReactDebugTool$1.addHook(ReactComponentTreeHook);
var url = ExecutionEnvironment.canUseDOM && window.location.href || "";
/[?&]react_perf\b/.test(url) && ReactDebugTool$1.beginProfiling();
var ReactDebugTool_1 = ReactDebugTool$1, debugTool = null, ReactDebugTool = ReactDebugTool_1;
debugTool = ReactDebugTool;
var ReactInstrumentation = {
debugTool: debugTool
};
function ReactNativeContainerInfo(tag) {
return {
_tag: tag
};
}
var ReactNativeContainerInfo_1 = ReactNativeContainerInfo, ClassComponent = ReactTypeOfWork.ClassComponent;
function isValidOwner(object) {
return !(!object || "function" != typeof object.attachRef || "function" != typeof object.detachRef);
}
var ReactOwner = {
addComponentAsRefTo: function(component, ref, owner) {
if (owner && owner.tag === ClassComponent) {
var inst = owner.stateNode;
(inst.refs === emptyObject ? inst.refs = {} : inst.refs)[ref] = component.getPublicInstance();
} else invariant(isValidOwner(owner), "addComponentAsRefTo(...): Only a ReactOwner can have refs. You might " + "be adding a ref to a component that was not created inside a component's " + "`render` method, or you have multiple copies of React loaded " + "(details: https://fb.me/react-refs-must-have-owner)."),
owner.attachRef(ref, component);
},
removeComponentAsRefFrom: function(component, ref, owner) {
if (owner && owner.tag === ClassComponent) {
var inst = owner.stateNode;
inst && inst.refs[ref] === component.getPublicInstance() && delete inst.refs[ref];
} else {
invariant(isValidOwner(owner), "removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might " + "be removing a ref to a component that was not created inside a component's " + "`render` method, or you have multiple copies of React loaded " + "(details: https://fb.me/react-refs-must-have-owner).");
var ownerPublicInstance = owner.getPublicInstance();
ownerPublicInstance && ownerPublicInstance.refs[ref] === component.getPublicInstance() && owner.detachRef(ref);
}
}
}, ReactOwner_1 = ReactOwner, ReactCompositeComponentTypes$1 = {
ImpureClass: 0,
PureClass: 1,
StatelessFunctional: 2
}, ReactRef = {}, ReactCompositeComponentTypes = ReactCompositeComponentTypes$1, _require$1 = ReactGlobalSharedState_1, ReactComponentTreeHook$1 = _require$1.ReactComponentTreeHook, warning$2 = warning, warnedAboutStatelessRefs = {};
function attachRef(ref, component, owner) {
if (component._compositeType === ReactCompositeComponentTypes.StatelessFunctional) {
var info = "", ownerName = void 0;
owner && ("function" == typeof owner.getName && (ownerName = owner.getName()), ownerName && (info += "\n\nCheck the render method of `" + ownerName + "`."));
var warningKey = ownerName || component._debugID, element = component._currentElement;
element && element._source && (warningKey = element._source.fileName + ":" + element._source.lineNumber),
warnedAboutStatelessRefs[warningKey] || (warnedAboutStatelessRefs[warningKey] = !0,
warning$2(!1, "Stateless function components cannot be given refs. " + "Attempts to access this ref will fail.%s%s", info, ReactComponentTreeHook$1.getStackAddendumByID(component._debugID)));
}
"function" == typeof ref ? ref(component.getPublicInstance()) : ReactOwner_1.addComponentAsRefTo(component, ref, owner);
}
function detachRef(ref, component, owner) {
"function" == typeof ref ? ref(null) : ReactOwner_1.removeComponentAsRefFrom(component, ref, owner);
}
ReactRef.attachRefs = function(instance, element) {
if (null !== element && "object" == typeof element) {
var ref = element.ref;
null != ref && attachRef(ref, instance, element._owner);
}
}, ReactRef.shouldUpdateRefs = function(prevElement, nextElement) {
var prevRef = null, prevOwner = null;
null !== prevElement && "object" == typeof prevElement && (prevRef = prevElement.ref,
prevOwner = prevElement._owner);
var nextRef = null, nextOwner = null;
return null !== nextElement && "object" == typeof nextElement && (nextRef = nextElement.ref,
nextOwner = nextElement._owner), prevRef !== nextRef || "string" == typeof nextRef && nextOwner !== prevOwner;
}, ReactRef.detachRefs = function(instance, element) {
if (null !== element && "object" == typeof element) {
var ref = element.ref;
null != ref && detachRef(ref, instance, element._owner);
}
};
var ReactRef_1 = ReactRef;
function attachRefs() {
ReactRef_1.attachRefs(this, this._currentElement);
}
var ReactReconciler = {
mountComponent: function(internalInstance, transaction, hostParent, hostContainerInfo, context, parentDebugID) {
0 !== internalInstance._debugID && ReactInstrumentation.debugTool.onBeforeMountComponent(internalInstance._debugID, internalInstance._currentElement, parentDebugID);
var markup = internalInstance.mountComponent(transaction, hostParent, hostContainerInfo, context, parentDebugID);
return internalInstance._currentElement && null != internalInstance._currentElement.ref && transaction.getReactMountReady().enqueue(attachRefs, internalInstance),
0 !== internalInstance._debugID && ReactInstrumentation.debugTool.onMountComponent(internalInstance._debugID),
markup;
},
getHostNode: function(internalInstance) {
return internalInstance.getHostNode();
},
unmountComponent: function(internalInstance, safely, skipLifecycle) {
0 !== internalInstance._debugID && ReactInstrumentation.debugTool.onBeforeUnmountComponent(internalInstance._debugID),
ReactRef_1.detachRefs(internalInstance, internalInstance._currentElement), internalInstance.unmountComponent(safely, skipLifecycle),
0 !== internalInstance._debugID && ReactInstrumentation.debugTool.onUnmountComponent(internalInstance._debugID);
},
receiveComponent: function(internalInstance, nextElement, transaction, context) {
var prevElement = internalInstance._currentElement;
if (nextElement !== prevElement || context !== internalInstance._context) {
0 !== internalInstance._debugID && ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, nextElement);
var refsChanged = ReactRef_1.shouldUpdateRefs(prevElement, nextElement);
refsChanged && ReactRef_1.detachRefs(internalInstance, prevElement), internalInstance.receiveComponent(nextElement, transaction, context),
refsChanged && internalInstance._currentElement && null != internalInstance._currentElement.ref && transaction.getReactMountReady().enqueue(attachRefs, internalInstance),
0 !== internalInstance._debugID && ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID);
}
},
performUpdateIfNecessary: function(internalInstance, transaction, updateBatchNumber) {
if (internalInstance._updateBatchNumber !== updateBatchNumber) return void warning(null == internalInstance._updateBatchNumber || internalInstance._updateBatchNumber === updateBatchNumber + 1, "performUpdateIfNecessary: Unexpected batch number (current %s, " + "pending %s)", updateBatchNumber, internalInstance._updateBatchNumber);
0 !== internalInstance._debugID && ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, internalInstance._currentElement),
internalInstance.performUpdateIfNecessary(transaction), 0 !== internalInstance._debugID && ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID);
}
}, ReactReconciler_1 = ReactReconciler, ReactInstanceMap = {
remove: function(key) {
key._reactInternalInstance = void 0;
},
get: function(key) {
return key._reactInternalInstance;
},
has: function(key) {
return void 0 !== key._reactInternalInstance;
},
set: function(key, value) {
key._reactInternalInstance = value;
}
}, ReactInstanceMap_1 = ReactInstanceMap, OBSERVED_ERROR = {}, TransactionImpl = {
reinitializeTransaction: function() {
this.transactionWrappers = this.getTransactionWrappers(), this.wrapperInitData ? this.wrapperInitData.length = 0 : this.wrapperInitData = [],
this._isInTransaction = !1;
},
_isInTransaction: !1,
getTransactionWrappers: null,
isInTransaction: function() {
return !!this._isInTransaction;
},
perform: function(method, scope, a, b, c, d, e, f) {
invariant(!this.isInTransaction(), "Transaction.perform(...): Cannot initialize a transaction when there " + "is already an outstanding transaction.");
var errorThrown, ret;
try {
this._isInTransaction = !0, errorThrown = !0, this.initializeAll(0), ret = method.call(scope, a, b, c, d, e, f),
errorThrown = !1;
} finally {
try {
if (errorThrown) try {
this.closeAll(0);
} catch (err) {} else this.closeAll(0);
} finally {
this._isInTransaction = !1;
}
}
return ret;
},
initializeAll: function(startIndex) {
for (var transactionWrappers = this.transactionWrappers, i = startIndex; i < transactionWrappers.length; i++) {
var wrapper = transactionWrappers[i];
try {
this.wrapperInitData[i] = OBSERVED_ERROR, this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null;
} finally {
if (this.wrapperInitData[i] === OBSERVED_ERROR) try {
this.initializeAll(i + 1);
} catch (err) {}
}
}
},
closeAll: function(startIndex) {
invariant(this.isInTransaction(), "Transaction.closeAll(): Cannot close transaction when none are open.");
for (var transactionWrappers = this.transactionWrappers, i = startIndex; i < transactionWrappers.length; i++) {
var errorThrown, wrapper = transactionWrappers[i], initData = this.wrapperInitData[i];
try {
errorThrown = !0, initData !== OBSERVED_ERROR && wrapper.close && wrapper.close.call(this, initData),
errorThrown = !1;
} finally {
if (errorThrown) try {
this.closeAll(i + 1);
} catch (e) {}
}
}
this.wrapperInitData.length = 0;
}
}, Transaction = TransactionImpl, dirtyComponents = [], updateBatchNumber = 0, batchingStrategy = null;
function ensureInjected() {
invariant(ReactUpdates.ReactReconcileTransaction && batchingStrategy, "ReactUpdates: must inject a reconcile transaction class and batching " + "strategy");
}
var NESTED_UPDATES = {
initialize: function() {
this.dirtyComponentsLength = dirtyComponents.length;
},
close: function() {
this.dirtyComponentsLength !== dirtyComponents.length ? (dirtyComponents.splice(0, this.dirtyComponentsLength),
flushBatchedUpdates()) : dirtyComponents.length = 0;
}
}, TRANSACTION_WRAPPERS = [ NESTED_UPDATES ];
function ReactUpdatesFlushTransaction() {
this.reinitializeTransaction(), this.dirtyComponentsLength = null, this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled(!0);
}
Object.assign(ReactUpdatesFlushTransaction.prototype, Transaction, {
getTransactionWrappers: function() {
return TRANSACTION_WRAPPERS;
},
destructor: function() {
this.dirtyComponentsLength = null, ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction),
this.reconcileTransaction = null;
},
perform: function(method, scope, a) {
return Transaction.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a);
}
}), PooledClass_1.addPoolingTo(ReactUpdatesFlushTransaction);
function batchedUpdates$1(callback, a, b, c, d, e) {
return ensureInjected(), batchingStrategy.batchedUpdates(callback, a, b, c, d, e);
}
function mountOrderComparator(c1, c2) {
return c1._mountOrder - c2._mountOrder;
}
function runBatchedUpdates(transaction) {
var len = transaction.dirtyComponentsLength;
invariant(len === dirtyComponents.length, "Expected flush transaction's stored dirty-components length (%s) to " + "match dirty-components array length (%s).", len, dirtyComponents.length),
dirtyComponents.sort(mountOrderComparator), updateBatchNumber++;
for (var i = 0; i < len; i++) {
var component = dirtyComponents[i];
ReactReconciler_1.performUpdateIfNecessary(component, transaction.reconcileTransaction, updateBatchNumber);
}
}
var flushBatchedUpdates = function() {
for (;dirtyComponents.length; ) {
var transaction = ReactUpdatesFlushTransaction.getPooled();
transaction.perform(runBatchedUpdates, null, transaction), ReactUpdatesFlushTransaction.release(transaction);
}
};
function enqueueUpdate$1(component) {
if (ensureInjected(), !batchingStrategy.isBatchingUpdates) return void batchingStrategy.batchedUpdates(enqueueUpdate$1, component);
dirtyComponents.push(component), null == component._updateBatchNumber && (component._updateBatchNumber = updateBatchNumber + 1);
}
var ReactUpdatesInjection = {
injectReconcileTransaction: function(ReconcileTransaction) {
invariant(ReconcileTransaction, "ReactUpdates: must provide a reconcile transaction class"),
ReactUpdates.ReactReconcileTransaction = ReconcileTransaction;
},
injectBatchingStrategy: function(_batchingStrategy) {
invariant(_batchingStrategy, "ReactUpdates: must provide a batching strategy"),
invariant("function" == typeof _batchingStrategy.batchedUpdates, "ReactUpdates: must provide a batchedUpdates() function"),
invariant("boolean" == typeof _batchingStrategy.isBatchingUpdates, "ReactUpdates: must provide an isBatchingUpdates boolean attribute"),
batchingStrategy = _batchingStrategy;
},
getBatchingStrategy: function() {
return batchingStrategy;
}
}, ReactUpdates = {
ReactReconcileTransaction: null,
batchedUpdates: batchedUpdates$1,
enqueueUpdate: enqueueUpdate$1,
flushBatchedUpdates: flushBatchedUpdates,
injection: ReactUpdatesInjection
}, ReactUpdates_1 = ReactUpdates, ReactCurrentOwner = ReactGlobalSharedState_1.ReactCurrentOwner, warning$3 = warning, warnOnInvalidCallback = function(callback, callerName) {
warning$3(null === callback || "function" == typeof callback, "%s(...): Expected the last optional `callback` argument to be a " + "function. Instead received: %s.", callerName, "" + callback);
};
function enqueueUpdate(internalInstance) {
ReactUpdates_1.enqueueUpdate(internalInstance);
}
function getInternalInstanceReadyForUpdate(publicInstance, callerName) {
var internalInstance = ReactInstanceMap_1.get(publicInstance);
if (!internalInstance) {
var ctor = publicInstance.constructor;
return warning$3(!1, "Can only update a mounted or mounting component. This usually means " + "you called setState, replaceState, or forceUpdate on an unmounted " + "component. This is a no-op.\n\nPlease check the code for the " + "%s component.", ctor && (ctor.displayName || ctor.name) || "ReactClass"),
null;
}
return warning$3(null == ReactCurrentOwner.current, "Cannot update during an existing state transition (such as within " + "`render` or another component's constructor). Render methods should " + "be a pure function of props and state; constructor side-effects are " + "an anti-pattern, but can be moved to `componentWillMount`."),
internalInstance;
}
var ReactUpdateQueue = {
isMounted: function(publicInstance) {
var owner = ReactCurrentOwner.current;
null !== owner && (warning$3(owner._warnedAboutRefsInRender, "%s is accessing isMounted inside its render() function. " + "render() should be a pure function of props and state. It should " + "never access something that requires stale data from the previous " + "render, such as refs. Move this logic to componentDidMount and " + "componentDidUpdate instead.", owner.getName() || "A component"),
owner._warnedAboutRefsInRender = !0);
var internalInstance = ReactInstanceMap_1.get(publicInstance);
return !!internalInstance && !!internalInstance._renderedComponent;
},
enqueueCallbackInternal: function(internalInstance, callback) {
internalInstance._pendingCallbacks ? internalInstance._pendingCallbacks.push(callback) : internalInstance._pendingCallbacks = [ callback ],
enqueueUpdate(internalInstance);
},
enqueueForceUpdate: function(publicInstance, callback, callerName) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance);
internalInstance && (callback = void 0 === callback ? null : callback, null !== callback && (warnOnInvalidCallback(callback, callerName),
internalInstance._pendingCallbacks ? internalInstance._pendingCallbacks.push(callback) : internalInstance._pendingCallbacks = [ callback ]),
internalInstance._pendingForceUpdate = !0, enqueueUpdate(internalInstance));
},
enqueueReplaceState: function(publicInstance, completeState, callback, callerName) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance);
internalInstance && (internalInstance._pendingStateQueue = [ completeState ], internalInstance._pendingReplaceState = !0,
callback = void 0 === callback ? null : callback, null !== callback && (warnOnInvalidCallback(callback, callerName),
internalInstance._pendingCallbacks ? internalInstance._pendingCallbacks.push(callback) : internalInstance._pendingCallbacks = [ callback ]),
enqueueUpdate(internalInstance));
},
enqueueSetState: function(publicInstance, partialState, callback, callerName) {
ReactInstrumentation.debugTool.onSetState(), warning$3(null != partialState, "setState(...): You passed an undefined or null state object; " + "instead, use forceUpdate().");
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance);
if (internalInstance) {
(internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = [])).push(partialState),
callback = void 0 === callback ? null : callback, null !== callback && (warnOnInvalidCallback(callback, callerName),
internalInstance._pendingCallbacks ? internalInstance._pendingCallbacks.push(callback) : internalInstance._pendingCallbacks = [ callback ]),
enqueueUpdate(internalInstance);
}
},
enqueueElementInternal: function(internalInstance, nextElement, nextContext) {
internalInstance._pendingElement = nextElement, internalInstance._context = nextContext,
enqueueUpdate(internalInstance);
}
}, ReactUpdateQueue_1 = ReactUpdateQueue, injected = !1, ReactComponentEnvironment = {
replaceNodeWithMarkup: null,
processChildrenUpdates: null,
injection: {
injectEnvironment: function(environment) {
invariant(!injected, "ReactCompositeComponent: injectEnvironment() can only be called once."),
ReactComponentEnvironment.replaceNodeWithMarkup = environment.replaceNodeWithMarkup,
ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates,
injected = !0;
}
}
}, ReactComponentEnvironment_1 = ReactComponentEnvironment, ReactNodeTypes = {
HOST: 0,
COMPOSITE: 1,
EMPTY: 2,
getType: function(node) {
return null === node || !1 === node ? ReactNodeTypes.EMPTY : React.isValidElement(node) ? "function" == typeof node.type ? ReactNodeTypes.COMPOSITE : ReactNodeTypes.HOST : void invariant(!1, "Unexpected node: %s", node);
}
}, ReactNodeTypes_1 = ReactNodeTypes;
function shouldUpdateReactComponent(prevElement, nextElement) {
var prevEmpty = null === prevElement || !1 === prevElement, nextEmpty = null === nextElement || !1 === nextElement;
if (prevEmpty || nextEmpty) return prevEmpty === nextEmpty;
var prevType = typeof prevElement, nextType = typeof nextElement;
return "string" === prevType || "number" === prevType ? "string" === nextType || "number" === nextType : "object" === nextType && prevElement.type === nextElement.type && prevElement.key === nextElement.key;
}
var shouldUpdateReactComponent_1 = shouldUpdateReactComponent, ReactCurrentOwner$1 = ReactGlobalSharedState_1.ReactCurrentOwner, _require2 = ReactGlobalSharedState_1, ReactDebugCurrentFrame = _require2.ReactDebugCurrentFrame, warningAboutMissingGetChildContext = {};
function StatelessComponent(Component) {}
StatelessComponent.prototype.render = function() {
return (0, ReactInstanceMap_1.get(this)._currentElement.type)(this.props, this.context, this.updater);
};
function shouldConstruct(Component) {
return !(!Component.prototype || !Component.prototype.isReactComponent);
}
function isPureComponent(Component) {
return !(!Component.prototype || !Component.prototype.isPureReactComponent);
}
function measureLifeCyclePerf(fn, debugID, timerType) {
if (0 === debugID) return fn();
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(debugID, timerType);
try {
return fn();
} finally {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(debugID, timerType);
}
}
var nextMountID = 1, ReactCompositeComponent = {
construct: function(element) {
this._currentElement = element, this._rootNodeID = 0, this._compositeType = null,
this._instance = null, this._hostParent = null, this._hostContainerInfo = null,
this._updateBatchNumber = null, this._pendingElement = null, this._pendingStateQueue = null,
this._pendingReplaceState = !1, this._pendingForceUpdate = !1, this._renderedNodeType = null,
this._renderedComponent = null, this._context = null, this._mountOrder = 0, this._topLevelWrapper = null,
this._pendingCallbacks = null, this._calledComponentWillUnmount = !1, this._warnedAboutRefsInRender = !1;
},
mountComponent: function(transaction, hostParent, hostContainerInfo, context) {
var _this = this;
this._context = context, this._mountOrder = nextMountID++, this._hostParent = hostParent,
this._hostContainerInfo = hostContainerInfo;
var renderedElement, publicProps = this._currentElement.props, publicContext = this._processContext(context), Component = this._currentElement.type, updateQueue = transaction.getUpdateQueue(), doConstruct = shouldConstruct(Component), inst = this._constructComponent(doConstruct, publicProps, publicContext, updateQueue);
doConstruct || null != inst && null != inst.render ? isPureComponent(Component) ? this._compositeType = ReactCompositeComponentTypes$1.PureClass : this._compositeType = ReactCompositeComponentTypes$1.ImpureClass : (renderedElement = inst,
warning(!Component.childContextTypes, "%s(...): childContextTypes cannot be defined on a functional component.", Component.displayName || Component.name || "Component"),
invariant(null === inst || !1 === inst || React.isValidElement(inst), "%s(...): A valid React element (or null) must be returned. You may have " + "returned undefined, an array or some other invalid object.", Component.displayName || Component.name || "Component"),
inst = new StatelessComponent(Component), this._compositeType = ReactCompositeComponentTypes$1.StatelessFunctional),
null == inst.render && warning(!1, "%s(...): No `render` method found on the returned component " + "instance: you may have forgotten to define `render`.", Component.displayName || Component.name || "Component");
var propsMutated = inst.props !== publicProps, componentName = Component.displayName || Component.name || "Component";
warning(void 0 === inst.props || !propsMutated, "%s(...): When calling super() in `%s`, make sure to pass " + "up the same props that your component's constructor was passed.", componentName, componentName),
inst.props = publicProps, inst.context = publicContext, inst.refs = emptyObject,
inst.updater = updateQueue, this._instance = inst, ReactInstanceMap_1.set(inst, this),
warning(!inst.getInitialState || inst.getInitialState.isReactClassApproved || inst.state, "getInitialState was defined on %s, a plain JavaScript class. " + "This is only supported for classes created using React.createClass. " + "Did you mean to define a state property instead?", this.getName() || "a component"),
warning(!inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved, "getDefaultProps was defined on %s, a plain JavaScript class. " + "This is only supported for classes created using React.createClass. " + "Use a static property to define defaultProps instead.", this.getName() || "a component"),
warning(!inst.propTypes, "propTypes was defined as an instance property on %s. Use a static " + "property to define propTypes instead.", this.getName() || "a component"),
warning(!inst.contextTypes, "contextTypes was defined as an instance property on %s. Use a " + "static property to define contextTypes instead.", this.getName() || "a component"),
warning("function" != typeof inst.componentShouldUpdate, "%s has a method called " + "componentShouldUpdate(). Did you mean shouldComponentUpdate()? " + "The name is phrased as a question because the function is " + "expected to return a value.", this.getName() || "A component"),
warning("function" != typeof inst.componentDidUnmount, "%s has a method called " + "componentDidUnmount(). But there is no such lifecycle method. " + "Did you mean componentWillUnmount()?", this.getName() || "A component"),
warning("function" != typeof inst.componentWillRecieveProps, "%s has a method called " + "componentWillRecieveProps(). Did you mean componentWillReceiveProps()?", this.getName() || "A component"),
isPureComponent(Component) && void 0 !== inst.shouldComponentUpdate && warning(!1, "%s has a method called shouldComponentUpdate(). " + "shouldComponentUpdate should not be used when extending React.PureComponent. " + "Please extend React.Component if shouldComponentUpdate is used.", this.getName() || "A pure component"),
warning(!inst.defaultProps, "Setting defaultProps as an instance property on %s is not supported and will be ignored." + " Instead, define defaultProps as a static property on %s.", this.getName() || "a component", this.getName() || "a component");
var initialState = inst.state;
void 0 === initialState && (inst.state = initialState = null), invariant("object" == typeof initialState && !Array.isArray(initialState), "%s.state: must be set to an object or null", this.getName() || "ReactCompositeComponent"),
this._pendingStateQueue = null, this._pendingReplaceState = !1, this._pendingForceUpdate = !1,
inst.componentWillMount && (measureLifeCyclePerf(function() {
return inst.componentWillMount();
}, this._debugID, "componentWillMount"), this._pendingStateQueue && (inst.state = this._processPendingState(inst.props, inst.context)));
var markup;
markup = inst.unstable_handleError ? this.performInitialMountWithErrorHandling(renderedElement, hostParent, hostContainerInfo, transaction, context) : this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context),
inst.componentDidMount && transaction.getReactMountReady().enqueue(function() {
measureLifeCyclePerf(function() {
return inst.componentDidMount();
}, _this._debugID, "componentDidMount");
});
var callbacks = this._pendingCallbacks;
if (callbacks) {
this._pendingCallbacks = null;
for (var i = 0; i < callbacks.length; i++) transaction.getReactMountReady().enqueue(callbacks[i], inst);
}
return markup;
},
_constructComponent: function(doConstruct, publicProps, publicContext, updateQueue) {
ReactCurrentOwner$1.current = this;
try {
return this._constructComponentWithoutOwner(doConstruct, publicProps, publicContext, updateQueue);
} finally {
ReactCurrentOwner$1.current = null;
}
},
_constructComponentWithoutOwner: function(doConstruct, publicProps, publicContext, updateQueue) {
var Component = this._currentElement.type;
return doConstruct ? measureLifeCyclePerf(function() {
return new Component(publicProps, publicContext, updateQueue);
}, this._debugID, "ctor") : measureLifeCyclePerf(function() {
return Component(publicProps, publicContext, updateQueue);
}, this._debugID, "render");
},
performInitialMountWithErrorHandling: function(renderedElement, hostParent, hostContainerInfo, transaction, context) {
var markup, checkpoint = transaction.checkpoint();
try {
markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context);
} catch (e) {
transaction.rollback(checkpoint), this._instance.unstable_handleError(e), this._pendingStateQueue && (this._instance.state = this._processPendingState(this._instance.props, this._instance.context)),
checkpoint = transaction.checkpoint(), this._renderedComponent.unmountComponent(!0, !0),
transaction.rollback(checkpoint), markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context);
}
return markup;
},
performInitialMount: function(renderedElement, hostParent, hostContainerInfo, transaction, context) {
void 0 === renderedElement && (renderedElement = this._renderValidatedComponent());
var nodeType = ReactNodeTypes_1.getType(renderedElement);
this._renderedNodeType = nodeType;
var child = this._instantiateReactComponent(renderedElement, nodeType !== ReactNodeTypes_1.EMPTY);
this._renderedComponent = child;
var debugID = 0;
debugID = this._debugID;
var markup = ReactReconciler_1.mountComponent(child, transaction, hostParent, hostContainerInfo, this._processChildContext(context), debugID);
if (0 !== debugID) {
var childDebugIDs = 0 !== child._debugID ? [ child._debugID ] : [];
ReactInstrumentation.debugTool.onSetChildren(debugID, childDebugIDs);
}
return markup;
},
getHostNode: function() {
return ReactReconciler_1.getHostNode(this._renderedComponent);
},
unmountComponent: function(safely, skipLifecycle) {
if (this._renderedComponent) {
var inst = this._instance;
if (inst.componentWillUnmount && !inst._calledComponentWillUnmount) if (inst._calledComponentWillUnmount = !0,
safely) {
if (!skipLifecycle) {
var name = this.getName() + ".componentWillUnmount()";
ReactErrorUtils_1.invokeGuardedCallbackAndCatchFirstError(name, inst.componentWillUnmount, inst);
}
} else measureLifeCyclePerf(function() {
return inst.componentWillUnmount();
}, this._debugID, "componentWillUnmount");
this._renderedComponent && (ReactReconciler_1.unmountComponent(this._renderedComponent, safely, skipLifecycle),
this._renderedNodeType = null, this._renderedComponent = null, this._instance = null),
this._pendingStateQueue = null, this._pendingReplaceState = !1, this._pendingForceUpdate = !1,
this._pendingCallbacks = null, this._pendingElement = null, this._context = null,
this._rootNodeID = 0, this._topLevelWrapper = null, ReactInstanceMap_1.remove(inst);
}
},
_maskContext: function(context) {
var Component = this._currentElement.type, contextTypes = Component.contextTypes;
if (!contextTypes) return emptyObject;
var maskedContext = {};
for (var contextName in contextTypes) maskedContext[contextName] = context[contextName];
return maskedContext;
},
_processContext: function(context) {
var maskedContext = this._maskContext(context), Component = this._currentElement.type;
return Component.contextTypes && this._checkContextTypes(Component.contextTypes, maskedContext, "context"),
maskedContext;
},
_processChildContext: function(currentContext) {
var childContext, Component = this._currentElement.type, inst = this._instance;
if ("function" == typeof inst.getChildContext) {
ReactInstrumentation.debugTool.onBeginProcessingChildContext();
try {
childContext = inst.getChildContext();
} finally {
ReactInstrumentation.debugTool.onEndProcessingChildContext();
}
invariant("object" == typeof Component.childContextTypes, "%s.getChildContext(): childContextTypes must be defined in order to " + "use getChildContext().", this.getName() || "ReactCompositeComponent"),
this._checkContextTypes(Component.childContextTypes, childContext, "child context");
for (var name in childContext) invariant(name in Component.childContextTypes, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || "ReactCompositeComponent", name);
return Object.assign({}, currentContext, childContext);
}
var componentName = this.getName();
return warningAboutMissingGetChildContext[componentName] || (warningAboutMissingGetChildContext[componentName] = !0,
warning(!Component.childContextTypes, "%s.childContextTypes is specified but there is no getChildContext() method " + "on the instance. You can either define getChildContext() on %s or remove " + "childContextTypes from it.", componentName, componentName)),
currentContext;
},
_checkContextTypes: function(typeSpecs, values, location) {
ReactDebugCurrentFrame.current = this._debugID, checkPropTypes(typeSpecs, values, location, this.getName(), ReactDebugCurrentFrame.getStackAddendum),
ReactDebugCurrentFrame.current = null;
},
receiveComponent: function(nextElement, transaction, nextContext) {
var prevElement = this._currentElement, prevContext = this._context;
this._pendingElement = null, this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext);
},
performUpdateIfNecessary: function(transaction) {
if (null != this._pendingElement) ReactReconciler_1.receiveComponent(this, this._pendingElement, transaction, this._context); else if (null !== this._pendingStateQueue || this._pendingForceUpdate) this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context); else {
var callbacks = this._pendingCallbacks;
if (this._pendingCallbacks = null, callbacks) for (var j = 0; j < callbacks.length; j++) transaction.getReactMountReady().enqueue(callbacks[j], this.getPublicInstance());
this._updateBatchNumber = null;
}
},
updateComponent: function(transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) {
var inst = this._instance;
invariant(null != inst, "Attempted to update component `%s` that has already been unmounted " + "(or failed to mount).", this.getName() || "ReactCompositeComponent");
var nextContext, willReceive = !1;
this._context === nextUnmaskedContext ? nextContext = inst.context : (nextContext = this._processContext(nextUnmaskedContext),
willReceive = !0);
var prevProps = prevParentElement.props, nextProps = nextParentElement.props;
if (prevParentElement !== nextParentElement && (willReceive = !0), willReceive && inst.componentWillReceiveProps) {
var beforeState = inst.state;
measureLifeCyclePerf(function() {
return inst.componentWillReceiveProps(nextProps, nextContext);
}, this._debugID, "componentWillReceiveProps");
var afterState = inst.state;
beforeState !== afterState && (inst.state = beforeState, inst.updater.enqueueReplaceState(inst, afterState),
warning(!1, "%s.componentWillReceiveProps(): Assigning directly to " + "this.state is deprecated (except inside a component's " + "constructor). Use setState instead.", this.getName() || "ReactCompositeComponent"));
}
var callbacks = this._pendingCallbacks;
this._pendingCallbacks = null;
var nextState = this._processPendingState(nextProps, nextContext), shouldUpdate = !0;
if (!this._pendingForceUpdate) {
var prevState = inst.state;
shouldUpdate = willReceive || nextState !== prevState, inst.shouldComponentUpdate ? shouldUpdate = measureLifeCyclePerf(function() {
return inst.shouldComponentUpdate(nextProps, nextState, nextContext);
}, this._debugID, "shouldComponentUpdate") : this._compositeType === ReactCompositeComponentTypes$1.PureClass && (shouldUpdate = !shallowEqual(prevProps, nextProps) || !shallowEqual(inst.state, nextState));
}
if (warning(void 0 !== shouldUpdate, "%s.shouldComponentUpdate(): Returned undefined instead of a " + "boolean value. Make sure to return true or false.", this.getName() || "ReactCompositeComponent"),
this._updateBatchNumber = null, shouldUpdate ? (this._pendingForceUpdate = !1, this._performComponentUpdate(nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext)) : (this._currentElement = nextParentElement,
this._context = nextUnmaskedContext, inst.props = nextProps, inst.state = nextState,
inst.context = nextContext), callbacks) for (var j = 0; j < callbacks.length; j++) transaction.getReactMountReady().enqueue(callbacks[j], this.getPublicInstance());
},
_processPendingState: function(props, context) {
var inst = this._instance, queue = this._pendingStateQueue, replace = this._pendingReplaceState;
if (this._pendingReplaceState = !1, this._pendingStateQueue = null, !queue) return inst.state;
if (replace && 1 === queue.length) return queue[0];
for (var nextState = replace ? queue[0] : inst.state, dontMutate = !0, i = replace ? 1 : 0; i < queue.length; i++) {
var partial = queue[i], partialState = "function" == typeof partial ? partial.call(inst, nextState, props, context) : partial;
partialState && (dontMutate ? (dontMutate = !1, nextState = Object.assign({}, nextState, partialState)) : Object.assign(nextState, partialState));
}
return nextState;
},
_performComponentUpdate: function(nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) {
var prevProps, prevState, _this2 = this, inst = this._instance, hasComponentDidUpdate = !!inst.componentDidUpdate;
hasComponentDidUpdate && (prevProps = inst.props, prevState = inst.state), inst.componentWillUpdate && measureLifeCyclePerf(function() {
return inst.componentWillUpdate(nextProps, nextState, nextContext);
}, this._debugID, "componentWillUpdate"), this._currentElement = nextElement, this._context = unmaskedContext,
inst.props = nextProps, inst.state = nextState, inst.context = nextContext, inst.unstable_handleError ? this._updateRenderedComponentWithErrorHandling(transaction, unmaskedContext) : this._updateRenderedComponent(transaction, unmaskedContext),
hasComponentDidUpdate && transaction.getReactMountReady().enqueue(function() {
measureLifeCyclePerf(inst.componentDidUpdate.bind(inst, prevProps, prevState), _this2._debugID, "componentDidUpdate");
});
},
_updateRenderedComponentWithErrorHandling: function(transaction, context) {
var checkpoint = transaction.checkpoint();
try {
this._updateRenderedComponent(transaction, context);
} catch (e) {
transaction.rollback(checkpoint), this._instance.unstable_handleError(e), this._pendingStateQueue && (this._instance.state = this._processPendingState(this._instance.props, this._instance.context)),
checkpoint = transaction.checkpoint(), this._updateRenderedComponentWithNextElement(transaction, context, null, !0),
this._updateRenderedComponent(transaction, context);
}
},
_updateRenderedComponent: function(transaction, context) {
var nextRenderedElement = this._renderValidatedComponent();
this._updateRenderedComponentWithNextElement(transaction, context, nextRenderedElement, !1);
},
_updateRenderedComponentWithNextElement: function(transaction, context, nextRenderedElement, safely) {
var prevComponentInstance = this._renderedComponent, prevRenderedElement = prevComponentInstance._currentElement, debugID = 0;
if (debugID = this._debugID, shouldUpdateReactComponent_1(prevRenderedElement, nextRenderedElement)) ReactReconciler_1.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context)); else {
var oldHostNode = ReactReconciler_1.getHostNode(prevComponentInstance), nodeType = ReactNodeTypes_1.getType(nextRenderedElement);
this._renderedNodeType = nodeType;
var child = this._instantiateReactComponent(nextRenderedElement, nodeType !== ReactNodeTypes_1.EMPTY);
this._renderedComponent = child;
var nextMarkup = ReactReconciler_1.mountComponent(child, transaction, this._hostParent, this._hostContainerInfo, this._processChildContext(context), debugID);
if (ReactReconciler_1.unmountComponent(prevComponentInstance, safely, !1), 0 !== debugID) {
var childDebugIDs = 0 !== child._debugID ? [ child._debugID ] : [];
ReactInstrumentation.debugTool.onSetChildren(debugID, childDebugIDs);
}
this._replaceNodeWithMarkup(oldHostNode, nextMarkup, prevComponentInstance);
}
},
_replaceNodeWithMarkup: function(oldHostNode, nextMarkup, prevInstance) {
ReactComponentEnvironment_1.replaceNodeWithMarkup(oldHostNode, nextMarkup, prevInstance);
},
_renderValidatedComponentWithoutOwnerOrContext: function() {
var renderedElement, inst = this._instance;
return renderedElement = measureLifeCyclePerf(function() {
return inst.render();
}, this._debugID, "render"), void 0 === renderedElement && inst.render._isMockFunction && (renderedElement = null),
renderedElement;
},
_renderValidatedComponent: function() {
var renderedElement;
if (0 && this._compositeType === ReactCompositeComponentTypes$1.StatelessFunctional) renderedElement = this._renderValidatedComponentWithoutOwnerOrContext(); else {
ReactCurrentOwner$1.current = this;
try {
renderedElement = this._renderValidatedComponentWithoutOwnerOrContext();
} finally {
ReactCurrentOwner$1.current = null;
}
}
return invariant(null === renderedElement || !1 === renderedElement || React.isValidElement(renderedElement), "%s.render(): A valid React element (or null) must be returned. You may have " + "returned undefined, an array or some other invalid object.", this.getName() || "ReactCompositeComponent"),
renderedElement;
},
attachRef: function(ref, component) {
var inst = this.getPublicInstance();
invariant(null != inst, "Stateless function components cannot have refs.");
var publicComponentInstance = component.getPublicInstance();
(inst.refs === emptyObject ? inst.refs = {} : inst.refs)[ref] = publicComponentInstance;
},
detachRef: function(ref) {
delete this.getPublicInstance().refs[ref];
},
getName: function() {
var type = this._currentElement.type, constructor = this._instance && this._instance.constructor;
return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null;
},
getPublicInstance: function() {
var inst = this._instance;
return this._compositeType === ReactCompositeComponentTypes$1.StatelessFunctional ? null : inst;
},
_instantiateReactComponent: null
}, ReactCompositeComponent_1 = ReactCompositeComponent, emptyComponentFactory, ReactEmptyComponentInjection = {
injectEmptyComponentFactory: function(factory) {
emptyComponentFactory = factory;
}
}, ReactEmptyComponent = {
create: function(instantiate) {
return emptyComponentFactory(instantiate);
}
};
ReactEmptyComponent.injection = ReactEmptyComponentInjection;
var ReactEmptyComponent_1 = ReactEmptyComponent, genericComponentClass = null, textComponentClass = null, ReactHostComponentInjection = {
injectGenericComponentClass: function(componentClass) {
genericComponentClass = componentClass;
},
injectTextComponentClass: function(componentClass) {
textComponentClass = componentClass;
}
};
function createInternalComponent(element) {
return invariant(genericComponentClass, "There is no registered component for the tag %s", element.type),
new genericComponentClass(element);
}
function createInstanceForText(text) {
return new textComponentClass(text);
}
function isTextComponent(component) {
return component instanceof textComponentClass;
}
var ReactHostComponent = {
createInternalComponent: createInternalComponent,
createInstanceForText: createInstanceForText,
isTextComponent: isTextComponent,
injection: ReactHostComponentInjection
}, ReactHostComponent_1 = ReactHostComponent, nextDebugID = 1, ReactCompositeComponentWrapper = function(element) {
this.construct(element);
};
function getDeclarationErrorAddendum(owner) {
if (owner) {
var name = owner.getName();
if (name) return "\n\nCheck the render method of `" + name + "`.";
}
return "";
}
function isInternalComponentType(type) {
return "function" == typeof type && void 0 !== type.prototype && "function" == typeof type.prototype.mountComponent && "function" == typeof type.prototype.receiveComponent;
}
function instantiateReactComponent(node, shouldHaveDebugID) {
var instance;
if (null === node || !1 === node) instance = ReactEmptyComponent_1.create(instantiateReactComponent); else if ("object" == typeof node) {
var element = node, type = element.type;
if ("function" != typeof type && "string" != typeof type) {
var info = "";
(void 0 === type || "object" == typeof type && null !== type && 0 === Object.keys(type).length) && (info += " You likely forgot to export your component from the file " + "it's defined in."),
info += getDeclarationErrorAddendum(element._owner), invariant(!1, "Element type is invalid: expected a string (for built-in components) " + "or a class/function (for composite components) but got: %s.%s", null == type ? type : typeof type, info);
}
"string" == typeof element.type ? instance = ReactHostComponent_1.createInternalComponent(element) : isInternalComponentType(element.type) ? (instance = new element.type(element),
instance.getHostNode || (instance.getHostNode = instance.getNativeNode)) : instance = new ReactCompositeComponentWrapper(element);
} else "string" == typeof node || "number" == typeof node ? instance = ReactHostComponent_1.createInstanceForText(node) : invariant(!1, "Encountered invalid React node of type %s", typeof node);
return warning("function" == typeof instance.mountComponent && "function" == typeof instance.receiveComponent && "function" == typeof instance.getHostNode && "function" == typeof instance.unmountComponent, "Only React Components can be mounted."),
instance._mountIndex = 0, instance._mountImage = null, instance._debugID = shouldHaveDebugID ? nextDebugID++ : 0,
Object.preventExtensions && Object.preventExtensions(instance), instance;
}
Object.assign(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent_1, {
_instantiateReactComponent: instantiateReactComponent
});
var instantiateReactComponent_1 = instantiateReactComponent, DevOnlyStubShim = null, ReactNativeFeatureFlags = require("ReactNativeFeatureFlags"), ReactCurrentOwner$2 = ReactGlobalSharedState_1.ReactCurrentOwner, injectedFindNode = ReactNativeFeatureFlags.useFiber ? function(fiber) {
return DevOnlyStubShim.findHostInstance(fiber);
} : function(instance) {
return instance;
};
function findNodeHandle(componentOrHandle) {
var owner = ReactCurrentOwner$2.current;
if (null !== owner && (warning(owner._warnedAboutRefsInRender, "%s is accessing findNodeHandle inside its render(). " + "render() should be a pure function of props and state. It should " + "never access something that requires stale data from the previous " + "render, such as refs. Move this logic to componentDidMount and " + "componentDidUpdate instead.", owner.getName() || "A component"),
owner._warnedAboutRefsInRender = !0), null == componentOrHandle) return null;
if ("number" == typeof componentOrHandle) return componentOrHandle;
var component = componentOrHandle, internalInstance = ReactInstanceMap_1.get(component);
return internalInstance ? injectedFindNode(internalInstance) : component || (invariant("object" == typeof component && ("_rootNodeID" in component || "_nativeTag" in component) || null != component.render && "function" == typeof component.render, "findNodeHandle(...): Argument is not a component " + "(type: %s, keys: %s)", typeof component, Object.keys(component)),
void invariant(!1, "findNodeHandle(...): Unable to find node handle for unmounted " + "component."));
}
var findNodeHandle_1 = findNodeHandle, TopLevelWrapper = function() {};
TopLevelWrapper.prototype.isReactComponent = {}, TopLevelWrapper.displayName = "TopLevelWrapper",
TopLevelWrapper.prototype.render = function() {
return this.props.child;
}, TopLevelWrapper.isReactTopLevelWrapper = !0;
function mountComponentIntoNode(componentInstance, containerTag, transaction) {
var markup = ReactReconciler_1.mountComponent(componentInstance, transaction, null, ReactNativeContainerInfo_1(containerTag), emptyObject, 0);
componentInstance._renderedComponent._topLevelWrapper = componentInstance, ReactNativeMount._mountImageIntoNode(markup, containerTag);
}
function batchedMountComponentIntoNode(componentInstance, containerTag) {
var transaction = ReactUpdates_1.ReactReconcileTransaction.getPooled();
transaction.perform(mountComponentIntoNode, null, componentInstance, containerTag, transaction),
ReactUpdates_1.ReactReconcileTransaction.release(transaction);
}
var ReactNativeMount = {
_instancesByContainerID: {},
findNodeHandle: findNodeHandle_1,
renderComponent: function(nextElement, containerTag, callback) {
var nextWrappedElement = React.createElement(TopLevelWrapper, {
child: nextElement
}), topRootNodeID = containerTag, prevComponent = ReactNativeMount._instancesByContainerID[topRootNodeID];
if (prevComponent) {
var prevWrappedElement = prevComponent._currentElement, prevElement = prevWrappedElement.props.child;
if (shouldUpdateReactComponent_1(prevElement, nextElement)) return ReactUpdateQueue_1.enqueueElementInternal(prevComponent, nextWrappedElement, emptyObject),
callback && ReactUpdateQueue_1.enqueueCallbackInternal(prevComponent, callback),
prevComponent;
ReactNativeMount.unmountComponentAtNode(containerTag);
}
if (!ReactNativeTagHandles_1.reactTagIsNativeTopRootID(containerTag)) return console.error("You cannot render into anything but a top root"),
null;
ReactNativeTagHandles_1.assertRootTag(containerTag);
var instance = instantiateReactComponent_1(nextWrappedElement, !1);
if (ReactNativeMount._instancesByContainerID[containerTag] = instance, callback) {
var nonNullCallback = callback;
instance._pendingCallbacks = [ function() {
nonNullCallback.call(instance._renderedComponent.getPublicInstance());
} ];
}
return ReactUpdates_1.batchedUpdates(batchedMountComponentIntoNode, instance, containerTag),
instance._renderedComponent.getPublicInstance();
},
_mountImageIntoNode: function(mountImage, containerID) {
var childTag = mountImage;
UIManager.setChildren(containerID, [ childTag ]);
},
unmountComponentAtNodeAndRemoveContainer: function(containerTag) {
ReactNativeMount.unmountComponentAtNode(containerTag), UIManager.removeRootView(containerTag);
},
unmountComponentAtNode: function(containerTag) {
if (!ReactNativeTagHandles_1.reactTagIsNativeTopRootID(containerTag)) return console.error("You cannot render into anything but a top root"),
!1;
var instance = ReactNativeMount._instancesByContainerID[containerTag];
return !!instance && (ReactInstrumentation.debugTool.onBeginFlush(), ReactNativeMount.unmountComponentFromNode(instance, containerTag),
delete ReactNativeMount._instancesByContainerID[containerTag], ReactInstrumentation.debugTool.onEndFlush(),
!0);
},
unmountComponentFromNode: function(instance, containerID) {
ReactReconciler_1.unmountComponent(instance), UIManager.removeSubviewsFromContainerWithID(containerID);
}
}, ReactNativeMount_1 = ReactNativeMount, RESET_BATCHED_UPDATES = {
initialize: emptyFunction,
close: function() {
ReactDefaultBatchingStrategy.isBatchingUpdates = !1;
}
}, FLUSH_BATCHED_UPDATES = {
initialize: emptyFunction,
close: ReactUpdates_1.flushBatchedUpdates.bind(ReactUpdates_1)
}, TRANSACTION_WRAPPERS$1 = [ FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES ];
function ReactDefaultBatchingStrategyTransaction() {
this.reinitializeTransaction();
}
Object.assign(ReactDefaultBatchingStrategyTransaction.prototype, Transaction, {
getTransactionWrappers: function() {
return TRANSACTION_WRAPPERS$1;
}
});
var transaction = new ReactDefaultBatchingStrategyTransaction(), ReactDefaultBatchingStrategy = {
isBatchingUpdates: !1,
batchedUpdates: function(callback, a, b, c, d, e) {
var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates;
return ReactDefaultBatchingStrategy.isBatchingUpdates = !0, alreadyBatchingUpdates ? callback(a, b, c, d, e) : transaction.perform(callback, null, a, b, c, d, e);
}
}, ReactDefaultBatchingStrategy_1 = ReactDefaultBatchingStrategy, dangerouslyProcessChildrenUpdates = function(inst, childrenUpdates) {
if (childrenUpdates.length) {
for (var moveFromIndices, moveToIndices, addChildTags, addAtIndices, removeAtIndices, containerTag = ReactNativeComponentTree_1.getNodeFromInstance(inst), i = 0; i < childrenUpdates.length; i++) {
var update = childrenUpdates[i];
if ("MOVE_EXISTING" === update.type) (moveFromIndices || (moveFromIndices = [])).push(update.fromIndex),
(moveToIndices || (moveToIndices = [])).push(update.toIndex); else if ("REMOVE_NODE" === update.type) (removeAtIndices || (removeAtIndices = [])).push(update.fromIndex); else if ("INSERT_MARKUP" === update.type) {
var mountImage = update.content, tag = mountImage;
(addAtIndices || (addAtIndices = [])).push(update.toIndex), (addChildTags || (addChildTags = [])).push(tag);
}
}
UIManager.manageChildren(containerTag, moveFromIndices, moveToIndices, addChildTags, addAtIndices, removeAtIndices);
}
}, ReactNativeDOMIDOperations = {
dangerouslyProcessChildrenUpdates: dangerouslyProcessChildrenUpdates,
dangerouslyReplaceNodeWithMarkupByID: function(id, mountImage) {
var oldTag = id;
UIManager.replaceExistingNonRootView(oldTag, mountImage);
}
}, ReactNativeDOMIDOperations_1 = ReactNativeDOMIDOperations;
function validateCallback(callback) {
invariant(!callback || "function" == typeof callback, "Invalid argument passed as callback. Expected a function. Instead " + "received: %s", callback);
}
var validateCallback_1 = validateCallback;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
var CallbackQueue = function() {
function CallbackQueue() {
_classCallCheck(this, CallbackQueue), this._callbacks = null, this._contexts = null;
}
return CallbackQueue.prototype.enqueue = function(callback, context) {
this._callbacks = this._callbacks || [], this._callbacks.push(callback), this._contexts = this._contexts || [],
this._contexts.push(context);
}, CallbackQueue.prototype.notifyAll = function() {
var callbacks = this._callbacks, contexts = this._contexts;
if (callbacks && contexts) {
invariant(callbacks.length === contexts.length, "Mismatched list of contexts in callback queue"),
this._callbacks = null, this._contexts = null;
for (var i = 0; i < callbacks.length; i++) validateCallback_1(callbacks[i]), callbacks[i].call(contexts[i]);
callbacks.length = 0, contexts.length = 0;
}
}, CallbackQueue.prototype.checkpoint = function() {
return this._callbacks ? this._callbacks.length : 0;
}, CallbackQueue.prototype.rollback = function(len) {
this._callbacks && this._contexts && (this._callbacks.length = len, this._contexts.length = len);
}, CallbackQueue.prototype.reset = function() {
this._callbacks = null, this._contexts = null;
}, CallbackQueue.prototype.destructor = function() {
this.reset();
}, CallbackQueue;
}(), CallbackQueue_1 = PooledClass_1.addPoolingTo(CallbackQueue), ON_DOM_READY_QUEUEING = {
initialize: function() {
this.reactMountReady.reset();
},
close: function() {
this.reactMountReady.notifyAll();
}
}, TRANSACTION_WRAPPERS$2 = [ ON_DOM_READY_QUEUEING ];
TRANSACTION_WRAPPERS$2.push({
initialize: ReactInstrumentation.debugTool.onBeginFlush,
close: ReactInstrumentation.debugTool.onEndFlush
});
function ReactNativeReconcileTransaction() {
this.reinitializeTransaction(), this.reactMountReady = CallbackQueue_1.getPooled();
}
var Mixin = {
getTransactionWrappers: function() {
return TRANSACTION_WRAPPERS$2;
},
getReactMountReady: function() {
return this.reactMountReady;
},
getUpdateQueue: function() {
return ReactUpdateQueue_1;
},
checkpoint: function() {
return this.reactMountReady.checkpoint();
},
rollback: function(checkpoint) {
this.reactMountReady.rollback(checkpoint);
},
destructor: function() {
CallbackQueue_1.release(this.reactMountReady), this.reactMountReady = null;
}
};
Object.assign(ReactNativeReconcileTransaction.prototype, Transaction, ReactNativeReconcileTransaction, Mixin),
PooledClass_1.addPoolingTo(ReactNativeReconcileTransaction);
var ReactNativeReconcileTransaction_1 = ReactNativeReconcileTransaction, ReactNativeComponentEnvironment = {
processChildrenUpdates: ReactNativeDOMIDOperations_1.dangerouslyProcessChildrenUpdates,
replaceNodeWithMarkup: ReactNativeDOMIDOperations_1.dangerouslyReplaceNodeWithMarkupByID,
clearNode: function() {},
ReactReconcileTransaction: ReactNativeReconcileTransaction_1
}, ReactNativeComponentEnvironment_1 = ReactNativeComponentEnvironment, ReactNativeTextComponent = function(text) {
this._currentElement = text, this._stringText = "" + text, this._hostParent = null,
this._rootNodeID = 0;
};
Object.assign(ReactNativeTextComponent.prototype, {
mountComponent: function(transaction, hostParent, hostContainerInfo, context) {
invariant(context.isInAParentText, 'RawText "%s" must be wrapped in an explicit <Text> component.', this._stringText),
this._hostParent = hostParent;
var tag = ReactNativeTagHandles_1.allocateTag();
this._rootNodeID = tag;
var nativeTopRootTag = hostContainerInfo._tag;
return UIManager.createView(tag, "RCTRawText", nativeTopRootTag, {
text: this._stringText
}), ReactNativeComponentTree_1.precacheNode(this, tag), tag;
},
getHostNode: function() {
return this._rootNodeID;
},
receiveComponent: function(nextText, transaction, context) {
if (nextText !== this._currentElement) {
this._currentElement = nextText;
var nextStringText = "" + nextText;
nextStringText !== this._stringText && (this._stringText = nextStringText, UIManager.updateView(this._rootNodeID, "RCTRawText", {
text: this._stringText
}));
}
},
unmountComponent: function() {
ReactNativeComponentTree_1.uncacheNode(this), this._currentElement = null, this._stringText = null,
this._rootNodeID = 0;
}
});
var ReactNativeTextComponent_1 = ReactNativeTextComponent, ReactSimpleEmptyComponent = function(placeholderElement, instantiate) {
this._currentElement = null, this._renderedComponent = instantiate(placeholderElement);
};
Object.assign(ReactSimpleEmptyComponent.prototype, {
mountComponent: function(transaction, hostParent, hostContainerInfo, context, parentDebugID) {
return ReactReconciler_1.mountComponent(this._renderedComponent, transaction, hostParent, hostContainerInfo, context, parentDebugID);
},
receiveComponent: function() {},
getHostNode: function() {
return ReactReconciler_1.getHostNode(this._renderedComponent);
},
unmountComponent: function(safely, skipLifecycle) {
ReactReconciler_1.unmountComponent(this._renderedComponent, safely, skipLifecycle),
this._renderedComponent = null;
}
});
var ReactSimpleEmptyComponent_1 = ReactSimpleEmptyComponent;
function inject$1() {
ReactGenericBatching_1.injection.injectStackBatchedUpdates(ReactUpdates_1.batchedUpdates),
ReactUpdates_1.injection.injectReconcileTransaction(ReactNativeComponentEnvironment_1.ReactReconcileTransaction),
ReactUpdates_1.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy_1),
ReactComponentEnvironment_1.injection.injectEnvironment(ReactNativeComponentEnvironment_1);
var EmptyComponent = function(instantiate) {
var View = require("View");
return new ReactSimpleEmptyComponent_1(React.createElement(View, {
collapsable: !0,
style: {
position: "absolute"
}
}), instantiate);
};
ReactEmptyComponent_1.injection.injectEmptyComponentFactory(EmptyComponent), ReactHostComponent_1.injection.injectTextComponentClass(ReactNativeTextComponent_1),
ReactHostComponent_1.injection.injectGenericComponentClass(function(tag) {
var info = "";
"string" == typeof tag && /^[a-z]/.test(tag) && (info += " Each component name should start with an uppercase letter."),
invariant(!1, "Expected a component class, got %s.%s", tag, info);
});
}
var ReactNativeStackInjection = {
inject: inject$1
};
function getComponentName(instanceOrFiber) {
if ("function" == typeof instanceOrFiber.getName) {
return instanceOrFiber.getName();
}
if ("number" == typeof instanceOrFiber.tag) {
var fiber = instanceOrFiber, type = fiber.type;
if ("string" == typeof type) return type;
if ("function" == typeof type) return type.displayName || type.name;
}
return null;
}
var getComponentName_1 = getComponentName, getInspectorDataForViewTag = void 0, traverseOwnerTreeUp = function(hierarchy, instance) {
instance && (hierarchy.unshift(instance), traverseOwnerTreeUp(hierarchy, instance._currentElement._owner));
}, getOwnerHierarchy = function(instance) {
var hierarchy = [];
return traverseOwnerTreeUp(hierarchy, instance), hierarchy;
}, lastNotNativeInstance = function(hierarchy) {
for (var i = hierarchy.length - 1; i > 1; i--) {
var instance = hierarchy[i];
if (!instance.viewConfig) return instance;
}
return hierarchy[0];
}, getHostProps = function(component) {
var instance = component._instance;
return instance ? instance.props || emptyObject : emptyObject;
}, createHierarchy = function(componentHierarchy) {
return componentHierarchy.map(function(component) {
return {
name: getComponentName_1(component),
getInspectorData: function() {
return {
measure: function(callback) {
return UIManager.measure(component.getHostNode(), callback);
},
props: getHostProps(component),
source: component._currentElement && component._currentElement._source
};
}
};
});
};
getInspectorDataForViewTag = function(viewTag) {
var component = ReactNativeComponentTree_1.getClosestInstanceFromNode(viewTag);
if (!component) return {
hierarchy: [],
props: emptyObject,
selection: null,
source: null
};
var componentHierarchy = getOwnerHierarchy(component), instance = lastNotNativeInstance(componentHierarchy), hierarchy = createHierarchy(componentHierarchy), props = getHostProps(instance), source = instance._currentElement && instance._currentElement._source;
return {
hierarchy: hierarchy,
props: props,
selection: componentHierarchy.indexOf(instance),
source: source
};
};
var ReactNativeStackInspector = {
getInspectorDataForViewTag: getInspectorDataForViewTag
}, findNumericNodeHandleStack = function(componentOrHandle) {
var nodeHandle = findNodeHandle_1(componentOrHandle);
return null == nodeHandle || "number" == typeof nodeHandle ? nodeHandle : nodeHandle.getHostNode();
};
function _classCallCheck$2(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
var objects = {}, uniqueID = 1, emptyObject$3 = {}, ReactNativePropRegistry = function() {
function ReactNativePropRegistry() {
_classCallCheck$2(this, ReactNativePropRegistry);
}
return ReactNativePropRegistry.register = function(object) {
var id = ++uniqueID;
return Object.freeze(object), objects[id] = object, id;
}, ReactNativePropRegistry.getByID = function(id) {
if (!id) return emptyObject$3;
var object = objects[id];
return object || (console.warn("Invalid style with id `" + id + "`. Skipping ..."),
emptyObject$3);
}, ReactNativePropRegistry;
}(), ReactNativePropRegistry_1 = ReactNativePropRegistry, emptyObject$2 = {}, removedKeys = null, removedKeyCount = 0;
function defaultDiffer(prevProp, nextProp) {
return "object" != typeof nextProp || null === nextProp || deepDiffer(prevProp, nextProp);
}
function resolveObject(idOrObject) {
return "number" == typeof idOrObject ? ReactNativePropRegistry_1.getByID(idOrObject) : idOrObject;
}
function restoreDeletedValuesInNestedArray(updatePayload, node, validAttributes) {
if (Array.isArray(node)) for (var i = node.length; i-- && removedKeyCount > 0; ) restoreDeletedValuesInNestedArray(updatePayload, node[i], validAttributes); else if (node && removedKeyCount > 0) {
var obj = resolveObject(node);
for (var propKey in removedKeys) if (removedKeys[propKey]) {
var nextProp = obj[propKey];
if (void 0 !== nextProp) {
var attributeConfig = validAttributes[propKey];
if (attributeConfig) {
if ("function" == typeof nextProp && (nextProp = !0), void 0 === nextProp && (nextProp = null),
"object" != typeof attributeConfig) updatePayload[propKey] = nextProp; else if ("function" == typeof attributeConfig.diff || "function" == typeof attributeConfig.process) {
var nextValue = "function" == typeof attributeConfig.process ? attributeConfig.process(nextProp) : nextProp;
updatePayload[propKey] = nextValue;
}
removedKeys[propKey] = !1, removedKeyCount--;
}
}
}
}
}
function diffNestedArrayProperty(updatePayload, prevArray, nextArray, validAttributes) {
var i, minLength = prevArray.length < nextArray.length ? prevArray.length : nextArray.length;
for (i = 0; i < minLength; i++) updatePayload = diffNestedProperty(updatePayload, prevArray[i], nextArray[i], validAttributes);
for (;i < prevArray.length; i++) updatePayload = clearNestedProperty(updatePayload, prevArray[i], validAttributes);
for (;i < nextArray.length; i++) updatePayload = addNestedProperty(updatePayload, nextArray[i], validAttributes);
return updatePayload;
}
function diffNestedProperty(updatePayload, prevProp, nextProp, validAttributes) {
return updatePayload || prevProp !== nextProp ? prevProp && nextProp ? Array.isArray(prevProp) || Array.isArray(nextProp) ? Array.isArray(prevProp) && Array.isArray(nextProp) ? diffNestedArrayProperty(updatePayload, prevProp, nextProp, validAttributes) : Array.isArray(prevProp) ? diffProperties(updatePayload, flattenStyle(prevProp), resolveObject(nextProp), validAttributes) : diffProperties(updatePayload, resolveObject(prevProp), flattenStyle(nextProp), validAttributes) : diffProperties(updatePayload, resolveObject(prevProp), resolveObject(nextProp), validAttributes) : nextProp ? addNestedProperty(updatePayload, nextProp, validAttributes) : prevProp ? clearNestedProperty(updatePayload, prevProp, validAttributes) : updatePayload : updatePayload;
}
function addNestedProperty(updatePayload, nextProp, validAttributes) {
if (!nextProp) return updatePayload;
if (!Array.isArray(nextProp)) return addProperties(updatePayload, resolveObject(nextProp), validAttributes);
for (var i = 0; i < nextProp.length; i++) updatePayload = addNestedProperty(updatePayload, nextProp[i], validAttributes);
return updatePayload;
}
function clearNestedProperty(updatePayload, prevProp, validAttributes) {
if (!prevProp) return updatePayload;
if (!Array.isArray(prevProp)) return clearProperties(updatePayload, resolveObject(prevProp), validAttributes);
for (var i = 0; i < prevProp.length; i++) updatePayload = clearNestedProperty(updatePayload, prevProp[i], validAttributes);
return updatePayload;
}
function diffProperties(updatePayload, prevProps, nextProps, validAttributes) {
var attributeConfig, nextProp, prevProp;
for (var propKey in nextProps) if (attributeConfig = validAttributes[propKey]) if (prevProp = prevProps[propKey],
nextProp = nextProps[propKey], "function" == typeof nextProp && (nextProp = !0,
"function" == typeof prevProp && (prevProp = !0)), void 0 === nextProp && (nextProp = null,
void 0 === prevProp && (prevProp = null)), removedKeys && (removedKeys[propKey] = !1),
updatePayload && void 0 !== updatePayload[propKey]) {
if ("object" != typeof attributeConfig) updatePayload[propKey] = nextProp; else if ("function" == typeof attributeConfig.diff || "function" == typeof attributeConfig.process) {
var nextValue = "function" == typeof attributeConfig.process ? attributeConfig.process(nextProp) : nextProp;
updatePayload[propKey] = nextValue;
}
} else if (prevProp !== nextProp) if ("object" != typeof attributeConfig) defaultDiffer(prevProp, nextProp) && ((updatePayload || (updatePayload = {}))[propKey] = nextProp); else if ("function" == typeof attributeConfig.diff || "function" == typeof attributeConfig.process) {
var shouldUpdate = void 0 === prevProp || ("function" == typeof attributeConfig.diff ? attributeConfig.diff(prevProp, nextProp) : defaultDiffer(prevProp, nextProp));
shouldUpdate && (nextValue = "function" == typeof attributeConfig.process ? attributeConfig.process(nextProp) : nextProp,
(updatePayload || (updatePayload = {}))[propKey] = nextValue);
} else removedKeys = null, removedKeyCount = 0, updatePayload = diffNestedProperty(updatePayload, prevProp, nextProp, attributeConfig),
removedKeyCount > 0 && updatePayload && (restoreDeletedValuesInNestedArray(updatePayload, nextProp, attributeConfig),
removedKeys = null);
for (propKey in prevProps) void 0 === nextProps[propKey] && (attributeConfig = validAttributes[propKey]) && (updatePayload && void 0 !== updatePayload[propKey] || void 0 !== (prevProp = prevProps[propKey]) && ("object" != typeof attributeConfig || "function" == typeof attributeConfig.diff || "function" == typeof attributeConfig.process ? ((updatePayload || (updatePayload = {}))[propKey] = null,
removedKeys || (removedKeys = {}), removedKeys[propKey] || (removedKeys[propKey] = !0,
removedKeyCount++)) : updatePayload = clearNestedProperty(updatePayload, prevProp, attributeConfig)));
return updatePayload;
}
function addProperties(updatePayload, props, validAttributes) {
return diffProperties(updatePayload, emptyObject$2, props, validAttributes);
}
function clearProperties(updatePayload, prevProps, validAttributes) {
return diffProperties(updatePayload, prevProps, emptyObject$2, validAttributes);
}
var ReactNativeAttributePayload = {
create: function(props, validAttributes) {
return addProperties(null, props, validAttributes);
},
diff: function(prevProps, nextProps, validAttributes) {
return diffProperties(null, prevProps, nextProps, validAttributes);
}
}, ReactNativeAttributePayload_1 = ReactNativeAttributePayload;
function mountSafeCallback$1(context, callback) {
return function() {
if (callback) {
if ("boolean" == typeof context.__isMounted) {
if (!context.__isMounted) return;
} else if ("function" == typeof context.isMounted && !context.isMounted()) return;
return callback.apply(context, arguments);
}
};
}
function throwOnStylesProp(component, props) {
if (void 0 !== props.styles) {
var owner = component._owner || null, name = component.constructor.displayName, msg = "`styles` is not a supported property of `" + name + "`, did " + "you mean `style` (singular)?";
throw owner && owner.constructor && owner.constructor.displayName && (msg += "\n\nCheck the `" + owner.constructor.displayName + "` parent " + " component."),
new Error(msg);
}
}
function warnForStyleProps(props, validAttributes) {
for (var key in validAttributes.style) validAttributes[key] || void 0 === props[key] || console.error("You are setting the style `{ " + key + ": ... }` as a prop. You " + "should nest it in a style object. " + "E.g. `{ style: { " + key + ": ... } }`");
}
var NativeMethodsMixinUtils = {
mountSafeCallback: mountSafeCallback$1,
throwOnStylesProp: throwOnStylesProp,
warnForStyleProps: warnForStyleProps
};
function _classCallCheck$1(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _possibleConstructorReturn(self, call) {
if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return !call || "object" != typeof call && "function" != typeof call ? self : call;
}
function _inherits(subClass, superClass) {
if ("function" != typeof superClass && null !== superClass) 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: !1,
writable: !0,
configurable: !0
}
}), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass);
}
var ReactNativeFeatureFlags$1 = require("ReactNativeFeatureFlags"), mountSafeCallback = NativeMethodsMixinUtils.mountSafeCallback, findNumericNodeHandle = ReactNativeFeatureFlags$1.useFiber ? DevOnlyStubShim : findNumericNodeHandleStack, ReactNativeComponent = function(_React$Component) {
_inherits(ReactNativeComponent, _React$Component);
function ReactNativeComponent() {
return _classCallCheck$1(this, ReactNativeComponent), _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
return ReactNativeComponent.prototype.blur = function() {
TextInputState.blurTextInput(findNumericNodeHandle(this));
}, ReactNativeComponent.prototype.focus = function() {
TextInputState.focusTextInput(findNumericNodeHandle(this));
}, ReactNativeComponent.prototype.measure = function(callback) {
UIManager.measure(findNumericNodeHandle(this), mountSafeCallback(this, callback));
}, ReactNativeComponent.prototype.measureInWindow = function(callback) {
UIManager.measureInWindow(findNumericNodeHandle(this), mountSafeCallback(this, callback));
}, ReactNativeComponent.prototype.measureLayout = function(relativeToNativeNode, onSuccess, onFail) {
UIManager.measureLayout(findNumericNodeHandle(this), relativeToNativeNode, mountSafeCallback(this, onFail), mountSafeCallback(this, onSuccess));
}, ReactNativeComponent.prototype.setNativeProps = function(nativeProps) {
injectedSetNativeProps(this, nativeProps);
}, ReactNativeComponent;
}(React.Component);
function setNativePropsFiber(componentOrHandle, nativeProps) {
var maybeInstance = void 0;
try {
maybeInstance = findNodeHandle_1(componentOrHandle);
} catch (error) {}
if (null != maybeInstance) {
var viewConfig = maybeInstance.viewConfig, updatePayload = ReactNativeAttributePayload_1.create(nativeProps, viewConfig.validAttributes);
UIManager.updateView(maybeInstance._nativeTag, viewConfig.uiViewClassName, updatePayload);
}
}
function setNativePropsStack(componentOrHandle, nativeProps) {
var maybeInstance = findNodeHandle_1(componentOrHandle);
if (null != maybeInstance) {
var viewConfig = void 0;
if (void 0 !== maybeInstance.viewConfig) viewConfig = maybeInstance.viewConfig; else if (void 0 !== maybeInstance._instance && void 0 !== maybeInstance._instance.viewConfig) viewConfig = maybeInstance._instance.viewConfig; else {
for (;void 0 !== maybeInstance._renderedComponent; ) maybeInstance = maybeInstance._renderedComponent;
viewConfig = maybeInstance.viewConfig;
}
var tag = "function" == typeof maybeInstance.getHostNode ? maybeInstance.getHostNode() : maybeInstance._rootNodeID, updatePayload = ReactNativeAttributePayload_1.create(nativeProps, viewConfig.validAttributes);
UIManager.updateView(tag, viewConfig.uiViewClassName, updatePayload);
}
}
var injectedSetNativeProps = void 0;
injectedSetNativeProps = ReactNativeFeatureFlags$1.useFiber ? setNativePropsFiber : setNativePropsStack;
var ReactNativeComponent_1 = ReactNativeComponent, ReactNativeFeatureFlags$2 = require("ReactNativeFeatureFlags"), mountSafeCallback$2 = NativeMethodsMixinUtils.mountSafeCallback, throwOnStylesProp$1 = NativeMethodsMixinUtils.throwOnStylesProp, warnForStyleProps$1 = NativeMethodsMixinUtils.warnForStyleProps, findNumericNodeHandle$1 = ReactNativeFeatureFlags$2.useFiber ? DevOnlyStubShim : findNumericNodeHandleStack, NativeMethodsMixin = {
measure: function(callback) {
UIManager.measure(findNumericNodeHandle$1(this), mountSafeCallback$2(this, callback));
},
measureInWindow: function(callback) {
UIManager.measureInWindow(findNumericNodeHandle$1(this), mountSafeCallback$2(this, callback));
},
measureLayout: function(relativeToNativeNode, onSuccess, onFail) {
UIManager.measureLayout(findNumericNodeHandle$1(this), relativeToNativeNode, mountSafeCallback$2(this, onFail), mountSafeCallback$2(this, onSuccess));
},
setNativeProps: function(nativeProps) {
injectedSetNativeProps$1(this, nativeProps);
},
focus: function() {
TextInputState.focusTextInput(findNumericNodeHandle$1(this));
},
blur: function() {
TextInputState.blurTextInput(findNumericNodeHandle$1(this));
}
};
function setNativePropsFiber$1(componentOrHandle, nativeProps) {
var maybeInstance = void 0;
try {
maybeInstance = findNodeHandle_1(componentOrHandle);
} catch (error) {}
if (null != maybeInstance) {
var viewConfig = maybeInstance.viewConfig;
warnForStyleProps$1(nativeProps, viewConfig.validAttributes);
var updatePayload = ReactNativeAttributePayload_1.create(nativeProps, viewConfig.validAttributes);
UIManager.updateView(maybeInstance._nativeTag, viewConfig.uiViewClassName, updatePayload);
}
}
function setNativePropsStack$1(componentOrHandle, nativeProps) {
var maybeInstance = findNodeHandle_1(componentOrHandle);
if (null != maybeInstance) {
var viewConfig = void 0;
if (void 0 !== maybeInstance.viewConfig) viewConfig = maybeInstance.viewConfig; else if (void 0 !== maybeInstance._instance && void 0 !== maybeInstance._instance.viewConfig) viewConfig = maybeInstance._instance.viewConfig; else {
for (;void 0 !== maybeInstance._renderedComponent; ) maybeInstance = maybeInstance._renderedComponent;
viewConfig = maybeInstance.viewConfig;
}
var tag = "function" == typeof maybeInstance.getHostNode ? maybeInstance.getHostNode() : maybeInstance._rootNodeID;
warnForStyleProps$1(nativeProps, viewConfig.validAttributes);
var updatePayload = ReactNativeAttributePayload_1.create(nativeProps, viewConfig.validAttributes);
UIManager.updateView(tag, viewConfig.uiViewClassName, updatePayload);
}
}
var injectedSetNativeProps$1 = void 0;
injectedSetNativeProps$1 = ReactNativeFeatureFlags$2.useFiber ? setNativePropsFiber$1 : setNativePropsStack$1;
var NativeMethodsMixin_DEV = NativeMethodsMixin;
invariant(!NativeMethodsMixin_DEV.componentWillMount && !NativeMethodsMixin_DEV.componentWillReceiveProps, "Do not override existing functions."),
NativeMethodsMixin_DEV.componentWillMount = function() {
throwOnStylesProp$1(this, this.props);
}, NativeMethodsMixin_DEV.componentWillReceiveProps = function(newProps) {
throwOnStylesProp$1(this, newProps);
};
var NativeMethodsMixin_1 = NativeMethodsMixin, TouchHistoryMath = {
centroidDimension: function(touchHistory, touchesChangedAfter, isXAxis, ofCurrent) {
var touchBank = touchHistory.touchBank, total = 0, count = 0, oneTouchData = 1 === touchHistory.numberActiveTouches ? touchHistory.touchBank[touchHistory.indexOfSingleActiveTouch] : null;
if (null !== oneTouchData) oneTouchData.touchActive && oneTouchData.currentTimeStamp > touchesChangedAfter && (total += ofCurrent && isXAxis ? oneTouchData.currentPageX : ofCurrent && !isXAxis ? oneTouchData.currentPageY : !ofCurrent && isXAxis ? oneTouchData.previousPageX : oneTouchData.previousPageY,
count = 1); else for (var i = 0; i < touchBank.length; i++) {
var touchTrack = touchBank[i];
if (null !== touchTrack && void 0 !== touchTrack && touchTrack.touchActive && touchTrack.currentTimeStamp >= touchesChangedAfter) {
var toAdd;
toAdd = ofCurrent && isXAxis ? touchTrack.currentPageX : ofCurrent && !isXAxis ? touchTrack.currentPageY : !ofCurrent && isXAxis ? touchTrack.previousPageX : touchTrack.previousPageY,
total += toAdd, count++;
}
}
return count > 0 ? total / count : TouchHistoryMath.noCentroid;
},
currentCentroidXOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) {
return TouchHistoryMath.centroidDimension(touchHistory, touchesChangedAfter, !0, !0);
},
currentCentroidYOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) {
return TouchHistoryMath.centroidDimension(touchHistory, touchesChangedAfter, !1, !0);
},
previousCentroidXOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) {
return TouchHistoryMath.centroidDimension(touchHistory, touchesChangedAfter, !0, !1);
},
previousCentroidYOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) {
return TouchHistoryMath.centroidDimension(touchHistory, touchesChangedAfter, !1, !1);
},
currentCentroidX: function(touchHistory) {
return TouchHistoryMath.centroidDimension(touchHistory, 0, !0, !0);
},
currentCentroidY: function(touchHistory) {
return TouchHistoryMath.centroidDimension(touchHistory, 0, !1, !0);
},
noCentroid: -1
}, TouchHistoryMath_1 = TouchHistoryMath;
function escape(key) {
var escaperLookup = {
"=": "=0",
":": "=2"
};
return "$" + ("" + key).replace(/[=:]/g, function(match) {
return escaperLookup[match];
});
}
var unescapeInDev = emptyFunction;
unescapeInDev = function(key) {
var unescapeRegex = /(=0|=2)/g, unescaperLookup = {
"=0": "=",
"=2": ":"
};
return ("" + ("." === key[0] && "$" === key[1] ? key.substring(2) : key.substring(1))).replace(unescapeRegex, function(match) {
return unescaperLookup[match];
});
};
var KeyEscapeUtils = {
escape: escape,
unescapeInDev: unescapeInDev
}, KeyEscapeUtils_1 = KeyEscapeUtils, ITERATOR_SYMBOL = "function" == typeof Symbol && Symbol.iterator, FAUX_ITERATOR_SYMBOL = "@@iterator", REACT_ELEMENT_TYPE = "function" == typeof Symbol && Symbol.for && Symbol.for("react.element") || 60103, getCurrentStackAddendum = ReactGlobalSharedState_1.ReactComponentTreeHook.getCurrentStackAddendum, SEPARATOR = ".", SUBSEPARATOR = ":", didWarnAboutMaps = !1;
function getComponentKey(component, index) {
return component && "object" == typeof component && null != component.key ? KeyEscapeUtils_1.escape(component.key) : index.toString(36);
}
function traverseStackChildrenImpl(children, nameSoFar, callback, traverseContext) {
var type = typeof children;
if ("undefined" !== type && "boolean" !== type || (children = null), null === children || "string" === type || "number" === type || "object" === type && children.$$typeof === REACT_ELEMENT_TYPE) return callback(traverseContext, children, "" === nameSoFar ? SEPARATOR + getComponentKey(children, 0) : nameSoFar),
1;
var child, nextName, subtreeCount = 0, nextNamePrefix = "" === nameSoFar ? SEPARATOR : nameSoFar + SUBSEPARATOR;
if (Array.isArray(children)) for (var i = 0; i < children.length; i++) child = children[i],
nextName = nextNamePrefix + getComponentKey(child, i), subtreeCount += traverseStackChildrenImpl(child, nextName, callback, traverseContext); else {
var iteratorFn = ITERATOR_SYMBOL && children[ITERATOR_SYMBOL] || children[FAUX_ITERATOR_SYMBOL];
if ("function" == typeof iteratorFn) {
iteratorFn === children.entries && (warning(didWarnAboutMaps, "Using Maps as children is unsupported and will likely yield " + "unexpected results. Convert it to a sequence/iterable of keyed " + "ReactElements instead.%s", getCurrentStackAddendum()),
didWarnAboutMaps = !0);
for (var step, iterator = iteratorFn.call(children), ii = 0; !(step = iterator.next()).done; ) child = step.value,
nextName = nextNamePrefix + getComponentKey(child, ii++), subtreeCount += traverseStackChildrenImpl(child, nextName, callback, traverseContext);
} else if ("object" === type) {
var addendum = "";
addendum = " If you meant to render a collection of children, use an array " + "instead." + getCurrentStackAddendum();
var childrenString = "" + children;
invariant(!1, "Objects are not valid as a React child (found: %s).%s", "[object Object]" === childrenString ? "object with keys {" + Object.keys(children).join(", ") + "}" : childrenString, addendum);
}
}
return subtreeCount;
}
function traverseStackChildren(children, callback, traverseContext) {
return null == children ? 0 : traverseStackChildrenImpl(children, "", callback, traverseContext);
}
var traverseStackChildren_1 = traverseStackChildren, ReactComponentTreeHook$2;
"undefined" != typeof process && process.env && "development" == "test" && (ReactComponentTreeHook$2 = ReactGlobalSharedState_1.ReactComponentTreeHook);
function instantiateChild(childInstances, child, name, selfDebugID) {
var keyUnique = void 0 === childInstances[name];
ReactComponentTreeHook$2 || (ReactComponentTreeHook$2 = ReactGlobalSharedState_1.ReactComponentTreeHook),
keyUnique || warning(!1, "flattenChildren(...):" + "Encountered two children with the same key, `%s`. " + "Keys should be unique so that components maintain their identity " + "across updates. Non-unique keys may cause children to be " + "duplicated and/or omitted — the behavior is unsupported and " + "could change in a future version.%s", KeyEscapeUtils_1.unescapeInDev(name), ReactComponentTreeHook$2.getStackAddendumByID(selfDebugID)),
null != child && keyUnique && (childInstances[name] = instantiateReactComponent_1(child, !0));
}
var ReactChildReconciler = {
instantiateChildren: function(nestedChildNodes, transaction, context, selfDebugID) {
if (null == nestedChildNodes) return null;
var childInstances = {};
return traverseStackChildren_1(nestedChildNodes, function(childInsts, child, name) {
return instantiateChild(childInsts, child, name, selfDebugID);
}, childInstances), childInstances;
},
updateChildren: function(prevChildren, nextChildren, mountImages, removedNodes, transaction, hostParent, hostContainerInfo, context, selfDebugID) {
if (nextChildren || prevChildren) {
var name, prevChild;
for (name in nextChildren) if (nextChildren.hasOwnProperty(name)) {
prevChild = prevChildren && prevChildren[name];
var prevElement = prevChild && prevChild._currentElement, nextElement = nextChildren[name];
if (null != prevChild && shouldUpdateReactComponent_1(prevElement, nextElement)) ReactReconciler_1.receiveComponent(prevChild, nextElement, transaction, context),
nextChildren[name] = prevChild; else {
var nextChildInstance = instantiateReactComponent_1(nextElement, !0);
nextChildren[name] = nextChildInstance;
var nextChildMountImage = ReactReconciler_1.mountComponent(nextChildInstance, transaction, hostParent, hostContainerInfo, context, selfDebugID);
mountImages.push(nextChildMountImage), prevChild && (removedNodes[name] = ReactReconciler_1.getHostNode(prevChild),
ReactReconciler_1.unmountComponent(prevChild, !1, !1));
}
}
for (name in prevChildren) !prevChildren.hasOwnProperty(name) || nextChildren && nextChildren.hasOwnProperty(name) || (prevChild = prevChildren[name],
removedNodes[name] = ReactReconciler_1.getHostNode(prevChild), ReactReconciler_1.unmountComponent(prevChild, !1, !1));
}
},
unmountChildren: function(renderedChildren, safely, skipLifecycle) {
for (var name in renderedChildren) if (renderedChildren.hasOwnProperty(name)) {
var renderedChild = renderedChildren[name];
ReactReconciler_1.unmountComponent(renderedChild, safely, skipLifecycle);
}
}
}, ReactChildReconciler_1 = ReactChildReconciler, ReactComponentTreeHook$3;
"undefined" != typeof process && process.env && "development" == "test" && (ReactComponentTreeHook$3 = ReactGlobalSharedState_1.ReactComponentTreeHook);
function flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID) {
if (traverseContext && "object" == typeof traverseContext) {
var result = traverseContext, keyUnique = void 0 === result[name];
ReactComponentTreeHook$3 || (ReactComponentTreeHook$3 = ReactGlobalSharedState_1.ReactComponentTreeHook),
keyUnique || warning(!1, "flattenChildren(...): Encountered two children with the same key, " + "`%s`. " + "Keys should be unique so that components maintain their identity " + "across updates. Non-unique keys may cause children to be " + "duplicated and/or omitted — the behavior is unsupported and " + "could change in a future version.%s", KeyEscapeUtils_1.unescapeInDev(name), ReactComponentTreeHook$3.getStackAddendumByID(selfDebugID)),
keyUnique && null != child && (result[name] = child);
}
}
function flattenStackChildren(children, selfDebugID) {
if (null == children) return children;
var result = {};
return traverseStackChildren_1(children, function(traverseContext, child, name) {
return flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID);
}, result), result;
}
var flattenStackChildren_1 = flattenStackChildren, ReactCurrentOwner$3 = ReactGlobalSharedState_1.ReactCurrentOwner;
function makeInsertMarkup(markup, afterNode, toIndex) {
return {
type: "INSERT_MARKUP",
content: markup,
fromIndex: null,
fromNode: null,
toIndex: toIndex,
afterNode: afterNode
};
}
function makeMove(child, afterNode, toIndex) {
return {
type: "MOVE_EXISTING",
content: null,
fromIndex: child._mountIndex,
fromNode: ReactReconciler_1.getHostNode(child),
toIndex: toIndex,
afterNode: afterNode
};
}
function makeRemove(child, node) {
return {
type: "REMOVE_NODE",
content: null,
fromIndex: child._mountIndex,
fromNode: node,
toIndex: null,
afterNode: null
};
}
function makeSetMarkup(markup) {
return {
type: "SET_MARKUP",
content: markup,
fromIndex: null,
fromNode: null,
toIndex: null,
afterNode: null
};
}
function makeTextContent(textContent) {
return {
type: "TEXT_CONTENT",
content: textContent,
fromIndex: null,
fromNode: null,
toIndex: null,
afterNode: null
};
}
function enqueue(queue, update) {
return update && (queue = queue || [], queue.push(update)), queue;
}
function processQueue(inst, updateQueue) {
ReactComponentEnvironment_1.processChildrenUpdates(inst, updateQueue);
}
var setChildrenForInstrumentation = emptyFunction, getDebugID = function(inst) {
if (!inst._debugID) {
var internal;
(internal = ReactInstanceMap_1.get(inst)) && (inst = internal);
}
return inst._debugID;
};
setChildrenForInstrumentation = function(children) {
var debugID = getDebugID(this);
0 !== debugID && ReactInstrumentation.debugTool.onSetChildren(debugID, children ? Object.keys(children).map(function(key) {
return children[key]._debugID;
}) : []);
};
var ReactMultiChild = {
_reconcilerInstantiateChildren: function(nestedChildren, transaction, context) {
var selfDebugID = getDebugID(this);
if (this._currentElement) try {
return ReactCurrentOwner$3.current = this._currentElement._owner, ReactChildReconciler_1.instantiateChildren(nestedChildren, transaction, context, selfDebugID);
} finally {
ReactCurrentOwner$3.current = null;
}
return ReactChildReconciler_1.instantiateChildren(nestedChildren, transaction, context);
},
_reconcilerUpdateChildren: function(prevChildren, nextNestedChildrenElements, mountImages, removedNodes, transaction, context) {
var nextChildren, selfDebugID = 0;
if (selfDebugID = getDebugID(this), this._currentElement) {
try {
ReactCurrentOwner$3.current = this._currentElement._owner, nextChildren = flattenStackChildren_1(nextNestedChildrenElements, selfDebugID);
} finally {
ReactCurrentOwner$3.current = null;
}
return ReactChildReconciler_1.updateChildren(prevChildren, nextChildren, mountImages, removedNodes, transaction, this, this._hostContainerInfo, context, selfDebugID),
nextChildren;
}
return nextChildren = flattenStackChildren_1(nextNestedChildrenElements, selfDebugID),
ReactChildReconciler_1.updateChildren(prevChildren, nextChildren, mountImages, removedNodes, transaction, this, this._hostContainerInfo, context, selfDebugID),
nextChildren;
},
mountChildren: function(nestedChildren, transaction, context) {
var children = this._reconcilerInstantiateChildren(nestedChildren, transaction, context);
this._renderedChildren = children;
var mountImages = [], index = 0;
for (var name in children) if (children.hasOwnProperty(name)) {
var child = children[name], selfDebugID = 0;
selfDebugID = getDebugID(this);
var mountImage = ReactReconciler_1.mountComponent(child, transaction, this, this._hostContainerInfo, context, selfDebugID);
child._mountIndex = index++, mountImages.push(mountImage);
}
return setChildrenForInstrumentation.call(this, children), mountImages;
},
updateTextContent: function(nextContent) {
var prevChildren = this._renderedChildren;
ReactChildReconciler_1.unmountChildren(prevChildren, !1, !1);
for (var name in prevChildren) prevChildren.hasOwnProperty(name) && invariant(!1, "updateTextContent called on non-empty component.");
processQueue(this, [ makeTextContent(nextContent) ]);
},
updateMarkup: function(nextMarkup) {
var prevChildren = this._renderedChildren;
ReactChildReconciler_1.unmountChildren(prevChildren, !1, !1);
for (var name in prevChildren) prevChildren.hasOwnProperty(name) && invariant(!1, "updateTextContent called on non-empty component.");
processQueue(this, [ makeSetMarkup(nextMarkup) ]);
},
updateChildren: function(nextNestedChildrenElements, transaction, context) {
this._updateChildren(nextNestedChildrenElements, transaction, context);
},
_updateChildren: function(nextNestedChildrenElements, transaction, context) {
var prevChildren = this._renderedChildren, removedNodes = {}, mountImages = [], nextChildren = this._reconcilerUpdateChildren(prevChildren, nextNestedChildrenElements, mountImages, removedNodes, transaction, context);
if (nextChildren || prevChildren) {
var name, updates = null, nextIndex = 0, lastIndex = 0, nextMountIndex = 0, lastPlacedNode = null;
for (name in nextChildren) if (nextChildren.hasOwnProperty(name)) {
var prevChild = prevChildren && prevChildren[name], nextChild = nextChildren[name];
prevChild === nextChild ? (updates = enqueue(updates, this.moveChild(prevChild, lastPlacedNode, nextIndex, lastIndex)),
lastIndex = Math.max(prevChild._mountIndex, lastIndex), prevChild._mountIndex = nextIndex) : (prevChild && (lastIndex = Math.max(prevChild._mountIndex, lastIndex)),
updates = enqueue(updates, this._mountChildAtIndex(nextChild, mountImages[nextMountIndex], lastPlacedNode, nextIndex, transaction, context)),
nextMountIndex++), nextIndex++, lastPlacedNode = ReactReconciler_1.getHostNode(nextChild);
}
for (name in removedNodes) removedNodes.hasOwnProperty(name) && (updates = enqueue(updates, this._unmountChild(prevChildren[name], removedNodes[name])));
updates && processQueue(this, updates), this._renderedChildren = nextChildren, setChildrenForInstrumentation.call(this, nextChildren);
}
},
unmountChildren: function(safely, skipLifecycle) {
var renderedChildren = this._renderedChildren;
ReactChildReconciler_1.unmountChildren(renderedChildren, safely, skipLifecycle),
this._renderedChildren = null;
},
moveChild: function(child, afterNode, toIndex, lastIndex) {
if (child._mountIndex < lastIndex) return makeMove(child, afterNode, toIndex);
},
createChild: function(child, afterNode, mountImage) {
return makeInsertMarkup(mountImage, afterNode, child._mountIndex);
},
removeChild: function(child, node) {
return makeRemove(child, node);
},
_mountChildAtIndex: function(child, mountImage, afterNode, index, transaction, context) {
return child._mountIndex = index, this.createChild(child, afterNode, mountImage);
},
_unmountChild: function(child, node) {
var update = this.removeChild(child, node);
return child._mountIndex = null, update;
}
}, ReactMultiChild_1 = ReactMultiChild, ReactNativeBaseComponent = function(viewConfig) {
this.viewConfig = viewConfig;
};
ReactNativeBaseComponent.Mixin = {
getPublicInstance: function() {
return this;
},
unmountComponent: function(safely, skipLifecycle) {
ReactNativeComponentTree_1.uncacheNode(this), this.unmountChildren(safely, skipLifecycle),
this._rootNodeID = 0;
},
initializeChildren: function(children, containerTag, transaction, context) {
var mountImages = this.mountChildren(children, transaction, context);
if (mountImages.length) {
for (var createdTags = [], i = 0, l = mountImages.length; i < l; i++) {
var mountImage = mountImages[i], childTag = mountImage;
createdTags[i] = childTag;
}
UIManager.setChildren(containerTag, createdTags);
}
},
receiveComponent: function(nextElement, transaction, context) {
var prevElement = this._currentElement;
this._currentElement = nextElement;
for (var key in this.viewConfig.validAttributes) nextElement.props.hasOwnProperty(key) && deepFreezeAndThrowOnMutationInDev(nextElement.props[key]);
var updatePayload = ReactNativeAttributePayload_1.diff(prevElement.props, nextElement.props, this.viewConfig.validAttributes);
updatePayload && UIManager.updateView(this._rootNodeID, this.viewConfig.uiViewClassName, updatePayload),
this.updateChildren(nextElement.props.children, transaction, context);
},
getName: function() {
return this.constructor.displayName || this.constructor.name || "Unknown";
},
getHostNode: function() {
return this._rootNodeID;
},
mountComponent: function(transaction, hostParent, hostContainerInfo, context) {
var tag = ReactNativeTagHandles_1.allocateTag();
this._rootNodeID = tag, this._hostParent = hostParent, this._hostContainerInfo = hostContainerInfo;
for (var key in this.viewConfig.validAttributes) this._currentElement.props.hasOwnProperty(key) && deepFreezeAndThrowOnMutationInDev(this._currentElement.props[key]);
var updatePayload = ReactNativeAttributePayload_1.create(this._currentElement.props, this.viewConfig.validAttributes), nativeTopRootTag = hostContainerInfo._tag;
return UIManager.createView(tag, this.viewConfig.uiViewClassName, nativeTopRootTag, updatePayload),
ReactNativeComponentTree_1.precacheNode(this, tag), this.initializeChildren(this._currentElement.props.children, tag, transaction, context),
tag;
}
}, Object.assign(ReactNativeBaseComponent.prototype, ReactMultiChild_1, ReactNativeBaseComponent.Mixin, NativeMethodsMixin_1);
var ReactNativeBaseComponent_1 = ReactNativeBaseComponent, createReactNativeComponentClassStack = function(viewConfig) {
var Constructor = function(element) {
this._currentElement = element, this._topLevelWrapper = null, this._hostParent = null,
this._hostContainerInfo = null, this._rootNodeID = 0, this._renderedChildren = null;
};
return Constructor.displayName = viewConfig.uiViewClassName, Constructor.viewConfig = viewConfig,
Constructor.propTypes = viewConfig.propTypes, Constructor.prototype = new ReactNativeBaseComponent_1(viewConfig),
Constructor.prototype.constructor = Constructor, Constructor;
}, createReactNativeComponentClassStack_1 = createReactNativeComponentClassStack, ReactNativeFeatureFlags$3 = require("ReactNativeFeatureFlags"), createReactNativeComponentClass = ReactNativeFeatureFlags$3.useFiber ? DevOnlyStubShim : createReactNativeComponentClassStack_1, ReactNativeFeatureFlags$4 = require("ReactNativeFeatureFlags"), findNumericNodeHandle$2 = ReactNativeFeatureFlags$4.useFiber ? DevOnlyStubShim : findNumericNodeHandleStack;
function takeSnapshot(view, options) {
return "number" != typeof view && "window" !== view && (view = findNumericNodeHandle$2(view) || "window"),
UIManager.__takeSnapshot(view, options);
}
var takeSnapshot_1 = takeSnapshot, lowPriorityWarning = function() {}, printWarning = function(format) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) args[_key - 1] = arguments[_key];
var argIndex = 0, message = "Warning: " + format.replace(/%s/g, function() {
return args[argIndex++];
});
"undefined" != typeof console && console.warn(message);
try {
throw new Error(message);
} catch (x) {}
};
lowPriorityWarning = function(condition, format) {
if (void 0 === format) throw new Error("`warning(condition, format, ...args)` requires a warning " + "message argument");
if (!condition) {
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) args[_key2 - 2] = arguments[_key2];
printWarning.apply(void 0, [ format ].concat(args));
}
};
var lowPriorityWarning_1 = lowPriorityWarning, _extends$2 = Object.assign || function(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]);
}
return target;
};
function roundFloat(val) {
var base = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 2, n = Math.pow(10, base);
return Math.floor(val * n) / n;
}
function consoleTable(table) {
console.table(table);
}
function getLastMeasurements() {
return ReactDebugTool_1.getFlushHistory();
}
function getExclusive() {
var flushHistory = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : getLastMeasurements(), aggregatedStats = {}, affectedIDs = {};
function updateAggregatedStats(treeSnapshot, instanceID, timerType, applyUpdate) {
var displayName = treeSnapshot[instanceID].displayName, key = displayName, stats = aggregatedStats[key];
stats || (affectedIDs[key] = {}, stats = aggregatedStats[key] = {
key: key,
instanceCount: 0,
counts: {},
durations: {},
totalDuration: 0
}), stats.durations[timerType] || (stats.durations[timerType] = 0), stats.counts[timerType] || (stats.counts[timerType] = 0),
affectedIDs[key][instanceID] = !0, applyUpdate(stats);
}
return flushHistory.forEach(function(flush) {
var measurements = flush.measurements, treeSnapshot = flush.treeSnapshot;
measurements.forEach(function(measurement) {
var duration = measurement.duration, instanceID = measurement.instanceID, timerType = measurement.timerType;
updateAggregatedStats(treeSnapshot, instanceID, timerType, function(stats) {
stats.totalDuration += duration, stats.durations[timerType] += duration, stats.counts[timerType]++;
});
});
}), Object.keys(aggregatedStats).map(function(key) {
return _extends$2({}, aggregatedStats[key], {
instanceCount: Object.keys(affectedIDs[key]).length
});
}).sort(function(a, b) {
return b.totalDuration - a.totalDuration;
});
}
function getInclusive() {
var flushHistory = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : getLastMeasurements(), aggregatedStats = {}, affectedIDs = {};
function updateAggregatedStats(treeSnapshot, instanceID, applyUpdate) {
var _treeSnapshot$instanc = treeSnapshot[instanceID], displayName = _treeSnapshot$instanc.displayName, ownerID = _treeSnapshot$instanc.ownerID, owner = treeSnapshot[ownerID], key = (owner ? owner.displayName + " > " : "") + displayName, stats = aggregatedStats[key];
stats || (affectedIDs[key] = {}, stats = aggregatedStats[key] = {
key: key,
instanceCount: 0,
inclusiveRenderDuration: 0,
renderCount: 0
}), affectedIDs[key][instanceID] = !0, applyUpdate(stats);
}
var isCompositeByID = {};
return flushHistory.forEach(function(flush) {
flush.measurements.forEach(function(measurement) {
var instanceID = measurement.instanceID;
"render" === measurement.timerType && (isCompositeByID[instanceID] = !0);
});
}), flushHistory.forEach(function(flush) {
var measurements = flush.measurements, treeSnapshot = flush.treeSnapshot;
measurements.forEach(function(measurement) {
var duration = measurement.duration, instanceID = measurement.instanceID;
if ("render" === measurement.timerType) {
updateAggregatedStats(treeSnapshot, instanceID, function(stats) {
stats.renderCount++;
});
for (var nextParentID = instanceID; nextParentID; ) isCompositeByID[nextParentID] && updateAggregatedStats(treeSnapshot, nextParentID, function(stats) {
stats.inclusiveRenderDuration += duration;
}), nextParentID = treeSnapshot[nextParentID].parentID;
}
});
}), Object.keys(aggregatedStats).map(function(key) {
return _extends$2({}, aggregatedStats[key], {
instanceCount: Object.keys(affectedIDs[key]).length
});
}).sort(function(a, b) {
return b.inclusiveRenderDuration - a.inclusiveRenderDuration;
});
}
function getWasted() {
var flushHistory = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : getLastMeasurements(), aggregatedStats = {}, affectedIDs = {};
function updateAggregatedStats(treeSnapshot, instanceID, applyUpdate) {
var _treeSnapshot$instanc2 = treeSnapshot[instanceID], displayName = _treeSnapshot$instanc2.displayName, ownerID = _treeSnapshot$instanc2.ownerID, owner = treeSnapshot[ownerID], key = (owner ? owner.displayName + " > " : "") + displayName, stats = aggregatedStats[key];
stats || (affectedIDs[key] = {}, stats = aggregatedStats[key] = {
key: key,
instanceCount: 0,
inclusiveRenderDuration: 0,
renderCount: 0
}), affectedIDs[key][instanceID] = !0, applyUpdate(stats);
}
return flushHistory.forEach(function(flush) {
var measurements = flush.measurements, treeSnapshot = flush.treeSnapshot, operations = flush.operations, isDefinitelyNotWastedByID = {};
operations.forEach(function(operation) {
for (var instanceID = operation.instanceID, nextParentID = instanceID; nextParentID; ) isDefinitelyNotWastedByID[nextParentID] = !0,
nextParentID = treeSnapshot[nextParentID].parentID;
});
var renderedCompositeIDs = {};
measurements.forEach(function(measurement) {
var instanceID = measurement.instanceID;
"render" === measurement.timerType && (renderedCompositeIDs[instanceID] = !0);
}), measurements.forEach(function(measurement) {
var duration = measurement.duration, instanceID = measurement.instanceID;
if ("render" === measurement.timerType) {
var updateCount = treeSnapshot[instanceID].updateCount;
if (!isDefinitelyNotWastedByID[instanceID] && 0 !== updateCount) {
updateAggregatedStats(treeSnapshot, instanceID, function(stats) {
stats.renderCount++;
});
for (var nextParentID = instanceID; nextParentID; ) renderedCompositeIDs[nextParentID] && !isDefinitelyNotWastedByID[nextParentID] && updateAggregatedStats(treeSnapshot, nextParentID, function(stats) {
stats.inclusiveRenderDuration += duration;
}), nextParentID = treeSnapshot[nextParentID].parentID;
}
}
});
}), Object.keys(aggregatedStats).map(function(key) {
return _extends$2({}, aggregatedStats[key], {
instanceCount: Object.keys(affectedIDs[key]).length
});
}).sort(function(a, b) {
return b.inclusiveRenderDuration - a.inclusiveRenderDuration;
});
}
function getOperations() {
var flushHistory = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : getLastMeasurements(), stats = [];
return flushHistory.forEach(function(flush, flushIndex) {
var operations = flush.operations, treeSnapshot = flush.treeSnapshot;
operations.forEach(function(operation) {
var instanceID = operation.instanceID, type = operation.type, payload = operation.payload, _treeSnapshot$instanc3 = treeSnapshot[instanceID], displayName = _treeSnapshot$instanc3.displayName, ownerID = _treeSnapshot$instanc3.ownerID, owner = treeSnapshot[ownerID], key = (owner ? owner.displayName + " > " : "") + displayName;
stats.push({
flushIndex: flushIndex,
instanceID: instanceID,
key: key,
type: type,
ownerID: ownerID,
payload: payload
});
});
}), stats;
}
function printExclusive(flushHistory) {
consoleTable(getExclusive(flushHistory).map(function(item) {
var key = item.key, instanceCount = item.instanceCount, totalDuration = item.totalDuration, renderCount = item.counts.render || 0, renderDuration = item.durations.render || 0;
return {
Component: key,
"Total time (ms)": roundFloat(totalDuration),
"Instance count": instanceCount,
"Total render time (ms)": roundFloat(renderDuration),
"Average render time (ms)": renderCount ? roundFloat(renderDuration / renderCount) : void 0,
"Render count": renderCount,
"Total lifecycle time (ms)": roundFloat(totalDuration - renderDuration)
};
}));
}
function printInclusive(flushHistory) {
consoleTable(getInclusive(flushHistory).map(function(item) {
var key = item.key, instanceCount = item.instanceCount, inclusiveRenderDuration = item.inclusiveRenderDuration, renderCount = item.renderCount;
return {
"Owner > Component": key,
"Inclusive render time (ms)": roundFloat(inclusiveRenderDuration),
"Instance count": instanceCount,
"Render count": renderCount
};
}));
}
function printWasted(flushHistory) {
consoleTable(getWasted(flushHistory).map(function(item) {
var key = item.key, instanceCount = item.instanceCount, inclusiveRenderDuration = item.inclusiveRenderDuration, renderCount = item.renderCount;
return {
"Owner > Component": key,
"Inclusive wasted time (ms)": roundFloat(inclusiveRenderDuration),
"Instance count": instanceCount,
"Render count": renderCount
};
}));
}
function printOperations(flushHistory) {
consoleTable(getOperations(flushHistory).map(function(stat) {
return {
"Owner > Node": stat.key,
Operation: stat.type,
Payload: "object" == typeof stat.payload ? JSON.stringify(stat.payload) : stat.payload,
"Flush index": stat.flushIndex,
"Owner Component ID": stat.ownerID,
"DOM Component ID": stat.instanceID
};
}));
}
var warnedAboutPrintDOM = !1;
function printDOM(measurements) {
return lowPriorityWarning_1(warnedAboutPrintDOM, "`ReactPerf.printDOM(...)` is deprecated. Use " + "`ReactPerf.printOperations(...)` instead."),
warnedAboutPrintDOM = !0, printOperations(measurements);
}
var warnedAboutGetMeasurementsSummaryMap = !1;
function getMeasurementsSummaryMap(measurements) {
return lowPriorityWarning_1(warnedAboutGetMeasurementsSummaryMap, "`ReactPerf.getMeasurementsSummaryMap(...)` is deprecated. Use " + "`ReactPerf.getWasted(...)` instead."),
warnedAboutGetMeasurementsSummaryMap = !0, getWasted(measurements);
}
function start() {
ReactDebugTool_1.beginProfiling();
}
function stop() {
ReactDebugTool_1.endProfiling();
}
function isRunning() {
return ReactDebugTool_1.isProfiling();
}
var ReactPerfAnalysis = {
getLastMeasurements: getLastMeasurements,
getExclusive: getExclusive,
getInclusive: getInclusive,
getWasted: getWasted,
getOperations: getOperations,
printExclusive: printExclusive,
printInclusive: printInclusive,
printWasted: printWasted,
printOperations: printOperations,
start: start,
stop: stop,
isRunning: isRunning,
printDOM: printDOM,
getMeasurementsSummaryMap: getMeasurementsSummaryMap
}, ReactPerf = ReactPerfAnalysis;
ReactNativeInjection.inject(), ReactNativeStackInjection.inject();
var render = function(element, mountInto, callback) {
return ReactNativeMount_1.renderComponent(element, mountInto, callback);
}, ReactNativeStack = {
NativeComponent: ReactNativeComponent_1,
hasReactNativeInitialized: !1,
findNodeHandle: findNumericNodeHandleStack,
render: render,
unmountComponentAtNode: ReactNativeMount_1.unmountComponentAtNode,
unstable_batchedUpdates: ReactUpdates_1.batchedUpdates,
unmountComponentAtNodeAndRemoveContainer: ReactNativeMount_1.unmountComponentAtNodeAndRemoveContainer,
__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
NativeMethodsMixin: NativeMethodsMixin_1,
ReactGlobalSharedState: ReactGlobalSharedState_1,
ReactNativeComponentTree: ReactNativeComponentTree_1,
ReactNativePropRegistry: ReactNativePropRegistry_1,
TouchHistoryMath: TouchHistoryMath_1,
createReactNativeComponentClass: createReactNativeComponentClass,
takeSnapshot: takeSnapshot_1
}
};
Object.assign(ReactNativeStack.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, {
ReactDebugTool: ReactDebugTool_1,
ReactPerf: ReactPerf
}), "undefined" != typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" == typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject && __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({
ComponentTree: {
getClosestInstanceFromNode: function(node) {
return ReactNativeComponentTree_1.getClosestInstanceFromNode(node);
},
getNodeFromInstance: function(inst) {
for (;inst._renderedComponent; ) inst = inst._renderedComponent;
return inst ? ReactNativeComponentTree_1.getNodeFromInstance(inst) : null;
}
},
Mount: ReactNativeMount_1,
Reconciler: ReactReconciler_1,
getInspectorDataForViewTag: ReactNativeStackInspector.getInspectorDataForViewTag
});
var ReactNativeStackEntry = ReactNativeStack;
module.exports = ReactNativeStackEntry;
|
import Ember from 'ember';
const {assign} = Ember;
export default {
name: 'jquery-ajax-oauth-prefilter',
after: 'ember-simple-auth',
initialize(application) {
let session = application.lookup('service:session');
Ember.$.ajaxPrefilter(function (options) {
session.authorize('authorizer:oauth2', function (headerName, headerValue) {
let headerObject = {};
headerObject[headerName] = headerValue;
options.headers = assign(options.headers || {}, headerObject);
});
});
}
};
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.runTapticImpactOccurred = runTapticImpactOccurred;
var _vkBridge = _interopRequireDefault(require("@vkontakte/vk-bridge"));
function runTapticImpactOccurred(style) {
if (_vkBridge.default.supports('VKWebAppTapticImpactOccurred')) {
_vkBridge.default.send('VKWebAppTapticImpactOccurred', {
style: style
}).catch(function () {
return undefined;
});
}
}
//# sourceMappingURL=taptic.js.map |
describe("expression", function() {
var rootEl;
beforeEach(function() {
rootEl = browser.rootEl;
browser.get("./examples/example-example89/index-jquery.html");
});
it('should calculate expression in binding', function() {
expect(element(by.binding('1+2')).getText()).toEqual('1+2=3');
});
});
|
import Colors from '../colors';
import ColorManipulator from '../../utils/color-manipulator';
import Spacing from '../spacing';
/*
* Light Theme is the default theme used in material-ui. It is guaranteed to
* have all theme variables needed for every component. Variables not defined
* in a custom theme will default to these values.
*/
export default {
spacing: Spacing,
fontFamily: 'Roboto, sans-serif',
palette: {
primary1Color: Colors.cyan500,
primary2Color: Colors.cyan700,
primary3Color: Colors.grey400,
accent1Color: Colors.pinkA200,
accent2Color: Colors.grey100,
accent3Color: Colors.grey500,
textColor: Colors.darkBlack,
alternateTextColor: Colors.white,
canvasColor: Colors.white,
borderColor: Colors.grey300,
disabledColor: ColorManipulator.fade(Colors.darkBlack, 0.3),
pickerHeaderColor: Colors.cyan500,
clockCircleColor: ColorManipulator.fade(Colors.darkBlack, 0.07),
shadowColor: Colors.fullBlack,
},
};
|
beforeAll(function() {
RewardDetailsMockery = function(attrs) {
var attrs = attrs || {};
var data = {
id: 25935,
project_id: 6140,
description: "reward_descriptiom",
minimum_value: 20,
maximum_contributions: null,
deliver_at: "2014-12-01T02:00:00",
updated_at: "2014-08-13T16:08:07.67877",
paid_count: 82,
waiting_payment_count: 0
};
data = _.extend(data, attrs);
return [data];
};
jasmine.Ajax.stubRequest(new RegExp("("+apiPrefix + '\/reward_details)'+'(.*)')).andReturn({
'responseText' : JSON.stringify(RewardDetailsMockery())
});
});
|
module.exports={A:{A:{"2":"VB","8":"J C G","129":"B A","161":"E"},B:{"129":"D Y g H L"},C:{"1":"0 1 3 4 5 6 L M N O P Q R S T U V W X v Z a b c d e f K h i j k l m n o p q r s x y u t","2":"TB z","33":"F I J C G E B A D Y g H RB QB"},D:{"1":"0 1 3 4 5 6 f K h i j k l m n o p q r s x y u t FB AB CB UB DB","33":"F I J C G E B A D Y g H L M N O P Q R S T U V W X v Z a b c d e"},E:{"1":"E B A JB KB LB","33":"9 F I J C G EB GB HB IB"},F:{"1":"S T U V W X v Z a b c d e f K h i j k l m n o p q r s w","2":"E MB NB","33":"7 8 A D H L M N O P Q R OB PB SB"},G:{"1":"A aB bB cB dB","33":"2 9 G BB WB XB YB ZB"},H:{"2":"eB"},I:{"1":"t","33":"2 z F fB gB hB iB jB kB"},J:{"33":"C B"},K:{"1":"7 8 A D K w","2":"B"},L:{"1":"AB"},M:{"1":"u"},N:{"1":"B A"},O:{"33":"lB"},P:{"1":"F I"},Q:{"1":"mB"},R:{"1":"nB"}},B:5,C:"CSS3 2D Transforms"};
|
import UsersSelect from '~/users_select';
import ShortcutsNavigation from '~/behaviors/shortcuts/shortcuts_navigation';
import initBoards from '~/boards';
document.addEventListener('DOMContentLoaded', () => {
new UsersSelect(); // eslint-disable-line no-new
new ShortcutsNavigation(); // eslint-disable-line no-new
initBoards();
});
|
// flow-typed signature: 899226cdfae67586c21c8615d3d4fc42
// flow-typed version: <<STUB>>/tcomb_v^3.2.15/flow_v0.37.1
/**
* This is an autogenerated libdef stub for:
*
* 'tcomb'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'tcomb' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'tcomb/lib/Any' {
declare module.exports: any;
}
declare module 'tcomb/lib/Array' {
declare module.exports: any;
}
declare module 'tcomb/lib/assert' {
declare module.exports: any;
}
declare module 'tcomb/lib/assign' {
declare module.exports: any;
}
declare module 'tcomb/lib/Boolean' {
declare module.exports: any;
}
declare module 'tcomb/lib/create' {
declare module.exports: any;
}
declare module 'tcomb/lib/Date' {
declare module.exports: any;
}
declare module 'tcomb/lib/declare' {
declare module.exports: any;
}
declare module 'tcomb/lib/decompose' {
declare module.exports: any;
}
declare module 'tcomb/lib/dict' {
declare module.exports: any;
}
declare module 'tcomb/lib/enums' {
declare module.exports: any;
}
declare module 'tcomb/lib/Error' {
declare module.exports: any;
}
declare module 'tcomb/lib/extend' {
declare module.exports: any;
}
declare module 'tcomb/lib/fail' {
declare module.exports: any;
}
declare module 'tcomb/lib/forbidNewOperator' {
declare module.exports: any;
}
declare module 'tcomb/lib/fromJSON' {
declare module.exports: any;
}
declare module 'tcomb/lib/func' {
declare module.exports: any;
}
declare module 'tcomb/lib/Function' {
declare module.exports: any;
}
declare module 'tcomb/lib/getDefaultInterfaceName' {
declare module.exports: any;
}
declare module 'tcomb/lib/getFunctionName' {
declare module.exports: any;
}
declare module 'tcomb/lib/getTypeName' {
declare module.exports: any;
}
declare module 'tcomb/lib/installTypeFormatter' {
declare module.exports: any;
}
declare module 'tcomb/lib/Integer' {
declare module.exports: any;
}
declare module 'tcomb/lib/interface' {
declare module.exports: any;
}
declare module 'tcomb/lib/intersection' {
declare module.exports: any;
}
declare module 'tcomb/lib/irreducible' {
declare module.exports: any;
}
declare module 'tcomb/lib/is' {
declare module.exports: any;
}
declare module 'tcomb/lib/isArray' {
declare module.exports: any;
}
declare module 'tcomb/lib/isBoolean' {
declare module.exports: any;
}
declare module 'tcomb/lib/isFunction' {
declare module.exports: any;
}
declare module 'tcomb/lib/isIdentity' {
declare module.exports: any;
}
declare module 'tcomb/lib/isInterface' {
declare module.exports: any;
}
declare module 'tcomb/lib/isMaybe' {
declare module.exports: any;
}
declare module 'tcomb/lib/isNil' {
declare module.exports: any;
}
declare module 'tcomb/lib/isNumber' {
declare module.exports: any;
}
declare module 'tcomb/lib/isObject' {
declare module.exports: any;
}
declare module 'tcomb/lib/isString' {
declare module.exports: any;
}
declare module 'tcomb/lib/isStruct' {
declare module.exports: any;
}
declare module 'tcomb/lib/isSubsetOf' {
declare module.exports: any;
}
declare module 'tcomb/lib/isType' {
declare module.exports: any;
}
declare module 'tcomb/lib/isTypeName' {
declare module.exports: any;
}
declare module 'tcomb/lib/isUnion' {
declare module.exports: any;
}
declare module 'tcomb/lib/list' {
declare module.exports: any;
}
declare module 'tcomb/lib/match' {
declare module.exports: any;
}
declare module 'tcomb/lib/maybe' {
declare module.exports: any;
}
declare module 'tcomb/lib/mixin' {
declare module.exports: any;
}
declare module 'tcomb/lib/Nil' {
declare module.exports: any;
}
declare module 'tcomb/lib/Number' {
declare module.exports: any;
}
declare module 'tcomb/lib/Object' {
declare module.exports: any;
}
declare module 'tcomb/lib/refinement' {
declare module.exports: any;
}
declare module 'tcomb/lib/RegExp' {
declare module.exports: any;
}
declare module 'tcomb/lib/String' {
declare module.exports: any;
}
declare module 'tcomb/lib/stringify' {
declare module.exports: any;
}
declare module 'tcomb/lib/struct' {
declare module.exports: any;
}
declare module 'tcomb/lib/tuple' {
declare module.exports: any;
}
declare module 'tcomb/lib/Type' {
declare module.exports: any;
}
declare module 'tcomb/lib/union' {
declare module.exports: any;
}
declare module 'tcomb/lib/update' {
declare module.exports: any;
}
// Filename aliases
declare module 'tcomb/index' {
declare module.exports: $Exports<'tcomb'>;
}
declare module 'tcomb/index.js' {
declare module.exports: $Exports<'tcomb'>;
}
declare module 'tcomb/lib/Any.js' {
declare module.exports: $Exports<'tcomb/lib/Any'>;
}
declare module 'tcomb/lib/Array.js' {
declare module.exports: $Exports<'tcomb/lib/Array'>;
}
declare module 'tcomb/lib/assert.js' {
declare module.exports: $Exports<'tcomb/lib/assert'>;
}
declare module 'tcomb/lib/assign.js' {
declare module.exports: $Exports<'tcomb/lib/assign'>;
}
declare module 'tcomb/lib/Boolean.js' {
declare module.exports: $Exports<'tcomb/lib/Boolean'>;
}
declare module 'tcomb/lib/create.js' {
declare module.exports: $Exports<'tcomb/lib/create'>;
}
declare module 'tcomb/lib/Date.js' {
declare module.exports: $Exports<'tcomb/lib/Date'>;
}
declare module 'tcomb/lib/declare.js' {
declare module.exports: $Exports<'tcomb/lib/declare'>;
}
declare module 'tcomb/lib/decompose.js' {
declare module.exports: $Exports<'tcomb/lib/decompose'>;
}
declare module 'tcomb/lib/dict.js' {
declare module.exports: $Exports<'tcomb/lib/dict'>;
}
declare module 'tcomb/lib/enums.js' {
declare module.exports: $Exports<'tcomb/lib/enums'>;
}
declare module 'tcomb/lib/Error.js' {
declare module.exports: $Exports<'tcomb/lib/Error'>;
}
declare module 'tcomb/lib/extend.js' {
declare module.exports: $Exports<'tcomb/lib/extend'>;
}
declare module 'tcomb/lib/fail.js' {
declare module.exports: $Exports<'tcomb/lib/fail'>;
}
declare module 'tcomb/lib/forbidNewOperator.js' {
declare module.exports: $Exports<'tcomb/lib/forbidNewOperator'>;
}
declare module 'tcomb/lib/fromJSON.js' {
declare module.exports: $Exports<'tcomb/lib/fromJSON'>;
}
declare module 'tcomb/lib/func.js' {
declare module.exports: $Exports<'tcomb/lib/func'>;
}
declare module 'tcomb/lib/Function.js' {
declare module.exports: $Exports<'tcomb/lib/Function'>;
}
declare module 'tcomb/lib/getDefaultInterfaceName.js' {
declare module.exports: $Exports<'tcomb/lib/getDefaultInterfaceName'>;
}
declare module 'tcomb/lib/getFunctionName.js' {
declare module.exports: $Exports<'tcomb/lib/getFunctionName'>;
}
declare module 'tcomb/lib/getTypeName.js' {
declare module.exports: $Exports<'tcomb/lib/getTypeName'>;
}
declare module 'tcomb/lib/installTypeFormatter.js' {
declare module.exports: $Exports<'tcomb/lib/installTypeFormatter'>;
}
declare module 'tcomb/lib/Integer.js' {
declare module.exports: $Exports<'tcomb/lib/Integer'>;
}
declare module 'tcomb/lib/interface.js' {
declare module.exports: $Exports<'tcomb/lib/interface'>;
}
declare module 'tcomb/lib/intersection.js' {
declare module.exports: $Exports<'tcomb/lib/intersection'>;
}
declare module 'tcomb/lib/irreducible.js' {
declare module.exports: $Exports<'tcomb/lib/irreducible'>;
}
declare module 'tcomb/lib/is.js' {
declare module.exports: $Exports<'tcomb/lib/is'>;
}
declare module 'tcomb/lib/isArray.js' {
declare module.exports: $Exports<'tcomb/lib/isArray'>;
}
declare module 'tcomb/lib/isBoolean.js' {
declare module.exports: $Exports<'tcomb/lib/isBoolean'>;
}
declare module 'tcomb/lib/isFunction.js' {
declare module.exports: $Exports<'tcomb/lib/isFunction'>;
}
declare module 'tcomb/lib/isIdentity.js' {
declare module.exports: $Exports<'tcomb/lib/isIdentity'>;
}
declare module 'tcomb/lib/isInterface.js' {
declare module.exports: $Exports<'tcomb/lib/isInterface'>;
}
declare module 'tcomb/lib/isMaybe.js' {
declare module.exports: $Exports<'tcomb/lib/isMaybe'>;
}
declare module 'tcomb/lib/isNil.js' {
declare module.exports: $Exports<'tcomb/lib/isNil'>;
}
declare module 'tcomb/lib/isNumber.js' {
declare module.exports: $Exports<'tcomb/lib/isNumber'>;
}
declare module 'tcomb/lib/isObject.js' {
declare module.exports: $Exports<'tcomb/lib/isObject'>;
}
declare module 'tcomb/lib/isString.js' {
declare module.exports: $Exports<'tcomb/lib/isString'>;
}
declare module 'tcomb/lib/isStruct.js' {
declare module.exports: $Exports<'tcomb/lib/isStruct'>;
}
declare module 'tcomb/lib/isSubsetOf.js' {
declare module.exports: $Exports<'tcomb/lib/isSubsetOf'>;
}
declare module 'tcomb/lib/isType.js' {
declare module.exports: $Exports<'tcomb/lib/isType'>;
}
declare module 'tcomb/lib/isTypeName.js' {
declare module.exports: $Exports<'tcomb/lib/isTypeName'>;
}
declare module 'tcomb/lib/isUnion.js' {
declare module.exports: $Exports<'tcomb/lib/isUnion'>;
}
declare module 'tcomb/lib/list.js' {
declare module.exports: $Exports<'tcomb/lib/list'>;
}
declare module 'tcomb/lib/match.js' {
declare module.exports: $Exports<'tcomb/lib/match'>;
}
declare module 'tcomb/lib/maybe.js' {
declare module.exports: $Exports<'tcomb/lib/maybe'>;
}
declare module 'tcomb/lib/mixin.js' {
declare module.exports: $Exports<'tcomb/lib/mixin'>;
}
declare module 'tcomb/lib/Nil.js' {
declare module.exports: $Exports<'tcomb/lib/Nil'>;
}
declare module 'tcomb/lib/Number.js' {
declare module.exports: $Exports<'tcomb/lib/Number'>;
}
declare module 'tcomb/lib/Object.js' {
declare module.exports: $Exports<'tcomb/lib/Object'>;
}
declare module 'tcomb/lib/refinement.js' {
declare module.exports: $Exports<'tcomb/lib/refinement'>;
}
declare module 'tcomb/lib/RegExp.js' {
declare module.exports: $Exports<'tcomb/lib/RegExp'>;
}
declare module 'tcomb/lib/String.js' {
declare module.exports: $Exports<'tcomb/lib/String'>;
}
declare module 'tcomb/lib/stringify.js' {
declare module.exports: $Exports<'tcomb/lib/stringify'>;
}
declare module 'tcomb/lib/struct.js' {
declare module.exports: $Exports<'tcomb/lib/struct'>;
}
declare module 'tcomb/lib/tuple.js' {
declare module.exports: $Exports<'tcomb/lib/tuple'>;
}
declare module 'tcomb/lib/Type.js' {
declare module.exports: $Exports<'tcomb/lib/Type'>;
}
declare module 'tcomb/lib/union.js' {
declare module.exports: $Exports<'tcomb/lib/union'>;
}
declare module 'tcomb/lib/update.js' {
declare module.exports: $Exports<'tcomb/lib/update'>;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.