code
stringlengths 2
1.05M
|
---|
/*
* mobile table unit tests
*/
(function($){
module( "Basic Table", {
setup: function(){
var hash = "#basic-table-test";
if( location.hash != hash ){
stop();
$(document).one("pagechange", function() {
start();
});
$.mobile.changePage( hash );
}
},
teardown: function() {
}
});
asyncTest( "The page should be enhanced correctly" , function(){
setTimeout(function() {
var $table = $('#basic-table-test .ui-table');
ok( $table.length, ".ui-table class added to table element" );
start();
}, 800);
});
asyncTest( "Has data object attributed to table" , function(){
setTimeout(function(){
var $table = $('#basic-table-test .ui-table'),
self = $table.data( "mobile-table" );
ok( self , "Data object is available" );
start();
}, 800);
});
asyncTest( "Has headers option" , function(){
setTimeout(function() {
var $table = $('#basic-table-test .ui-table'),
self = $table.data( "mobile-table" );
ok( self.headers.length , "Header array is not empty");
equal( 5 , self.headers.length , "Number of headers is correct");
start();
}, 800);
});
module( "Reflow Mode", {
setup: function(){
var hash = "#reflow-table-test";
if( location.hash != hash ){
stop();
$(document).one("pagechange", function() {
start();
});
$.mobile.changePage( hash );
}
},
teardown: function() {
}
});
asyncTest( "The page should be enhanced correctly" , function(){
setTimeout(function() {
ok($('#reflow-table-test .ui-table-reflow').length, ".ui-table-reflow class added to table element");
start();
}, 800);
});
asyncTest( "The appropriate label is added" , function(){
setTimeout(function(){
var $table = $( "#reflow-table-test table" ),
$body = $table.find( "tbody" ),
$tds = $body.find( "td" ),
labels = $tds.find( "b.ui-table-cell-label" );
ok( labels , "Appropriate label placed" );
equal( $( labels[0] ).text(), "Movie Title" , "Appropriate label placed" );
start();
}, 800);
});
module( "Column toggle table Mode", {
setup: function(){
var hash = "#column-table-test";
if( location.hash != hash ){
stop();
$(document).one("pagechange", function() {
start();
});
$.mobile.changePage( hash );
}
},
teardown: function() {
}
});
asyncTest( "The page should be enhanced correctly" , function(){
setTimeout(function() {
var $popup = $('#column-table-test #movie-table-column-popup-popup');
ok($('#column-table-test .ui-table-columntoggle').length, ".ui-table-columntoggle class added to table element");
ok($('#column-table-test .ui-table-columntoggle-btn').length, ".ui-table-columntoggle-btn button added");
equal($('#column-table-test .ui-table-columntoggle-btn').text(), "Columns...", "Column toggle button has correct text");
ok( $popup.length, "dialog added" );
ok( $popup.is( ".ui-popup-hidden" ) , "dialog hidden");
ok($('#column-table-test #movie-table-column-popup-popup').find( "input[type=checkbox]" ).length > 0 , "Checkboxes added");
start();
}, 800);
});
asyncTest( "The dialog should become visible when button is clicked" , function(){
expect( 2 );
var $input;
$.testHelper.pageSequence([
function() {
$( ".ui-table-columntoggle-btn" ).click();
},
function() {
setTimeout(function() {
ok( $( "#movie-table-column-popup-popup" ).not( ".ui-popup-hidden" ) , "Table popup is shown on click" );
}, 800);
},
function() {
$input = $( ".ui-popup-container" ).find( "input:first" );
$input.click();
},
function(){
setTimeout(function(){
var headers = $( "#column-table-test table tr" ).find( "th:first" );
if( $input.is( ":checked" ) ){
ok( headers.not( ".ui-table-cell-hidden" ) );
} else {
ok( headers.is( ".ui-table-cell-hidden" ) );
}
}, 800);
},
function() {
start();
}
]);
});
})(jQuery);
|
/**
* Why has this not been moved to e.g. @tryghost/events or shared yet?
*
* - We currently massively overuse this utility, coupling together bits of the codebase in unexpected ways
* - We want to prevent this, not reinforce it
* * Having an @tryghost/events or shared/events module would reinforce this bad patter of using the same event emitter everywhere
*
* - Ideally, we want to refactor to:
* - either remove dependence on events where we can
* - or have separate event emitters for e.g. model layer and routing layer
*
*/
const events = require('events');
const util = require('util');
let EventRegistry;
let EventRegistryInstance;
EventRegistry = function () {
events.EventEmitter.call(this);
};
util.inherits(EventRegistry, events.EventEmitter);
EventRegistryInstance = new EventRegistry();
EventRegistryInstance.setMaxListeners(100);
module.exports = EventRegistryInstance;
|
/*! jQuery UI - v1.9.2 - 2013-01-11
* http://jqueryui.com
* Includes: jquery.ui.datepicker-hy.js
* Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(e){e.datepicker.regional.hy={closeText:"Փակել",prevText:"<Նախ.",nextText:"Հաջ.>",currentText:"Այսօր",monthNames:["Հունվար","Փետրվար","Մարտ","Ապրիլ","Մայիս","Հունիս","Հուլիս","Օգոստոս","Սեպտեմբեր","Հոկտեմբեր","Նոյեմբեր","Դեկտեմբեր"],monthNamesShort:["Հունվ","Փետր","Մարտ","Ապր","Մայիս","Հունիս","Հուլ","Օգս","Սեպ","Հոկ","Նոյ","Դեկ"],dayNames:["կիրակի","եկուշաբթի","երեքշաբթի","չորեքշաբթի","հինգշաբթի","ուրբաթ","շաբաթ"],dayNamesShort:["կիր","երկ","երք","չրք","հնգ","ուրբ","շբթ"],dayNamesMin:["կիր","երկ","երք","չրք","հնգ","ուրբ","շբթ"],weekHeader:"ՇԲՏ",dateFormat:"dd.mm.yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional.hy)}); |
import PropTypes, { configStyleValidator, styleValidator } from './PropTypes'
import Box from './components/Box'
import Email from './components/Email'
import Image from './components/Image'
import Item from './components/Item'
import Span from './components/Span'
import A from './components/A'
import renderEmail from './renderEmail'
const DEV = typeof process !== 'undefined' && process.env && process.env.NODE_ENV !== 'production'
configStyleValidator({
warn: DEV,
})
export {
PropTypes,
Box,
Email,
Image,
Item,
Span,
A,
configStyleValidator,
renderEmail,
}
export default {
PropTypes,
configStyleValidator,
renderEmail,
styleValidator,
}
|
import ResourceProcessorBase from './resource-processor-base';
class ManifestProcessor extends ResourceProcessorBase {
processResource (manifest, ctx, charset, urlReplacer) {
var lines = manifest.split('\n');
for (var i = 0; i < lines.length; i++) {
var line = lines[i].trim();
if (line && line !== 'CACHE MANIFEST' && line !== 'NETWORK:' && line !== 'FALLBACK:' &&
line !== 'CACHE:' && line[0] !== '#' && line !== '*') {
var isFallbackItem = line.indexOf(' ') !== -1;
if (isFallbackItem) {
var urls = line.split(' ');
lines[i] = urlReplacer(urls[0]) + ' ' + urlReplacer(urls[1]);
}
else
lines[i] = urlReplacer(line);
}
}
return lines.join('\n');
}
shouldProcessResource (ctx) {
return ctx.contentInfo.isManifest;
}
}
export default new ManifestProcessor();
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'flash', 'fo', {
access: 'Script atgongd',
accessAlways: 'Altíð',
accessNever: 'Ongantíð',
accessSameDomain: 'Sama navnaøki',
alignAbsBottom: 'Abs botnur',
alignAbsMiddle: 'Abs miðja',
alignBaseline: 'Basislinja',
alignTextTop: 'Tekst toppur',
bgcolor: 'Bakgrundslitur',
chkFull: 'Loyv fullan skerm',
chkLoop: 'Endurspæl',
chkMenu: 'Ger Flash skrá virkna',
chkPlay: 'Avspælingin byrjar sjálv',
flashvars: 'Variablar fyri Flash',
hSpace: 'Høgri breddi',
properties: 'Flash eginleikar',
propertiesTab: 'Eginleikar',
quality: 'Góðska',
qualityAutoHigh: 'Auto høg',
qualityAutoLow: 'Auto Lág',
qualityBest: 'Besta',
qualityHigh: 'Høg',
qualityLow: 'Lág',
qualityMedium: 'Meðal',
scale: 'Skalering',
scaleAll: 'Vís alt',
scaleFit: 'Neyv skalering',
scaleNoBorder: 'Eingin bordi',
title: 'Flash eginleikar',
vSpace: 'Vinstri breddi',
validateHSpace: 'HSpace má vera eitt tal.',
validateSrc: 'Vinarliga skriva tilknýti (URL)',
validateVSpace: 'VSpace má vera eitt tal.',
windowMode: 'Slag av rúti',
windowModeOpaque: 'Ikki transparent',
windowModeTransparent: 'Transparent',
windowModeWindow: 'Rútur'
});
|
/**
* @ngdoc filter
* @name map
* @kind function
*
* @description
* Returns a new collection of the results of each expression execution.
*/
angular.module('a8m.map', [])
.filter('map', ['$parse', function($parse) {
return function (collection, expression) {
collection = (isObject(collection))
? toArray(collection)
: collection;
if(!isArray(collection) || isUndefined(expression)) {
return collection;
}
return collection.map(function (elm) {
return $parse(expression)(elm);
});
}
}]);
|
var successCount = 0;
for each (arg in args) {
if (process(arg)) {
successCount++;
}
}
write(successCount + " out of " + args.length + " benchmarks passed the test", "test.result");
exit();
function process(name) {
log = name + ".result";
s = "";
stgWork = import(name + ".g");
s += "Processing STG:\n";
s += " - importing: ";
if (stgWork == null) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
save(stgWork, name + ".stg.work");
s += " - verification: ";
if (checkStgCombined(stgWork) != true) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
s += " - CSC check: ";
if (checkStgCsc(stgWork) == true) {
cscStgWork = stgWork;
s += "OK\n";
} else {
s += "CONFLICT\n";
s += " - Conflict resolution: ";
cscStgWork = resolveCscConflictMpsat(stgWork);
if (cscStgWork == null) {
cscStgWork = resolveCscConflictPetrify(stgWork);
if (cscStgWork == null) {
s += "FAILED\n";
write(s, log);
return false;
}
}
s += "OK\n";
save(cscStgWork, name + "-csc.stg.work");
}
s += "Complex gate:\n";
s += " - synthesis: ";
cgCircuitWork = synthComplexGateMpsat(cscStgWork);
if (cgCircuitWork == null) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
s += " - verification: ";
if (checkCircuitCombined(cgCircuitWork) != true) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
s += "Generalised C-element:\n";
s += " - synthesis: ";
gcCircuitWork = synthGeneralisedCelementMpsat(cscStgWork);
if (gcCircuitWork == null) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
s += " - verification: ";
if (checkCircuitCombined(gcCircuitWork) != true) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
s += "Standard C-element:\n";
s += " - synthesis: ";
stdcCircuitWork = synthStandardCelementMpsat(cscStgWork);
if (stdcCircuitWork == null) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
s += " - verification: ";
if (checkCircuitCombined(stdcCircuitWork) != true) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
s += "Technology mapping:\n";
s += " - synthesis: ";
tmCircuitWork = synthTechnologyMappingMpsat(cscStgWork);
if (tmCircuitWork == null) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
s += " - verification: ";
if (checkCircuitCombined(tmCircuitWork) != true) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
write(s, log);
return true;
}
|
(function () {
var common;
this.setAsDefault = function () {
var _external = window.external;
if (_external && ('AddSearchProvider' in _external) && ('IsSearchProviderInstalled' in _external)) {
var isInstalled = 0;
try {
isInstalled = _external.IsSearchProviderInstalled('https://gusouk.com');
if (isInstalled > 0) {
alert("已添加过此搜索引擎");
}
} catch (err) {
isInstalled = 0;
}
console.log("isInstalled: " + isInstalled);
_external.AddSearchProvider('https://gusouk.com/opensearch.xml');
} else {
window.open('http://mlongbo.com/set_as_default_search_engine/');
}
return false;
};
/**
* 切换弹出框显示
* @param {[type]} id [弹出框元素id]
* @param {[type]} eventName [事件名称]
*/
this.swithPopver = function (id,eventName) {
var ele = document.getElementById(id);
if ((eventName && eventName === 'blur') || ele.style.display === 'block') {
ele.style.display = 'none';
} else {
ele.style.display = 'block';
}
};
})();
console.info("谷搜客基于Google搜索,为喜爱谷歌搜索的朋友们免费提供高速稳定的搜索服务。搜索结果通过Google.com实时抓取,欢迎您在日常生活学习中使用谷搜客查询资料。");
console.info("如果你觉得谷搜客对你有帮助,请资助(支付宝账号: [email protected])我一下,资金将用于支持我开发及购买服务器资源。^_^");
console.info("本站使用开源项目gso(https://github.com/lenbo-ma/gso)搭建");
console.info("希望能够让更多的获取知识,加油!"); |
define(
({
insertTableTitle: "Insertar tabla",
modifyTableTitle: "Modificar tabla",
rows: "Filas:",
columns: "Columnas:",
align: "Alinear:",
cellPadding: "Relleno de celda:",
cellSpacing: "Espaciado de celda:",
tableWidth: "Ancho de tabla:",
backgroundColor: "Color de fondo:",
borderColor: "Color de borde:",
borderThickness: "Grosor del borde:",
percent: "por ciento",
pixels: "píxeles",
"default": "default",
left: "izquierda",
center: "centro",
right: "derecha",
buttonSet: "Establecer", // translated elsewhere?
buttonInsert: "Insertar",
buttonCancel: "Cancelar",
selectTableLabel: "Seleccionar tabla",
insertTableRowBeforeLabel: "Añadir fila antes",
insertTableRowAfterLabel: "Añadir fila después",
insertTableColumnBeforeLabel: "Añadir columna antes",
insertTableColumnAfterLabel: "Añadir columna después",
deleteTableRowLabel: "Suprimir fila",
deleteTableColumnLabel: "Suprimir columna"
})
);
|
/* Copyright (c) 2015-2017 The Open Source Geospatial Foundation
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* A component that renders an `ol.Map` and that can be used in any ExtJS
* layout.
*
* An example: A map component rendered insiide of a panel:
*
* @example preview
* var mapComponent = Ext.create('GeoExt.component.Map', {
* map: new ol.Map({
* layers: [
* new ol.layer.Tile({
* source: new ol.source.OSM()
* })
* ],
* view: new ol.View({
* center: ol.proj.fromLonLat([-8.751278, 40.611368]),
* zoom: 12
* })
* })
* });
* var mapPanel = Ext.create('Ext.panel.Panel', {
* title: 'GeoExt.component.Map Example',
* height: 200,
* items: [mapComponent],
* renderTo: Ext.getBody()
* });
*
* @class GeoExt.component.Map
*/
Ext.define('GeoExt.component.Map', {
extend: 'Ext.Component',
alias: [
'widget.gx_map',
'widget.gx_component_map'
],
requires: [
'GeoExt.data.store.Layers',
'GeoExt.util.Version'
],
mixins: [
'GeoExt.mixin.SymbolCheck'
],
// <debug>
symbols: [
'ol.layer.Base',
'ol.Map',
'ol.Map#addLayer',
'ol.Map#getLayers',
'ol.Map#getSize',
'ol.Map#getView',
'ol.Map#removeLayer',
'ol.Map#setTarget',
'ol.Map#setView',
'ol.Map#updateSize',
'ol.View',
'ol.View#calculateExtent',
'ol.View#fit',
'ol.View#getCenter',
'ol.View#setCenter'
],
// </debug>
/**
* @event pointerrest
*
* Fires if the user has left the pointer for an amount
* of #pointerRestInterval milliseconds at the *same location*. Use the
* configuration #pointerRestPixelTolerance to configure how long a pixel is
* considered to be on the *same location*.
*
* Please note that this event will only fire if the map has #pointerRest
* configured with `true`.
*
* @param {ol.MapBrowserEvent} olEvt The original and most recent
* MapBrowserEvent event.
* @param {ol.Pixel} lastPixel The originally captured pixel, which defined
* the center of the tolerance bounds (itself configurable with the the
* configuration #pointerRestPixelTolerance). If this is null, a
* completely *new* pointerrest event just happened.
*/
/**
* @event pointerrestout
*
* Fires if the user first was resting his pointer on the map element, but
* then moved the pointer out of the map completely.
*
* Please note that this event will only fire if the map has #pointerRest
* configured with `true`.
*
* @param {ol.MapBrowserEvent} olEvt The MapBrowserEvent event.
*/
config: {
/**
* A configured map or a configuration object for the map constructor.
*
* @cfg {ol.Map} map
*/
map: null,
/**
* A boolean flag to control whether the map component will fire the
* events #pointerrest and #pointerrestout. If this is set to `false`
* (the default), no such events will be fired.
*
* @cfg {Boolean} pointerRest Whether the component shall provide the
* `pointerrest` and `pointerrestout` events.
*/
pointerRest: false,
/**
* The amount of milliseconds after which we will consider a rested
* pointer as `pointerrest`. Only relevant if #pointerRest is `true`.
*
* @cfg {Number} pointerRestInterval The interval in milliseconds.
*/
pointerRestInterval: 1000,
/**
* The amount of pixels that a pointer may move in both vertical and
* horizontal direction, and still be considered to be a #pointerrest.
* Only relevant if #pointerRest is `true`.
*
* @cfg {Number} pointerRestPixelTolerance The tolerance in pixels.
*/
pointerRestPixelTolerance: 3
},
/**
* Whether we already rendered an ol.Map in this component. Will be
* updated in #onResize, after the first rendering happened.
*
* @property {Boolean} mapRendered
* @private
*/
mapRendered: false,
/**
* @property {GeoExt.data.store.Layers} layerStore
* @private
*/
layerStore: null,
/**
* The location of the last mousemove which we track to be able to fire
* the #pointerrest event. Only usable if #pointerRest is `true`.
*
* @property {ol.Pixel} lastPointerPixel
* @private
*/
lastPointerPixel: null,
/**
* Whether the pointer is currently over the map component. Only usable if
* the configuration #pointerRest is `true`.
*
* @property {Boolean} isMouseOverMapEl
* @private
*/
isMouseOverMapEl: null,
/**
* @inheritdoc
*/
constructor: function(config) {
var me = this;
me.callParent([config]);
if (!(me.getMap() instanceof ol.Map)) {
var olMap = new ol.Map({
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
me.setMap(olMap);
}
me.layerStore = Ext.create('GeoExt.data.store.Layers', {
storeId: me.getId() + '-store',
map: me.getMap()
});
me.on('resize', me.onResize, me);
},
/**
* (Re-)render the map when size changes.
*/
onResize: function() {
// Get the corresponding view of the controller (the mapComponent).
var me = this;
if (!me.mapRendered) {
var el = me.getTargetEl ? me.getTargetEl() : me.element;
me.getMap().setTarget(el.dom);
me.mapRendered = true;
} else {
me.getMap().updateSize();
}
},
/**
* Will contain a buffered version of #unbufferedPointerMove, but only if
* the configuration #pointerRest is true.
*
* @private
*/
bufferedPointerMove: Ext.emptyFn,
/**
* Bound as a eventlistener for pointermove on the OpenLayers map, but only
* if the configuration #pointerRest is true. Will eventually fire the
* special events #pointerrest or #pointerrestout.
*
* @param {ol.MapBrowserEvent} olEvt The MapBrowserEvent event.
* @private
*/
unbufferedPointerMove: function(olEvt) {
var me = this;
var tolerance = me.getPointerRestPixelTolerance();
var pixel = olEvt.pixel;
if (!me.isMouseOverMapEl) {
me.fireEvent('pointerrestout', olEvt);
return;
}
if (me.lastPointerPixel) {
var deltaX = Math.abs(me.lastPointerPixel[0] - pixel[0]);
var deltaY = Math.abs(me.lastPointerPixel[1] - pixel[1]);
if (deltaX > tolerance || deltaY > tolerance) {
me.lastPointerPixel = pixel;
} else {
// fire pointerrest, and include the original pointer pixel
me.fireEvent('pointerrest', olEvt, me.lastPointerPixel);
return;
}
} else {
me.lastPointerPixel = pixel;
}
// a new pointerrest event, the second argument (the 'original' pointer
// pixel) must be null, as we start from a totally new position
me.fireEvent('pointerrest', olEvt, null);
},
/**
* Creates #bufferedPointerMove from #unbufferedPointerMove and binds it
* to `pointermove` on the OpenLayers map.
*
* @private
*/
registerPointerRestEvents: function() {
var me = this;
var map = me.getMap();
if (me.bufferedPointerMove === Ext.emptyFn) {
me.bufferedPointerMove = Ext.Function.createBuffered(
me.unbufferedPointerMove,
me.getPointerRestInterval(),
me
);
}
// Check if we have to fire any pointer* events
map.on('pointermove', me.bufferedPointerMove);
if (!me.rendered) {
// make sure we do not fire any if the pointer left the component
me.on('afterrender', me.bindOverOutListeners, me);
} else {
me.bindOverOutListeners();
}
},
/**
* Registers listeners that'll take care of setting #isMouseOverMapEl to
* correct values.
*
* @private
*/
bindOverOutListeners: function() {
var me = this;
var mapEl = me.getTargetEl ? me.getTargetEl() : me.element;
if (mapEl) {
mapEl.on({
mouseover: me.onMouseOver,
mouseout: me.onMouseOut,
scope: me
});
}
},
/**
* Unregisters listeners that'll take care of setting #isMouseOverMapEl to
* correct values.
*
* @private
*/
unbindOverOutListeners: function() {
var me = this;
var mapEl = me.getTargetEl ? me.getTargetEl() : me.element;
if (mapEl) {
mapEl.un({
mouseover: me.onMouseOver,
mouseout: me.onMouseOut,
scope: me
});
}
},
/**
* Sets isMouseOverMapEl to true, see #pointerRest.
*
* @private
*/
onMouseOver: function() {
this.isMouseOverMapEl = true;
},
/**
* Sets isMouseOverMapEl to false, see #pointerRest.
*
* @private
*/
onMouseOut: function() {
this.isMouseOverMapEl = false;
},
/**
* Unregisters the #bufferedPointerMove event listener and unbinds the
* over- and out-listeners.
*/
unregisterPointerRestEvents: function() {
var me = this;
var map = me.getMap();
me.unbindOverOutListeners();
if (map) {
map.un('pointermove', me.bufferedPointerMove);
}
me.bufferedPointerMove = Ext.emptyFn;
},
/**
* Whenever the value of #pointerRest is changed, this method will take
* care of registering or unregistering internal event listeners.
*
* @param {Boolean} val The new value that someone set for `pointerRest`.
* @return {Boolean} The passed new value for `pointerRest` unchanged.
*/
applyPointerRest: function(val) {
if (val) {
this.registerPointerRestEvents();
} else {
this.unregisterPointerRestEvents();
}
return val;
},
/**
* Whenever the value of #pointerRestInterval is changed, this method will
* take to reinitialize the #bufferedPointerMove method and handlers to
* actually trigger the event.
*
* @param {Boolean} val The new value that someone set for
* `pointerRestInterval`.
* @return {Boolean} The passed new value for `pointerRestInterval`
* unchanged.
*/
applyPointerRestInterval: function(val) {
var me = this;
var isEnabled = me.getPointerRest();
if (isEnabled) {
// Toggle to rebuild the buffered pointer move.
me.setPointerRest(false);
me.setPointerRest(isEnabled);
}
return val;
},
/**
* Returns the center coordinate of the view.
*
* @return {ol.Coordinate} The center of the map view as `ol.Coordinate`.
*/
getCenter: function() {
return this.getMap().getView().getCenter();
},
/**
* Set the center of the view.
*
* @param {ol.Coordinate} center The new center as `ol.Coordinate`.
*/
setCenter: function(center) {
this.getMap().getView().setCenter(center);
},
/**
* Returns the extent of the current view.
*
* @return {ol.Extent} The extent of the map view as `ol.Extent`.
*/
getExtent: function() {
return this.getView().calculateExtent(this.getMap().getSize());
},
/**
* Set the extent of the view.
*
* @param {ol.Extent} extent The extent as `ol.Extent`.
*/
setExtent: function(extent) {
// Check for backwards compatibility
if (GeoExt.util.Version.isOl3()) {
this.getView().fit(extent, this.getMap().getSize());
} else {
this.getView().fit(extent);
}
},
/**
* Returns the layers of the map.
*
* @return {ol.Collection} The layer collection.
*/
getLayers: function() {
return this.getMap().getLayers();
},
/**
* Add a layer to the map.
*
* @param {ol.layer.Base} layer The layer to add.
*/
addLayer: function(layer) {
if (layer instanceof ol.layer.Base) {
this.getMap().addLayer(layer);
} else {
Ext.Error.raise('Can not add layer ' + layer + ' as it is not ' +
'an instance of ol.layer.Base');
}
},
/**
* Remove a layer from the map.
*
* @param {ol.layer.Base} layer The layer to remove.
*/
removeLayer: function(layer) {
if (layer instanceof ol.layer.Base) {
if (Ext.Array.contains(this.getLayers().getArray(), layer)) {
this.getMap().removeLayer(layer);
}
} else {
Ext.Error.raise('Can not remove layer ' + layer + ' as it is not ' +
'an instance of ol.layer.Base');
}
},
/**
* Returns the `GeoExt.data.store.Layers`.
*
* @return {GeoExt.data.store.Layers} The layer store.
*/
getStore: function() {
return this.layerStore;
},
/**
* Returns the view of the map.
*
* @return {ol.View} The `ol.View` of the map.
*/
getView: function() {
return this.getMap().getView();
},
/**
* Set the view of the map.
*
* @param {ol.View} view The `ol.View` to use for the map.
*/
setView: function(view) {
this.getMap().setView(view);
}
});
|
/* @flow */
export default function extractSupportQuery(ruleSet: string): string {
return ruleSet
.split('{')[0]
.slice(9)
.trim()
}
|
// ## Globals
var argv = require('minimist')(process.argv.slice(2));
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();
var changed = require('gulp-changed');
var concat = require('gulp-concat');
var flatten = require('gulp-flatten');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var lazypipe = require('lazypipe');
var less = require('gulp-less');
var merge = require('merge-stream');
var minifyCss = require('gulp-minify-css');
var plumber = require('gulp-plumber');
var rev = require('gulp-rev');
var runSequence = require('run-sequence');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
// See https://github.com/austinpray/asset-builder
var manifest = require('asset-builder')('./assets/manifest.json');
// `path` - Paths to base asset directories. With trailing slashes.
// - `path.source` - Path to the source files. Default: `assets/`
// - `path.dist` - Path to the build directory. Default: `dist/`
var path = manifest.paths;
// `config` - Store arbitrary configuration values here.
var config = manifest.config || {};
// `globs` - These ultimately end up in their respective `gulp.src`.
// - `globs.js` - Array of asset-builder JS dependency objects. Example:
// ```
// {type: 'js', name: 'main.js', globs: []}
// ```
// - `globs.css` - Array of asset-builder CSS dependency objects. Example:
// ```
// {type: 'css', name: 'main.css', globs: []}
// ```
// - `globs.fonts` - Array of font path globs.
// - `globs.images` - Array of image path globs.
// - `globs.bower` - Array of all the main Bower files.
var globs = manifest.globs;
// `project` - paths to first-party assets.
// - `project.js` - Array of first-party JS assets.
// - `project.css` - Array of first-party CSS assets.
var project = manifest.getProjectGlobs();
// CLI options
var enabled = {
// Enable static asset revisioning when `--production`
rev: argv.production,
// Disable source maps when `--production`
maps: !argv.production,
// Fail styles task on error when `--production`
failStyleTask: argv.production,
// Fail due to JSHint warnings only when `--production`
failJSHint: argv.production,
// Strip debug statments from javascript when `--production`
stripJSDebug: argv.production
};
// Path to the compiled assets manifest in the dist directory
var revManifest = path.dist + 'assets.json';
// ## Reusable Pipelines
// See https://github.com/OverZealous/lazypipe
// ### CSS processing pipeline
// Example
// ```
// gulp.src(cssFiles)
// .pipe(cssTasks('main.css')
// .pipe(gulp.dest(path.dist + 'styles'))
// ```
var cssTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(!enabled.failStyleTask, plumber());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
.pipe(function() {
return gulpif('*.scss', sass({
outputStyle: 'nested', // libsass doesn't support expanded yet
precision: 10,
includePaths: ['.'],
errLogToConsole: !enabled.failStyleTask
}));
})
.pipe(concat, filename)
.pipe(autoprefixer, {
browsers: [
'last 2 versions',
'ie 8',
'ie 9',
'android 2.3',
'android 4',
'opera 12'
]
})
.pipe(minifyCss, {
advanced: false,
rebase: false
})
.pipe(function() {
return gulpif(enabled.rev, rev());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.write('.', {
sourceRoot: 'assets/styles/'
}));
})();
};
// ### JS processing pipeline
// Example
// ```
// gulp.src(jsFiles)
// .pipe(jsTasks('main.js')
// .pipe(gulp.dest(path.dist + 'scripts'))
// ```
var jsTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
.pipe(concat, filename)
.pipe(uglify, {
compress: {
'drop_debugger': enabled.stripJSDebug
}
})
.pipe(function() {
return gulpif(enabled.rev, rev());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.write('.', {
sourceRoot: 'assets/scripts/'
}));
})();
};
// ### Write to rev manifest
// If there are any revved files then write them to the rev manifest.
// See https://github.com/sindresorhus/gulp-rev
var writeToManifest = function(directory) {
return lazypipe()
.pipe(gulp.dest, path.dist + directory)
.pipe(browserSync.stream, {match: '**/*.{js,css}'})
.pipe(rev.manifest, revManifest, {
base: path.dist,
merge: true
})
.pipe(gulp.dest, path.dist)();
};
// ## Gulp tasks
// Run `gulp -T` for a task summary
// ### Styles
// `gulp styles` - Compiles, combines, and optimizes Bower CSS and project CSS.
// By default this task will only log a warning if a precompiler error is
// raised. If the `--production` flag is set: this task will fail outright.
gulp.task('styles', ['wiredep'], function() {
var merged = merge();
manifest.forEachDependency('css', function(dep) {
var cssTasksInstance = cssTasks(dep.name);
if (!enabled.failStyleTask) {
cssTasksInstance.on('error', function(err) {
console.error(err.message);
this.emit('end');
});
}
merged.add(gulp.src(dep.globs, {base: 'styles'})
.pipe(cssTasksInstance));
});
return merged
.pipe(writeToManifest('styles'));
});
// ### Scripts
// `gulp scripts` - Runs JSHint then compiles, combines, and optimizes Bower JS
// and project JS.
gulp.task('scripts', ['jshint'], function() {
var merged = merge();
manifest.forEachDependency('js', function(dep) {
merged.add(
gulp.src(dep.globs, {base: 'scripts'})
.pipe(jsTasks(dep.name))
);
});
return merged
.pipe(writeToManifest('scripts'));
});
// ### Fonts
// `gulp fonts` - Grabs all the fonts and outputs them in a flattened directory
// structure. See: https://github.com/armed/gulp-flatten
gulp.task('fonts', function() {
return gulp.src(globs.fonts)
.pipe(flatten())
.pipe(gulp.dest(path.dist + 'fonts'))
.pipe(browserSync.stream());
});
// ### Images
// `gulp images` - Run lossless compression on all the images.
gulp.task('images', function() {
return gulp.src(globs.images)
.pipe(imagemin({
progressive: true,
interlaced: true,
svgoPlugins: [{removeUnknownsAndDefaults: false}, {cleanupIDs: false}]
}))
.pipe(gulp.dest(path.dist + 'images'))
.pipe(browserSync.stream());
});
// ### JSHint
// `gulp jshint` - Lints configuration JSON and project JS.
gulp.task('jshint', function() {
return gulp.src([
'bower.json', 'gulpfile.js'
].concat(project.js))
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(gulpif(enabled.failJSHint, jshint.reporter('fail')));
});
// ### Clean
// `gulp clean` - Deletes the build folder entirely.
gulp.task('clean', require('del').bind(null, [path.dist]));
// ### Watch
// `gulp watch` - Use BrowserSync to proxy your dev server and synchronize code
// changes across devices. Specify the hostname of your dev server at
// `manifest.config.devUrl`. When a modification is made to an asset, run the
// build step for that asset and inject the changes into the page.
// See: http://www.browsersync.io
gulp.task('watch', function() {
browserSync.init({
files: ['{lib,templates}/**/*.php', '*.php'],
proxy: config.devUrl,
snippetOptions: {
whitelist: ['/wp-admin/admin-ajax.php'],
blacklist: ['/wp-admin/**']
}
});
gulp.watch([path.source + 'styles/**/*'], ['styles']);
gulp.watch([path.source + 'scripts/**/*'], ['jshint', 'scripts']);
gulp.watch([path.source + 'fonts/**/*'], ['fonts']);
gulp.watch([path.source + 'images/**/*'], ['images']);
gulp.watch(['bower.json', 'assets/manifest.json'], ['build']);
});
// ### Build
// `gulp build` - Run all the build tasks but don't clean up beforehand.
// Generally you should be running `gulp` instead of `gulp build`.
gulp.task('build', function(callback) {
runSequence('styles',
'scripts',
['fonts', 'images'],
callback);
});
// ### Wiredep
// `gulp wiredep` - Automatically inject Less and Sass Bower dependencies. See
// https://github.com/taptapship/wiredep
gulp.task('wiredep', function() {
var wiredep = require('wiredep').stream;
return gulp.src(project.css)
.pipe(wiredep())
.pipe(changed(path.source + 'styles', {
hasChanged: changed.compareSha1Digest
}))
.pipe(gulp.dest(path.source + 'styles'));
});
// ### Gulp
// `gulp` - Run a complete build. To compile for production run `gulp --production`.
gulp.task('default', ['clean'], function() {
gulp.start('build');
});
|
import {
moduleForComponent,
test
} from 'ember-qunit';
moduleForComponent('daterange-picker', 'DaterangePickerComponent', {
// specify the other units that are required for this test
// needs: ['component:foo', 'helper:bar']
});
test('it renders', function() {
expect(2);
// creates the component instance
var component = this.subject();
equal(component._state, 'preRender');
// appends the component to the page
this.append();
equal(component._state, 'inDOM');
});
|
/* Get Programming with JavaScript
* Listing 4.02
* Displaying information from similar objects
*/
var movie1;
var movie2;
var movie3;
movie1 = {
title: "Inside Out",
actors: "Amy Poehler, Bill Hader",
directors: "Pete Doctor, Ronaldo Del Carmen"
};
movie2 = {
title: "Spectre",
actors: "Daniel Craig, Christoph Waltz",
directors: "Sam Mendes"
};
movie3 = {
title: "Star Wars: Episode VII - The Force Awakens",
actors: "Harrison Ford, Mark Hamill, Carrie Fisher",
directors: "J.J.Abrams"
};
console.log("Movie information for " + movie1.title);
console.log("------------------------------");
console.log("Actors: " + movie1.actors);
console.log("Directors: " + movie1.directors);
console.log("------------------------------");
console.log("Movie information for " + movie2.title);
console.log("------------------------------");
console.log("Actors: " + movie2.actors);
console.log("Directors: " + movie2.directors);
console.log("------------------------------");
console.log("Movie information for " + movie3.title);
console.log("------------------------------");
console.log("Actors: " + movie3.actors);
console.log("Directors: " + movie3.directors);
console.log("------------------------------");
/* Further Adventures
*
* 1) Add a fourth movie and display its info
*
* 2) All the movie info is in one big block on the console.
* Change the code to space out the different movies.
*
* 3) Create objects to represent three calendar events
*
* 4) Display info from the three events on the console.
*
*/
|
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _blacklist = require('blacklist');
var _blacklist2 = _interopRequireDefault(_blacklist);
var _classnames = require('classnames');
var _classnames2 = _interopRequireDefault(_classnames);
var _constants = require('../constants');
var _constants2 = _interopRequireDefault(_constants);
module.exports = _react2['default'].createClass({
displayName: 'Row',
propTypes: {
children: _react2['default'].PropTypes.node.isRequired,
className: _react2['default'].PropTypes.string,
gutter: _react2['default'].PropTypes.number,
style: _react2['default'].PropTypes.object
},
getDefaultProps: function getDefaultProps() {
return {
gutter: _constants2['default'].width.gutter
};
},
render: function render() {
var gutter = this.props.gutter;
var rowStyle = {
display: 'flex',
flexWrap: 'wrap',
msFlexWrap: 'wrap',
WebkitFlexWrap: 'wrap',
marginLeft: gutter / -2,
marginRight: gutter / -2
};
var className = (0, _classnames2['default'])('Row', this.props.className);
var props = (0, _blacklist2['default'])(this.props, 'className', 'gutter', 'style');
return _react2['default'].createElement('div', _extends({}, props, { style: _extends(rowStyle, this.props.style), className: className }));
}
}); |
version https://git-lfs.github.com/spec/v1
oid sha256:ba35426ce7731b677aeb9fca46043dc31d9cd6a87abedb15382e4c3bc001b548
size 1760
|
// SocketStream 0.3
// ----------------
'use strict';
// console.log('CHECK');
// console.log(process.env);
// console.log('/CHECK');
require('colors');
var EventEmitter2 = require('eventemitter2').EventEmitter2;
// Get current version from package.json
var version = exports.version = require('./utils/file').loadPackageJSON().version;
// Set root path of your project
var root = exports.root = process.cwd().replace(/\\/g, '/'); // replace '\' with '/' to support Windows
// Warn if attempting to start without a cwd (e.g. through upstart script)
if (root === '/') {
throw new Error('You must change into the project directory before starting your SocketStream app');
}
// Set environment
// console.log("SS ENV IS ", process.env['SS_ENV']);
var env = exports.env = (process.env['NODE_ENV'] || process.env['SS_ENV'] || 'development').toLowerCase();
// Session & Session Store
var session = exports.session = require('./session');
// logging
var log = require('./utils/log');
// Create an internal API object which is passed to sub-modules and can be used within your app
var api = exports.api = {
version: version,
root: root,
env: env,
log: log,
session: session,
// Call ss.api.add('name_of_api', value_or_function) from your app to safely extend the 'ss' internal API object passed through to your /server code
add: function(name, fn) {
if (api[name]) {
throw new Error('Unable to register internal API extension \'' + name + '\' as this name has already been taken');
} else {
api[name] = fn;
return true;
}
}
};
// Create internal Events bus
// Note: only used by the ss-console module for now. This idea will be expended upon in SocketStream 0.4
var events = exports.events = new EventEmitter2();
// Publish Events
var publish = exports.publish = require('./publish/index')();
// HTTP
var http = exports.http = require('./http/index')(root);
// Client Asset Manager
var client = exports.client = require('./client/index')(api, http.router);
// Allow other libs to send assets to the client
api.client = {send: client.assets.send};
// Incoming Request Responders
var responders = exports.responders = require('./request/index')(api);
// Websocket Layer (transport, message responders, transmit incoming events)
var ws = exports.ws = require('./websocket/index')(api, responders);
// Only one instance of the server can be started at once
var serverInstance = null;
// Public API
var start = function(httpServer) {
var responder, fn, sessionID, id,
// Load SocketStream server instance
server = {
responders: responders.load(),
eventTransport: publish.transport.load(),
sessionStore: session.store.get()
};
// Extend the internal API with a publish object you can call from your own server-side code
api.publish = publish.api(server.eventTransport);
// Start web stack
if (httpServer) {
api.log.info('Starting SocketStream %s in %s mode...'.green, version, env);
// Bind responders to websocket
ws.load(httpServer, server.responders, server.eventTransport);
// Append SocketStream middleware to stack
http.load(client.options.dirs['static'], server.sessionStore, session.options);
// Load Client Asset Manager
client.load(api);
// Send server instance to any registered modules (e.g. console)
events.emit('server:start', server);
// If no HTTP server is passed return an API to allow for server-side testing
// Note this feature is currently considered 'experimental' and the implementation will
// be changed in SocketStream 0.4 to ensure any type of Request Responder can be tested
} else {
sessionID = session.create();
for (id in server.responders) {
if (server.responders.hasOwnProperty(id)) {
responder = server.responders[id];
if (responder.name && responder.interfaces.internal) {
fn = function(){
var args = Array.prototype.slice.call(arguments),
cb = args.pop();
return responder.interfaces.internal(args, {sessionId: sessionID, transport: 'test'}, function(err, params){ cb(params); });
};
api.add(responder.name, fn);
}
}
}
}
return api;
};
// Ensure server can only be started once
exports.start = function(httpServer) {
return serverInstance || (serverInstance = start(httpServer));
};
|
"use strict";
exports.__esModule = true;
exports["default"] = isDate;
function isDate(value) {
return value instanceof Date && !isNaN(+value);
}
//# sourceMappingURL=isDate.js.map
module.exports = exports["default"];
//# sourceMappingURL=isDate.js.map |
/**
* # wrap/modernizr
*
* Wrap global instance for use in RequireJS modules
*
* > http://draeton.github.io/stitches<br/>
* > Copyright 2013 Matthew Cobbs<br/>
* > Licensed under the MIT license.
*/
define(function () {
"use strict";
return Modernizr;
}); |
/*!
* Reference link dialog plugin for Editor.md
*
* @file reference-link-dialog.js
* @author pandao
* @version 1.2.1
* @updateTime 2015-06-09
* {@link https://github.com/pandao/editor.md}
* @license MIT
*/
(function () {
var factory = function (exports) {
var pluginName = "reference-link-dialog";
var ReLinkId = 1;
exports.fn.referenceLinkDialog = function () {
var _this = this;
var cm = this.cm;
var lang = this.lang;
var editor = this.editor;
var settings = this.settings;
var cursor = cm.getCursor();
var selection = cm.getSelection();
var dialogLang = lang.dialog.referenceLink;
var classPrefix = this.classPrefix;
var dialogName = classPrefix + pluginName, dialog;
cm.focus();
if (editor.find("." + dialogName).length < 1) {
var dialogHTML = "<div class=\"" + classPrefix + "form\">" +
"<label>" + dialogLang.name + "</label>" +
"<input type=\"text\" value=\"[" + ReLinkId + "]\" data-name />" +
"<br/>" +
"<label>" + dialogLang.urlId + "</label>" +
"<input type=\"text\" data-url-id />" +
"<br/>" +
"<label>" + dialogLang.url + "</label>" +
"<input type=\"text\" value=\"http://\" data-url />" +
"<br/>" +
"<label>" + dialogLang.urlTitle + "</label>" +
"<input type=\"text\" value=\"" + selection + "\" data-title />" +
"<br/>" +
"</div>";
dialog = this.createDialog({
name: dialogName,
title: dialogLang.title,
width: 380,
height: 296,
content: dialogHTML,
mask: settings.dialogShowMask,
drag: settings.dialogDraggable,
lockScreen: settings.dialogLockScreen,
maskStyle: {
opacity: settings.dialogMaskOpacity,
backgroundColor: settings.dialogMaskBgColor
},
buttons: {
enter: [lang.buttons.enter, function () {
var name = this.find("[data-name]").val();
var url = this.find("[data-url]").val();
var rid = this.find("[data-url-id]").val();
var title = this.find("[data-title]").val();
if (name === "") {
alert(dialogLang.nameEmpty);
return false;
}
if (rid === "") {
alert(dialogLang.idEmpty);
return false;
}
if (url === "http://" || url === "") {
alert(dialogLang.urlEmpty);
return false;
}
//cm.replaceSelection("[" + title + "][" + name + "]\n[" + name + "]: " + url + "");
cm.replaceSelection("[" + name + "][" + rid + "]");
if (selection === "") {
cm.setCursor(cursor.line, cursor.ch + 1);
}
title = (title === "") ? "" : " \"" + title + "\"";
cm.setValue(cm.getValue() + "\n[" + rid + "]: " + url + title + "");
this.hide().lockScreen(false).hideMask();
return false;
}],
cancel: [lang.buttons.cancel, function () {
this.hide().lockScreen(false).hideMask();
return false;
}]
}
});
}
dialog = editor.find("." + dialogName);
dialog.find("[data-name]").val("[" + ReLinkId + "]");
dialog.find("[data-url-id]").val("");
dialog.find("[data-url]").val("http://");
dialog.find("[data-title]").val(selection);
this.dialogShowMask(dialog);
this.dialogLockScreen();
dialog.show();
ReLinkId++;
};
};
// CommonJS/Node.js
if (typeof require === "function" && typeof exports === "object" && typeof module === "object") {
module.exports = factory;
}
else if (typeof define === "function") // AMD/CMD/Sea.js
{
if (define.amd) { // for Require.js
define(["editormd"], function (editormd) {
factory(editormd);
});
} else { // for Sea.js
define(function (require) {
var editormd = require("./../../editormd");
factory(editormd);
});
}
}
else {
factory(window.editormd);
}
})();
|
'use strict';
exports.__esModule = true;
exports['default'] = publish;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _Subject = require('../Subject');
var _Subject2 = _interopRequireDefault(_Subject);
var _multicast = require('./multicast');
var _multicast2 = _interopRequireDefault(_multicast);
function subjectFactory() {
return new _Subject2['default']();
}
function publish() {
return _multicast2['default'].call(this, subjectFactory);
}
//# sourceMappingURL=publish.js.map
module.exports = exports['default'];
//# sourceMappingURL=publish.js.map |
define(['underscore','backbone','aura'], function(_,Backbone,Aura) {
console.log('loading index.js')
var app=Aura({debug: { enable: true}});
app.components.addSource('aura', '../node_webkit/auraext');
app.components.addSource('kse', '../kse/aura_components');
app.use('../node_webkit/auraext/aura-backbone')
.use('../node_webkit/auraext/aura-yadb')
.use('../node_webkit/auraext/aura-yase')
.use('../node_webkit/auraext/aura-rangy')
.use('../node_webkit/auraext/aura-toc')
.start({ widgets: 'body' }).then(function() {
console.log('Aura Started');
})
}); |
;(function() {
var ValueDirective = function() {
};
_.extend(ValueDirective.prototype, {
matcher: function($el) {
return $el.data('value');
},
run: function($el) {
$el.html($el.data('value'));
}
});
window.app = new xin.App({
el: xin.$('body'),
directives: {
'[data-role=app]': xin.directive.AppDirective,
'[data-role]': xin.directive.RoleDirective,
'[data-uri]': xin.directive.URIDirective,
'[data-bind]': xin.directive.BindDirective,
'[data-value]': ValueDirective,
'[data-background]': xin.directive.BackgroundDirective
},
middlewares: {
'AuthMiddleware': AuthMiddleware
},
providers: {
}
});
_.extend(app, {
db: null,
user: {},
config: function(param) {
if(param) {
return window.config[param];
} else {
return window.config;
}
},
invoke: function(api, param, cb) {
api = api.split('.');
if(typeof(param) == "function") {
window.API[api[0]][api[1]](param);
} else {
delete arguments[0];
var opt = [],
j = 0;
for (var i in arguments) {
opt.push(arguments[i]);
}
window.API[api[0]][api[1]].apply(this, opt);
}
},
loading: {
show: function(options) {
ActivityIndicator.show(options);
},
hide: function() {
ActivityIndicator.hide();
}
},
storage: function(type, key, value, cb) {
if (!key && !value) return;
if(key && !value) {
var res = window[type].getItem(key);
try {
res = JSON.parse(res);
} catch(e) {}
if(cb) cb(res);
} else if(key && value) {
if(typeof value !== "string") value = JSON.stringify(value);
window[type].setItem(key, value);
}
},
sessionStorage: function(key, value) {
if(typeof value === 'function') {
this.storage('sessionStorage', key, undefined, value);
} else {
this.storage('sessionStorage', key, value);
}
},
localStorage: function(key, value) {
if(typeof value === 'function') {
this.storage('localStorage', key, undefined, value);
} else {
this.storage('localStorage', key, value);
}
},
clearStorage: function(type) { // type = localStorage || sessionStorage
if(!type) {
localStorage.clear();
sessionStorage.clear();
return;
}
if(type === 'localStorage' || type === 'sessionStorage') {
window[type].clear();
}
}
});
})();
|
import getDocument from './get-document';
export default function(node) {
const _document = getDocument(node);
return _document.defaultView || window;
}
|
var expect = require('expect.js');
var helpers = require('../helpers');
var fakeRepositoryFactory = function () {
function FakeRepository() { }
FakeRepository.prototype.getRegistryClient = function () {
return {
unregister: function (name, cb) {
cb(null, { name: name });
}
};
};
return FakeRepository;
};
var unregister = helpers.command('unregister');
var unregisterFactory = function () {
return helpers.command('unregister', {
'../core/PackageRepository': fakeRepositoryFactory()
});
};
describe('bower unregister', function () {
it('correctly reads arguments', function () {
expect(unregister.readOptions(['jquery']))
.to.eql(['jquery']);
});
it('errors if name is not provided', function () {
return helpers.run(unregister).fail(function (reason) {
expect(reason.message).to.be('Usage: bower unregister <name> <url>');
expect(reason.code).to.be('EINVFORMAT');
});
});
it('should call registry client with name', function () {
var unregister = unregisterFactory();
return helpers.run(unregister, ['some-name'])
.spread(function (result) {
expect(result).to.eql({
// Result from register action on stub
name: 'some-name'
});
});
});
it('should confirm in interactive mode', function () {
var register = unregisterFactory();
var promise = helpers.run(register,
['some-name', {
interactive: true,
registry: { register: 'http://localhost' }
}]
);
return helpers.expectEvent(promise.logger, 'confirm')
.spread(function (e) {
expect(e.type).to.be('confirm');
expect(e.message).to.be('You are about to remove component "some-name" from the bower registry (http://localhost). It is generally considered bad behavior to remove versions of a library that others are depending on. Are you really sure?');
expect(e.default).to.be(false);
});
});
it('should skip confirming when forcing', function () {
var register = unregisterFactory();
return helpers.run(register,
['some-name',
{ interactive: true, force: true }
]
);
});
});
|
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var React = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _clsx = _interopRequireDefault(require("clsx"));
var _utils = require("@material-ui/utils");
var _unstyled = require("@material-ui/unstyled");
var _experimentalStyled = _interopRequireDefault(require("../styles/experimentalStyled"));
var _useThemeProps = _interopRequireDefault(require("../styles/useThemeProps"));
var _Paper = _interopRequireDefault(require("../Paper"));
var _cardClasses = require("./cardClasses");
const overridesResolver = (props, styles) => styles.root || {};
const useUtilityClasses = styleProps => {
const {
classes
} = styleProps;
const slots = {
root: ['root']
};
return (0, _unstyled.unstable_composeClasses)(slots, _cardClasses.getCardUtilityClass, classes);
};
const CardRoot = (0, _experimentalStyled.default)(_Paper.default, {}, {
name: 'MuiCard',
slot: 'Root',
overridesResolver
})(() => {
/* Styles applied to the root element. */
return {
overflow: 'hidden'
};
});
const Card = /*#__PURE__*/React.forwardRef(function Card(inProps, ref) {
const props = (0, _useThemeProps.default)({
props: inProps,
name: 'MuiCard'
});
const {
className,
raised = false
} = props,
other = (0, _objectWithoutPropertiesLoose2.default)(props, ["className", "raised"]);
const styleProps = (0, _extends2.default)({}, props, {
raised
});
const classes = useUtilityClasses(styleProps);
return /*#__PURE__*/React.createElement(CardRoot, (0, _extends2.default)({
className: (0, _clsx.default)(classes.root, className),
elevation: raised ? 8 : undefined,
ref: ref,
styleProps: styleProps
}, other));
});
process.env.NODE_ENV !== "production" ? Card.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The content of the component.
*/
children: _propTypes.default.node,
/**
* Override or extend the styles applied to the component.
*/
classes: _propTypes.default.object,
/**
* @ignore
*/
className: _propTypes.default.string,
/**
* If `true`, the card will use raised styling.
* @default false
*/
raised: (0, _utils.chainPropTypes)(_propTypes.default.bool, props => {
if (props.raised && props.variant === 'outlined') {
return new Error('Material-UI: Combining `raised={true}` with `variant="outlined"` has no effect.');
}
return null;
}),
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: _propTypes.default.object
} : void 0;
var _default = Card;
exports.default = _default; |
var searchData=
[
['embedderdatafields',['EmbedderDataFields',['../classv8_1_1Context.html#a8e8a8c567e2d193f25f1ec211db0b5f9',1,'v8::Context']]],
['empty',['Empty',['../classv8_1_1String.html#aa393d47baa54467fe57001065e49194b',1,'v8::String']]],
['endofstream',['EndOfStream',['../classv8_1_1OutputStream.html#a6c5c308367fc5776bcbedff0e94d6049',1,'v8::OutputStream']]],
['enqueuemicrotask',['EnqueueMicrotask',['../classv8_1_1Isolate.html#a79a222a1a662d08479d5a1880c6793c5',1,'v8::Isolate::EnqueueMicrotask(Local< Function > microtask)'],['../classv8_1_1Isolate.html#ad4d6c7dfdfc6c1bc857841de7e9967c3',1,'v8::Isolate::EnqueueMicrotask(MicrotaskCallback microtask, void *data=NULL)']]],
['enter',['Enter',['../classv8_1_1Isolate.html#aec80bb49b6b7647ff75e8f2cc9484ea3',1,'v8::Isolate::Enter()'],['../classv8_1_1Context.html#a6995c49d9897eb49053f07874b825133',1,'v8::Context::Enter()']]],
['entropysource',['EntropySource',['../namespacev8.html#a3a9840e090970cbda2427cf6f5594fba',1,'v8']]],
['entry_5fhook',['entry_hook',['../structv8_1_1Isolate_1_1CreateParams.html#aa7aa18bbe2d86713e5b074a93b38dc60',1,'v8::Isolate::CreateParams']]],
['escapablehandlescope',['EscapableHandleScope',['../classv8_1_1EscapableHandleScope.html',1,'v8']]],
['escape',['Escape',['../classv8_1_1EscapableHandleScope.html#afdf0d3850978f65d1a827f78b3a2b6fd',1,'v8::EscapableHandleScope']]],
['eternal',['Eternal',['../singletonv8_1_1Eternal.html',1,'v8']]],
['eventcallback',['EventCallback',['../classv8_1_1Debug.html#a6ce314ecd3234c74ad97bd4e6e8ae782',1,'v8::Debug']]],
['eventdetails',['EventDetails',['../classv8_1_1Debug_1_1EventDetails.html',1,'v8::Debug']]],
['exception',['Exception',['../classv8_1_1Exception.html',1,'v8']]],
['exception',['Exception',['../classv8_1_1TryCatch.html#a99c425f29b3355b4294cbe762377f99b',1,'v8::TryCatch']]],
['exit',['Exit',['../classv8_1_1Isolate.html#a64a8503cafd00d1d2cadfbb0c2345054',1,'v8::Isolate::Exit()'],['../classv8_1_1Context.html#a2db09d4fefb26023a40d88972a4c1599',1,'v8::Context::Exit()']]],
['expectedruntime',['ExpectedRuntime',['../classv8_1_1Platform.html#ace7f666b2b5995bb0e898e12fa660718',1,'v8::Platform']]],
['extension',['Extension',['../classv8_1_1Extension.html',1,'v8']]],
['extensionconfiguration',['ExtensionConfiguration',['../classv8_1_1ExtensionConfiguration.html',1,'v8']]],
['external',['External',['../classv8_1_1External.html',1,'v8']]],
['externalize',['Externalize',['../classv8_1_1ArrayBuffer.html#a8b90b72486cfacb4fbec157f4803f889',1,'v8::ArrayBuffer::Externalize()'],['../classv8_1_1SharedArrayBuffer.html#afe025bbf668e64439cfc0044b353eb41',1,'v8::SharedArrayBuffer::Externalize()']]],
['externalonebytestringresource',['ExternalOneByteStringResource',['../classv8_1_1String_1_1ExternalOneByteStringResource.html',1,'v8::String']]],
['externalonebytestringresourceimpl',['ExternalOneByteStringResourceImpl',['../classv8_1_1ExternalOneByteStringResourceImpl.html',1,'v8']]],
['externalresourcevisitor',['ExternalResourceVisitor',['../classv8_1_1ExternalResourceVisitor.html',1,'v8']]],
['externalsourcestream',['ExternalSourceStream',['../classv8_1_1ScriptCompiler_1_1ExternalSourceStream.html',1,'v8::ScriptCompiler']]],
['externalstringresource',['ExternalStringResource',['../classv8_1_1String_1_1ExternalStringResource.html',1,'v8::String']]],
['externalstringresourcebase',['ExternalStringResourceBase',['../classv8_1_1String_1_1ExternalStringResourceBase.html',1,'v8::String']]]
];
|
module.exports = function (app) {
app.get('/', function (req, res) {
if (req.logout) {
req.logout();
}
res.redirect('/');
});
}; |
define([
"require", // require.toUrl
"./main", // to export dijit.BackgroundIframe
"dojo/_base/config",
"dojo/dom-construct", // domConstruct.create
"dojo/dom-style", // domStyle.set
"dojo/_base/lang", // lang.extend lang.hitch
"dojo/on",
"dojo/sniff" // has("ie"), has("trident"), has("quirks")
], function(require, dijit, config, domConstruct, domStyle, lang, on, has){
// module:
// dijit/BackgroundIFrame
// Flag for whether to create background iframe behind popups like Menus and Dialog.
// A background iframe is useful to prevent problems with popups appearing behind applets/pdf files,
// and is also useful on older versions of IE (IE6 and IE7) to prevent the "bleed through select" problem.
// By default, it's enabled for IE6-11, excluding Windows Phone 8.
// TODO: For 2.0, make this false by default. Also, possibly move definition to has.js so that this module can be
// conditionally required via dojo/has!bgIfame?dijit/BackgroundIframe
has.add("config-bgIframe",
(has("ie") || has("trident")) && !/IEMobile\/10\.0/.test(navigator.userAgent)); // No iframe on WP8, to match 1.9 behavior
var _frames = new function(){
// summary:
// cache of iframes
var queue = [];
this.pop = function(){
var iframe;
if(queue.length){
iframe = queue.pop();
iframe.style.display="";
}else{
// transparency needed for DialogUnderlay and for tooltips on IE (to see screen near connector)
if(has("ie") < 9){
var burl = config["dojoBlankHtmlUrl"] || require.toUrl("dojo/resources/blank.html") || "javascript:\"\"";
var html="<iframe src='" + burl + "' role='presentation'"
+ " style='position: absolute; left: 0px; top: 0px;"
+ "z-index: -1; filter:Alpha(Opacity=\"0\");'>";
iframe = document.createElement(html);
}else{
iframe = domConstruct.create("iframe");
iframe.src = 'javascript:""';
iframe.className = "dijitBackgroundIframe";
iframe.setAttribute("role", "presentation");
domStyle.set(iframe, "opacity", 0.1);
}
iframe.tabIndex = -1; // Magic to prevent iframe from getting focus on tab keypress - as style didn't work.
}
return iframe;
};
this.push = function(iframe){
iframe.style.display="none";
queue.push(iframe);
}
}();
dijit.BackgroundIframe = function(/*DomNode*/ node){
// summary:
// For IE/FF z-index shenanigans. id attribute is required.
//
// description:
// new dijit.BackgroundIframe(node).
//
// Makes a background iframe as a child of node, that fills
// area (and position) of node
if(!node.id){ throw new Error("no id"); }
if(has("config-bgIframe")){
var iframe = (this.iframe = _frames.pop());
node.appendChild(iframe);
if(has("ie")<7 || has("quirks")){
this.resize(node);
this._conn = on(node, 'resize', lang.hitch(this, "resize", node));
}else{
domStyle.set(iframe, {
width: '100%',
height: '100%'
});
}
}
};
lang.extend(dijit.BackgroundIframe, {
resize: function(node){
// summary:
// Resize the iframe so it's the same size as node.
// Needed on IE6 and IE/quirks because height:100% doesn't work right.
if(this.iframe){
domStyle.set(this.iframe, {
width: node.offsetWidth + 'px',
height: node.offsetHeight + 'px'
});
}
},
destroy: function(){
// summary:
// destroy the iframe
if(this._conn){
this._conn.remove();
this._conn = null;
}
if(this.iframe){
this.iframe.parentNode.removeChild(this.iframe);
_frames.push(this.iframe);
delete this.iframe;
}
}
});
return dijit.BackgroundIframe;
});
|
const getWebpackConfig = require('./get-webpack-config');
module.exports = {
globals: {
__DEV__: false,
__PROD__: false,
__DEVSERVER__: false,
__CLIENT__: false,
__SERVER__: false,
'process.env.NODE_ENV': false
},
settings: {
'import/resolver': {
webpack: {
config: getWebpackConfig()
}
}
}
};
|
var urlRegexp = /^(http|udp|ftp|dht)s?:\/\//;
/**
* Returns true if str is a URL.
*
* @param {String} str
* @return {Boolean}
*/
exports.isURL = function(str) {
return urlRegexp.test(str);
};
/**
* Returns true if n is an integer.
*
* @param {Number} n
* @return {Boolean}
*/
exports.isInteger = function(n) {
return !isNaN(parseInt(n, 10));
};
/**
* Splits a path into an array, platform safe.
*
* @param {String} path
* @return {Array.<String>}
*/
exports.splitPath = function(path) {
return path.split(path.sep);
};
/**
* Returns true if part of buffer `b` beginning at `start` matches buffer `a`.
*
* @param {Buffer} a
* @param {Buffer} b
* @param {Number} start
*/
exports.buffersMatch = function(a, b, start) {
for (var i = 0, l = b.length; i < l; i++) {
if (a[start + i] !== b[i]) {
return false;
}
}
return true;
};
|
/* eslint max-len: 0 */
import webpack from 'webpack';
import merge from 'webpack-merge';
import baseConfig from './webpack.config.base';
const port = process.env.PORT || 3000;
export default merge(baseConfig, {
debug: true,
devtool: 'cheap-module-eval-source-map',
entry: [
`webpack-hot-middleware/client?path=http://localhost:${port}/__webpack_hmr`,
'./app/index'
],
output: {
publicPath: `http://localhost:${port}/dist/`
},
module: {
loaders: [
{
test: /\.global\.css$/,
loaders: [
'style-loader',
'css-loader?sourceMap'
]
},
{
test: /^((?!\.global).)*\.css$/,
loaders: [
'style-loader',
'css-loader?modules&sourceMap&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
]
}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development')
})
],
target: 'electron-renderer'
});
|
export const API_FAIL = 'API_FAIL';
export const SAVE_TIMELINE_FAIL = 'SAVE_TIMELINE_FAIL';
|
/*global GLOBE, Em */
GLOBE.Top10Controller = Em.ArrayController.extend({
needs: ['application'],
relays: [],
actions: {
showRelayDetail: function(fingerprint) {
this.transitionToRoute('relayDetail', fingerprint);
}
}
}); |
import {default as getTeam} from './getTeam'
import {default as createTeam} from './createTeam'
import {default as addUserToTeam} from './addUserToTeam'
import {default as addCollaboratorToRepo} from './addCollaboratorToRepo'
import {default as getCollaboratorsForRepo} from './getCollaboratorsForRepo'
import {default as removeUserFromOrganizations} from './removeUserFromOrganizations'
import {default as removeUserFromOrganization} from './removeUserFromOrganization'
/**
* NOTE: this service's functions are exported the way they are to enable
* certain stubbing functionality functionality for testing that relies on the
* way the module is cached and later required by dependent modules.
*/
export default {
getTeam,
createTeam,
addUserToTeam,
addCollaboratorToRepo,
getCollaboratorsForRepo,
removeUserFromOrganization,
removeUserFromOrganizations,
}
|
/* ###########################################################################
GLOBAL ASSETS RELEASE v6.0.2
BUILD DATE: 20100224
########################################################################### */
// init values
hele = new Array();
newspause = 4; // time to pause news items in seconds
fx = op = ni = 0;
tp = ns = 1;
nop = .1;
nextf = -1;
mout = "mout";
done = false;
newspause = newspause * 1000;
function featurefade(selectedf){
if (is.docom){
if (done){
done = false;
if (selectedf != 0){
hele['subhover'+selectedf].style.visibility = "visible";
hele['mout'].style.visibility = "visible";
if (fx != 0){
hele['feature'+fx].style.zIndex = 10;
hele['subhover'+fx].style.visibility = "hidden";
}
hele['feature'+selectedf].style.zIndex = 20;
hele['feature'+selectedf].style.visibility = "visible";
fc = fx;
fx = selectedf;
setTimeout('fadein();',1);
}else{
hele['mout'].style.visibility = "hidden";
hele['subhover'+fx].style.visibility = "hidden";
fc = fx;
fx = selectedf;
op = 1;
setTimeout('fadeout();',1);
}
}else{
nextf = selectedf;
}
}
}
function fadein(){
if (!is.op && !is.iemac && !is.oldmoz){
setopacity('feature'+fx,.99);
}else{
setopacity('feature'+fx,1);
}
if (fc != 0){
hele['feature'+fc].style.visibility = "hidden";
}
op = 0;
done = true;
if (nextf != -1){
featurefade(nextf);
nextf = -1;
}
}
function fadeout(){
if (!is.op && !is.iemac && !is.oldmoz){
op = op - .5;
if (op <= 0){
op = 0;
hele['feature'+fc].style.visibility = "hidden";
setopacity('feature'+fc,.99);
done = true;
}else{
setopacity('feature'+fc,op);
setTimeout('fadeout();',50);
}
}else{
hele['feature'+fc].style.visibility = "hidden";
done = true;
}
}
function fadenews(){
if (nop == .1){
nx = ns + 1;
if(nx > tp){
nx = 1;
}
if (!is.safari && !is.oldmoz && !is.ns6 && !is.iemac){
setopacity('newsitem'+nx,.1);
}else{
var nn = 1;
while (hele['newsitem'+nn]){
if (nn != nx){
hele['newsitem'+nn].style.visibility = "hidden";
}else{
if (!is.oldmoz){
setopacity('newsitem'+nn,.99);
}
hele['newsitem'+nn].style.visibility = "visible";
}
nn++;
}
}
hele['newsitem'+nx].style.visibility = "visible";
hele['newsitem'+ns].style.zIndex = 3;
hele['newsitem'+nx].style.zIndex = 5;
}
if (!is.safari && !is.oldmoz && !is.ns6){
nop = nop + .2;
if (nop >= .99){
nop = .1;
hele['newsitem'+ns].style.visibility = "hidden";
setopacity('newsitem'+ns,.99);
ns++;
if(ns > tp){
ns = 1;
}
setTimeout('fadenews();',newspause);
}else{
setopacity('newsitem'+nx,nop);
setTimeout('fadenews();',130);
}
}else{
ns++;
if(ns > tp){
ns = 1;
}
setTimeout('fadenews();',newspause);
}
}
function setopacity(cobj,opac){
if (document.all && !is.op && !is.iemac){ //ie
hele[cobj].filters.alpha.opacity = opac * 100;
}else{
hele[cobj].style.MozOpacity = opac;
hele[cobj].style.opacity = opac;
}
}
var rollNames=["",""];
function prephome(){
if (is.docom && !hele['newsitem1']){
while (document.getElementById('newsitem'+tp)){
hele['newsitem'+tp] = document.getElementById('newsitem'+tp);
hele['newsitem'+tp].style.left='10px';
if (is.oldmoz){
setopacity('newsitem'+tp,1);
hele['newsitem'+tp].style.visibility = "hidden";
}
if (is.iewin){
hele['newsitem'+tp].style.backgroundImage = 'url(/im/bg_home_b3_iewin.gif)';
}
if (tp == 1){
hele['newsitem1'].style.zIndex = 3;
}
if (is.oldmoz && tp == 1){
hele['newsitem'+tp].style.visibility = "visible";
}
tp++;
}
tp--;
// get names for omniture
if(rollNames[0] == "" && document.getElementById('ipfeature')){
rollNames[0] = document.getElementById('ipfeature').src.replace(/.*\/b1_([^\/.]+_d).jpg/,"$1");;
rollNames[1] = document.getElementById('ipsub1').src.replace(/.*\/b1_([^\/.]+)_p1.gif/,"$1_s");;
rollNames[2] = document.getElementById('ipsub2').src.replace(/.*\/b1_([^\/.]+)_p2.gif/,"$1_s");;
rollNames[3] = document.getElementById('ipsub3').src.replace(/.*\/b1_([^\/.]+)_p3.gif/,"$1_s");;
}
var sf = 1;
while (document.getElementById('subhover'+sf)){
hele['subhover'+sf] = document.getElementById('subhover'+sf);
hele['feature'+sf] = document.getElementById('feature'+sf);
if (!is.op && !is.iemac && !is.oldmoz){
setopacity('feature'+sf,1);
}
sf++;
}
hele['mout'] = document.getElementById('mout');
if (tp > 0){
setTimeout('fadenews();',newspause);
}
}
// for old code with new page
if (!document.getElementById('mtopics')){
movin();
}
}
// omniture code
function customlink(thisfeature) {
if(window.s_account){
s_linkType='o';
s_linkName=thisfeature;
s_lnk=s_co(this);
s_gs(s_account);
}
}
// legacy function
var rollCount=[0,0,0,0];
function sendRollData() {}
|
import * as chai from 'chai';
const expect = chai.expect;
const chaiAsPromised = require('chai-as-promised');
import * as sinon from 'sinon';
import * as sinonAsPromised from 'sinon-as-promised';
import { ClickReport } from '../src/models/click_report';
chai.use(chaiAsPromised);
describe('ClickReport', () => {
const tableName = 'ClickReports-table';
const campaignId = 'thatCampaignId';
let tNameStub;
const clickReportHashKey = 'campaignId';
const clickReportRangeKey = 'timestamp';
before(() => {
sinon.stub(ClickReport, '_client').resolves(true);
tNameStub = sinon.stub(ClickReport, 'tableName', { get: () => tableName});
});
describe('#get', () => {
it('calls the DynamoDB get method with correct params', (done) => {
ClickReport.get(campaignId, clickReportRangeKey).then(() => {
const args = ClickReport._client.lastCall.args;
expect(args[0]).to.equal('get');
expect(args[1]).to.have.deep.property(`Key.${clickReportHashKey}`, campaignId);
expect(args[1]).to.have.deep.property(`Key.${clickReportRangeKey}`, clickReportRangeKey);
expect(args[1]).to.have.property('TableName', tableName);
done();
});
});
});
describe('#hashKey', () => {
it('returns the hash key name', () => {
expect(ClickReport.hashKey).to.equal(clickReportHashKey);
});
});
describe('#rangeKey', () => {
it('returns the range key name', () => {
expect(ClickReport.rangeKey).to.equal(clickReportRangeKey);
});
});
after(() => {
ClickReport._client.restore();
tNameStub.restore();
});
});
|
/*!
* jQuery JavaScript Library v1.10.2 -wrap,-css,-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:01Z
*/
(function( window, undefined ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//"use strict";
var
// The deferred used on DOM ready
readyList,
// A central reference to the root jQuery(document)
rootjQuery,
// Support: IE<10
// For `typeof xmlNode.method` instead of `xmlNode.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
location = window.location,
document = window.document,
docElem = document.documentElement,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// [[Class]] -> type pairs
class2type = {},
// List of deleted data cache ids, so we can reuse them
core_deletedIds = [],
core_version = "1.10.2 -wrap,-css,-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,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
// The ready event handler
completed = function( event ) {
// readyState === "complete" is good enough for us to call the dom ready in oldIE
if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
detach();
jQuery.ready();
}
},
// Clean-up method for dom ready events
detach = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: core_version,
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var src, copyIsArray, copy, name, options, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
/* jshint eqeqeq: false */
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
if ( obj == null ) {
return String( obj );
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},
isPlainObject: function( obj ) {
var key;
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Support: IE<9
// Handle iteration over inherited properties before own properties.
if ( jQuery.support.ownLast ) {
for ( key in obj ) {
return core_hasOwn.call( obj, key );
}
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
},
parseJSON: function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
if ( data === null ) {
return data;
}
if ( typeof data === "string" ) {
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
if ( data ) {
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
}
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && jQuery.trim( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
core_push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return core_concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var args, proxy, tmp;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
},
// A method for quickly swapping in/out CSS properties to get correct calculations.
// Note: this method belongs to the css module but it's needed here for the support module.
// If support gets modularized, this method should be moved back to the css module.
swap: function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || type !== "function" &&
( length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj );
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
/*!
* Sizzle CSS Selector Engine v1.10.2
* http://sizzlejs.com/
*
* Copyright 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-07-03
*/
(function( window, undefined ) {
var i,
support,
cachedruns,
Expr,
getText,
isXML,
compile,
outermostContext,
sortInput,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
hasDuplicate = false,
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
return 0;
},
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments quoted,
// then not containing pseudos/brackets,
// then attribute selectors/non-parenthetical expressions,
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rsibling = new RegExp( whitespace + "*[+~]" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rescape = /'|\\/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
// BMP codepoint
high < 0 ?
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( documentIsHTML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// QSA path
if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
nid = old = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key += " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied
*/
function addHandle( attrs, handler ) {
var arr = attrs.split("|"),
i = attrs.length;
while ( i-- ) {
Expr.attrHandle[ arr[i] ] = handler;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Detect xml
* @param {Element|Object} elem An element or a document
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var doc = node ? node.ownerDocument || node : preferredDoc,
parent = doc.defaultView;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsHTML = !isXML( doc );
// Support: IE>8
// If iframe document is assigned to "document" variable and if iframe has been reloaded,
// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
// IE6-8 do not support the defaultView property so parent will be undefined
if ( parent && parent.attachEvent && parent !== parent.top ) {
parent.attachEvent( "onbeforeunload", function() {
setDocument();
});
}
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans)
support.attributes = assert(function( div ) {
div.className = "i";
return !div.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if getElementsByClassName can be trusted
support.getElementsByClassName = assert(function( div ) {
div.innerHTML = "<div class='a'></div><div class='a i'></div>";
// Support: Safari<4
// Catch class over-caching
div.firstChild.className = "i";
// Support: Opera<10
// Catch gEBCN failure to find non-leading classes
return div.getElementsByClassName("i").length === 2;
});
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( div ) {
docElem.appendChild( div ).id = expando;
return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Support: Opera 10-12/IE8
// ^= $= *= and empty values
// Should not select anything
// Support: Windows 8 Native Apps
// The type attribute is restricted during .innerHTML assignment
var input = doc.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "t", "" );
if ( div.querySelectorAll("[t^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
/* Contains
---------------------------------------------------------------------- */
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Document order sorting
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b );
if ( compare ) {
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === doc || contains(preferredDoc, a) ) {
return -1;
}
if ( b === doc || contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
}
// Not directly comparable, sort on existence of method
return a.compareDocumentPosition ? -1 : 1;
} :
function( a, b ) {
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
// Parentless nodes are either documents or disconnected
} else if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return doc;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, document, null, [elem] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined;
return val === undefined ?
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null :
val;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[5] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] && match[4] !== undefined ) {
match[2] = match[4];
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var data, cache, outerCache,
dirkey = dirruns + " " + doneName;
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
if ( (data = cache[1]) === true || data === cachedruns ) {
return data === true;
}
} else {
cache = outerCache[ dir ] = [ dirkey ];
cache[1] = matcher( elem, context, xml ) || cachedruns;
if ( cache[1] === true ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
// A counter to specify which element is currently being matched
var matcherCachedRuns = 0,
bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = matcherCachedRuns;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++matcherCachedRuns;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed ) {
var i, tokens, token, type, find,
match = tokenize( selector );
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && context.nodeType === 9 && documentIsHTML &&
Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && context.parentNode || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
!documentIsHTML,
results,
rsibling.test( selector )
);
return results;
}
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Support: Chrome<14
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = hasDuplicate;
// Initialize against the default document
setDocument();
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( div1 ) {
// Should return 1, but returns 4 (following)
return div1.compareDocumentPosition( document.createElement("div") ) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild.getAttribute("href") === "#" ;
}) ) {
addHandle( "type|href|height|width", function( elem, name, isXML ) {
if ( !isXML ) {
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
});
}
// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if ( !support.attributes || !assert(function( div ) {
div.innerHTML = "<input/>";
div.firstChild.setAttribute( "value", "" );
return div.firstChild.getAttribute( "value" ) === "";
}) ) {
addHandle( "value", function( elem, name, isXML ) {
if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
});
}
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if ( !assert(function( div ) {
return div.getAttribute("disabled") == null;
}) ) {
addHandle( booleans, function( elem, name, isXML ) {
var val;
if ( !isXML ) {
return (val = elem.getAttributeNode( name )) && val.specified ?
val.value :
elem[ name ] === true ? name.toLowerCase() : null;
}
});
}
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Flag to know if list is currently firing
firing,
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// First callback to fire (used internally by add and fireWith)
firingStart,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( list && ( !fired || stack ) ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function( support ) {
var all, a, input, select, fragment, opt, eventName, isSupported, i,
div = document.createElement("div");
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// Finish early in limited (non-browser) environments
all = div.getElementsByTagName("*") || [];
a = div.getElementsByTagName("a")[ 0 ];
if ( !a || !a.style || !all.length ) {
return support;
}
// First batch of tests
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
support.getSetAttribute = div.className !== "t";
// IE strips leading whitespace when .innerHTML is used
support.leadingWhitespace = div.firstChild.nodeType === 3;
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
support.tbody = !div.getElementsByTagName("tbody").length;
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
support.htmlSerialize = !!div.getElementsByTagName("link").length;
// Get the style information from getAttribute
// (IE uses .cssText instead)
support.style = /top/.test( a.getAttribute("style") );
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
support.hrefNormalized = a.getAttribute("href") === "/a";
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
support.opacity = /^0.5/.test( a.style.opacity );
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
support.cssFloat = !!a.style.cssFloat;
// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
support.checkOn = !!input.value;
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
support.optSelected = opt.selected;
// Tests for enctype support on a form (#6743)
support.enctype = !!document.createElement("form").enctype;
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
support.html5Clone = document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>";
// Will be defined later
support.inlineBlockNeedsLayout = false;
support.shrinkWrapBlocks = false;
support.pixelPosition = false;
support.deleteExpando = true;
support.noCloneEvent = true;
support.reliableMarginRight = true;
support.boxSizingReliable = true;
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE<9
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
// Check if we can trust getAttribute("value")
input = document.createElement("input");
input.setAttribute( "value", "" );
support.input = input.getAttribute( "value" ) === "";
// Check if an input maintains its value after becoming a radio
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "checked", "t" );
input.setAttribute( "name", "t" );
fragment = document.createDocumentFragment();
fragment.appendChild( input );
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<9
// Opera does not clone events (and typeof div.attachEvent === undefined).
// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
if ( div.attachEvent ) {
div.attachEvent( "onclick", function() {
support.noCloneEvent = false;
});
div.cloneNode( true ).click();
}
// Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event)
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
for ( i in { submit: true, change: true, focusin: true }) {
div.setAttribute( eventName = "on" + i, "t" );
support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false;
}
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Support: IE<9
// Iteration over object's inherited properties before its own.
for ( i in jQuery( support ) ) {
break;
}
support.ownLast = i !== "0";
// Run tests that need a body at doc ready
jQuery(function() {
var container, marginDiv, tds,
divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px";
body.appendChild( container ).appendChild( div );
// Support: IE8
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Support: IE8
// Check if empty table cells still have offsetWidth/Height
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check box-sizing and margin behavior.
div.innerHTML = "";
div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
// Workaround failing boxSizing test due to offsetWidth returning wrong value
// with some non-1 values of body zoom, ticket #13543
jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() {
support.boxSizing = div.offsetWidth === 4;
});
// Use window.getComputedStyle because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = div.appendChild( document.createElement("div") );
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== core_strundefined ) {
// Support: IE<8
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Support: IE6
// Check if elements with layout shrink-wrap their children
div.style.display = "block";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
if ( support.inlineBlockNeedsLayout ) {
// Prevent IE 6 from affecting layout for positioned elements #11048
// Prevent IE from shrinking the body in IE 7 mode #12869
// Support: IE<8
body.style.zoom = 1;
}
}
body.removeChild( container );
// Null elements to avoid leaks in IE
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
all = select = fragment = opt = a = input = null;
return support;
})({});
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
function internalData( elem, name, data, pvt /* Internal Use Only */ ){
if ( !jQuery.acceptData( elem ) ) {
return;
}
var ret, thisCache,
internalKey = jQuery.expando,
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
id = elem[ internalKey ] = core_deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
// Avoid exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
cache[ id ] = isNode ? {} : { toJSON: jQuery.noop };
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( typeof name === "string" ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
}
function internalRemoveData( elem, name, pvt ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
} else {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = name.concat( jQuery.map( name, jQuery.camelCase ) );
}
i = name.length;
while ( i-- ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
/* jshint eqeqeq: false */
} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
/* jshint eqeqeq: true */
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
}
jQuery.extend({
cache: {},
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"applet": true,
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data ) {
return internalData( elem, name, data );
},
removeData: function( elem, name ) {
return internalRemoveData( elem, name );
},
// For internal use only.
_data: function( elem, name, data ) {
return internalData( elem, name, data, true );
},
_removeData: function( elem, name ) {
return internalRemoveData( elem, name, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
// Do not set data on non-element because it will not be cleared (#8335).
if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) {
return false;
}
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var attrs, name,
data = null,
i = 0,
elem = this[0];
// Special expections of .data basically thwart jQuery.access,
// so implement the relevant behavior ourselves
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attrs = elem.attributes;
for ( ; i < attrs.length; i++ ) {
name = attrs[i].name;
if ( name.indexOf("data-") === 0 ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
return arguments.length > 1 ?
// Sets one value
this.each(function() {
jQuery.data( this, key, value );
}) :
// Gets one value
// Try to fetch any internally stored data first
elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null;
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery._removeData( elem, type + "queue" );
jQuery._removeData( elem, key );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook,
rclass = /[\t\r\n\f]/g,
rreturn = /\r/g,
rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute,
getSetInput = jQuery.support.input;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
elem.className = jQuery.trim( cur );
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
elem.className = value ? jQuery.trim( cur ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value;
if ( typeof stateVal === "boolean" && type === "string" ) {
return stateVal ? this.addClass( value ) : this.removeClass( value );
}
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
classNames = value.match( core_rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
if ( self.hasClass( className ) ) {
self.removeClass( className );
} else {
self.addClass( className );
}
}
// Toggle whole class name
} else if ( type === core_strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var ret, hooks, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// Use proper attribute retrieval(#6932, #12072)
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) {
optionSet = true;
}
}
// force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attr: function( elem, name, value ) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === core_strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( core_rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
elem[ propName ] = false;
// Support: IE<9
// Also clear defaultChecked/defaultSelected (if appropriate)
} else {
elem[ jQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
elem[ name ];
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr( elem, "tabindex" );
return tabindex ?
parseInt( tabindex, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
-1;
}
}
}
});
// Hooks for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
// IE<8 needs the *property* name
elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
// Use defaultChecked and defaultSelected for oldIE
} else {
elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr;
jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ?
function( elem, name, isXML ) {
var fn = jQuery.expr.attrHandle[ name ],
ret = isXML ?
undefined :
/* jshint eqeqeq: false */
(jQuery.expr.attrHandle[ name ] = undefined) !=
getter( elem, name, isXML ) ?
name.toLowerCase() :
null;
jQuery.expr.attrHandle[ name ] = fn;
return ret;
} :
function( elem, name, isXML ) {
return isXML ?
undefined :
elem[ jQuery.camelCase( "default-" + name ) ] ?
name.toLowerCase() :
null;
};
});
// fix oldIE attroperties
if ( !getSetInput || !getSetAttribute ) {
jQuery.attrHooks.value = {
set: function( elem, value, name ) {
if ( jQuery.nodeName( elem, "input" ) ) {
// Does not return so that setAttribute is also used
elem.defaultValue = value;
} else {
// Use nodeHook if defined (#1954); otherwise setAttribute is fine
return nodeHook && nodeHook.set( elem, value, name );
}
}
};
}
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = {
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
elem.setAttributeNode(
(ret = elem.ownerDocument.createAttribute( name ))
);
}
ret.value = value += "";
// Break association with cloned elements by also using setAttribute (#9646)
return name === "value" || value === elem.getAttribute( name ) ?
value :
undefined;
}
};
jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords =
// Some attributes are constructed with empty-string values when not defined
function( elem, name, isXML ) {
var ret;
return isXML ?
undefined :
(ret = elem.getAttributeNode( name )) && ret.value !== "" ?
ret.value :
null;
};
jQuery.valHooks.button = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
return ret && ret.specified ?
ret.value :
undefined;
},
set: nodeHook.set
};
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
set: function( elem, value, name ) {
nodeHook.set( elem, value === "" ? false : value, name );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
};
});
}
// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !jQuery.support.hrefNormalized ) {
// href/src property should get the full normalized URL (#10299/#12915)
jQuery.each([ "href", "src" ], function( i, name ) {
jQuery.propHooks[ name ] = {
get: function( elem ) {
return elem.getAttribute( name, 4 );
}
};
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Note: IE uppercases css property names, but if we were to .toLowerCase()
// .cssText, that would destroy case senstitivity in URL's, like in "background"
return elem.style.cssText || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !jQuery.support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
var rformElems = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var tmp, events, t, handleObjIn,
special, eventHandle, handleObj,
handlers, type, namespaces, origType,
elemData = jQuery._data( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, handleObj, tmp,
origCount, t, events,
special, handlers, type,
namespaces, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery._removeData( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var handle, ontype, cur,
bubbleType, special, tmp, i,
eventPath = [ elem || document ],
type = core_hasOwn.call( event, "type" ) ? event.type : event,
namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
try {
elem[ type ]();
} catch ( e ) {
// IE<9 dies on focus/blur to hidden element (#1486,#12518)
// only reproducible on winXP IE8 native, not IE9 in IE8 mode
}
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, ret, handleObj, matched, j,
handlerQueue = [],
args = core_slice.call( arguments ),
handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var sel, handleObj, matches, i,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
/* jshint eqeqeq: false */
for ( ; cur != this; cur = cur.parentNode || this ) {
/* jshint eqeqeq: true */
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: IE<9
// Fix target property (#1925)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Support: Chrome 23+, Safari?
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Support: IE<9
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
event.metaKey = !!event.metaKey;
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var body, eventDoc, doc,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
try {
this.focus();
return false;
} catch ( e ) {
// Support: IE<9
// If we error on focus to hidden element (#1486, #12518),
// let .trigger() run the handlers
}
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Even when returnValue equals to undefined Firefox will still show alert
if ( event.result !== undefined ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === core_strundefined ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( !e ) {
return;
}
// If preventDefault exists, run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// Support: IE
// Otherwise set the returnValue property of the original event to false
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( !e ) {
return;
}
// If stopPropagation exists, run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// Support: IE
// Set the cancelBubble property of the original event to true
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "submitBubbles" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "submitBubbles", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "changeBubbles", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var type, origFn;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
var isSimple = /^.[^:#\[\.,]*$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i,
ret = [],
self = this,
len = self.length;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector || [], true) );
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector(cur, selectors)) ) {
cur = ret.push( cur );
break;
}
}
}
return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( jQuery.unique(all) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
ret = jQuery.unique( ret );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
ret = ret.reverse();
}
}
return this.pushStack( ret );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
}));
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( isSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
manipulation_rcheckableType = /^(?:checkbox|radio)$/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
area: [ 1, "<map>", "</map>" ],
param: [ 1, "<object>", "</object>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
_default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
append: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
// If this is a select, ensure that it displays empty (#12336)
// Support: IE<9
if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
elem.options.length = 0;
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var
// Snapshot the DOM in case .domManip sweeps something relevant into its fragment
args = jQuery.map( this, function( elem ) {
return [ elem.nextSibling, elem.parentNode ];
}),
i = 0;
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
var next = args[ i++ ],
parent = args[ i++ ];
if ( parent ) {
// Don't use the snapshot next if it has moved (#13810)
if ( next && next.parentNode !== parent ) {
next = this.nextSibling;
}
jQuery( this ).remove();
parent.insertBefore( elem, next );
}
// Allow new content to include elements from the context set
}, true );
// Force removal if there was no new content (e.g., from empty arguments)
return i ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback, allowIntersection ) {
// Flatten any nested arrays
args = core_concat.apply( [], args );
var first, node, hasScripts,
scripts, doc, fragment,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[0],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[0] = value.call( this, index, self.html() );
}
self.domManip( args, callback, allowIntersection );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[i], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Hope ajax is available...
jQuery._evalUrl( node.src );
} else {
jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
}
}
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
}
}
return this;
}
});
// Support: IE<8
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[1];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var elem,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
}
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function fixCloneNodeIssues( src, dest ) {
var nodeName, e, data;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 copies events bound via attachEvent when using cloneNode.
if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) {
data = jQuery._data( dest );
for ( e in data.events ) {
jQuery.removeEvent( dest, e, data.handle );
}
// Event data gets referenced instead of copied if the expando gets copied too
dest.removeAttribute( jQuery.expando );
}
// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
if ( nodeName === "script" && dest.text !== src.text ) {
disableScript( dest ).text = src.text;
restoreScript( dest );
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
} else if ( nodeName === "object" ) {
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.defaultSelected = dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone(true);
jQuery( insert[i] )[ original ]( elems );
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
core_push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
function getAll( context, tag ) {
var elems, elem,
i = 0,
found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) :
undefined;
if ( !found ) {
for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) {
if ( !tag || jQuery.nodeName( elem, tag ) ) {
found.push( elem );
} else {
jQuery.merge( found, getAll( elem, tag ) );
}
}
}
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], found ) :
found;
}
// Used in buildFragment, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( manipulation_rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var destElements, node, clone, i, srcElements,
inPage = jQuery.contains( elem.ownerDocument, elem );
if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
// Fix all IE cloning issues
for ( i = 0; (node = srcElements[i]) != null; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
fixCloneNodeIssues( node, destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0; (node = srcElements[i]) != null; i++ ) {
cloneCopyEvent( node, destElements[i] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
destElements = srcElements = node = null;
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var j, elem, contains,
tmp, tag, tbody, wrap,
l = elems.length,
// Ensure a safe fragment
safe = createSafeFragment( context ),
nodes = [],
i = 0;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || safe.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2];
// Descend through wrappers to the right content
j = wrap[0];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Manually add leading whitespace removed by IE
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
elem = tag === "table" && !rtbody.test( elem ) ?
tmp.firstChild :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !rtbody.test( elem ) ?
tmp :
0;
j = elem && elem.childNodes.length;
while ( j-- ) {
if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) {
elem.removeChild( tbody );
}
}
}
jQuery.merge( nodes, tmp.childNodes );
// Fix #12392 for WebKit and IE > 9
tmp.textContent = "";
// Fix #12392 for oldIE
while ( tmp.firstChild ) {
tmp.removeChild( tmp.firstChild );
}
// Remember the top-level container for proper cleanup
tmp = safe.lastChild;
}
}
}
// Fix #11356: Clear elements from fragment
if ( tmp ) {
safe.removeChild( tmp );
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !jQuery.support.appendChecked ) {
jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
}
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( safe.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
tmp = null;
return safe;
},
cleanData: function( elems, /* internal */ acceptData ) {
var elem, type, id, data,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( typeof elem.removeAttribute !== core_strundefined ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
core_deletedIds.push( id );
}
}
}
}
},
_evalUrl: function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function(){
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !manipulation_rcheckableType.test( type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
jQuery.fn.extend({
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
}
});
var
// Document location
ajaxLocParts,
ajaxLocation,
ajax_nonce = jQuery.now(),
ajax_rquery = /\?/,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat("*");
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( (dataType = dataTypes[i++]) ) {
// Prepend if requested
if ( dataType[0] === "+" ) {
dataType = dataType.slice( 1 ) || "*";
(structure[ dataType ] = structure[ dataType ] || []).unshift( func );
// Otherwise append
} else {
(structure[ dataType ] = structure[ dataType ] || []).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
});
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var deep, key,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, response, type,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){
jQuery.fn[ type ] = function( fn ){
return this.on( type, fn );
};
});
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Cross-domain detection vars
parts,
// Loop variable
i,
// URL without anti-cache param
cacheURL,
// Response headers as string
responseHeadersString,
// timeout handle
timeoutTimer,
// To know if global events are to be dispatched
fireGlobals,
transport,
// Response headers
responseHeaders,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks("once memory"),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while ( (match = rheaders.exec( responseHeadersString )) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""];
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger("ajaxStart");
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
cacheURL = s.url;
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if ( s.cache === false ) {
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) :
// Otherwise add one to the end
cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++;
}
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert( s, response, jqXHR, isSuccess );
// If successful, handle type chaining
if ( isSuccess ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 || s.type === "HEAD" ) {
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var firstDataType, ct, finalDataType, type,
contents = s.contents,
dataTypes = s.dataTypes;
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
/* Chain conversions given the request and the original response
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while ( current ) {
if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}
// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
prev = current;
current = dataTypes.shift();
if ( current ) {
// There's only work to do if current dataType is non-auto
if ( current === "*" ) {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split( " " );
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.unshift( tmp[ 1 ] );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s[ "throws" ] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
}
}
return { state: "success", data: response };
}
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || jQuery("head")[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement("script");
script.async = true;
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( script.parentNode ) {
script.parentNode.removeChild( script );
}
// Dereference the script
script = null;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
// Use native DOM manipulation to avoid our domManip AJAX trickery
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( undefined, true );
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
var xhrCallbacks, xhrSupported,
xhrId = 0,
// #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject && function() {
// Abort all pending requests
var key;
for ( key in xhrCallbacks ) {
xhrCallbacks[ key ]( undefined, true );
}
};
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
xhrSupported = jQuery.ajaxSettings.xhr();
jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
xhrSupported = jQuery.support.ajax = !!xhrSupported;
// Create transport if the browser can provide an xhr
if ( xhrSupported ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var handle, i,
xhr = s.xhr();
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( err ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status, responseHeaders, statusText, responses;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occurred
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
responses = {};
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
if ( typeof xhr.responseText === "string" ) {
responses.text = xhr.responseText;
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
if ( !s.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback );
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback( undefined, true );
}
}
};
}
});
}
// Limit scope pollution from any deprecated API
// (function() {
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// })();
if ( typeof module === "object" && module && typeof module.exports === "object" ) {
// Expose jQuery as module.exports in loaders that implement the Node
// module pattern (including browserify). Do not create the global, since
// the user will be storing it themselves locally, and globals are frowned
// upon in the Node module world.
module.exports = jQuery;
} else {
// Otherwise expose jQuery to the global object as usual
window.jQuery = window.$ = jQuery;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function () { return jQuery; } );
}
}
})( window );
|
'use strict';
//
// Data-forge enumerator for iterating a standard JavaScript array.
//
var TakeIterator = function (iterator, takeAmount) {
var self = this;
self._iterator = iterator;
self._takeAmount = takeAmount;
};
module.exports = TakeIterator;
TakeIterator.prototype.moveNext = function () {
var self = this;
if (--self._takeAmount >= 0) {
return self._iterator.moveNext();
}
return false;
};
TakeIterator.prototype.getCurrent = function () {
var self = this;
return self._iterator.getCurrent();
};
|
define([], function() {
/**
* A specialized version of `_.map` for arrays without support for callback
* shorthands or `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function arrayMap(array, iteratee) {
var index = -1,
length = array.length,
result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
return arrayMap;
});
|
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* SHA-1 implementation in JavaScript (c) Chris Veness 2002-2014 / MIT Licence */
/* */
/* - see http://csrc.nist.gov/groups/ST/toolkit/secure_hashing.html */
/* http://csrc.nist.gov/groups/ST/toolkit/examples.html */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* jshint node:true *//* global define, escape, unescape */
'use strict';
/**
* SHA-1 hash function reference implementation.
*
* @namespace
*/
var Sha1 = {};
/**
* Generates SHA-1 hash of string.
*
* @param {string} msg - (Unicode) string to be hashed.
* @returns {string} Hash of msg as hex character string.
*/
Sha1.hash = function(msg) {
// convert string to UTF-8, as SHA only deals with byte-streams
msg = msg.utf8Encode();
// constants [§4.2.1]
var K = [ 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6 ];
// PREPROCESSING
msg += String.fromCharCode(0x80); // add trailing '1' bit (+ 0's padding) to string [§5.1.1]
// convert string msg into 512-bit/16-integer blocks arrays of ints [§5.2.1]
var l = msg.length/4 + 2; // length (in 32-bit integers) of msg + ‘1’ + appended length
var N = Math.ceil(l/16); // number of 16-integer-blocks required to hold 'l' ints
var M = new Array(N);
for (var i=0; i<N; i++) {
M[i] = new Array(16);
for (var j=0; j<16; j++) { // encode 4 chars per integer, big-endian encoding
M[i][j] = (msg.charCodeAt(i*64+j*4)<<24) | (msg.charCodeAt(i*64+j*4+1)<<16) |
(msg.charCodeAt(i*64+j*4+2)<<8) | (msg.charCodeAt(i*64+j*4+3));
} // note running off the end of msg is ok 'cos bitwise ops on NaN return 0
}
// add length (in bits) into final pair of 32-bit integers (big-endian) [§5.1.1]
// note: most significant word would be (len-1)*8 >>> 32, but since JS converts
// bitwise-op args to 32 bits, we need to simulate this by arithmetic operators
M[N-1][14] = ((msg.length-1)*8) / Math.pow(2, 32); M[N-1][14] = Math.floor(M[N-1][14]);
M[N-1][15] = ((msg.length-1)*8) & 0xffffffff;
// set initial hash value [§5.3.1]
var H0 = 0x67452301;
var H1 = 0xefcdab89;
var H2 = 0x98badcfe;
var H3 = 0x10325476;
var H4 = 0xc3d2e1f0;
// HASH COMPUTATION [§6.1.2]
var W = new Array(80); var a, b, c, d, e;
for (var i=0; i<N; i++) {
// 1 - prepare message schedule 'W'
for (var t=0; t<16; t++) W[t] = M[i][t];
for (var t=16; t<80; t++) W[t] = Sha1.ROTL(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16], 1);
// 2 - initialise five working variables a, b, c, d, e with previous hash value
a = H0; b = H1; c = H2; d = H3; e = H4;
// 3 - main loop
for (var t=0; t<80; t++) {
var s = Math.floor(t/20); // seq for blocks of 'f' functions and 'K' constants
var T = (Sha1.ROTL(a,5) + Sha1.f(s,b,c,d) + e + K[s] + W[t]) & 0xffffffff;
e = d;
d = c;
c = Sha1.ROTL(b, 30);
b = a;
a = T;
}
// 4 - compute the new intermediate hash value (note 'addition modulo 2^32')
H0 = (H0+a) & 0xffffffff;
H1 = (H1+b) & 0xffffffff;
H2 = (H2+c) & 0xffffffff;
H3 = (H3+d) & 0xffffffff;
H4 = (H4+e) & 0xffffffff;
}
return Sha1.toHexStr(H0) + Sha1.toHexStr(H1) + Sha1.toHexStr(H2) +
Sha1.toHexStr(H3) + Sha1.toHexStr(H4);
};
/**
* Function 'f' [§4.1.1].
* @private
*/
Sha1.f = function(s, x, y, z) {
switch (s) {
case 0: return (x & y) ^ (~x & z); // Ch()
case 1: return x ^ y ^ z; // Parity()
case 2: return (x & y) ^ (x & z) ^ (y & z); // Maj()
case 3: return x ^ y ^ z; // Parity()
}
};
/**
* Rotates left (circular left shift) value x by n positions [§3.2.5].
* @private
*/
Sha1.ROTL = function(x, n) {
return (x<<n) | (x>>>(32-n));
};
/**
* Hexadecimal representation of a number.
* @private
*/
Sha1.toHexStr = function(n) {
// note can't use toString(16) as it is implementation-dependant,
// and in IE returns signed numbers when used on full words
var s="", v;
for (var i=7; i>=0; i--) { v = (n>>>(i*4)) & 0xf; s += v.toString(16); }
return s;
};
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/** Extend String object with method to encode multi-byte string to utf8
* - monsur.hossa.in/2012/07/20/utf-8-in-javascript.html */
if (typeof String.prototype.utf8Encode == 'undefined') {
String.prototype.utf8Encode = function() {
return unescape( encodeURIComponent( this ) );
};
}
/** Extend String object with method to decode utf8 string to multi-byte */
if (typeof String.prototype.utf8Decode == 'undefined') {
String.prototype.utf8Decode = function() {
try {
return decodeURIComponent( escape( this ) );
} catch (e) {
return this; // invalid UTF-8? return as-is
}
};
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
if (typeof module != 'undefined' && module.exports) module.exports = Sha1; // CommonJs export
if (typeof define == 'function' && define.amd) define([], function() { return Sha1; }); // AMD |
/**
@module ember
@submodule ember-routing-htmlbars
*/
import Ember from "ember-metal/core"; // Handlebars, uuid, FEATURES, assert, deprecate
import { uuid } from "ember-metal/utils";
import run from "ember-metal/run_loop";
import { readUnwrappedModel } from "ember-views/streams/utils";
import { isSimpleClick } from "ember-views/system/utils";
import ActionManager from "ember-views/system/action_manager";
import { isStream } from "ember-metal/streams/utils";
function actionArgs(parameters, actionName) {
var ret, i, l;
if (actionName === undefined) {
ret = new Array(parameters.length);
for (i=0, l=parameters.length;i<l;i++) {
ret[i] = readUnwrappedModel(parameters[i]);
}
} else {
ret = new Array(parameters.length + 1);
ret[0] = actionName;
for (i=0, l=parameters.length;i<l; i++) {
ret[i + 1] = readUnwrappedModel(parameters[i]);
}
}
return ret;
}
var ActionHelper = {};
// registeredActions is re-exported for compatibility with older plugins
// that were using this undocumented API.
ActionHelper.registeredActions = ActionManager.registeredActions;
export { ActionHelper };
var keys = ["alt", "shift", "meta", "ctrl"];
var POINTER_EVENT_TYPE_REGEX = /^click|mouse|touch/;
var isAllowedEvent = function(event, allowedKeys) {
if (typeof allowedKeys === "undefined") {
if (POINTER_EVENT_TYPE_REGEX.test(event.type)) {
return isSimpleClick(event);
} else {
allowedKeys = '';
}
}
if (allowedKeys.indexOf("any") >= 0) {
return true;
}
for (var i=0, l=keys.length;i<l;i++) {
if (event[keys[i] + "Key"] && allowedKeys.indexOf(keys[i]) === -1) {
return false;
}
}
return true;
};
ActionHelper.registerAction = function(actionNameOrStream, options, allowedKeys) {
var actionId = uuid();
var eventName = options.eventName;
var parameters = options.parameters;
ActionManager.registeredActions[actionId] = {
eventName: eventName,
handler(event) {
if (!isAllowedEvent(event, allowedKeys)) { return true; }
if (options.preventDefault !== false) {
event.preventDefault();
}
if (options.bubbles === false) {
event.stopPropagation();
}
var target = options.target.value();
var actionName;
if (isStream(actionNameOrStream)) {
actionName = actionNameOrStream.value();
Ember.assert("You specified a quoteless path to the {{action}} helper " +
"which did not resolve to an action name (a string). " +
"Perhaps you meant to use a quoted actionName? (e.g. {{action 'save'}}).",
typeof actionName === 'string');
} else {
actionName = actionNameOrStream;
}
run(function runRegisteredAction() {
if (target.send) {
target.send.apply(target, actionArgs(parameters, actionName));
} else {
Ember.assert("The action '" + actionName + "' did not exist on " + target, typeof target[actionName] === 'function');
target[actionName].apply(target, actionArgs(parameters));
}
});
}
};
options.view.on('willClearRender', function() {
delete ActionManager.registeredActions[actionId];
});
return actionId;
};
/**
The `{{action}}` helper provides a useful shortcut for registering an HTML
element within a template for a single DOM event and forwarding that
interaction to the template's controller or specified `target` option.
If the controller does not implement the specified action, the event is sent
to the current route, and it bubbles up the route hierarchy from there.
For more advanced event handling see [Ember.Component](/api/classes/Ember.Component.html)
### Use
Given the following application Handlebars template on the page
```handlebars
<div {{action 'anActionName'}}>
click me
</div>
```
And application code
```javascript
App.ApplicationController = Ember.Controller.extend({
actions: {
anActionName: function() {
}
}
});
```
Will result in the following rendered HTML
```html
<div class="ember-view">
<div data-ember-action="1">
click me
</div>
</div>
```
Clicking "click me" will trigger the `anActionName` action of the
`App.ApplicationController`. In this case, no additional parameters will be passed.
If you provide additional parameters to the helper:
```handlebars
<button {{action 'edit' post}}>Edit</button>
```
Those parameters will be passed along as arguments to the JavaScript
function implementing the action.
### Event Propagation
Events triggered through the action helper will automatically have
`.preventDefault()` called on them. You do not need to do so in your event
handlers. If you need to allow event propagation (to handle file inputs for
example) you can supply the `preventDefault=false` option to the `{{action}}` helper:
```handlebars
<div {{action "sayHello" preventDefault=false}}>
<input type="file" />
<input type="checkbox" />
</div>
```
To disable bubbling, pass `bubbles=false` to the helper:
```handlebars
<button {{action 'edit' post bubbles=false}}>Edit</button>
```
If you need the default handler to trigger you should either register your
own event handler, or use event methods on your view class. See [Ember.View](/api/classes/Ember.View.html)
'Responding to Browser Events' for more information.
### Specifying DOM event type
By default the `{{action}}` helper registers for DOM `click` events. You can
supply an `on` option to the helper to specify a different DOM event name:
```handlebars
<div {{action "anActionName" on="doubleClick"}}>
click me
</div>
```
See `Ember.View` 'Responding to Browser Events' for a list of
acceptable DOM event names.
### Specifying whitelisted modifier keys
By default the `{{action}}` helper will ignore click event with pressed modifier
keys. You can supply an `allowedKeys` option to specify which keys should not be ignored.
```handlebars
<div {{action "anActionName" allowedKeys="alt"}}>
click me
</div>
```
This way the `{{action}}` will fire when clicking with the alt key pressed down.
Alternatively, supply "any" to the `allowedKeys` option to accept any combination of modifier keys.
```handlebars
<div {{action "anActionName" allowedKeys="any"}}>
click me with any key pressed
</div>
```
### Specifying a Target
There are several possible target objects for `{{action}}` helpers:
In a typical Ember application, where templates are managed through use of the
`{{outlet}}` helper, actions will bubble to the current controller, then
to the current route, and then up the route hierarchy.
Alternatively, a `target` option can be provided to the helper to change
which object will receive the method call. This option must be a path
to an object, accessible in the current context:
```handlebars
{{! the application template }}
<div {{action "anActionName" target=view}}>
click me
</div>
```
```javascript
App.ApplicationView = Ember.View.extend({
actions: {
anActionName: function() {}
}
});
```
### Additional Parameters
You may specify additional parameters to the `{{action}}` helper. These
parameters are passed along as the arguments to the JavaScript function
implementing the action.
```handlebars
{{#each person in people}}
<div {{action "edit" person}}>
click me
</div>
{{/each}}
```
Clicking "click me" will trigger the `edit` method on the current controller
with the value of `person` as a parameter.
@method action
@for Ember.Handlebars.helpers
@param {String} actionName
@param {Object} [context]*
@param {Hash} options
*/
export function actionHelper(params, hash, options, env) {
var view = env.data.view;
var target;
if (!hash.target) {
target = view.getStream('controller');
} else if (isStream(hash.target)) {
target = hash.target;
} else {
target = view.getStream(hash.target);
}
// Ember.assert("You specified a quoteless path to the {{action}} helper which did not resolve to an action name (a string). Perhaps you meant to use a quoted actionName? (e.g. {{action 'save'}}).", !params[0].isStream);
// Ember.deprecate("You specified a quoteless path to the {{action}} helper which did not resolve to an action name (a string). Perhaps you meant to use a quoted actionName? (e.g. {{action 'save'}}).", params[0].isStream);
var actionOptions = {
eventName: hash.on || "click",
parameters: params.slice(1),
view: view,
bubbles: hash.bubbles,
preventDefault: hash.preventDefault,
target: target,
withKeyCode: hash.withKeyCode
};
var actionId = ActionHelper.registerAction(params[0], actionOptions, hash.allowedKeys);
env.dom.setAttribute(options.element, 'data-ember-action', actionId);
}
|
import './polyfills.js';
export { WebGLRenderTargetCube } from './renderers/WebGLRenderTargetCube.js';
export { WebGLRenderTarget } from './renderers/WebGLRenderTarget.js';
export { WebGLRenderer } from './renderers/WebGLRenderer.js';
// export { WebGL2Renderer } from './renderers/WebGL2Renderer.js';
export { ShaderLib } from './renderers/shaders/ShaderLib.js';
export { UniformsLib } from './renderers/shaders/UniformsLib.js';
export { UniformsUtils } from './renderers/shaders/UniformsUtils.js';
export { ShaderChunk } from './renderers/shaders/ShaderChunk.js';
export { FogExp2 } from './scenes/FogExp2.js';
export { Fog } from './scenes/Fog.js';
export { Scene } from './scenes/Scene.js';
export { LensFlare } from './objects/LensFlare.js';
export { Sprite } from './objects/Sprite.js';
export { LOD } from './objects/LOD.js';
export { SkinnedMesh } from './objects/SkinnedMesh.js';
export { Skeleton } from './objects/Skeleton.js';
export { Bone } from './objects/Bone.js';
export { Mesh } from './objects/Mesh.js';
export { LineSegments } from './objects/LineSegments.js';
export { LineLoop } from './objects/LineLoop.js';
export { Line } from './objects/Line.js';
export { Points } from './objects/Points.js';
export { Group } from './objects/Group.js';
export { VideoTexture } from './textures/VideoTexture.js';
export { DataTexture } from './textures/DataTexture.js';
export { CompressedTexture } from './textures/CompressedTexture.js';
export { CubeTexture } from './textures/CubeTexture.js';
export { CanvasTexture } from './textures/CanvasTexture.js';
export { DepthTexture } from './textures/DepthTexture.js';
export { Texture } from './textures/Texture.js';
export * from './geometries/Geometries.js';
export * from './materials/Materials.js';
export { CompressedTextureLoader } from './loaders/CompressedTextureLoader.js';
export { DataTextureLoader } from './loaders/DataTextureLoader.js';
export { CubeTextureLoader } from './loaders/CubeTextureLoader.js';
export { TextureLoader } from './loaders/TextureLoader.js';
export { ObjectLoader } from './loaders/ObjectLoader.js';
export { MaterialLoader } from './loaders/MaterialLoader.js';
export { BufferGeometryLoader } from './loaders/BufferGeometryLoader.js';
export { DefaultLoadingManager, LoadingManager } from './loaders/LoadingManager.js';
export { JSONLoader } from './loaders/JSONLoader.js';
export { ImageLoader } from './loaders/ImageLoader.js';
export { ImageBitmapLoader } from './loaders/ImageBitmapLoader.js';
export { FontLoader } from './loaders/FontLoader.js';
export { FileLoader } from './loaders/FileLoader.js';
export { Loader } from './loaders/Loader.js';
export { LoaderUtils } from './loaders/LoaderUtils.js';
export { Cache } from './loaders/Cache.js';
export { AudioLoader } from './loaders/AudioLoader.js';
export { SpotLightShadow } from './lights/SpotLightShadow.js';
export { SpotLight } from './lights/SpotLight.js';
export { PointLight } from './lights/PointLight.js';
export { RectAreaLight } from './lights/RectAreaLight.js';
export { HemisphereLight } from './lights/HemisphereLight.js';
export { DirectionalLightShadow } from './lights/DirectionalLightShadow.js';
export { DirectionalLight } from './lights/DirectionalLight.js';
export { AmbientLight } from './lights/AmbientLight.js';
export { LightShadow } from './lights/LightShadow.js';
export { Light } from './lights/Light.js';
export { StereoCamera } from './cameras/StereoCamera.js';
export { PerspectiveCamera } from './cameras/PerspectiveCamera.js';
export { OrthographicCamera } from './cameras/OrthographicCamera.js';
export { CubeCamera } from './cameras/CubeCamera.js';
export { ArrayCamera } from './cameras/ArrayCamera.js';
export { Camera } from './cameras/Camera.js';
export { AudioListener } from './audio/AudioListener.js';
export { PositionalAudio } from './audio/PositionalAudio.js';
export { AudioContext } from './audio/AudioContext.js';
export { AudioAnalyser } from './audio/AudioAnalyser.js';
export { Audio } from './audio/Audio.js';
export { VectorKeyframeTrack } from './animation/tracks/VectorKeyframeTrack.js';
export { StringKeyframeTrack } from './animation/tracks/StringKeyframeTrack.js';
export { QuaternionKeyframeTrack } from './animation/tracks/QuaternionKeyframeTrack.js';
export { NumberKeyframeTrack } from './animation/tracks/NumberKeyframeTrack.js';
export { ColorKeyframeTrack } from './animation/tracks/ColorKeyframeTrack.js';
export { BooleanKeyframeTrack } from './animation/tracks/BooleanKeyframeTrack.js';
export { PropertyMixer } from './animation/PropertyMixer.js';
export { PropertyBinding } from './animation/PropertyBinding.js';
export { KeyframeTrack } from './animation/KeyframeTrack.js';
export { AnimationUtils } from './animation/AnimationUtils.js';
export { AnimationObjectGroup } from './animation/AnimationObjectGroup.js';
export { AnimationMixer } from './animation/AnimationMixer.js';
export { AnimationClip } from './animation/AnimationClip.js';
export { Uniform } from './core/Uniform.js';
export { InstancedBufferGeometry } from './core/InstancedBufferGeometry.js';
export { BufferGeometry } from './core/BufferGeometry.js';
export { Geometry } from './core/Geometry.js';
export { InterleavedBufferAttribute } from './core/InterleavedBufferAttribute.js';
export { InstancedInterleavedBuffer } from './core/InstancedInterleavedBuffer.js';
export { InterleavedBuffer } from './core/InterleavedBuffer.js';
export { InstancedBufferAttribute } from './core/InstancedBufferAttribute.js';
export * from './core/BufferAttribute.js';
export { Face3 } from './core/Face3.js';
export { Object3D } from './core/Object3D.js';
export { Raycaster } from './core/Raycaster.js';
export { Layers } from './core/Layers.js';
export { EventDispatcher } from './core/EventDispatcher.js';
export { Clock } from './core/Clock.js';
export { QuaternionLinearInterpolant } from './math/interpolants/QuaternionLinearInterpolant.js';
export { LinearInterpolant } from './math/interpolants/LinearInterpolant.js';
export { DiscreteInterpolant } from './math/interpolants/DiscreteInterpolant.js';
export { CubicInterpolant } from './math/interpolants/CubicInterpolant.js';
export { Interpolant } from './math/Interpolant.js';
export { Triangle } from './math/Triangle.js';
export { _Math as Math } from './math/Math.js';
export { Spherical } from './math/Spherical.js';
export { Cylindrical } from './math/Cylindrical.js';
export { Plane } from './math/Plane.js';
export { Frustum } from './math/Frustum.js';
export { Sphere } from './math/Sphere.js';
export { Ray } from './math/Ray.js';
export { Matrix4 } from './math/Matrix4.js';
export { Matrix3 } from './math/Matrix3.js';
export { Box3 } from './math/Box3.js';
export { Box2 } from './math/Box2.js';
export { Line3 } from './math/Line3.js';
export { Euler } from './math/Euler.js';
export { Vector4 } from './math/Vector4.js';
export { Vector3 } from './math/Vector3.js';
export { Vector2 } from './math/Vector2.js';
export { Quaternion } from './math/Quaternion.js';
export { Color } from './math/Color.js';
export { ImmediateRenderObject } from './extras/objects/ImmediateRenderObject.js';
export { VertexNormalsHelper } from './helpers/VertexNormalsHelper.js';
export { SpotLightHelper } from './helpers/SpotLightHelper.js';
export { SkeletonHelper } from './helpers/SkeletonHelper.js';
export { PointLightHelper } from './helpers/PointLightHelper.js';
export { RectAreaLightHelper } from './helpers/RectAreaLightHelper.js';
export { HemisphereLightHelper } from './helpers/HemisphereLightHelper.js';
export { GridHelper } from './helpers/GridHelper.js';
export { PolarGridHelper } from './helpers/PolarGridHelper.js';
export { FaceNormalsHelper } from './helpers/FaceNormalsHelper.js';
export { DirectionalLightHelper } from './helpers/DirectionalLightHelper.js';
export { CameraHelper } from './helpers/CameraHelper.js';
export { BoxHelper } from './helpers/BoxHelper.js';
export { Box3Helper } from './helpers/Box3Helper.js';
export { PlaneHelper } from './helpers/PlaneHelper.js';
export { ArrowHelper } from './helpers/ArrowHelper.js';
export { AxesHelper } from './helpers/AxesHelper.js';
export * from './extras/curves/Curves.js';
export { Shape } from './extras/core/Shape.js';
export { Path } from './extras/core/Path.js';
export { ShapePath } from './extras/core/ShapePath.js';
export { Font } from './extras/core/Font.js';
export { CurvePath } from './extras/core/CurvePath.js';
export { Curve } from './extras/core/Curve.js';
export { ShapeUtils } from './extras/ShapeUtils.js';
export { SceneUtils } from './extras/SceneUtils.js';
export { WebGLUtils } from './renderers/webgl/WebGLUtils.js';
export * from './constants.js';
export * from './Three.Legacy.js';
|
import {
cachedData,
getCurrentHoverElement,
setCurrentHoverElement,
addInteractionClass,
} from '~/code_navigation/utils';
afterEach(() => {
if (cachedData.has('current')) {
cachedData.delete('current');
}
});
describe('getCurrentHoverElement', () => {
it.each`
value
${'test'}
${undefined}
`('it returns cached current key', ({ value }) => {
if (value) {
cachedData.set('current', value);
}
expect(getCurrentHoverElement()).toEqual(value);
});
});
describe('setCurrentHoverElement', () => {
it('sets cached current key', () => {
setCurrentHoverElement('test');
expect(getCurrentHoverElement()).toEqual('test');
});
});
describe('addInteractionClass', () => {
beforeEach(() => {
setFixtures(
'<div data-path="index.js"><div class="blob-content"><div id="LC1" class="line"><span>console</span><span>.</span><span>log</span></div><div id="LC2" class="line"><span>function</span></div></div></div>',
);
});
it.each`
line | char | index
${0} | ${0} | ${0}
${0} | ${8} | ${2}
${1} | ${0} | ${0}
`(
'it sets code navigation attributes for line $line and character $char',
({ line, char, index }) => {
addInteractionClass('index.js', { start_line: line, start_char: char });
expect(document.querySelectorAll(`#LC${line + 1} span`)[index].classList).toContain(
'js-code-navigation',
);
},
);
});
|
const path = require(`path`)
exports.chunkNamer = chunk => {
if (chunk.name) return chunk.name
let n = []
chunk.forEachModule(m => {
n.push(path.relative(m.context, m.userRequest))
})
return n.join(`_`)
}
|
var engine = require('../');
var express = require('express');
var path = require('path');
var app = express();
app.engine('dot', engine.__express);
app.set('views', path.join(__dirname, './views'));
app.set('view engine', 'dot');
app.get('/', function(req, res) {
res.render('index', { fromServer: 'Hello from server', });
});
app.get('/layout', function(req, res) {
res.render('layout/index');
});
app.get('/cascade', function(req, res) {
res.render('cascade/me');
});
app.get('/partial', function(req, res) {
res.render('partial/index');
});
app.get('/helper', function(req, res) {
// helper as a property
engine.helper.myHelperProperty = 'Hello from server property helper';
// helper as a method
engine.helper.myHelperMethod = function(param) {
return 'Hello from server method helper (parameter: ' + param + ', server model: ' + this.model.fromServer + ')';
}
res.render('helper/index', { fromServer: 'Hello from server', });
});
var server = app.listen(2015, function() {
console.log('Run the example at http://locahost:%d', server.address().port);
});
|
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var WSProcessor = require('./wsprocessor');
var TCPProcessor = require('./tcpprocessor');
var logger = require('pomelo-logger').getLogger('pomelo', __filename);
var HTTP_METHODS = [
'GET', 'POST', 'DELETE', 'PUT', 'HEAD'
];
var ST_STARTED = 1;
var ST_CLOSED = 2;
var DEFAULT_TIMEOUT = 90;
/**
* Switcher for tcp and websocket protocol
*
* @param {Object} server tcp server instance from node.js net module
*/
var Switcher = function(server, opts) {
EventEmitter.call(this);
this.server = server;
this.wsprocessor = new WSProcessor();
this.tcpprocessor = new TCPProcessor(opts.closeMethod);
this.id = 1;
this.timers = {};
this.timeout = opts.timeout || DEFAULT_TIMEOUT;
this.setNoDelay = opts.setNoDelay;
this.server.on('connection', this.newSocket.bind(this));
this.wsprocessor.on('connection', this.emit.bind(this, 'connection'));
this.tcpprocessor.on('connection', this.emit.bind(this, 'connection'));
this.state = ST_STARTED;
};
util.inherits(Switcher, EventEmitter);
module.exports = Switcher;
Switcher.prototype.newSocket = function(socket) {
if(this.state !== ST_STARTED) {
return;
}
// if set connection timeout
if(!!this.timeout) {
var timer = setTimeout(function() {
logger.warn('connection is timeout without communication, the remote ip is %s && port is %s', socket.remoteAddress, socket.remotePort);
socket.destroy();
}, this.timeout * 1000);
this.timers[this.id] = timer;
socket.id = this.id++;
}
var self = this;
socket.once('close', function() {
if (!!socket.id) {
clearTimeout(self.timers[socket.id]);
delete self.timers[socket.id];
}
});
socket.once('data', function(data) {
if(!!socket.id) {
clearTimeout(self.timers[socket.id]);
delete self.timers[socket.id];
}
if(isHttp(data)) {
processHttp(self, self.wsprocessor, socket, data);
} else {
if(!!self.setNoDelay) {
socket.setNoDelay(true);
}
processTcp(self, self.tcpprocessor, socket, data);
}
});
};
Switcher.prototype.close = function() {
if(this.state !== ST_STARTED) {
return;
}
this.state = ST_CLOSED;
this.wsprocessor.close();
this.tcpprocessor.close();
};
var isHttp = function(data) {
var head = data.toString('utf8', 0, 4);
for(var i=0, l=HTTP_METHODS.length; i<l; i++) {
if(head.indexOf(HTTP_METHODS[i]) === 0) {
return true;
}
}
return false;
};
var processHttp = function(switcher, processor, socket, data) {
processor.add(socket, data);
};
var processTcp = function(switcher, processor, socket, data) {
processor.add(socket, data);
};
|
'use strict';
var app = angular.module('myApp.payloads.directives', []);
app.directive('runPayload', ['Payload', 'Command', '$routeParams', 'showToast', 'showErrors', 'gettextCatalog', function(Payload, Command, $routeParams, showToast, showErrors, gettextCatalog) {
var link = function( scope, element, attrs ) {
scope.location = { slug: $routeParams.id };
var box = { slug: $routeParams.box_id };
var loadCommands = function() {
Command.query().$promise.then(function(results) {
scope.commands = results;
scope.loading_commands = undefined;
});
};
scope.runCommand = function() {
scope.processing = true;
updateCT();
};
var updateCT = function() {
var cmd = scope.command.selected;
scope.command.selected = undefined;
Payload.create({}, {
location_id: scope.location.slug,
box_id: box.slug,
payload: {
box_ids: box.slug,
command_id: cmd,
save: true
}
}).$promise.then(function() {
showToast(gettextCatalog.getString('Payload running, please wait.'));
}, function(errors) {
showErrors(errors);
});
};
loadCommands();
};
return {
link: link,
scope: {
command: '=',
allowed: '@'
},
templateUrl: 'components/payloads/_run_payload.html',
};
}]);
|
/* flatpickr v4.6.0, @license MIT */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.flatpickr = factory());
}(this, function () { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var HOOKS = [
"onChange",
"onClose",
"onDayCreate",
"onDestroy",
"onKeyDown",
"onMonthChange",
"onOpen",
"onParseConfig",
"onReady",
"onValueUpdate",
"onYearChange",
"onPreCalendarPosition",
];
var defaults = {
_disable: [],
_enable: [],
allowInput: false,
altFormat: "F j, Y",
altInput: false,
altInputClass: "form-control input",
animate: typeof window === "object" &&
window.navigator.userAgent.indexOf("MSIE") === -1,
ariaDateFormat: "F j, Y",
clickOpens: true,
closeOnSelect: true,
conjunction: ", ",
dateFormat: "Y-m-d",
defaultHour: 12,
defaultMinute: 0,
defaultSeconds: 0,
disable: [],
disableMobile: false,
enable: [],
enableSeconds: false,
enableTime: false,
errorHandler: function (err) {
return typeof console !== "undefined" && console.warn(err);
},
getWeek: function (givenDate) {
var date = new Date(givenDate.getTime());
date.setHours(0, 0, 0, 0);
// Thursday in current week decides the year.
date.setDate(date.getDate() + 3 - ((date.getDay() + 6) % 7));
// January 4 is always in week 1.
var week1 = new Date(date.getFullYear(), 0, 4);
// Adjust to Thursday in week 1 and count number of weeks from date to week1.
return (1 +
Math.round(((date.getTime() - week1.getTime()) / 86400000 -
3 +
((week1.getDay() + 6) % 7)) /
7));
},
hourIncrement: 1,
ignoredFocusElements: [],
inline: false,
locale: "default",
minuteIncrement: 5,
mode: "single",
nextArrow: "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 17 17'><g></g><path d='M13.207 8.472l-7.854 7.854-0.707-0.707 7.146-7.146-7.146-7.148 0.707-0.707 7.854 7.854z' /></svg>",
noCalendar: false,
now: new Date(),
onChange: [],
onClose: [],
onDayCreate: [],
onDestroy: [],
onKeyDown: [],
onMonthChange: [],
onOpen: [],
onParseConfig: [],
onReady: [],
onValueUpdate: [],
onYearChange: [],
onPreCalendarPosition: [],
plugins: [],
position: "auto",
positionElement: undefined,
prevArrow: "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 17 17'><g></g><path d='M5.207 8.471l7.146 7.147-0.707 0.707-7.853-7.854 7.854-7.853 0.707 0.707-7.147 7.146z' /></svg>",
shorthandCurrentMonth: false,
showMonths: 1,
static: false,
time_24hr: false,
weekNumbers: false,
wrap: false
};
var english = {
weekdays: {
shorthand: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
longhand: [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
]
},
months: {
shorthand: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
],
longhand: [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
]
},
daysInMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
firstDayOfWeek: 0,
ordinal: function (nth) {
var s = nth % 100;
if (s > 3 && s < 21)
return "th";
switch (s % 10) {
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
},
rangeSeparator: " to ",
weekAbbreviation: "Wk",
scrollTitle: "Scroll to increment",
toggleTitle: "Click to toggle",
amPM: ["AM", "PM"],
yearAriaLabel: "Year",
time_24hr: false
};
var pad = function (number) { return ("0" + number).slice(-2); };
var int = function (bool) { return (bool === true ? 1 : 0); };
/* istanbul ignore next */
function debounce(func, wait, immediate) {
if (immediate === void 0) { immediate = false; }
var timeout;
return function () {
var context = this, args = arguments;
timeout !== null && clearTimeout(timeout);
timeout = window.setTimeout(function () {
timeout = null;
if (!immediate)
func.apply(context, args);
}, wait);
if (immediate && !timeout)
func.apply(context, args);
};
}
var arrayify = function (obj) {
return obj instanceof Array ? obj : [obj];
};
function toggleClass(elem, className, bool) {
if (bool === true)
return elem.classList.add(className);
elem.classList.remove(className);
}
function createElement(tag, className, content) {
var e = window.document.createElement(tag);
className = className || "";
content = content || "";
e.className = className;
if (content !== undefined)
e.textContent = content;
return e;
}
function clearNode(node) {
while (node.firstChild)
node.removeChild(node.firstChild);
}
function findParent(node, condition) {
if (condition(node))
return node;
else if (node.parentNode)
return findParent(node.parentNode, condition);
return undefined; // nothing found
}
function createNumberInput(inputClassName, opts) {
var wrapper = createElement("div", "numInputWrapper"), numInput = createElement("input", "numInput " + inputClassName), arrowUp = createElement("span", "arrowUp"), arrowDown = createElement("span", "arrowDown");
if (navigator.userAgent.indexOf("MSIE 9.0") === -1) {
numInput.type = "number";
}
else {
numInput.type = "text";
numInput.pattern = "\\d*";
}
if (opts !== undefined)
for (var key in opts)
numInput.setAttribute(key, opts[key]);
wrapper.appendChild(numInput);
wrapper.appendChild(arrowUp);
wrapper.appendChild(arrowDown);
return wrapper;
}
function getEventTarget(event) {
if (typeof event.composedPath === "function") {
var path = event.composedPath();
return path[0];
}
return event.target;
}
var doNothing = function () { return undefined; };
var monthToStr = function (monthNumber, shorthand, locale) { return locale.months[shorthand ? "shorthand" : "longhand"][monthNumber]; };
var revFormat = {
D: doNothing,
F: function (dateObj, monthName, locale) {
dateObj.setMonth(locale.months.longhand.indexOf(monthName));
},
G: function (dateObj, hour) {
dateObj.setHours(parseFloat(hour));
},
H: function (dateObj, hour) {
dateObj.setHours(parseFloat(hour));
},
J: function (dateObj, day) {
dateObj.setDate(parseFloat(day));
},
K: function (dateObj, amPM, locale) {
dateObj.setHours((dateObj.getHours() % 12) +
12 * int(new RegExp(locale.amPM[1], "i").test(amPM)));
},
M: function (dateObj, shortMonth, locale) {
dateObj.setMonth(locale.months.shorthand.indexOf(shortMonth));
},
S: function (dateObj, seconds) {
dateObj.setSeconds(parseFloat(seconds));
},
U: function (_, unixSeconds) { return new Date(parseFloat(unixSeconds) * 1000); },
W: function (dateObj, weekNum, locale) {
var weekNumber = parseInt(weekNum);
var date = new Date(dateObj.getFullYear(), 0, 2 + (weekNumber - 1) * 7, 0, 0, 0, 0);
date.setDate(date.getDate() - date.getDay() + locale.firstDayOfWeek);
return date;
},
Y: function (dateObj, year) {
dateObj.setFullYear(parseFloat(year));
},
Z: function (_, ISODate) { return new Date(ISODate); },
d: function (dateObj, day) {
dateObj.setDate(parseFloat(day));
},
h: function (dateObj, hour) {
dateObj.setHours(parseFloat(hour));
},
i: function (dateObj, minutes) {
dateObj.setMinutes(parseFloat(minutes));
},
j: function (dateObj, day) {
dateObj.setDate(parseFloat(day));
},
l: doNothing,
m: function (dateObj, month) {
dateObj.setMonth(parseFloat(month) - 1);
},
n: function (dateObj, month) {
dateObj.setMonth(parseFloat(month) - 1);
},
s: function (dateObj, seconds) {
dateObj.setSeconds(parseFloat(seconds));
},
u: function (_, unixMillSeconds) {
return new Date(parseFloat(unixMillSeconds));
},
w: doNothing,
y: function (dateObj, year) {
dateObj.setFullYear(2000 + parseFloat(year));
}
};
var tokenRegex = {
D: "(\\w+)",
F: "(\\w+)",
G: "(\\d\\d|\\d)",
H: "(\\d\\d|\\d)",
J: "(\\d\\d|\\d)\\w+",
K: "",
M: "(\\w+)",
S: "(\\d\\d|\\d)",
U: "(.+)",
W: "(\\d\\d|\\d)",
Y: "(\\d{4})",
Z: "(.+)",
d: "(\\d\\d|\\d)",
h: "(\\d\\d|\\d)",
i: "(\\d\\d|\\d)",
j: "(\\d\\d|\\d)",
l: "(\\w+)",
m: "(\\d\\d|\\d)",
n: "(\\d\\d|\\d)",
s: "(\\d\\d|\\d)",
u: "(.+)",
w: "(\\d\\d|\\d)",
y: "(\\d{2})"
};
var formats = {
// get the date in UTC
Z: function (date) { return date.toISOString(); },
// weekday name, short, e.g. Thu
D: function (date, locale, options) {
return locale.weekdays.shorthand[formats.w(date, locale, options)];
},
// full month name e.g. January
F: function (date, locale, options) {
return monthToStr(formats.n(date, locale, options) - 1, false, locale);
},
// padded hour 1-12
G: function (date, locale, options) {
return pad(formats.h(date, locale, options));
},
// hours with leading zero e.g. 03
H: function (date) { return pad(date.getHours()); },
// day (1-30) with ordinal suffix e.g. 1st, 2nd
J: function (date, locale) {
return locale.ordinal !== undefined
? date.getDate() + locale.ordinal(date.getDate())
: date.getDate();
},
// AM/PM
K: function (date, locale) { return locale.amPM[int(date.getHours() > 11)]; },
// shorthand month e.g. Jan, Sep, Oct, etc
M: function (date, locale) {
return monthToStr(date.getMonth(), true, locale);
},
// seconds 00-59
S: function (date) { return pad(date.getSeconds()); },
// unix timestamp
U: function (date) { return date.getTime() / 1000; },
W: function (date, _, options) {
return options.getWeek(date);
},
// full year e.g. 2016
Y: function (date) { return date.getFullYear(); },
// day in month, padded (01-30)
d: function (date) { return pad(date.getDate()); },
// hour from 1-12 (am/pm)
h: function (date) { return (date.getHours() % 12 ? date.getHours() % 12 : 12); },
// minutes, padded with leading zero e.g. 09
i: function (date) { return pad(date.getMinutes()); },
// day in month (1-30)
j: function (date) { return date.getDate(); },
// weekday name, full, e.g. Thursday
l: function (date, locale) {
return locale.weekdays.longhand[date.getDay()];
},
// padded month number (01-12)
m: function (date) { return pad(date.getMonth() + 1); },
// the month number (1-12)
n: function (date) { return date.getMonth() + 1; },
// seconds 0-59
s: function (date) { return date.getSeconds(); },
// Unix Milliseconds
u: function (date) { return date.getTime(); },
// number of the day of the week
w: function (date) { return date.getDay(); },
// last two digits of year e.g. 16 for 2016
y: function (date) { return String(date.getFullYear()).substring(2); }
};
var createDateFormatter = function (_a) {
var _b = _a.config, config = _b === void 0 ? defaults : _b, _c = _a.l10n, l10n = _c === void 0 ? english : _c;
return function (dateObj, frmt, overrideLocale) {
var locale = overrideLocale || l10n;
if (config.formatDate !== undefined) {
return config.formatDate(dateObj, frmt, locale);
}
return frmt
.split("")
.map(function (c, i, arr) {
return formats[c] && arr[i - 1] !== "\\"
? formats[c](dateObj, locale, config)
: c !== "\\"
? c
: "";
})
.join("");
};
};
var createDateParser = function (_a) {
var _b = _a.config, config = _b === void 0 ? defaults : _b, _c = _a.l10n, l10n = _c === void 0 ? english : _c;
return function (date, givenFormat, timeless, customLocale) {
if (date !== 0 && !date)
return undefined;
var locale = customLocale || l10n;
var parsedDate;
var dateOrig = date;
if (date instanceof Date)
parsedDate = new Date(date.getTime());
else if (typeof date !== "string" &&
date.toFixed !== undefined // timestamp
)
// create a copy
parsedDate = new Date(date);
else if (typeof date === "string") {
// date string
var format = givenFormat || (config || defaults).dateFormat;
var datestr = String(date).trim();
if (datestr === "today") {
parsedDate = new Date();
timeless = true;
}
else if (/Z$/.test(datestr) ||
/GMT$/.test(datestr) // datestrings w/ timezone
)
parsedDate = new Date(date);
else if (config && config.parseDate)
parsedDate = config.parseDate(date, format);
else {
parsedDate =
!config || !config.noCalendar
? new Date(new Date().getFullYear(), 0, 1, 0, 0, 0, 0)
: new Date(new Date().setHours(0, 0, 0, 0));
var matched = void 0, ops = [];
for (var i = 0, matchIndex = 0, regexStr = ""; i < format.length; i++) {
var token_1 = format[i];
var isBackSlash = token_1 === "\\";
var escaped = format[i - 1] === "\\" || isBackSlash;
if (tokenRegex[token_1] && !escaped) {
regexStr += tokenRegex[token_1];
var match = new RegExp(regexStr).exec(date);
if (match && (matched = true)) {
ops[token_1 !== "Y" ? "push" : "unshift"]({
fn: revFormat[token_1],
val: match[++matchIndex]
});
}
}
else if (!isBackSlash)
regexStr += "."; // don't really care
ops.forEach(function (_a) {
var fn = _a.fn, val = _a.val;
return (parsedDate = fn(parsedDate, val, locale) || parsedDate);
});
}
parsedDate = matched ? parsedDate : undefined;
}
}
/* istanbul ignore next */
if (!(parsedDate instanceof Date && !isNaN(parsedDate.getTime()))) {
config.errorHandler(new Error("Invalid date provided: " + dateOrig));
return undefined;
}
if (timeless === true)
parsedDate.setHours(0, 0, 0, 0);
return parsedDate;
};
};
/**
* Compute the difference in dates, measured in ms
*/
function compareDates(date1, date2, timeless) {
if (timeless === void 0) { timeless = true; }
if (timeless !== false) {
return (new Date(date1.getTime()).setHours(0, 0, 0, 0) -
new Date(date2.getTime()).setHours(0, 0, 0, 0));
}
return date1.getTime() - date2.getTime();
}
var isBetween = function (ts, ts1, ts2) {
return ts > Math.min(ts1, ts2) && ts < Math.max(ts1, ts2);
};
var duration = {
DAY: 86400000
};
if (typeof Object.assign !== "function") {
Object.assign = function (target) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
if (!target) {
throw TypeError("Cannot convert undefined or null to object");
}
var _loop_1 = function (source) {
if (source) {
Object.keys(source).forEach(function (key) { return (target[key] = source[key]); });
}
};
for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {
var source = args_1[_a];
_loop_1(source);
}
return target;
};
}
var DEBOUNCED_CHANGE_MS = 300;
function FlatpickrInstance(element, instanceConfig) {
var self = {
config: __assign({}, defaults, flatpickr.defaultConfig),
l10n: english
};
self.parseDate = createDateParser({ config: self.config, l10n: self.l10n });
self._handlers = [];
self.pluginElements = [];
self.loadedPlugins = [];
self._bind = bind;
self._setHoursFromDate = setHoursFromDate;
self._positionCalendar = positionCalendar;
self.changeMonth = changeMonth;
self.changeYear = changeYear;
self.clear = clear;
self.close = close;
self._createElement = createElement;
self.destroy = destroy;
self.isEnabled = isEnabled;
self.jumpToDate = jumpToDate;
self.open = open;
self.redraw = redraw;
self.set = set;
self.setDate = setDate;
self.toggle = toggle;
function setupHelperFunctions() {
self.utils = {
getDaysInMonth: function (month, yr) {
if (month === void 0) { month = self.currentMonth; }
if (yr === void 0) { yr = self.currentYear; }
if (month === 1 && ((yr % 4 === 0 && yr % 100 !== 0) || yr % 400 === 0))
return 29;
return self.l10n.daysInMonth[month];
}
};
}
function init() {
self.element = self.input = element;
self.isOpen = false;
parseConfig();
setupLocale();
setupInputs();
setupDates();
setupHelperFunctions();
if (!self.isMobile)
build();
bindEvents();
if (self.selectedDates.length || self.config.noCalendar) {
if (self.config.enableTime) {
setHoursFromDate(self.config.noCalendar
? self.latestSelectedDateObj || self.config.minDate
: undefined);
}
updateValue(false);
}
setCalendarWidth();
self.showTimeInput =
self.selectedDates.length > 0 || self.config.noCalendar;
var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
/* TODO: investigate this further
Currently, there is weird positioning behavior in safari causing pages
to scroll up. https://github.com/chmln/flatpickr/issues/563
However, most browsers are not Safari and positioning is expensive when used
in scale. https://github.com/chmln/flatpickr/issues/1096
*/
if (!self.isMobile && isSafari) {
positionCalendar();
}
triggerEvent("onReady");
}
function bindToInstance(fn) {
return fn.bind(self);
}
function setCalendarWidth() {
var config = self.config;
if (config.weekNumbers === false && config.showMonths === 1)
return;
else if (config.noCalendar !== true) {
window.requestAnimationFrame(function () {
if (self.calendarContainer !== undefined) {
self.calendarContainer.style.visibility = "hidden";
self.calendarContainer.style.display = "block";
}
if (self.daysContainer !== undefined) {
var daysWidth = (self.days.offsetWidth + 1) * config.showMonths;
self.daysContainer.style.width = daysWidth + "px";
self.calendarContainer.style.width =
daysWidth +
(self.weekWrapper !== undefined
? self.weekWrapper.offsetWidth
: 0) +
"px";
self.calendarContainer.style.removeProperty("visibility");
self.calendarContainer.style.removeProperty("display");
}
});
}
}
/**
* The handler for all events targeting the time inputs
*/
function updateTime(e) {
if (self.selectedDates.length === 0) {
setDefaultTime();
}
if (e !== undefined && e.type !== "blur") {
timeWrapper(e);
}
var prevValue = self._input.value;
setHoursFromInputs();
updateValue();
if (self._input.value !== prevValue) {
self._debouncedChange();
}
}
function ampm2military(hour, amPM) {
return (hour % 12) + 12 * int(amPM === self.l10n.amPM[1]);
}
function military2ampm(hour) {
switch (hour % 24) {
case 0:
case 12:
return 12;
default:
return hour % 12;
}
}
/**
* Syncs the selected date object time with user's time input
*/
function setHoursFromInputs() {
if (self.hourElement === undefined || self.minuteElement === undefined)
return;
var hours = (parseInt(self.hourElement.value.slice(-2), 10) || 0) % 24, minutes = (parseInt(self.minuteElement.value, 10) || 0) % 60, seconds = self.secondElement !== undefined
? (parseInt(self.secondElement.value, 10) || 0) % 60
: 0;
if (self.amPM !== undefined) {
hours = ampm2military(hours, self.amPM.textContent);
}
var limitMinHours = self.config.minTime !== undefined ||
(self.config.minDate &&
self.minDateHasTime &&
self.latestSelectedDateObj &&
compareDates(self.latestSelectedDateObj, self.config.minDate, true) ===
0);
var limitMaxHours = self.config.maxTime !== undefined ||
(self.config.maxDate &&
self.maxDateHasTime &&
self.latestSelectedDateObj &&
compareDates(self.latestSelectedDateObj, self.config.maxDate, true) ===
0);
if (limitMaxHours) {
var maxTime = self.config.maxTime !== undefined
? self.config.maxTime
: self.config.maxDate;
hours = Math.min(hours, maxTime.getHours());
if (hours === maxTime.getHours())
minutes = Math.min(minutes, maxTime.getMinutes());
if (minutes === maxTime.getMinutes())
seconds = Math.min(seconds, maxTime.getSeconds());
}
if (limitMinHours) {
var minTime = self.config.minTime !== undefined
? self.config.minTime
: self.config.minDate;
hours = Math.max(hours, minTime.getHours());
if (hours === minTime.getHours())
minutes = Math.max(minutes, minTime.getMinutes());
if (minutes === minTime.getMinutes())
seconds = Math.max(seconds, minTime.getSeconds());
}
setHours(hours, minutes, seconds);
}
/**
* Syncs time input values with a date
*/
function setHoursFromDate(dateObj) {
var date = dateObj || self.latestSelectedDateObj;
if (date)
setHours(date.getHours(), date.getMinutes(), date.getSeconds());
}
function setDefaultHours() {
var hours = self.config.defaultHour;
var minutes = self.config.defaultMinute;
var seconds = self.config.defaultSeconds;
if (self.config.minDate !== undefined) {
var minHr = self.config.minDate.getHours();
var minMinutes = self.config.minDate.getMinutes();
hours = Math.max(hours, minHr);
if (hours === minHr)
minutes = Math.max(minMinutes, minutes);
if (hours === minHr && minutes === minMinutes)
seconds = self.config.minDate.getSeconds();
}
if (self.config.maxDate !== undefined) {
var maxHr = self.config.maxDate.getHours();
var maxMinutes = self.config.maxDate.getMinutes();
hours = Math.min(hours, maxHr);
if (hours === maxHr)
minutes = Math.min(maxMinutes, minutes);
if (hours === maxHr && minutes === maxMinutes)
seconds = self.config.maxDate.getSeconds();
}
setHours(hours, minutes, seconds);
}
/**
* Sets the hours, minutes, and optionally seconds
* of the latest selected date object and the
* corresponding time inputs
* @param {Number} hours the hour. whether its military
* or am-pm gets inferred from config
* @param {Number} minutes the minutes
* @param {Number} seconds the seconds (optional)
*/
function setHours(hours, minutes, seconds) {
if (self.latestSelectedDateObj !== undefined) {
self.latestSelectedDateObj.setHours(hours % 24, minutes, seconds || 0, 0);
}
if (!self.hourElement || !self.minuteElement || self.isMobile)
return;
self.hourElement.value = pad(!self.config.time_24hr
? ((12 + hours) % 12) + 12 * int(hours % 12 === 0)
: hours);
self.minuteElement.value = pad(minutes);
if (self.amPM !== undefined)
self.amPM.textContent = self.l10n.amPM[int(hours >= 12)];
if (self.secondElement !== undefined)
self.secondElement.value = pad(seconds);
}
/**
* Handles the year input and incrementing events
* @param {Event} event the keyup or increment event
*/
function onYearInput(event) {
var year = parseInt(event.target.value) + (event.delta || 0);
if (year / 1000 > 1 ||
(event.key === "Enter" && !/[^\d]/.test(year.toString()))) {
changeYear(year);
}
}
/**
* Essentially addEventListener + tracking
* @param {Element} element the element to addEventListener to
* @param {String} event the event name
* @param {Function} handler the event handler
*/
function bind(element, event, handler, options) {
if (event instanceof Array)
return event.forEach(function (ev) { return bind(element, ev, handler, options); });
if (element instanceof Array)
return element.forEach(function (el) { return bind(el, event, handler, options); });
element.addEventListener(event, handler, options);
self._handlers.push({
element: element,
event: event,
handler: handler,
options: options
});
}
/**
* A mousedown handler which mimics click.
* Minimizes latency, since we don't need to wait for mouseup in most cases.
* Also, avoids handling right clicks.
*
* @param {Function} handler the event handler
*/
function onClick(handler) {
return function (evt) {
evt.which === 1 && handler(evt);
};
}
function triggerChange() {
triggerEvent("onChange");
}
/**
* Adds all the necessary event listeners
*/
function bindEvents() {
if (self.config.wrap) {
["open", "close", "toggle", "clear"].forEach(function (evt) {
Array.prototype.forEach.call(self.element.querySelectorAll("[data-" + evt + "]"), function (el) {
return bind(el, "click", self[evt]);
});
});
}
if (self.isMobile) {
setupMobile();
return;
}
var debouncedResize = debounce(onResize, 50);
self._debouncedChange = debounce(triggerChange, DEBOUNCED_CHANGE_MS);
if (self.daysContainer && !/iPhone|iPad|iPod/i.test(navigator.userAgent))
bind(self.daysContainer, "mouseover", function (e) {
if (self.config.mode === "range")
onMouseOver(e.target);
});
bind(window.document.body, "keydown", onKeyDown);
if (!self.config.inline && !self.config.static)
bind(window, "resize", debouncedResize);
if (window.ontouchstart !== undefined)
bind(window.document, "touchstart", documentClick);
else
bind(window.document, "mousedown", onClick(documentClick));
bind(window.document, "focus", documentClick, { capture: true });
if (self.config.clickOpens === true) {
bind(self._input, "focus", self.open);
bind(self._input, "mousedown", onClick(self.open));
}
if (self.daysContainer !== undefined) {
bind(self.monthNav, "mousedown", onClick(onMonthNavClick));
bind(self.monthNav, ["keyup", "increment"], onYearInput);
bind(self.daysContainer, "mousedown", onClick(selectDate));
}
if (self.timeContainer !== undefined &&
self.minuteElement !== undefined &&
self.hourElement !== undefined) {
var selText = function (e) {
return e.target.select();
};
bind(self.timeContainer, ["increment"], updateTime);
bind(self.timeContainer, "blur", updateTime, { capture: true });
bind(self.timeContainer, "mousedown", onClick(timeIncrement));
bind([self.hourElement, self.minuteElement], ["focus", "click"], selText);
if (self.secondElement !== undefined)
bind(self.secondElement, "focus", function () { return self.secondElement && self.secondElement.select(); });
if (self.amPM !== undefined) {
bind(self.amPM, "mousedown", onClick(function (e) {
updateTime(e);
triggerChange();
}));
}
}
}
/**
* Set the calendar view to a particular date.
* @param {Date} jumpDate the date to set the view to
* @param {boolean} triggerChange if change events should be triggered
*/
function jumpToDate(jumpDate, triggerChange) {
var jumpTo = jumpDate !== undefined
? self.parseDate(jumpDate)
: self.latestSelectedDateObj ||
(self.config.minDate && self.config.minDate > self.now
? self.config.minDate
: self.config.maxDate && self.config.maxDate < self.now
? self.config.maxDate
: self.now);
var oldYear = self.currentYear;
var oldMonth = self.currentMonth;
try {
if (jumpTo !== undefined) {
self.currentYear = jumpTo.getFullYear();
self.currentMonth = jumpTo.getMonth();
}
}
catch (e) {
/* istanbul ignore next */
e.message = "Invalid date supplied: " + jumpTo;
self.config.errorHandler(e);
}
if (triggerChange && self.currentYear !== oldYear) {
triggerEvent("onYearChange");
buildMonthSwitch();
}
if (triggerChange &&
(self.currentYear !== oldYear || self.currentMonth !== oldMonth)) {
triggerEvent("onMonthChange");
}
self.redraw();
}
/**
* The up/down arrow handler for time inputs
* @param {Event} e the click event
*/
function timeIncrement(e) {
if (~e.target.className.indexOf("arrow"))
incrementNumInput(e, e.target.classList.contains("arrowUp") ? 1 : -1);
}
/**
* Increments/decrements the value of input associ-
* ated with the up/down arrow by dispatching an
* "increment" event on the input.
*
* @param {Event} e the click event
* @param {Number} delta the diff (usually 1 or -1)
* @param {Element} inputElem the input element
*/
function incrementNumInput(e, delta, inputElem) {
var target = e && e.target;
var input = inputElem ||
(target && target.parentNode && target.parentNode.firstChild);
var event = createEvent("increment");
event.delta = delta;
input && input.dispatchEvent(event);
}
function build() {
var fragment = window.document.createDocumentFragment();
self.calendarContainer = createElement("div", "flatpickr-calendar");
self.calendarContainer.tabIndex = -1;
if (!self.config.noCalendar) {
fragment.appendChild(buildMonthNav());
self.innerContainer = createElement("div", "flatpickr-innerContainer");
if (self.config.weekNumbers) {
var _a = buildWeeks(), weekWrapper = _a.weekWrapper, weekNumbers = _a.weekNumbers;
self.innerContainer.appendChild(weekWrapper);
self.weekNumbers = weekNumbers;
self.weekWrapper = weekWrapper;
}
self.rContainer = createElement("div", "flatpickr-rContainer");
self.rContainer.appendChild(buildWeekdays());
if (!self.daysContainer) {
self.daysContainer = createElement("div", "flatpickr-days");
self.daysContainer.tabIndex = -1;
}
buildDays();
self.rContainer.appendChild(self.daysContainer);
self.innerContainer.appendChild(self.rContainer);
fragment.appendChild(self.innerContainer);
}
if (self.config.enableTime) {
fragment.appendChild(buildTime());
}
toggleClass(self.calendarContainer, "rangeMode", self.config.mode === "range");
toggleClass(self.calendarContainer, "animate", self.config.animate === true);
toggleClass(self.calendarContainer, "multiMonth", self.config.showMonths > 1);
self.calendarContainer.appendChild(fragment);
var customAppend = self.config.appendTo !== undefined &&
self.config.appendTo.nodeType !== undefined;
if (self.config.inline || self.config.static) {
self.calendarContainer.classList.add(self.config.inline ? "inline" : "static");
if (self.config.inline) {
if (!customAppend && self.element.parentNode)
self.element.parentNode.insertBefore(self.calendarContainer, self._input.nextSibling);
else if (self.config.appendTo !== undefined)
self.config.appendTo.appendChild(self.calendarContainer);
}
if (self.config.static) {
var wrapper = createElement("div", "flatpickr-wrapper");
if (self.element.parentNode)
self.element.parentNode.insertBefore(wrapper, self.element);
wrapper.appendChild(self.element);
if (self.altInput)
wrapper.appendChild(self.altInput);
wrapper.appendChild(self.calendarContainer);
}
}
if (!self.config.static && !self.config.inline)
(self.config.appendTo !== undefined
? self.config.appendTo
: window.document.body).appendChild(self.calendarContainer);
}
function createDay(className, date, dayNumber, i) {
var dateIsEnabled = isEnabled(date, true), dayElement = createElement("span", "flatpickr-day " + className, date.getDate().toString());
dayElement.dateObj = date;
dayElement.$i = i;
dayElement.setAttribute("aria-label", self.formatDate(date, self.config.ariaDateFormat));
if (className.indexOf("hidden") === -1 &&
compareDates(date, self.now) === 0) {
self.todayDateElem = dayElement;
dayElement.classList.add("today");
dayElement.setAttribute("aria-current", "date");
}
if (dateIsEnabled) {
dayElement.tabIndex = -1;
if (isDateSelected(date)) {
dayElement.classList.add("selected");
self.selectedDateElem = dayElement;
if (self.config.mode === "range") {
toggleClass(dayElement, "startRange", self.selectedDates[0] &&
compareDates(date, self.selectedDates[0], true) === 0);
toggleClass(dayElement, "endRange", self.selectedDates[1] &&
compareDates(date, self.selectedDates[1], true) === 0);
if (className === "nextMonthDay")
dayElement.classList.add("inRange");
}
}
}
else {
dayElement.classList.add("flatpickr-disabled");
}
if (self.config.mode === "range") {
if (isDateInRange(date) && !isDateSelected(date))
dayElement.classList.add("inRange");
}
if (self.weekNumbers &&
self.config.showMonths === 1 &&
className !== "prevMonthDay" &&
dayNumber % 7 === 1) {
self.weekNumbers.insertAdjacentHTML("beforeend", "<span class='flatpickr-day'>" + self.config.getWeek(date) + "</span>");
}
triggerEvent("onDayCreate", dayElement);
return dayElement;
}
function focusOnDayElem(targetNode) {
targetNode.focus();
if (self.config.mode === "range")
onMouseOver(targetNode);
}
function getFirstAvailableDay(delta) {
var startMonth = delta > 0 ? 0 : self.config.showMonths - 1;
var endMonth = delta > 0 ? self.config.showMonths : -1;
for (var m = startMonth; m != endMonth; m += delta) {
var month = self.daysContainer.children[m];
var startIndex = delta > 0 ? 0 : month.children.length - 1;
var endIndex = delta > 0 ? month.children.length : -1;
for (var i = startIndex; i != endIndex; i += delta) {
var c = month.children[i];
if (c.className.indexOf("hidden") === -1 && isEnabled(c.dateObj))
return c;
}
}
return undefined;
}
function getNextAvailableDay(current, delta) {
var givenMonth = current.className.indexOf("Month") === -1
? current.dateObj.getMonth()
: self.currentMonth;
var endMonth = delta > 0 ? self.config.showMonths : -1;
var loopDelta = delta > 0 ? 1 : -1;
for (var m = givenMonth - self.currentMonth; m != endMonth; m += loopDelta) {
var month = self.daysContainer.children[m];
var startIndex = givenMonth - self.currentMonth === m
? current.$i + delta
: delta < 0
? month.children.length - 1
: 0;
var numMonthDays = month.children.length;
for (var i = startIndex; i >= 0 && i < numMonthDays && i != (delta > 0 ? numMonthDays : -1); i += loopDelta) {
var c = month.children[i];
if (c.className.indexOf("hidden") === -1 &&
isEnabled(c.dateObj) &&
Math.abs(current.$i - i) >= Math.abs(delta))
return focusOnDayElem(c);
}
}
self.changeMonth(loopDelta);
focusOnDay(getFirstAvailableDay(loopDelta), 0);
return undefined;
}
function focusOnDay(current, offset) {
var dayFocused = isInView(document.activeElement || document.body);
var startElem = current !== undefined
? current
: dayFocused
? document.activeElement
: self.selectedDateElem !== undefined && isInView(self.selectedDateElem)
? self.selectedDateElem
: self.todayDateElem !== undefined && isInView(self.todayDateElem)
? self.todayDateElem
: getFirstAvailableDay(offset > 0 ? 1 : -1);
if (startElem === undefined)
return self._input.focus();
if (!dayFocused)
return focusOnDayElem(startElem);
getNextAvailableDay(startElem, offset);
}
function buildMonthDays(year, month) {
var firstOfMonth = (new Date(year, month, 1).getDay() - self.l10n.firstDayOfWeek + 7) % 7;
var prevMonthDays = self.utils.getDaysInMonth((month - 1 + 12) % 12);
var daysInMonth = self.utils.getDaysInMonth(month), days = window.document.createDocumentFragment(), isMultiMonth = self.config.showMonths > 1, prevMonthDayClass = isMultiMonth ? "prevMonthDay hidden" : "prevMonthDay", nextMonthDayClass = isMultiMonth ? "nextMonthDay hidden" : "nextMonthDay";
var dayNumber = prevMonthDays + 1 - firstOfMonth, dayIndex = 0;
// prepend days from the ending of previous month
for (; dayNumber <= prevMonthDays; dayNumber++, dayIndex++) {
days.appendChild(createDay(prevMonthDayClass, new Date(year, month - 1, dayNumber), dayNumber, dayIndex));
}
// Start at 1 since there is no 0th day
for (dayNumber = 1; dayNumber <= daysInMonth; dayNumber++, dayIndex++) {
days.appendChild(createDay("", new Date(year, month, dayNumber), dayNumber, dayIndex));
}
// append days from the next month
for (var dayNum = daysInMonth + 1; dayNum <= 42 - firstOfMonth &&
(self.config.showMonths === 1 || dayIndex % 7 !== 0); dayNum++, dayIndex++) {
days.appendChild(createDay(nextMonthDayClass, new Date(year, month + 1, dayNum % daysInMonth), dayNum, dayIndex));
}
//updateNavigationCurrentMonth();
var dayContainer = createElement("div", "dayContainer");
dayContainer.appendChild(days);
return dayContainer;
}
function buildDays() {
if (self.daysContainer === undefined) {
return;
}
clearNode(self.daysContainer);
// TODO: week numbers for each month
if (self.weekNumbers)
clearNode(self.weekNumbers);
var frag = document.createDocumentFragment();
for (var i = 0; i < self.config.showMonths; i++) {
var d = new Date(self.currentYear, self.currentMonth, 1);
d.setMonth(self.currentMonth + i);
frag.appendChild(buildMonthDays(d.getFullYear(), d.getMonth()));
}
self.daysContainer.appendChild(frag);
self.days = self.daysContainer.firstChild;
if (self.config.mode === "range" && self.selectedDates.length === 1) {
onMouseOver();
}
}
function buildMonthSwitch() {
if (self.config.showMonths > 1)
return;
var shouldBuildMonth = function (month) {
if (self.config.minDate !== undefined &&
self.currentYear === self.config.minDate.getFullYear() &&
month < self.config.minDate.getMonth()) {
return false;
}
return !(self.config.maxDate !== undefined &&
self.currentYear === self.config.maxDate.getFullYear() &&
month > self.config.maxDate.getMonth());
};
self.monthsDropdownContainer.tabIndex = -1;
self.monthsDropdownContainer.innerHTML = "";
for (var i = 0; i < 12; i++) {
if (!shouldBuildMonth(i))
continue;
var month = createElement("option", "flatpickr-monthDropdown-month");
month.value = new Date(self.currentYear, i).getMonth().toString();
month.textContent = monthToStr(i, false, self.l10n);
month.tabIndex = -1;
if (self.currentMonth === i) {
month.selected = true;
}
self.monthsDropdownContainer.appendChild(month);
}
}
function buildMonth() {
var container = createElement("div", "flatpickr-month");
var monthNavFragment = window.document.createDocumentFragment();
var monthElement;
if (self.config.showMonths > 1) {
monthElement = createElement("span", "cur-month");
}
else {
self.monthsDropdownContainer = createElement("select", "flatpickr-monthDropdown-months");
bind(self.monthsDropdownContainer, "change", function (e) {
var target = e.target;
var selectedMonth = parseInt(target.value, 10);
self.changeMonth(selectedMonth - self.currentMonth);
triggerEvent("onMonthChange");
});
buildMonthSwitch();
monthElement = self.monthsDropdownContainer;
}
var yearInput = createNumberInput("cur-year", { tabindex: "-1" });
var yearElement = yearInput.getElementsByTagName("input")[0];
yearElement.setAttribute("aria-label", self.l10n.yearAriaLabel);
if (self.config.minDate) {
yearElement.setAttribute("min", self.config.minDate.getFullYear().toString());
}
if (self.config.maxDate) {
yearElement.setAttribute("max", self.config.maxDate.getFullYear().toString());
yearElement.disabled =
!!self.config.minDate &&
self.config.minDate.getFullYear() === self.config.maxDate.getFullYear();
}
var currentMonth = createElement("div", "flatpickr-current-month");
currentMonth.appendChild(monthElement);
currentMonth.appendChild(yearInput);
monthNavFragment.appendChild(currentMonth);
container.appendChild(monthNavFragment);
return {
container: container,
yearElement: yearElement,
monthElement: monthElement
};
}
function buildMonths() {
clearNode(self.monthNav);
self.monthNav.appendChild(self.prevMonthNav);
if (self.config.showMonths) {
self.yearElements = [];
self.monthElements = [];
}
for (var m = self.config.showMonths; m--;) {
var month = buildMonth();
self.yearElements.push(month.yearElement);
self.monthElements.push(month.monthElement);
self.monthNav.appendChild(month.container);
}
self.monthNav.appendChild(self.nextMonthNav);
}
function buildMonthNav() {
self.monthNav = createElement("div", "flatpickr-months");
self.yearElements = [];
self.monthElements = [];
self.prevMonthNav = createElement("span", "flatpickr-prev-month");
self.prevMonthNav.innerHTML = self.config.prevArrow;
self.nextMonthNav = createElement("span", "flatpickr-next-month");
self.nextMonthNav.innerHTML = self.config.nextArrow;
buildMonths();
Object.defineProperty(self, "_hidePrevMonthArrow", {
get: function () { return self.__hidePrevMonthArrow; },
set: function (bool) {
if (self.__hidePrevMonthArrow !== bool) {
toggleClass(self.prevMonthNav, "flatpickr-disabled", bool);
self.__hidePrevMonthArrow = bool;
}
}
});
Object.defineProperty(self, "_hideNextMonthArrow", {
get: function () { return self.__hideNextMonthArrow; },
set: function (bool) {
if (self.__hideNextMonthArrow !== bool) {
toggleClass(self.nextMonthNav, "flatpickr-disabled", bool);
self.__hideNextMonthArrow = bool;
}
}
});
self.currentYearElement = self.yearElements[0];
updateNavigationCurrentMonth();
return self.monthNav;
}
function buildTime() {
self.calendarContainer.classList.add("hasTime");
if (self.config.noCalendar)
self.calendarContainer.classList.add("noCalendar");
self.timeContainer = createElement("div", "flatpickr-time");
self.timeContainer.tabIndex = -1;
var separator = createElement("span", "flatpickr-time-separator", ":");
var hourInput = createNumberInput("flatpickr-hour");
self.hourElement = hourInput.getElementsByTagName("input")[0];
var minuteInput = createNumberInput("flatpickr-minute");
self.minuteElement = minuteInput.getElementsByTagName("input")[0];
self.hourElement.tabIndex = self.minuteElement.tabIndex = -1;
self.hourElement.value = pad(self.latestSelectedDateObj
? self.latestSelectedDateObj.getHours()
: self.config.time_24hr
? self.config.defaultHour
: military2ampm(self.config.defaultHour));
self.minuteElement.value = pad(self.latestSelectedDateObj
? self.latestSelectedDateObj.getMinutes()
: self.config.defaultMinute);
self.hourElement.setAttribute("step", self.config.hourIncrement.toString());
self.minuteElement.setAttribute("step", self.config.minuteIncrement.toString());
self.hourElement.setAttribute("min", self.config.time_24hr ? "0" : "1");
self.hourElement.setAttribute("max", self.config.time_24hr ? "23" : "12");
self.minuteElement.setAttribute("min", "0");
self.minuteElement.setAttribute("max", "59");
self.timeContainer.appendChild(hourInput);
self.timeContainer.appendChild(separator);
self.timeContainer.appendChild(minuteInput);
if (self.config.time_24hr)
self.timeContainer.classList.add("time24hr");
if (self.config.enableSeconds) {
self.timeContainer.classList.add("hasSeconds");
var secondInput = createNumberInput("flatpickr-second");
self.secondElement = secondInput.getElementsByTagName("input")[0];
self.secondElement.value = pad(self.latestSelectedDateObj
? self.latestSelectedDateObj.getSeconds()
: self.config.defaultSeconds);
self.secondElement.setAttribute("step", self.minuteElement.getAttribute("step"));
self.secondElement.setAttribute("min", "0");
self.secondElement.setAttribute("max", "59");
self.timeContainer.appendChild(createElement("span", "flatpickr-time-separator", ":"));
self.timeContainer.appendChild(secondInput);
}
if (!self.config.time_24hr) {
// add self.amPM if appropriate
self.amPM = createElement("span", "flatpickr-am-pm", self.l10n.amPM[int((self.latestSelectedDateObj
? self.hourElement.value
: self.config.defaultHour) > 11)]);
self.amPM.title = self.l10n.toggleTitle;
self.amPM.tabIndex = -1;
self.timeContainer.appendChild(self.amPM);
}
return self.timeContainer;
}
function buildWeekdays() {
if (!self.weekdayContainer)
self.weekdayContainer = createElement("div", "flatpickr-weekdays");
else
clearNode(self.weekdayContainer);
for (var i = self.config.showMonths; i--;) {
var container = createElement("div", "flatpickr-weekdaycontainer");
self.weekdayContainer.appendChild(container);
}
updateWeekdays();
return self.weekdayContainer;
}
function updateWeekdays() {
var firstDayOfWeek = self.l10n.firstDayOfWeek;
var weekdays = self.l10n.weekdays.shorthand.slice();
if (firstDayOfWeek > 0 && firstDayOfWeek < weekdays.length) {
weekdays = weekdays.splice(firstDayOfWeek, weekdays.length).concat(weekdays.splice(0, firstDayOfWeek));
}
for (var i = self.config.showMonths; i--;) {
self.weekdayContainer.children[i].innerHTML = "\n <span class='flatpickr-weekday'>\n " + weekdays.join("</span><span class='flatpickr-weekday'>") + "\n </span>\n ";
}
}
/* istanbul ignore next */
function buildWeeks() {
self.calendarContainer.classList.add("hasWeeks");
var weekWrapper = createElement("div", "flatpickr-weekwrapper");
weekWrapper.appendChild(createElement("span", "flatpickr-weekday", self.l10n.weekAbbreviation));
var weekNumbers = createElement("div", "flatpickr-weeks");
weekWrapper.appendChild(weekNumbers);
return {
weekWrapper: weekWrapper,
weekNumbers: weekNumbers
};
}
function changeMonth(value, isOffset) {
if (isOffset === void 0) { isOffset = true; }
var delta = isOffset ? value : value - self.currentMonth;
if ((delta < 0 && self._hidePrevMonthArrow === true) ||
(delta > 0 && self._hideNextMonthArrow === true))
return;
self.currentMonth += delta;
if (self.currentMonth < 0 || self.currentMonth > 11) {
self.currentYear += self.currentMonth > 11 ? 1 : -1;
self.currentMonth = (self.currentMonth + 12) % 12;
triggerEvent("onYearChange");
buildMonthSwitch();
}
buildDays();
triggerEvent("onMonthChange");
updateNavigationCurrentMonth();
}
function clear(triggerChangeEvent, toInitial) {
if (triggerChangeEvent === void 0) { triggerChangeEvent = true; }
if (toInitial === void 0) { toInitial = true; }
self.input.value = "";
if (self.altInput !== undefined)
self.altInput.value = "";
if (self.mobileInput !== undefined)
self.mobileInput.value = "";
self.selectedDates = [];
self.latestSelectedDateObj = undefined;
if (toInitial === true) {
self.currentYear = self._initialDate.getFullYear();
self.currentMonth = self._initialDate.getMonth();
}
self.showTimeInput = false;
if (self.config.enableTime === true) {
setDefaultHours();
}
self.redraw();
if (triggerChangeEvent)
// triggerChangeEvent is true (default) or an Event
triggerEvent("onChange");
}
function close() {
self.isOpen = false;
if (!self.isMobile) {
if (self.calendarContainer !== undefined) {
self.calendarContainer.classList.remove("open");
}
if (self._input !== undefined) {
self._input.classList.remove("active");
}
}
triggerEvent("onClose");
}
function destroy() {
if (self.config !== undefined)
triggerEvent("onDestroy");
for (var i = self._handlers.length; i--;) {
var h = self._handlers[i];
h.element.removeEventListener(h.event, h.handler, h.options);
}
self._handlers = [];
if (self.mobileInput) {
if (self.mobileInput.parentNode)
self.mobileInput.parentNode.removeChild(self.mobileInput);
self.mobileInput = undefined;
}
else if (self.calendarContainer && self.calendarContainer.parentNode) {
if (self.config.static && self.calendarContainer.parentNode) {
var wrapper = self.calendarContainer.parentNode;
wrapper.lastChild && wrapper.removeChild(wrapper.lastChild);
if (wrapper.parentNode) {
while (wrapper.firstChild)
wrapper.parentNode.insertBefore(wrapper.firstChild, wrapper);
wrapper.parentNode.removeChild(wrapper);
}
}
else
self.calendarContainer.parentNode.removeChild(self.calendarContainer);
}
if (self.altInput) {
self.input.type = "text";
if (self.altInput.parentNode)
self.altInput.parentNode.removeChild(self.altInput);
delete self.altInput;
}
if (self.input) {
self.input.type = self.input._type;
self.input.classList.remove("flatpickr-input");
self.input.removeAttribute("readonly");
self.input.value = "";
}
[
"_showTimeInput",
"latestSelectedDateObj",
"_hideNextMonthArrow",
"_hidePrevMonthArrow",
"__hideNextMonthArrow",
"__hidePrevMonthArrow",
"isMobile",
"isOpen",
"selectedDateElem",
"minDateHasTime",
"maxDateHasTime",
"days",
"daysContainer",
"_input",
"_positionElement",
"innerContainer",
"rContainer",
"monthNav",
"todayDateElem",
"calendarContainer",
"weekdayContainer",
"prevMonthNav",
"nextMonthNav",
"monthsDropdownContainer",
"currentMonthElement",
"currentYearElement",
"navigationCurrentMonth",
"selectedDateElem",
"config",
].forEach(function (k) {
try {
delete self[k];
}
catch (_) { }
});
}
function isCalendarElem(elem) {
if (self.config.appendTo && self.config.appendTo.contains(elem))
return true;
return self.calendarContainer.contains(elem);
}
function documentClick(e) {
if (self.isOpen && !self.config.inline) {
var eventTarget_1 = getEventTarget(e);
var isCalendarElement = isCalendarElem(eventTarget_1);
var isInput = eventTarget_1 === self.input ||
eventTarget_1 === self.altInput ||
self.element.contains(eventTarget_1) ||
// web components
// e.path is not present in all browsers. circumventing typechecks
(e.path &&
e.path.indexOf &&
(~e.path.indexOf(self.input) ||
~e.path.indexOf(self.altInput)));
var lostFocus = e.type === "blur"
? isInput &&
e.relatedTarget &&
!isCalendarElem(e.relatedTarget)
: !isInput &&
!isCalendarElement &&
!isCalendarElem(e.relatedTarget);
var isIgnored = !self.config.ignoredFocusElements.some(function (elem) {
return elem.contains(eventTarget_1);
});
if (lostFocus && isIgnored) {
self.close();
if (self.config.mode === "range" && self.selectedDates.length === 1) {
self.clear(false);
self.redraw();
}
}
}
}
function changeYear(newYear) {
if (!newYear ||
(self.config.minDate && newYear < self.config.minDate.getFullYear()) ||
(self.config.maxDate && newYear > self.config.maxDate.getFullYear()))
return;
var newYearNum = newYear, isNewYear = self.currentYear !== newYearNum;
self.currentYear = newYearNum || self.currentYear;
if (self.config.maxDate &&
self.currentYear === self.config.maxDate.getFullYear()) {
self.currentMonth = Math.min(self.config.maxDate.getMonth(), self.currentMonth);
}
else if (self.config.minDate &&
self.currentYear === self.config.minDate.getFullYear()) {
self.currentMonth = Math.max(self.config.minDate.getMonth(), self.currentMonth);
}
if (isNewYear) {
self.redraw();
triggerEvent("onYearChange");
buildMonthSwitch();
}
}
function isEnabled(date, timeless) {
if (timeless === void 0) { timeless = true; }
var dateToCheck = self.parseDate(date, undefined, timeless); // timeless
if ((self.config.minDate &&
dateToCheck &&
compareDates(dateToCheck, self.config.minDate, timeless !== undefined ? timeless : !self.minDateHasTime) < 0) ||
(self.config.maxDate &&
dateToCheck &&
compareDates(dateToCheck, self.config.maxDate, timeless !== undefined ? timeless : !self.maxDateHasTime) > 0))
return false;
if (self.config.enable.length === 0 && self.config.disable.length === 0)
return true;
if (dateToCheck === undefined)
return false;
var bool = self.config.enable.length > 0, array = bool ? self.config.enable : self.config.disable;
for (var i = 0, d = void 0; i < array.length; i++) {
d = array[i];
if (typeof d === "function" &&
d(dateToCheck) // disabled by function
)
return bool;
else if (d instanceof Date &&
dateToCheck !== undefined &&
d.getTime() === dateToCheck.getTime())
// disabled by date
return bool;
else if (typeof d === "string" && dateToCheck !== undefined) {
// disabled by date string
var parsed = self.parseDate(d, undefined, true);
return parsed && parsed.getTime() === dateToCheck.getTime()
? bool
: !bool;
}
else if (
// disabled by range
typeof d === "object" &&
dateToCheck !== undefined &&
d.from &&
d.to &&
dateToCheck.getTime() >= d.from.getTime() &&
dateToCheck.getTime() <= d.to.getTime())
return bool;
}
return !bool;
}
function isInView(elem) {
if (self.daysContainer !== undefined)
return (elem.className.indexOf("hidden") === -1 &&
self.daysContainer.contains(elem));
return false;
}
function onKeyDown(e) {
// e.key e.keyCode
// "Backspace" 8
// "Tab" 9
// "Enter" 13
// "Escape" (IE "Esc") 27
// "ArrowLeft" (IE "Left") 37
// "ArrowUp" (IE "Up") 38
// "ArrowRight" (IE "Right") 39
// "ArrowDown" (IE "Down") 40
// "Delete" (IE "Del") 46
var isInput = e.target === self._input;
var allowInput = self.config.allowInput;
var allowKeydown = self.isOpen && (!allowInput || !isInput);
var allowInlineKeydown = self.config.inline && isInput && !allowInput;
if (e.keyCode === 13 && isInput) {
if (allowInput) {
self.setDate(self._input.value, true, e.target === self.altInput
? self.config.altFormat
: self.config.dateFormat);
return e.target.blur();
}
else {
self.open();
}
}
else if (isCalendarElem(e.target) ||
allowKeydown ||
allowInlineKeydown) {
var isTimeObj = !!self.timeContainer &&
self.timeContainer.contains(e.target);
switch (e.keyCode) {
case 13:
if (isTimeObj) {
e.preventDefault();
updateTime();
focusAndClose();
}
else
selectDate(e);
break;
case 27: // escape
e.preventDefault();
focusAndClose();
break;
case 8:
case 46:
if (isInput && !self.config.allowInput) {
e.preventDefault();
self.clear();
}
break;
case 37:
case 39:
if (!isTimeObj && !isInput) {
e.preventDefault();
if (self.daysContainer !== undefined &&
(allowInput === false ||
(document.activeElement && isInView(document.activeElement)))) {
var delta_1 = e.keyCode === 39 ? 1 : -1;
if (!e.ctrlKey)
focusOnDay(undefined, delta_1);
else {
e.stopPropagation();
changeMonth(delta_1);
focusOnDay(getFirstAvailableDay(1), 0);
}
}
}
else if (self.hourElement)
self.hourElement.focus();
break;
case 38:
case 40:
e.preventDefault();
var delta = e.keyCode === 40 ? 1 : -1;
if ((self.daysContainer && e.target.$i !== undefined) ||
e.target === self.input) {
if (e.ctrlKey) {
e.stopPropagation();
changeYear(self.currentYear - delta);
focusOnDay(getFirstAvailableDay(1), 0);
}
else if (!isTimeObj)
focusOnDay(undefined, delta * 7);
}
else if (e.target === self.currentYearElement) {
changeYear(self.currentYear - delta);
}
else if (self.config.enableTime) {
if (!isTimeObj && self.hourElement)
self.hourElement.focus();
updateTime(e);
self._debouncedChange();
}
break;
case 9:
if (isTimeObj) {
var elems = [
self.hourElement,
self.minuteElement,
self.secondElement,
self.amPM,
]
.concat(self.pluginElements)
.filter(function (x) { return x; });
var i = elems.indexOf(e.target);
if (i !== -1) {
var target = elems[i + (e.shiftKey ? -1 : 1)];
e.preventDefault();
(target || self._input).focus();
}
}
else if (!self.config.noCalendar &&
self.daysContainer &&
self.daysContainer.contains(e.target) &&
e.shiftKey) {
e.preventDefault();
self._input.focus();
}
break;
default:
break;
}
}
if (self.amPM !== undefined && e.target === self.amPM) {
switch (e.key) {
case self.l10n.amPM[0].charAt(0):
case self.l10n.amPM[0].charAt(0).toLowerCase():
self.amPM.textContent = self.l10n.amPM[0];
setHoursFromInputs();
updateValue();
break;
case self.l10n.amPM[1].charAt(0):
case self.l10n.amPM[1].charAt(0).toLowerCase():
self.amPM.textContent = self.l10n.amPM[1];
setHoursFromInputs();
updateValue();
break;
}
}
if (isInput || isCalendarElem(e.target)) {
triggerEvent("onKeyDown", e);
}
}
function onMouseOver(elem) {
if (self.selectedDates.length !== 1 ||
(elem &&
(!elem.classList.contains("flatpickr-day") ||
elem.classList.contains("flatpickr-disabled"))))
return;
var hoverDate = elem
? elem.dateObj.getTime()
: self.days.firstElementChild.dateObj.getTime(), initialDate = self.parseDate(self.selectedDates[0], undefined, true).getTime(), rangeStartDate = Math.min(hoverDate, self.selectedDates[0].getTime()), rangeEndDate = Math.max(hoverDate, self.selectedDates[0].getTime());
var containsDisabled = false;
var minRange = 0, maxRange = 0;
for (var t = rangeStartDate; t < rangeEndDate; t += duration.DAY) {
if (!isEnabled(new Date(t), true)) {
containsDisabled =
containsDisabled || (t > rangeStartDate && t < rangeEndDate);
if (t < initialDate && (!minRange || t > minRange))
minRange = t;
else if (t > initialDate && (!maxRange || t < maxRange))
maxRange = t;
}
}
for (var m = 0; m < self.config.showMonths; m++) {
var month = self.daysContainer.children[m];
var _loop_1 = function (i, l) {
var dayElem = month.children[i], date = dayElem.dateObj;
var timestamp = date.getTime();
var outOfRange = (minRange > 0 && timestamp < minRange) ||
(maxRange > 0 && timestamp > maxRange);
if (outOfRange) {
dayElem.classList.add("notAllowed");
["inRange", "startRange", "endRange"].forEach(function (c) {
dayElem.classList.remove(c);
});
return "continue";
}
else if (containsDisabled && !outOfRange)
return "continue";
["startRange", "inRange", "endRange", "notAllowed"].forEach(function (c) {
dayElem.classList.remove(c);
});
if (elem !== undefined) {
elem.classList.add(hoverDate <= self.selectedDates[0].getTime()
? "startRange"
: "endRange");
if (initialDate < hoverDate && timestamp === initialDate)
dayElem.classList.add("startRange");
else if (initialDate > hoverDate && timestamp === initialDate)
dayElem.classList.add("endRange");
if (timestamp >= minRange &&
(maxRange === 0 || timestamp <= maxRange) &&
isBetween(timestamp, initialDate, hoverDate))
dayElem.classList.add("inRange");
}
};
for (var i = 0, l = month.children.length; i < l; i++) {
_loop_1(i, l);
}
}
}
function onResize() {
if (self.isOpen && !self.config.static && !self.config.inline)
positionCalendar();
}
function setDefaultTime() {
self.setDate(self.config.minDate !== undefined
? new Date(self.config.minDate.getTime())
: new Date(), true);
setDefaultHours();
updateValue();
}
function open(e, positionElement) {
if (positionElement === void 0) { positionElement = self._positionElement; }
if (self.isMobile === true) {
if (e) {
e.preventDefault();
e.target && e.target.blur();
}
if (self.mobileInput !== undefined) {
self.mobileInput.focus();
self.mobileInput.click();
}
triggerEvent("onOpen");
return;
}
if (self._input.disabled || self.config.inline)
return;
var wasOpen = self.isOpen;
self.isOpen = true;
if (!wasOpen) {
self.calendarContainer.classList.add("open");
self._input.classList.add("active");
triggerEvent("onOpen");
positionCalendar(positionElement);
}
if (self.config.enableTime === true && self.config.noCalendar === true) {
if (self.selectedDates.length === 0) {
setDefaultTime();
}
if (self.config.allowInput === false &&
(e === undefined ||
!self.timeContainer.contains(e.relatedTarget))) {
setTimeout(function () { return self.hourElement.select(); }, 50);
}
}
}
function minMaxDateSetter(type) {
return function (date) {
var dateObj = (self.config["_" + type + "Date"] = self.parseDate(date, self.config.dateFormat));
var inverseDateObj = self.config["_" + (type === "min" ? "max" : "min") + "Date"];
if (dateObj !== undefined) {
self[type === "min" ? "minDateHasTime" : "maxDateHasTime"] =
dateObj.getHours() > 0 ||
dateObj.getMinutes() > 0 ||
dateObj.getSeconds() > 0;
}
if (self.selectedDates) {
self.selectedDates = self.selectedDates.filter(function (d) { return isEnabled(d); });
if (!self.selectedDates.length && type === "min")
setHoursFromDate(dateObj);
updateValue();
}
if (self.daysContainer) {
redraw();
if (dateObj !== undefined)
self.currentYearElement[type] = dateObj.getFullYear().toString();
else
self.currentYearElement.removeAttribute(type);
self.currentYearElement.disabled =
!!inverseDateObj &&
dateObj !== undefined &&
inverseDateObj.getFullYear() === dateObj.getFullYear();
}
};
}
function parseConfig() {
var boolOpts = [
"wrap",
"weekNumbers",
"allowInput",
"clickOpens",
"time_24hr",
"enableTime",
"noCalendar",
"altInput",
"shorthandCurrentMonth",
"inline",
"static",
"enableSeconds",
"disableMobile",
];
var userConfig = __assign({}, instanceConfig, JSON.parse(JSON.stringify(element.dataset || {})));
var formats = {};
self.config.parseDate = userConfig.parseDate;
self.config.formatDate = userConfig.formatDate;
Object.defineProperty(self.config, "enable", {
get: function () { return self.config._enable; },
set: function (dates) {
self.config._enable = parseDateRules(dates);
}
});
Object.defineProperty(self.config, "disable", {
get: function () { return self.config._disable; },
set: function (dates) {
self.config._disable = parseDateRules(dates);
}
});
var timeMode = userConfig.mode === "time";
if (!userConfig.dateFormat && (userConfig.enableTime || timeMode)) {
var defaultDateFormat = flatpickr.defaultConfig.dateFormat || defaults.dateFormat;
formats.dateFormat =
userConfig.noCalendar || timeMode
? "H:i" + (userConfig.enableSeconds ? ":S" : "")
: defaultDateFormat + " H:i" + (userConfig.enableSeconds ? ":S" : "");
}
if (userConfig.altInput &&
(userConfig.enableTime || timeMode) &&
!userConfig.altFormat) {
var defaultAltFormat = flatpickr.defaultConfig.altFormat || defaults.altFormat;
formats.altFormat =
userConfig.noCalendar || timeMode
? "h:i" + (userConfig.enableSeconds ? ":S K" : " K")
: defaultAltFormat + (" h:i" + (userConfig.enableSeconds ? ":S" : "") + " K");
}
if (!userConfig.altInputClass) {
self.config.altInputClass =
self.input.className + " " + self.config.altInputClass;
}
Object.defineProperty(self.config, "minDate", {
get: function () { return self.config._minDate; },
set: minMaxDateSetter("min")
});
Object.defineProperty(self.config, "maxDate", {
get: function () { return self.config._maxDate; },
set: minMaxDateSetter("max")
});
var minMaxTimeSetter = function (type) { return function (val) {
self.config[type === "min" ? "_minTime" : "_maxTime"] = self.parseDate(val, "H:i");
}; };
Object.defineProperty(self.config, "minTime", {
get: function () { return self.config._minTime; },
set: minMaxTimeSetter("min")
});
Object.defineProperty(self.config, "maxTime", {
get: function () { return self.config._maxTime; },
set: minMaxTimeSetter("max")
});
if (userConfig.mode === "time") {
self.config.noCalendar = true;
self.config.enableTime = true;
}
Object.assign(self.config, formats, userConfig);
for (var i = 0; i < boolOpts.length; i++)
self.config[boolOpts[i]] =
self.config[boolOpts[i]] === true ||
self.config[boolOpts[i]] === "true";
HOOKS.filter(function (hook) { return self.config[hook] !== undefined; }).forEach(function (hook) {
self.config[hook] = arrayify(self.config[hook] || []).map(bindToInstance);
});
self.isMobile =
!self.config.disableMobile &&
!self.config.inline &&
self.config.mode === "single" &&
!self.config.disable.length &&
!self.config.enable.length &&
!self.config.weekNumbers &&
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
for (var i = 0; i < self.config.plugins.length; i++) {
var pluginConf = self.config.plugins[i](self) || {};
for (var key in pluginConf) {
if (HOOKS.indexOf(key) > -1) {
self.config[key] = arrayify(pluginConf[key])
.map(bindToInstance)
.concat(self.config[key]);
}
else if (typeof userConfig[key] === "undefined")
self.config[key] = pluginConf[key];
}
}
triggerEvent("onParseConfig");
}
function setupLocale() {
if (typeof self.config.locale !== "object" &&
typeof flatpickr.l10ns[self.config.locale] === "undefined")
self.config.errorHandler(new Error("flatpickr: invalid locale " + self.config.locale));
self.l10n = __assign({}, flatpickr.l10ns["default"], (typeof self.config.locale === "object"
? self.config.locale
: self.config.locale !== "default"
? flatpickr.l10ns[self.config.locale]
: undefined));
tokenRegex.K = "(" + self.l10n.amPM[0] + "|" + self.l10n.amPM[1] + "|" + self.l10n.amPM[0].toLowerCase() + "|" + self.l10n.amPM[1].toLowerCase() + ")";
var userConfig = __assign({}, instanceConfig, JSON.parse(JSON.stringify(element.dataset || {})));
if (userConfig.time_24hr === undefined &&
flatpickr.defaultConfig.time_24hr === undefined) {
self.config.time_24hr = self.l10n.time_24hr;
}
self.formatDate = createDateFormatter(self);
self.parseDate = createDateParser({ config: self.config, l10n: self.l10n });
}
function positionCalendar(customPositionElement) {
if (self.calendarContainer === undefined)
return;
triggerEvent("onPreCalendarPosition");
var positionElement = customPositionElement || self._positionElement;
var calendarHeight = Array.prototype.reduce.call(self.calendarContainer.children, (function (acc, child) { return acc + child.offsetHeight; }), 0), calendarWidth = self.calendarContainer.offsetWidth, configPos = self.config.position.split(" "), configPosVertical = configPos[0], configPosHorizontal = configPos.length > 1 ? configPos[1] : null, inputBounds = positionElement.getBoundingClientRect(), distanceFromBottom = window.innerHeight - inputBounds.bottom, showOnTop = configPosVertical === "above" ||
(configPosVertical !== "below" &&
distanceFromBottom < calendarHeight &&
inputBounds.top > calendarHeight);
var top = window.pageYOffset +
inputBounds.top +
(!showOnTop ? positionElement.offsetHeight + 2 : -calendarHeight - 2);
toggleClass(self.calendarContainer, "arrowTop", !showOnTop);
toggleClass(self.calendarContainer, "arrowBottom", showOnTop);
if (self.config.inline)
return;
var left = window.pageXOffset +
inputBounds.left -
(configPosHorizontal != null && configPosHorizontal === "center"
? (calendarWidth - inputBounds.width) / 2
: 0);
var right = window.document.body.offsetWidth - inputBounds.right;
var rightMost = left + calendarWidth > window.document.body.offsetWidth;
var centerMost = right + calendarWidth > window.document.body.offsetWidth;
toggleClass(self.calendarContainer, "rightMost", rightMost);
if (self.config.static)
return;
self.calendarContainer.style.top = top + "px";
if (!rightMost) {
self.calendarContainer.style.left = left + "px";
self.calendarContainer.style.right = "auto";
}
else if (!centerMost) {
self.calendarContainer.style.left = "auto";
self.calendarContainer.style.right = right + "px";
}
else {
var doc = document.styleSheets[0];
// some testing environments don't have css support
if (doc === undefined)
return;
var bodyWidth = window.document.body.offsetWidth;
var centerLeft = Math.max(0, bodyWidth / 2 - calendarWidth / 2);
var centerBefore = ".flatpickr-calendar.centerMost:before";
var centerAfter = ".flatpickr-calendar.centerMost:after";
var centerIndex = doc.cssRules.length;
var centerStyle = "{left:" + inputBounds.left + "px;right:auto;}";
toggleClass(self.calendarContainer, "rightMost", false);
toggleClass(self.calendarContainer, "centerMost", true);
doc.insertRule(centerBefore + "," + centerAfter + centerStyle, centerIndex);
self.calendarContainer.style.left = centerLeft + "px";
self.calendarContainer.style.right = "auto";
}
}
function redraw() {
if (self.config.noCalendar || self.isMobile)
return;
updateNavigationCurrentMonth();
buildDays();
}
function focusAndClose() {
self._input.focus();
if (window.navigator.userAgent.indexOf("MSIE") !== -1 ||
navigator.msMaxTouchPoints !== undefined) {
// hack - bugs in the way IE handles focus keeps the calendar open
setTimeout(self.close, 0);
}
else {
self.close();
}
}
function selectDate(e) {
e.preventDefault();
e.stopPropagation();
var isSelectable = function (day) {
return day.classList &&
day.classList.contains("flatpickr-day") &&
!day.classList.contains("flatpickr-disabled") &&
!day.classList.contains("notAllowed");
};
var t = findParent(e.target, isSelectable);
if (t === undefined)
return;
var target = t;
var selectedDate = (self.latestSelectedDateObj = new Date(target.dateObj.getTime()));
var shouldChangeMonth = (selectedDate.getMonth() < self.currentMonth ||
selectedDate.getMonth() >
self.currentMonth + self.config.showMonths - 1) &&
self.config.mode !== "range";
self.selectedDateElem = target;
if (self.config.mode === "single")
self.selectedDates = [selectedDate];
else if (self.config.mode === "multiple") {
var selectedIndex = isDateSelected(selectedDate);
if (selectedIndex)
self.selectedDates.splice(parseInt(selectedIndex), 1);
else
self.selectedDates.push(selectedDate);
}
else if (self.config.mode === "range") {
if (self.selectedDates.length === 2) {
self.clear(false, false);
}
self.latestSelectedDateObj = selectedDate;
self.selectedDates.push(selectedDate);
// unless selecting same date twice, sort ascendingly
if (compareDates(selectedDate, self.selectedDates[0], true) !== 0)
self.selectedDates.sort(function (a, b) { return a.getTime() - b.getTime(); });
}
setHoursFromInputs();
if (shouldChangeMonth) {
var isNewYear = self.currentYear !== selectedDate.getFullYear();
self.currentYear = selectedDate.getFullYear();
self.currentMonth = selectedDate.getMonth();
if (isNewYear) {
triggerEvent("onYearChange");
buildMonthSwitch();
}
triggerEvent("onMonthChange");
}
updateNavigationCurrentMonth();
buildDays();
updateValue();
if (self.config.enableTime)
setTimeout(function () { return (self.showTimeInput = true); }, 50);
// maintain focus
if (!shouldChangeMonth &&
self.config.mode !== "range" &&
self.config.showMonths === 1)
focusOnDayElem(target);
else if (self.selectedDateElem !== undefined &&
self.hourElement === undefined) {
self.selectedDateElem && self.selectedDateElem.focus();
}
if (self.hourElement !== undefined)
self.hourElement !== undefined && self.hourElement.focus();
if (self.config.closeOnSelect) {
var single = self.config.mode === "single" && !self.config.enableTime;
var range = self.config.mode === "range" &&
self.selectedDates.length === 2 &&
!self.config.enableTime;
if (single || range) {
focusAndClose();
}
}
triggerChange();
}
var CALLBACKS = {
locale: [setupLocale, updateWeekdays],
showMonths: [buildMonths, setCalendarWidth, buildWeekdays],
minDate: [jumpToDate],
maxDate: [jumpToDate]
};
function set(option, value) {
if (option !== null && typeof option === "object") {
Object.assign(self.config, option);
for (var key in option) {
if (CALLBACKS[key] !== undefined)
CALLBACKS[key].forEach(function (x) { return x(); });
}
}
else {
self.config[option] = value;
if (CALLBACKS[option] !== undefined)
CALLBACKS[option].forEach(function (x) { return x(); });
else if (HOOKS.indexOf(option) > -1)
self.config[option] = arrayify(value);
}
self.redraw();
updateValue(false);
}
function setSelectedDate(inputDate, format) {
var dates = [];
if (inputDate instanceof Array)
dates = inputDate.map(function (d) { return self.parseDate(d, format); });
else if (inputDate instanceof Date || typeof inputDate === "number")
dates = [self.parseDate(inputDate, format)];
else if (typeof inputDate === "string") {
switch (self.config.mode) {
case "single":
case "time":
dates = [self.parseDate(inputDate, format)];
break;
case "multiple":
dates = inputDate
.split(self.config.conjunction)
.map(function (date) { return self.parseDate(date, format); });
break;
case "range":
dates = inputDate
.split(self.l10n.rangeSeparator)
.map(function (date) { return self.parseDate(date, format); });
break;
default:
break;
}
}
else
self.config.errorHandler(new Error("Invalid date supplied: " + JSON.stringify(inputDate)));
self.selectedDates = dates.filter(function (d) { return d instanceof Date && isEnabled(d, false); });
if (self.config.mode === "range")
self.selectedDates.sort(function (a, b) { return a.getTime() - b.getTime(); });
}
function setDate(date, triggerChange, format) {
if (triggerChange === void 0) { triggerChange = false; }
if (format === void 0) { format = self.config.dateFormat; }
if ((date !== 0 && !date) || (date instanceof Array && date.length === 0))
return self.clear(triggerChange);
setSelectedDate(date, format);
self.showTimeInput = self.selectedDates.length > 0;
self.latestSelectedDateObj = self.selectedDates[self.selectedDates.length - 1];
self.redraw();
jumpToDate();
setHoursFromDate();
if (self.selectedDates.length === 0) {
self.clear(false);
}
updateValue(triggerChange);
if (triggerChange)
triggerEvent("onChange");
}
function parseDateRules(arr) {
return arr
.slice()
.map(function (rule) {
if (typeof rule === "string" ||
typeof rule === "number" ||
rule instanceof Date) {
return self.parseDate(rule, undefined, true);
}
else if (rule &&
typeof rule === "object" &&
rule.from &&
rule.to)
return {
from: self.parseDate(rule.from, undefined),
to: self.parseDate(rule.to, undefined)
};
return rule;
})
.filter(function (x) { return x; }); // remove falsy values
}
function setupDates() {
self.selectedDates = [];
self.now = self.parseDate(self.config.now) || new Date();
// Workaround IE11 setting placeholder as the input's value
var preloadedDate = self.config.defaultDate ||
((self.input.nodeName === "INPUT" ||
self.input.nodeName === "TEXTAREA") &&
self.input.placeholder &&
self.input.value === self.input.placeholder
? null
: self.input.value);
if (preloadedDate)
setSelectedDate(preloadedDate, self.config.dateFormat);
self._initialDate =
self.selectedDates.length > 0
? self.selectedDates[0]
: self.config.minDate &&
self.config.minDate.getTime() > self.now.getTime()
? self.config.minDate
: self.config.maxDate &&
self.config.maxDate.getTime() < self.now.getTime()
? self.config.maxDate
: self.now;
self.currentYear = self._initialDate.getFullYear();
self.currentMonth = self._initialDate.getMonth();
if (self.selectedDates.length > 0)
self.latestSelectedDateObj = self.selectedDates[0];
if (self.config.minTime !== undefined)
self.config.minTime = self.parseDate(self.config.minTime, "H:i");
if (self.config.maxTime !== undefined)
self.config.maxTime = self.parseDate(self.config.maxTime, "H:i");
self.minDateHasTime =
!!self.config.minDate &&
(self.config.minDate.getHours() > 0 ||
self.config.minDate.getMinutes() > 0 ||
self.config.minDate.getSeconds() > 0);
self.maxDateHasTime =
!!self.config.maxDate &&
(self.config.maxDate.getHours() > 0 ||
self.config.maxDate.getMinutes() > 0 ||
self.config.maxDate.getSeconds() > 0);
Object.defineProperty(self, "showTimeInput", {
get: function () { return self._showTimeInput; },
set: function (bool) {
self._showTimeInput = bool;
if (self.calendarContainer)
toggleClass(self.calendarContainer, "showTimeInput", bool);
self.isOpen && positionCalendar();
}
});
}
function setupInputs() {
self.input = self.config.wrap
? element.querySelector("[data-input]")
: element;
/* istanbul ignore next */
if (!self.input) {
self.config.errorHandler(new Error("Invalid input element specified"));
return;
}
// hack: store previous type to restore it after destroy()
self.input._type = self.input.type;
self.input.type = "text";
self.input.classList.add("flatpickr-input");
self._input = self.input;
if (self.config.altInput) {
// replicate self.element
self.altInput = createElement(self.input.nodeName, self.config.altInputClass);
self._input = self.altInput;
self.altInput.placeholder = self.input.placeholder;
self.altInput.disabled = self.input.disabled;
self.altInput.required = self.input.required;
self.altInput.tabIndex = self.input.tabIndex;
self.altInput.type = "text";
self.input.setAttribute("type", "hidden");
if (!self.config.static && self.input.parentNode)
self.input.parentNode.insertBefore(self.altInput, self.input.nextSibling);
}
if (!self.config.allowInput)
self._input.setAttribute("readonly", "readonly");
self._positionElement = self.config.positionElement || self._input;
}
function setupMobile() {
var inputType = self.config.enableTime
? self.config.noCalendar
? "time"
: "datetime-local"
: "date";
self.mobileInput = createElement("input", self.input.className + " flatpickr-mobile");
self.mobileInput.step = self.input.getAttribute("step") || "any";
self.mobileInput.tabIndex = 1;
self.mobileInput.type = inputType;
self.mobileInput.disabled = self.input.disabled;
self.mobileInput.required = self.input.required;
self.mobileInput.placeholder = self.input.placeholder;
self.mobileFormatStr =
inputType === "datetime-local"
? "Y-m-d\\TH:i:S"
: inputType === "date"
? "Y-m-d"
: "H:i:S";
if (self.selectedDates.length > 0) {
self.mobileInput.defaultValue = self.mobileInput.value = self.formatDate(self.selectedDates[0], self.mobileFormatStr);
}
if (self.config.minDate)
self.mobileInput.min = self.formatDate(self.config.minDate, "Y-m-d");
if (self.config.maxDate)
self.mobileInput.max = self.formatDate(self.config.maxDate, "Y-m-d");
self.input.type = "hidden";
if (self.altInput !== undefined)
self.altInput.type = "hidden";
try {
if (self.input.parentNode)
self.input.parentNode.insertBefore(self.mobileInput, self.input.nextSibling);
}
catch (_a) { }
bind(self.mobileInput, "change", function (e) {
self.setDate(e.target.value, false, self.mobileFormatStr);
triggerEvent("onChange");
triggerEvent("onClose");
});
}
function toggle(e) {
if (self.isOpen === true)
return self.close();
self.open(e);
}
function triggerEvent(event, data) {
// If the instance has been destroyed already, all hooks have been removed
if (self.config === undefined)
return;
var hooks = self.config[event];
if (hooks !== undefined && hooks.length > 0) {
for (var i = 0; hooks[i] && i < hooks.length; i++)
hooks[i](self.selectedDates, self.input.value, self, data);
}
if (event === "onChange") {
self.input.dispatchEvent(createEvent("change"));
// many front-end frameworks bind to the input event
self.input.dispatchEvent(createEvent("input"));
}
}
function createEvent(name) {
var e = document.createEvent("Event");
e.initEvent(name, true, true);
return e;
}
function isDateSelected(date) {
for (var i = 0; i < self.selectedDates.length; i++) {
if (compareDates(self.selectedDates[i], date) === 0)
return "" + i;
}
return false;
}
function isDateInRange(date) {
if (self.config.mode !== "range" || self.selectedDates.length < 2)
return false;
return (compareDates(date, self.selectedDates[0]) >= 0 &&
compareDates(date, self.selectedDates[1]) <= 0);
}
function updateNavigationCurrentMonth() {
if (self.config.noCalendar || self.isMobile || !self.monthNav)
return;
self.yearElements.forEach(function (yearElement, i) {
var d = new Date(self.currentYear, self.currentMonth, 1);
d.setMonth(self.currentMonth + i);
if (self.config.showMonths > 1) {
self.monthElements[i].textContent =
monthToStr(d.getMonth(), self.config.shorthandCurrentMonth, self.l10n) + " ";
}
else {
self.monthsDropdownContainer.value = d.getMonth().toString();
}
yearElement.value = d.getFullYear().toString();
});
self._hidePrevMonthArrow =
self.config.minDate !== undefined &&
(self.currentYear === self.config.minDate.getFullYear()
? self.currentMonth <= self.config.minDate.getMonth()
: self.currentYear < self.config.minDate.getFullYear());
self._hideNextMonthArrow =
self.config.maxDate !== undefined &&
(self.currentYear === self.config.maxDate.getFullYear()
? self.currentMonth + 1 > self.config.maxDate.getMonth()
: self.currentYear > self.config.maxDate.getFullYear());
}
function getDateStr(format) {
return self.selectedDates
.map(function (dObj) { return self.formatDate(dObj, format); })
.filter(function (d, i, arr) {
return self.config.mode !== "range" ||
self.config.enableTime ||
arr.indexOf(d) === i;
})
.join(self.config.mode !== "range"
? self.config.conjunction
: self.l10n.rangeSeparator);
}
/**
* Updates the values of inputs associated with the calendar
*/
function updateValue(triggerChange) {
if (triggerChange === void 0) { triggerChange = true; }
if (self.mobileInput !== undefined && self.mobileFormatStr) {
self.mobileInput.value =
self.latestSelectedDateObj !== undefined
? self.formatDate(self.latestSelectedDateObj, self.mobileFormatStr)
: "";
}
self.input.value = getDateStr(self.config.dateFormat);
if (self.altInput !== undefined) {
self.altInput.value = getDateStr(self.config.altFormat);
}
if (triggerChange !== false)
triggerEvent("onValueUpdate");
}
function onMonthNavClick(e) {
var isPrevMonth = self.prevMonthNav.contains(e.target);
var isNextMonth = self.nextMonthNav.contains(e.target);
if (isPrevMonth || isNextMonth) {
changeMonth(isPrevMonth ? -1 : 1);
}
else if (self.yearElements.indexOf(e.target) >= 0) {
e.target.select();
}
else if (e.target.classList.contains("arrowUp")) {
self.changeYear(self.currentYear + 1);
}
else if (e.target.classList.contains("arrowDown")) {
self.changeYear(self.currentYear - 1);
}
}
function timeWrapper(e) {
e.preventDefault();
var isKeyDown = e.type === "keydown", input = e.target;
if (self.amPM !== undefined && e.target === self.amPM) {
self.amPM.textContent =
self.l10n.amPM[int(self.amPM.textContent === self.l10n.amPM[0])];
}
var min = parseFloat(input.getAttribute("min")), max = parseFloat(input.getAttribute("max")), step = parseFloat(input.getAttribute("step")), curValue = parseInt(input.value, 10), delta = e.delta ||
(isKeyDown ? (e.which === 38 ? 1 : -1) : 0);
var newValue = curValue + step * delta;
if (typeof input.value !== "undefined" && input.value.length === 2) {
var isHourElem = input === self.hourElement, isMinuteElem = input === self.minuteElement;
if (newValue < min) {
newValue =
max +
newValue +
int(!isHourElem) +
(int(isHourElem) && int(!self.amPM));
if (isMinuteElem)
incrementNumInput(undefined, -1, self.hourElement);
}
else if (newValue > max) {
newValue =
input === self.hourElement ? newValue - max - int(!self.amPM) : min;
if (isMinuteElem)
incrementNumInput(undefined, 1, self.hourElement);
}
if (self.amPM &&
isHourElem &&
(step === 1
? newValue + curValue === 23
: Math.abs(newValue - curValue) > step)) {
self.amPM.textContent =
self.l10n.amPM[int(self.amPM.textContent === self.l10n.amPM[0])];
}
input.value = pad(newValue);
}
}
init();
return self;
}
/* istanbul ignore next */
function _flatpickr(nodeList, config) {
// static list
var nodes = Array.prototype.slice
.call(nodeList)
.filter(function (x) { return x instanceof HTMLElement; });
var instances = [];
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
try {
if (node.getAttribute("data-fp-omit") !== null)
continue;
if (node._flatpickr !== undefined) {
node._flatpickr.destroy();
node._flatpickr = undefined;
}
node._flatpickr = FlatpickrInstance(node, config || {});
instances.push(node._flatpickr);
}
catch (e) {
console.error(e);
}
}
return instances.length === 1 ? instances[0] : instances;
}
/* istanbul ignore next */
if (typeof HTMLElement !== "undefined") {
// browser env
HTMLCollection.prototype.flatpickr = NodeList.prototype.flatpickr = function (config) {
return _flatpickr(this, config);
};
HTMLElement.prototype.flatpickr = function (config) {
return _flatpickr([this], config);
};
}
/* istanbul ignore next */
var flatpickr = function (selector, config) {
if (typeof selector === "string") {
return _flatpickr(window.document.querySelectorAll(selector), config);
}
else if (selector instanceof Node) {
return _flatpickr([selector], config);
}
else {
return _flatpickr(selector, config);
}
};
/* istanbul ignore next */
flatpickr.defaultConfig = {};
flatpickr.l10ns = {
en: __assign({}, english),
"default": __assign({}, english)
};
flatpickr.localize = function (l10n) {
flatpickr.l10ns["default"] = __assign({}, flatpickr.l10ns["default"], l10n);
};
flatpickr.setDefaults = function (config) {
flatpickr.defaultConfig = __assign({}, flatpickr.defaultConfig, config);
};
flatpickr.parseDate = createDateParser({});
flatpickr.formatDate = createDateFormatter({});
flatpickr.compareDates = compareDates;
/* istanbul ignore next */
if (typeof jQuery !== "undefined") {
jQuery.fn.flatpickr = function (config) {
return _flatpickr(this, config);
};
}
// eslint-disable-next-line @typescript-eslint/camelcase
Date.prototype.fp_incr = function (days) {
return new Date(this.getFullYear(), this.getMonth(), this.getDate() + (typeof days === "string" ? parseInt(days, 10) : days));
};
if (typeof window !== "undefined") {
window.flatpickr = flatpickr;
}
return flatpickr;
}));
|
define([
'gui/GuiTR'
], function (TR) {
'use strict';
var GuiConfig = function (guiParent, ctrlGui) {
this._ctrlGui = ctrlGui;
this._menu = null; // ui menu
this.init(guiParent);
};
GuiConfig.prototype = {
/** Initialize */
init: function (guiParent) {
// config stuffs
this._langs = Object.keys(TR.languages);
this._menu = guiParent.addMenu('Language');
this._menu.addCombobox('', this._langs.indexOf(TR.select), this.onLangChange.bind(this), this._langs);
},
onLangChange: function (value) {
TR.select = this._langs[parseInt(value, 10)];
this._ctrlGui.initGui();
}
};
return GuiConfig;
}); |
import React, { memo } from 'react';
import SideBarItemTemplateWithData from '../RoomList/SideBarItemTemplateWithData';
import UserItem from './UserItem';
const Row = ({ item, data }) => {
const { t, SideBarItemTemplate, avatarTemplate: AvatarTemplate, useRealName, extended } = data;
if (item.t === 'd' && !item.u) {
return (
<UserItem
id={`search-${item._id}`}
useRealName={useRealName}
t={t}
item={item}
SideBarItemTemplate={SideBarItemTemplate}
AvatarTemplate={AvatarTemplate}
/>
);
}
return (
<SideBarItemTemplateWithData
id={`search-${item._id}`}
tabIndex={-1}
extended={extended}
t={t}
room={item}
SideBarItemTemplate={SideBarItemTemplate}
AvatarTemplate={AvatarTemplate}
/>
);
};
export default memo(Row);
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.VueMask = {}));
}(this, function (exports) { 'use strict';
function _typeof(obj) {
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(source, true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(source).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
var placeholderChar = '_';
var strFunction = 'function';
var emptyArray = [];
function convertMaskToPlaceholder() {
var mask = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : emptyArray;
var placeholderChar$1 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : placeholderChar;
if (!isArray(mask)) {
throw new Error('Text-mask:convertMaskToPlaceholder; The mask property must be an array.');
}
if (mask.indexOf(placeholderChar$1) !== -1) {
throw new Error('Placeholder character must not be used as part of the mask. Please specify a character ' + 'that is not present in your mask as your placeholder character.\n\n' + "The placeholder character that was received is: ".concat(JSON.stringify(placeholderChar$1), "\n\n") + "The mask that was received is: ".concat(JSON.stringify(mask)));
}
return mask.map(function (char) {
return char instanceof RegExp ? placeholderChar$1 : char;
}).join('');
}
function isArray(value) {
return Array.isArray && Array.isArray(value) || value instanceof Array;
}
var strCaretTrap = '[]';
function processCaretTraps(mask) {
var indexes = [];
var indexOfCaretTrap;
while (indexOfCaretTrap = mask.indexOf(strCaretTrap), indexOfCaretTrap !== -1) {
indexes.push(indexOfCaretTrap);
mask.splice(indexOfCaretTrap, 1);
}
return {
maskWithoutCaretTraps: mask,
indexes: indexes
};
}
var emptyArray$1 = [];
var emptyString = '';
function conformToMask() {
var rawValue = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : emptyString;
var mask = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : emptyArray$1;
var config = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
if (!isArray(mask)) {
if (_typeof(mask) === strFunction) {
mask = mask(rawValue, config);
mask = processCaretTraps(mask).maskWithoutCaretTraps;
} else {
throw new Error('Text-mask:conformToMask; The mask property must be an array.');
}
}
var _config$guide = config.guide,
guide = _config$guide === void 0 ? true : _config$guide,
_config$previousConfo = config.previousConformedValue,
previousConformedValue = _config$previousConfo === void 0 ? emptyString : _config$previousConfo,
_config$placeholderCh = config.placeholderChar,
placeholderChar$1 = _config$placeholderCh === void 0 ? placeholderChar : _config$placeholderCh,
_config$placeholder = config.placeholder,
placeholder = _config$placeholder === void 0 ? convertMaskToPlaceholder(mask, placeholderChar$1) : _config$placeholder,
currentCaretPosition = config.currentCaretPosition,
keepCharPositions = config.keepCharPositions;
var suppressGuide = guide === false && previousConformedValue !== undefined;
var rawValueLength = rawValue.length;
var previousConformedValueLength = previousConformedValue.length;
var placeholderLength = placeholder.length;
var maskLength = mask.length;
var editDistance = rawValueLength - previousConformedValueLength;
var isAddition = editDistance > 0;
var indexOfFirstChange = currentCaretPosition + (isAddition ? -editDistance : 0);
var indexOfLastChange = indexOfFirstChange + Math.abs(editDistance);
if (keepCharPositions === true && !isAddition) {
var compensatingPlaceholderChars = emptyString;
for (var i = indexOfFirstChange; i < indexOfLastChange; i++) {
if (placeholder[i] === placeholderChar$1) {
compensatingPlaceholderChars += placeholderChar$1;
}
}
rawValue = rawValue.slice(0, indexOfFirstChange) + compensatingPlaceholderChars + rawValue.slice(indexOfFirstChange, rawValueLength);
}
var rawValueArr = rawValue.split(emptyString).map(function (char, i) {
return {
char: char,
isNew: i >= indexOfFirstChange && i < indexOfLastChange
};
});
for (var _i = rawValueLength - 1; _i >= 0; _i--) {
var char = rawValueArr[_i].char;
if (char !== placeholderChar$1) {
var shouldOffset = _i >= indexOfFirstChange && previousConformedValueLength === maskLength;
if (char === placeholder[shouldOffset ? _i - editDistance : _i]) {
rawValueArr.splice(_i, 1);
}
}
}
var conformedValue = emptyString;
var someCharsRejected = false;
placeholderLoop: for (var _i2 = 0; _i2 < placeholderLength; _i2++) {
var charInPlaceholder = placeholder[_i2];
if (charInPlaceholder === placeholderChar$1) {
if (rawValueArr.length > 0) {
while (rawValueArr.length > 0) {
var _rawValueArr$shift = rawValueArr.shift(),
rawValueChar = _rawValueArr$shift.char,
isNew = _rawValueArr$shift.isNew;
if (rawValueChar === placeholderChar$1 && suppressGuide !== true) {
conformedValue += placeholderChar$1;
continue placeholderLoop;
} else if (mask[_i2].test(rawValueChar)) {
if (keepCharPositions !== true || isNew === false || previousConformedValue === emptyString || guide === false || !isAddition) {
conformedValue += rawValueChar;
} else {
var rawValueArrLength = rawValueArr.length;
var indexOfNextAvailablePlaceholderChar = null;
for (var _i3 = 0; _i3 < rawValueArrLength; _i3++) {
var charData = rawValueArr[_i3];
if (charData.char !== placeholderChar$1 && charData.isNew === false) {
break;
}
if (charData.char === placeholderChar$1) {
indexOfNextAvailablePlaceholderChar = _i3;
break;
}
}
if (indexOfNextAvailablePlaceholderChar !== null) {
conformedValue += rawValueChar;
rawValueArr.splice(indexOfNextAvailablePlaceholderChar, 1);
} else {
_i2--;
}
}
continue placeholderLoop;
} else {
someCharsRejected = true;
}
}
}
if (suppressGuide === false) {
conformedValue += placeholder.substr(_i2, placeholderLength);
}
break;
} else {
conformedValue += charInPlaceholder;
}
}
if (suppressGuide && isAddition === false) {
var indexOfLastFilledPlaceholderChar = null;
for (var _i4 = 0; _i4 < conformedValue.length; _i4++) {
if (placeholder[_i4] === placeholderChar$1) {
indexOfLastFilledPlaceholderChar = _i4;
}
}
if (indexOfLastFilledPlaceholderChar !== null) {
conformedValue = conformedValue.substr(0, indexOfLastFilledPlaceholderChar + 1);
} else {
conformedValue = emptyString;
}
}
return {
conformedValue: conformedValue,
meta: {
someCharsRejected: someCharsRejected
}
};
}
var NEXT_CHAR_OPTIONAL = {
__nextCharOptional__: true
};
var defaultMaskReplacers = {
'#': /\d/,
A: /[a-z]/i,
N: /[a-z0-9]/i,
'?': NEXT_CHAR_OPTIONAL,
X: /./
};
var stringToRegexp = function stringToRegexp(str) {
var lastSlash = str.lastIndexOf('/');
return new RegExp(str.slice(1, lastSlash), str.slice(lastSlash + 1));
};
var makeRegexpOptional = function makeRegexpOptional(charRegexp) {
return stringToRegexp(charRegexp.toString().replace(/.(\/)[gmiyus]{0,6}$/, function (match) {
return match.replace('/', '?/');
}));
};
var escapeIfNeeded = function escapeIfNeeded(char) {
return '[\\^$.|?*+()'.indexOf(char) > -1 ? "\\".concat(char) : char;
};
var charRegexp = function charRegexp(char) {
return new RegExp("/[".concat(escapeIfNeeded(char), "]/"));
};
var isRegexp = function isRegexp(entity) {
return entity instanceof RegExp;
};
var castToRegexp = function castToRegexp(char) {
return isRegexp(char) ? char : charRegexp(char);
};
function stringMaskToRegExpMask(stringMask) {
return stringMask.split('').map(function (char, index, array) {
var maskChar = defaultMaskReplacers[char] || char;
var previousChar = array[index - 1];
var previousMaskChar = defaultMaskReplacers[previousChar] || previousChar;
if (maskChar === NEXT_CHAR_OPTIONAL) {
return null;
}
if (previousMaskChar === NEXT_CHAR_OPTIONAL) {
return makeRegexpOptional(castToRegexp(maskChar));
}
return maskChar;
}).filter(Boolean);
}
var trigger = function trigger(el, type) {
var e = document.createEvent('HTMLEvents');
e.initEvent(type, true, true);
el.dispatchEvent(e);
};
var queryInputElementInside = function queryInputElementInside(el) {
return el instanceof HTMLInputElement ? el : el.querySelector('input') || el;
};
var inBrowser = typeof window !== 'undefined';
var UA = inBrowser && window.navigator.userAgent.toLowerCase();
var isEdge = UA && UA.indexOf('edge/') > 0;
var isAndroid = UA && UA.indexOf('android') > 0;
var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge;
function createOptions() {
var elementOptions = new Map();
var defaultOptions = {
previousValue: '',
mask: []
};
function get(el) {
return elementOptions.get(el) || _objectSpread2({}, defaultOptions);
}
function partiallyUpdate(el, newOptions) {
elementOptions.set(el, _objectSpread2({}, get(el), {}, newOptions));
}
function remove(el) {
elementOptions.delete(el);
}
return {
partiallyUpdate: partiallyUpdate,
remove: remove,
get: get
};
}
var options = createOptions();
function triggerInputUpdate(el) {
var fn = trigger.bind(null, el, 'input');
if (isAndroid && isChrome) {
setTimeout(fn, 0);
} else {
fn();
}
}
function updateValue(el) {
var force = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var value = el.value;
var _options$get = options.get(el),
previousValue = _options$get.previousValue,
mask = _options$get.mask;
var isValueChanged = value !== previousValue;
var isLengthIncreased = value.length > previousValue.length;
var isUpdateNeeded = value && isValueChanged && isLengthIncreased;
if (force || isUpdateNeeded) {
var _conformToMask = conformToMask(value, mask, {
guide: false
}),
conformedValue = _conformToMask.conformedValue;
el.value = conformedValue;
triggerInputUpdate(el);
}
options.partiallyUpdate(el, {
previousValue: value
});
}
function updateMask(el, mask) {
options.partiallyUpdate(el, {
mask: stringMaskToRegExpMask(mask)
});
}
var directive = {
bind: function bind(el, _ref) {
var value = _ref.value;
el = queryInputElementInside(el);
updateMask(el, value);
updateValue(el);
},
componentUpdated: function componentUpdated(el, _ref2) {
var value = _ref2.value,
oldValue = _ref2.oldValue;
el = queryInputElementInside(el);
var isMaskChanged = value !== oldValue;
if (isMaskChanged) {
updateMask(el, value);
}
updateValue(el, isMaskChanged);
},
unbind: function unbind(el) {
el = queryInputElementInside(el);
options.remove(el);
}
};
var plugin = (function (Vue) {
Vue.directive('mask', directive);
});
exports.VueMaskDirective = directive;
exports.VueMaskPlugin = plugin;
exports.default = plugin;
Object.defineProperty(exports, '__esModule', { value: true });
}));
|
module.exports = {
visionKey: 'AIzaSyAA14j-7sIJLDTRZd3bYpZrmCEoFA9IN40',
pairingID: 'b5378ca6',
pairingKey: '690be2968f8f08b26fcc1f2c9c8f5b90',
recipesKey: 'qAjqbB5sPamshJwWJJh01Y3exb3Jp1wBzcOjsnrqegcRf1PCXT',
backUpRecipesKey: 'jHbWfZqPEUmsh0NElMAPdMXlfPm1p1M9n5NjsnPD1l0Vjhsjng'
}
|
!function(o){"object"==typeof module&&module.exports?module.exports=o.default=o:"function"==typeof define&&define.amd?define("highcharts/themes/sunset",["highcharts"],function(e){return o(e),o.Highcharts=e,o}):o("undefined"!=typeof Highcharts?Highcharts:void 0)}(function(e){function o(e,o,t,s){e.hasOwnProperty(o)||(e[o]=s.apply(null,t))}o(e=e?e._modules:{},"Extensions/Themes/Sunset.js",[e["Core/Globals.js"],e["Core/Utilities.js"]],function(e,o){o=o.setOptions,e.theme={colors:["#FDD089","#FF7F79","#A0446E","#251535"],colorAxis:{maxColor:"#60042E",minColor:"#FDD089"},plotOptions:{map:{nullColor:"#fefefc"}},navigator:{series:{color:"#FF7F79",lineColor:"#A0446E"}}},o(e.theme)}),o(e,"masters/themes/sunset.src.js",[],function(){})}); |
'use strict';
/**
* Module dependencies.
*/
var init = require('./config/init')(),
config = require('./config/config'),
mongoose = require('mongoose'),
chalk = require('chalk');
/**
* Main application entry file.
* Please note that the order of loading is important.
*/
// Bootstrap db connection
var db = mongoose.connect(config.db, function(err) {
if (err) {
console.error(chalk.red('Could not connect to MongoDB!'));
console.log(chalk.red(err));
}
});
// Init the express application
var app = require('./config/express')(db);
// Bootstrap passport config
require('./config/passport')();
// Start the app by listening on <port>
app.listen(config.port);
// Expose app
exports = module.exports = app;
// Logging initialization
console.log('MEAN.JS application started on port ' + config.port);
//Initialize add-on plugin
|
onOpenDialog = function(dialog) {
$('.ui-dialog').corner('6px').find('.ui-dialog-titlebar').corner('1px top');
$(document.body).addClass('hide-overflow');
}
onCloseDialog = function(dialog) {
$(document.body).removeClass('hide-overflow');
}
var wymeditor_inputs = [];
var wymeditors_loaded = 0;
// supply custom_wymeditor_boot_options if you want to override anything here.
if (typeof(custom_wymeditor_boot_options) == "undefined") { custom_wymeditor_boot_options = {}; }
var form_actions =
"<div id='dialog-form-actions' class='form-actions'>"
+ "<div class='form-actions-left'>"
+ "<input id='submit_button' class='wym_submit button' type='submit' value='{Insert}' class='button' />"
+ "<a href='' class='wym_cancel close_dialog button'>{Cancel}</a>"
+ "</div>"
+ "</div>";
var wymeditor_boot_options = $.extend({
skin: 'refinery'
, basePath: "/"
, wymPath: "/javascripts/wymeditor/jquery.refinery.wymeditor.js"
, cssSkinPath: "/stylesheets/wymeditor/skins/"
, jsSkinPath: "/javascripts/wymeditor/skins/"
, langPath: "/javascripts/wymeditor/lang/"
, iframeBasePath: '/'
, classesItems: [
{name: 'text-align', rules:['left', 'center', 'right', 'justify'], join: '-'}
, {name: 'image-align', rules:['left', 'right'], join: '-'}
, {name: 'font-size', rules:['small', 'normal', 'large'], join: '-'}
]
, containersItems: [
{'name': 'h1', 'title':'Heading_1', 'css':'wym_containers_h1'}
, {'name': 'h2', 'title':'Heading_2', 'css':'wym_containers_h2'}
, {'name': 'h3', 'title':'Heading_3', 'css':'wym_containers_h3'}
, {'name': 'p', 'title':'Paragraph', 'css':'wym_containers_p'}
]
, toolsItems: [
{'name': 'Bold', 'title': 'Bold', 'css': 'wym_tools_strong'}
,{'name': 'Italic', 'title': 'Emphasis', 'css': 'wym_tools_emphasis'}
,{'name': 'InsertOrderedList', 'title': 'Ordered_List', 'css': 'wym_tools_ordered_list'}
,{'name': 'InsertUnorderedList', 'title': 'Unordered_List', 'css': 'wym_tools_unordered_list'}
/*,{'name': 'Indent', 'title': 'Indent', 'css': 'wym_tools_indent'}
,{'name': 'Outdent', 'title': 'Outdent', 'css': 'wym_tools_outdent'}
,{'name': 'Undo', 'title': 'Undo', 'css': 'wym_tools_undo'}
,{'name': 'Redo', 'title': 'Redo', 'css': 'wym_tools_redo'}*/
,{'name': 'CreateLink', 'title': 'Link', 'css': 'wym_tools_link'}
,{'name': 'Unlink', 'title': 'Unlink', 'css': 'wym_tools_unlink'}
,{'name': 'InsertImage', 'title': 'Image', 'css': 'wym_tools_image'}
,{'name': 'InsertTable', 'title': 'Table', 'css': 'wym_tools_table'}
//,{'name': 'Paste', 'title': 'Paste_From_Word', 'css': 'wym_tools_paste'}
,{'name': 'ToggleHtml', 'title': 'HTML', 'css': 'wym_tools_html'}
]
,toolsHtml: "<ul class='wym_tools wym_section wym_buttons'>" + WYMeditor.TOOLS_ITEMS + WYMeditor.CLASSES + "</ul>"
,toolsItemHtml:
"<li class='" + WYMeditor.TOOL_CLASS + "'>"
+ "<a href='#' name='" + WYMeditor.TOOL_NAME + "' title='" + WYMeditor.TOOL_TITLE + "'>"
+ WYMeditor.TOOL_TITLE
+ "</a>"
+ "</li>"
, classesHtml: "<li class='wym_tools_class'>"
+ "<a href='#' name='" + WYMeditor.APPLY_CLASS + "' title='"+ titleize(WYMeditor.APPLY_CLASS) +"'></a>"
+ "<ul class='wym_classes wym_classes_hidden'>" + WYMeditor.CLASSES_ITEMS + "</ul>"
+ "</li>"
, classesItemHtml: "<li><a href='#' name='"+ WYMeditor.CLASS_NAME + "'>"+ WYMeditor.CLASS_TITLE+ "</a></li>"
, classesItemHtmlMultiple: "<li class='wym_tools_class_multiple_rules'>"
+ "<span>" + WYMeditor.CLASS_TITLE + "</span>"
+ "<ul>{classesItemHtml}</ul>"
+"</li>"
, containersHtml: "<ul class='wym_containers wym_section'>" + WYMeditor.CONTAINERS_ITEMS + "</ul>"
, containersItemHtml:
"<li class='" + WYMeditor.CONTAINER_CLASS + "'>"
+ "<a href='#' name='" + WYMeditor.CONTAINER_NAME + "' title='" + WYMeditor.CONTAINER_TITLE + "'></a>"
+ "</li>"
, boxHtml:
"<div class='wym_box'>"
+ "<div class='wym_area_top clearfix'>"
+ WYMeditor.CONTAINERS
+ WYMeditor.TOOLS
+ "</div>"
+ "<div class='wym_area_main'>"
+ WYMeditor.HTML
+ WYMeditor.IFRAME
+ WYMeditor.STATUS
+ "</div>"
+ "</div>"
, iframeHtml:
"<div class='wym_iframe wym_section'>"
+ "<iframe id='WYMeditor_" + WYMeditor.INDEX + "' src='" + WYMeditor.IFRAME_BASE_PATH + "wymiframe' frameborder='0'"
+ " onload='this.contentWindow.parent.WYMeditor.INSTANCES[" + WYMeditor.INDEX + "].initIframe(this);'></iframe>"
+"</div>"
, dialogImageHtml: ""
, dialogLinkHtml: ""
, dialogTableHtml:
"<div class='wym_dialog wym_dialog_table'>"
+ "<form>"
+ "<input type='hidden' id='wym_dialog_type' class='wym_dialog_type' value='"+ WYMeditor.DIALOG_TABLE + "' />"
+ "<div class='field'>"
+ "<label for='wym_caption'>{Caption}</label>"
+ "<input type='text' id='wym_caption' class='wym_caption' value='' size='40' />"
+ "</div>"
+ "<div class='field'>"
+ "<label for='wym_rows'>{Number_Of_Rows}</label>"
+ "<input type='text' id='wym_rows' class='wym_rows' value='3' size='3' />"
+ "</div>"
+ "<div class='field'>"
+ "<label for='wym_cols'>{Number_Of_Cols}</label>"
+ "<input type='text' id='wym_cols' class='wym_cols' value='2' size='3' />"
+ "</div>"
+ form_actions
+ "</form>"
+ "</div>"
, dialogPasteHtml:
"<div class='wym_dialog wym_dialog_paste'>"
+ "<form>"
+ "<input type='hidden' id='wym_dialog_type' class='wym_dialog_type' value='" + WYMeditor.DIALOG_PASTE + "' />"
+ "<div class='field'>"
+ "<textarea class='wym_text' rows='10' cols='50'></textarea>"
+ "</div>"
+ form_actions
+ "</form>"
+ "</div>"
, dialogPath: "/refinery/dialogs/"
, dialogFeatures: {
width: 866
, height: 455
, modal: true
, draggable: true
, resizable: false
, autoOpen: true
, open: onOpenDialog
, close: onCloseDialog
}
, dialogInlineFeatures: {
width: 600
, height: 485
, modal: true
, draggable: true
, resizable: false
, autoOpen: true
, open: onOpenDialog
, close: onCloseDialog
}
, dialogId: 'editor_dialog'
, dialogHtml:
"<!DOCTYPE html>"
+ "<html dir='" + WYMeditor.DIRECTION + "'>"
+ "<head>"
+ "<link rel='stylesheet' type='text/css' media='screen' href='" + WYMeditor.CSS_PATH + "' />"
+ "<title>" + WYMeditor.DIALOG_TITLE + "</title>"
+ "<script type='text/javascript' src='" + WYMeditor.JQUERY_PATH + "'></script>"
+ "<script type='text/javascript' src='" + WYMeditor.WYM_PATH + "'></script>"
+ "</head>"
+ "<body>"
+ "<div id='page'>" + WYMeditor.DIALOG_BODY + "</div>"
+ "</body>"
+ "</html>"
, postInit: function(wym)
{
// register loaded
wymeditors_loaded += 1;
// fire loaded if all editors loaded
if(WYMeditor.INSTANCES.length == wymeditors_loaded){
$('.wym_loading_overlay').remove();
WYMeditor.loaded();
}
$('.field.hide-overflow').removeClass('hide-overflow').css('height', 'auto');
}
, lang: (typeof(I18n.locale) != "undefined" ? I18n.locale : 'en')
}, custom_wymeditor_boot_options);
// custom function added by us to hook into when all wymeditor instances on the page have finally loaded:
WYMeditor.loaded = function(){};
$(function()
{
wymeditor_inputs = $('.wymeditor');
wymeditor_inputs.each(function(input) {
if ((containing_field = $(this).parents('.field')).get(0).style.height == '') {
containing_field.addClass('hide-overflow').css('height', $(this).outerHeight() - containing_field.offset().top + $(this).offset().top + 45);
}
$(this).hide();
});
wymeditor_inputs.wymeditor(wymeditor_boot_options);
});
|
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { integerPropType, deepmerge } from '@material-ui/utils';
import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled';
import Paper from '../Paper';
import capitalize from '../utils/capitalize';
import LinearProgress from '../LinearProgress';
import useThemeProps from '../styles/useThemeProps';
import experimentalStyled from '../styles/experimentalStyled';
import mobileStepperClasses, { getMobileStepperUtilityClass } from './mobileStepperClasses';
import { jsxs as _jsxs } from "react/jsx-runtime";
import { jsx as _jsx } from "react/jsx-runtime";
const overridesResolver = (props, styles) => {
const {
styleProps
} = props;
return deepmerge(_extends({}, styles[`position${capitalize(styleProps.position)}`], {
[`& .${mobileStepperClasses.dots}`]: styles.dots,
[`& .${mobileStepperClasses.dot}`]: _extends({}, styles.dot, styleProps.dotActive && styles.dotActive),
[`& .${mobileStepperClasses.dotActive}`]: styles.dotActive,
[`& .${mobileStepperClasses.progress}`]: styles.progress
}), styles.root || {});
};
const useUtilityClasses = styleProps => {
const {
classes,
position
} = styleProps;
const slots = {
root: ['root', `position${capitalize(position)}`],
dots: ['dots'],
dot: ['dot'],
dotActive: ['dotActive'],
progress: ['progress']
};
return composeClasses(slots, getMobileStepperUtilityClass, classes);
};
const MobileStepperRoot = experimentalStyled(Paper, {}, {
name: 'MuiMobileStepper',
slot: 'Root',
overridesResolver
})(({
theme,
styleProps
}) => _extends({
/* Styles applied to the root element. */
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
background: theme.palette.background.default,
padding: 8
}, styleProps.position === 'bottom' && {
position: 'fixed',
bottom: 0,
left: 0,
right: 0,
zIndex: theme.zIndex.mobileStepper
}, styleProps.position === 'top' && {
position: 'fixed',
top: 0,
left: 0,
right: 0,
zIndex: theme.zIndex.mobileStepper
}));
const MobileStepperDots = experimentalStyled('div', {}, {
name: 'MuiMobileStepper',
slot: 'Dots'
})(({
styleProps
}) => _extends({}, styleProps.variant === 'dots' && {
display: 'flex',
flexDirection: 'row'
}));
const MobileStepperDot = experimentalStyled('div', {}, {
name: 'MuiMobileStepper',
slot: 'Dot'
})(({
theme,
styleProps
}) => _extends({}, styleProps.variant === 'dots' && _extends({
transition: theme.transitions.create('background-color', {
duration: theme.transitions.duration.shortest
}),
backgroundColor: theme.palette.action.disabled,
borderRadius: '50%',
width: 8,
height: 8,
margin: '0 2px'
}, styleProps.dotActive && {
backgroundColor: theme.palette.primary.main
})));
const MobileStepperProgress = experimentalStyled(LinearProgress, {}, {
name: 'MuiMobileStepper',
slot: 'Progress'
})(({
styleProps
}) => _extends({}, styleProps.variant === 'progress' && {
width: '50%'
}));
const MobileStepper = /*#__PURE__*/React.forwardRef(function MobileStepper(inProps, ref) {
const props = useThemeProps({
props: inProps,
name: 'MuiMobileStepper'
});
const {
activeStep = 0,
backButton,
className,
LinearProgressProps,
nextButton,
position = 'bottom',
steps,
variant = 'dots'
} = props,
other = _objectWithoutPropertiesLoose(props, ["activeStep", "backButton", "className", "LinearProgressProps", "nextButton", "position", "steps", "variant"]);
const styleProps = _extends({}, props, {
activeStep,
position,
variant
});
const classes = useUtilityClasses(styleProps);
return /*#__PURE__*/_jsxs(MobileStepperRoot, _extends({
square: true,
elevation: 0,
className: clsx(classes.root, className),
ref: ref,
styleProps: styleProps
}, other, {
children: [backButton, variant === 'text' && /*#__PURE__*/_jsxs(React.Fragment, {
children: [activeStep + 1, " / ", steps]
}), variant === 'dots' && /*#__PURE__*/_jsx(MobileStepperDots, {
styleProps: styleProps,
className: classes.dots,
children: [...new Array(steps)].map((_, index) => /*#__PURE__*/_jsx(MobileStepperDot, {
className: clsx(classes.dot, index === activeStep && classes.dotActive),
styleProps: _extends({}, styleProps, {
dotActive: index === activeStep
})
}, index))
}), variant === 'progress' && /*#__PURE__*/_jsx(MobileStepperProgress, _extends({
styleProps: styleProps,
className: classes.progress,
variant: "determinate",
value: Math.ceil(activeStep / (steps - 1) * 100)
}, LinearProgressProps)), nextButton]
}));
});
process.env.NODE_ENV !== "production" ? MobileStepper.propTypes
/* remove-proptypes */
= {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* Set the active step (zero based index).
* Defines which dot is highlighted when the variant is 'dots'.
* @default 0
*/
activeStep: integerPropType,
/**
* A back button element. For instance, it can be a `Button` or an `IconButton`.
*/
backButton: PropTypes.node,
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* Props applied to the `LinearProgress` element.
*/
LinearProgressProps: PropTypes.object,
/**
* A next button element. For instance, it can be a `Button` or an `IconButton`.
*/
nextButton: PropTypes.node,
/**
* Set the positioning type.
* @default 'bottom'
*/
position: PropTypes.oneOf(['bottom', 'static', 'top']),
/**
* The total steps.
*/
steps: integerPropType.isRequired,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.object,
/**
* The variant to use.
* @default 'dots'
*/
variant: PropTypes.oneOf(['dots', 'progress', 'text'])
} : void 0;
export default MobileStepper; |
/* -----------------------------------------------
/* How to use? : Check the GitHub README
/* ----------------------------------------------- */
/* To load a config file (particles.json) you need to host this demo (MAMP/WAMP/local)... */
/*
particlesJS.load('particles-js', 'particles.json', function() {
console.log('particles.js loaded - callback');
});
*/
/* Otherwise just put the config content (json): */
particlesJS('particles-js',
{
"particles": {
"number": {
"value": 80,
"density": {
"enable": true,
"value_area": 800
}
},
"color": {
"value": "#888"
},
"shape": {
"type": "circle",
"stroke": {
"width": 0,
"color": "#000000"
},
"polygon": {
"nb_sides": 5
},
"image": {
"src": "img/github.svg",
"width": 100,
"height": 100
}
},
"opacity": {
"value": 0.5,
"random": false,
"anim": {
"enable": false,
"speed": 1,
"opacity_min": 0.1,
"sync": false
}
},
"size": {
"value": 5,
"random": true,
"anim": {
"enable": false,
"speed": 40,
"size_min": 0.1,
"sync": false
}
},
"line_linked": {
"enable": true,
"distance": 150,
"color": "#777",
"opacity": 0.4,
"width": 1
},
"move": {
"enable": true,
"speed": 6,
"direction": "none",
"random": false,
"straight": false,
"out_mode": "out",
"attract": {
"enable": false,
"rotateX": 600,
"rotateY": 1200
}
}
},
"interactivity": {
"detect_on": "canvas",
"events": {
"onhover": {
"enable": true,
"mode": "repulse"
},
"onclick": {
"enable": true,
"mode": "push"
},
"resize": true
},
"modes": {
"grab": {
"distance": 400,
"line_linked": {
"opacity": 1
}
},
"bubble": {
"distance": 400,
"size": 40,
"duration": 2,
"opacity": 8,
"speed": 3
},
"repulse": {
"distance": 200
},
"push": {
"particles_nb": 4
},
"remove": {
"particles_nb": 2
}
}
},
"retina_detect": true,
"config_demo": {
"hide_card": false,
"background_color": "#b61924",
"background_image": "",
"background_position": "50% 50%",
"background_repeat": "no-repeat",
"background_size": "cover"
}
}
); |
// Note: You must restart bin/webpack-watcher for changes to take effect
const merge = require('webpack-merge')
const sharedConfig = require('./shared.js')
module.exports = merge(sharedConfig, {
devtool: 'sourcemap',
stats: {
errorDetails: true
},
output: {
pathinfo: true
}
})
|
var global = require('../../global');
module.exports = function (packing, offset) {
var items = [].concat.apply([], packing.items);
var iso = "FM.FP-GJ-15-003";
// var number = packing.code;
// var colorName = packing.colorName;
var orderType = (packing.orderType || "").toString().toLowerCase() === "printing" ? "Printing" : "Finishing";
var locale = global.config.locale;
var buyerName = packing.buyerName ? packing.buyerName : "";
var colorType = packing.colorType ? packing.colorType : "";
var construction = packing.construction ? packing.construction : "";
var buyerAddress = packing.buyerAddress ? packing.buyerAddress : "";
var moment = require('moment');
moment.locale(locale.name);
var footerStack = [];
var footerStackValue = [];
var footerStackDivide = [];
if ((packing.orderType || "").toString().toLowerCase() === "solid") {
footerStack = ['Buyer', "Jenis Order", "Jenis Warna", 'Konstruksi', 'Tujuan'];
footerStackValue = [buyerName, orderType, colorType, construction, buyerAddress];
footerStackDivide = [':', ":", ":", ':', ':'];
} else if ((packing.orderType || "").toString().toLowerCase() === "printing") {
footerStack = ['Buyer', "Jenis Order", 'Konstruksi', 'Design/Motif', 'Tujuan'];
footerStackValue = [buyerName, orderType, construction, packing.designNumber && packing.designCode ? `${packing.designNumber} - ${packing.designCode}` : "", buyerAddress];
footerStackDivide = [':', ":", ":", ':', ':'];
} else {
footerStack = ['Buyer', "Jenis Order", 'Konstruksi', 'Tujuan'];
footerStackValue = [buyerName, orderType, construction, buyerAddress];
footerStackDivide = [':', ":", ":", ':'];
}
var header = [{
columns: [{
columns: [{
width: '*',
stack: [{
text: 'BON PENYERAHAN PRODUKSI',
style: ['size15'],
alignment: "center"
}]
}]
}]
}];
var line = [{
canvas: [{
type: 'line',
x1: 0,
y1: 5,
x2: 555,
y2: 5,
lineWidth: 0.5
}
]
}];
var subheader = [{
columns: [{
columns: [{
width: '*',
stack: [{
text: iso,
style: ['size09', 'bold'],
alignment: "right"
}
]
}]
}]
}];
var subheader2 = [{
columns: [{
width: '60%',
columns: [{
width: '*',
stack: ['Kepada Yth. Bagian Penjualan ', `Bersama ini kami kirimkan hasil produksi: Inspeksi ${orderType}`],
}],
style: ['size08']
}
,
{
width: '5%',
text: ''
},
{
width: '40%',
columns: [{
width: '40%',
stack: ['No', 'Sesuai No Order'],
}, {
width: '5%',
stack: [':', ':'],
}, {
width: '*',
stack: [packing.code, packing.productionOrderNo],
}],
style: ['size08']
}
]
}];
var thead = [{
text: 'NO',
style: 'tableHeader'
},
{
text: 'BARANG',
style: 'tableHeader'
},
{
text: `Jumlah (${packing.packingUom})`,
style: 'tableHeader'
},
{
text: 'Panjang (Meter)',
style: 'tableHeader'
},
{
text: 'Panjang Total (Meter)',
style: 'tableHeader'
},
{
text: 'Berat Total (Kg)',
style: 'tableHeader'
},
{
text: 'Keterangan',
style: 'tableHeader'
}
];
var gradeItem = "";
var totalJumlah = 0;
var totalBerat = 0;
var totalPanjang = 0;
var totalPanjangTotal = 0;
var totalBeratTotal = 0;
var tbody = items.map(function (item, index) {
// if (item.grade.toLowerCase() == "a" || item.grade.toLowerCase() == "b" || item.grade.toLowerCase() == "c") {
if (item.grade.toLowerCase() == "a") {
gradeItem = "BQ";
} else {
gradeItem = "BS";
}
totalJumlah += item.quantity;
totalBerat += item.weight;
totalPanjang += item.length;
totalPanjangTotal += item.length * item.quantity;
totalBeratTotal += item.weight * item.quantity;
return [{
text: (index + 1).toString() || '',
style: ['size08', 'center']
},
{
text: packing.colorName + ' ' + item.lot + ' ' + item.grade + ' ' + gradeItem,
style: ['size08', 'center']
},
{
text: item.quantity,
style: ['size08', 'center']
},
{
text: item.length,
style: ['size08', 'center']
},
{
text: (item.length * item.quantity).toFixed(2),
style: ['size08', 'center']
},
{
text: (item.weight * item.quantity).toFixed(2),
style: ['size08', 'center']
},
{
text: item.remark,
style: ['size08', 'center']
}
];
});
var tfoot = [[{
text: " ",
style: ['size08', 'center']
}, {
text: "Total",
style: ['size08', 'center']
}, {
text: totalJumlah.toFixed(2),
style: ['size08', 'center']
}, {
text: totalPanjang.toFixed(2),
style: ['size08', 'center']
}, {
text: totalPanjangTotal.toFixed(2),
style: ['size08', 'center']
}, {
text: totalBeratTotal.toFixed(2),
style: ['size08', 'center']
}, "",]];
tbody = tbody.length > 0 ? tbody : [
[{
text: "tidak ada barang",
style: ['size08', 'center'],
colSpan: 6
}, "", "", "", "", "", ""]
];
var table = [{
table: {
widths: ['5%', '35%', '10%', '10%', '10%', '10%', '20%'],
headerRows: 1,
body: [].concat([thead], tbody, tfoot),
}
}];
var footer = [{
stack: [{
columns: [{
columns: [{
width: '15%',
stack: footerStack
}, {
width: '2%',
stack: footerStackDivide
}, {
width: '*',
stack: footerStackValue
}]
}]
}
],
style: ['size08']
},
];
var footer2 = ['\n', {
columns: [{
width: '25%',
stack: ['\n', 'Diterima oleh:', '\n\n\n\n', '( )'],
style: ['center']
},
{
width: '25%',
stack: [],
},
{
width: '25%',
stack: [],
},
{
width: '25%',
stack: [`Sukoharjo, ${moment(packing.date).add(offset, 'h').format(locale.date.format)} `, 'Diserahkan oleh :', '\n\n\n\n', `( ${packing._createdBy} )`],
style: ['center']
}],
style: ['size08']
}];
var packingPDF = {
pageSize: 'A5',
pageOrientation: 'landscape',
pageMargins: 20,
// content: [].concat(header, line, subheader, subheader2, table, footer),
content: [].concat(header, line, subheader, subheader2, table, footer, footer2),
styles: {
size06: {
fontSize: 8
},
size07: {
fontSize: 9
},
size08: {
fontSize: 10
},
size09: {
fontSize: 11
},
size10: {
fontSize: 12
},
size15: {
fontSize: 17
},
size30: {
fontSize: 32
},
bold: {
bold: true
},
center: {
alignment: 'center'
},
left: {
alignment: 'left'
},
right: {
alignment: 'right'
},
justify: {
alignment: 'justify'
},
tableHeader: {
bold: true,
fontSize: 10,
color: 'black',
alignment: 'center'
}
}
};
return packingPDF;
} |
/**
* Interaction for the faq module
*
* @author Annelies Van Extergem <[email protected]>
* @author Jelmer Snoeck <[email protected]>
* @author Thomas Deceuninck <[email protected]>
*/
jsFrontend.faq =
{
// init, something like a constructor
init: function()
{
if($('#faqFeedbackForm').length > 0) jsFrontend.faq.feedback.init();
}
}
// feedback form
jsFrontend.faq.feedback =
{
init: function()
{
// useful status has been changed
$('#usefulY, #usefulN').on('click', function()
{
// get useful status
var useful = ($('#usefulY').attr('checked') ? true : false);
// show or hide the form
if(useful)
{
$('#message').prop('required', false);
$('form#feedback').submit();
}
else
{
$('#feedbackNoInfo').show();
$('#message').prop('required', true);
}
});
}
}
$(jsFrontend.faq.init); |
/*
* jQuery File Upload Plugin 5.32.0
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/*jslint nomen: true, unparam: true, regexp: true */
/*global define, window, document, location, File, Blob, FormData */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define([
'jquery',
'jquery.ui.widget'
], factory);
} else {
// Browser globals:
factory(window.jQuery);
}
}(function ($) {
'use strict';
// Detect file input support, based on
// http://viljamis.com/blog/2012/file-upload-support-on-mobile/
$.support.fileInput = !(new RegExp(
// Handle devices which give false positives for the feature detection:
'(Android (1\\.[0156]|2\\.[01]))' +
'|(Windows Phone (OS 7|8\\.0))|(XBLWP)|(ZuneWP)' +
'|(w(eb)?OSBrowser)|(webOS)' +
'|(Kindle/(1\\.0|2\\.[05]|3\\.0))'
).test(window.navigator.userAgent) ||
// Feature detection for all other devices:
$('<input type="file">').prop('disabled'));
// The FileReader API is not actually used, but works as feature detection,
// as e.g. Safari supports XHR file uploads via the FormData API,
// but not non-multipart XHR file uploads:
$.support.xhrFileUpload = !!(window.XMLHttpRequestUpload && window.FileReader);
$.support.xhrFormDataFileUpload = !!window.FormData;
// Detect support for Blob slicing (required for chunked uploads):
$.support.blobSlice = window.Blob && (Blob.prototype.slice ||
Blob.prototype.webkitSlice || Blob.prototype.mozSlice);
// The fileupload widget listens for change events on file input fields defined
// via fileInput setting and paste or drop events of the given dropZone.
// In addition to the default jQuery Widget methods, the fileupload widget
// exposes the "add" and "send" methods, to add or directly send files using
// the fileupload API.
// By default, files added via file input selection, paste, drag & drop or
// "add" method are uploaded immediately, but it is possible to override
// the "add" callback option to queue file uploads.
$.widget('blueimp.fileupload', {
options: {
// The drop target element(s), by the default the complete document.
// Set to null to disable drag & drop support:
dropZone: $(document),
// The paste target element(s), by the default the complete document.
// Set to null to disable paste support:
pasteZone: $(document),
// The file input field(s), that are listened to for change events.
// If undefined, it is set to the file input fields inside
// of the widget element on plugin initialization.
// Set to null to disable the change listener.
fileInput: undefined,
// By default, the file input field is replaced with a clone after
// each input field change event. This is required for iframe transport
// queues and allows change events to be fired for the same file
// selection, but can be disabled by setting the following option to false:
replaceFileInput: true,
// The parameter name for the file form data (the request argument name).
// If undefined or empty, the name property of the file input field is
// used, or "files[]" if the file input name property is also empty,
// can be a string or an array of strings:
paramName: undefined,
// By default, each file of a selection is uploaded using an individual
// request for XHR type uploads. Set to false to upload file
// selections in one request each:
singleFileUploads: true,
// To limit the number of files uploaded with one XHR request,
// set the following option to an integer greater than 0:
limitMultiFileUploads: undefined,
// Set the following option to true to issue all file upload requests
// in a sequential order:
sequentialUploads: false,
// To limit the number of concurrent uploads,
// set the following option to an integer greater than 0:
limitConcurrentUploads: undefined,
// Set the following option to true to force iframe transport uploads:
forceIframeTransport: false,
// Set the following option to the location of a redirect url on the
// origin server, for cross-domain iframe transport uploads:
redirect: undefined,
// The parameter name for the redirect url, sent as part of the form
// data and set to 'redirect' if this option is empty:
redirectParamName: undefined,
// Set the following option to the location of a postMessage window,
// to enable postMessage transport uploads:
postMessage: undefined,
// By default, XHR file uploads are sent as multipart/form-data.
// The iframe transport is always using multipart/form-data.
// Set to false to enable non-multipart XHR uploads:
multipart: true,
// To upload large files in smaller chunks, set the following option
// to a preferred maximum chunk size. If set to 0, null or undefined,
// or the browser does not support the required Blob API, files will
// be uploaded as a whole.
maxChunkSize: undefined,
// When a non-multipart upload or a chunked multipart upload has been
// aborted, this option can be used to resume the upload by setting
// it to the size of the already uploaded bytes. This option is most
// useful when modifying the options object inside of the "add" or
// "send" callbacks, as the options are cloned for each file upload.
uploadedBytes: undefined,
// By default, failed (abort or error) file uploads are removed from the
// global progress calculation. Set the following option to false to
// prevent recalculating the global progress data:
recalculateProgress: true,
// Interval in milliseconds to calculate and trigger progress events:
progressInterval: 100,
// Interval in milliseconds to calculate progress bitrate:
bitrateInterval: 500,
// By default, uploads are started automatically when adding files:
autoUpload: true,
// Error and info messages:
messages: {
uploadedBytes: 'Uploaded bytes exceed file size'
},
// Translation function, gets the message key to be translated
// and an object with context specific data as arguments:
i18n: function (message, context) {
message = this.messages[message] || message.toString();
if (context) {
$.each(context, function (key, value) {
message = message.replace('{' + key + '}', value);
});
}
return message;
},
// Additional form data to be sent along with the file uploads can be set
// using this option, which accepts an array of objects with name and
// value properties, a function returning such an array, a FormData
// object (for XHR file uploads), or a simple object.
// The form of the first fileInput is given as parameter to the function:
formData: function (form) {
return form.serializeArray();
},
// The add callback is invoked as soon as files are added to the fileupload
// widget (via file input selection, drag & drop, paste or add API call).
// If the singleFileUploads option is enabled, this callback will be
// called once for each file in the selection for XHR file uploads, else
// once for each file selection.
//
// The upload starts when the submit method is invoked on the data parameter.
// The data object contains a files property holding the added files
// and allows you to override plugin options as well as define ajax settings.
//
// Listeners for this callback can also be bound the following way:
// .bind('fileuploadadd', func);
//
// data.submit() returns a Promise object and allows to attach additional
// handlers using jQuery's Deferred callbacks:
// data.submit().done(func).fail(func).always(func);
add: function (e, data) {
if (data.autoUpload || (data.autoUpload !== false &&
$(this).fileupload('option', 'autoUpload'))) {
data.process().done(function () {
data.submit();
});
}
},
// Other callbacks:
// Callback for the submit event of each file upload:
// submit: function (e, data) {}, // .bind('fileuploadsubmit', func);
// Callback for the start of each file upload request:
// send: function (e, data) {}, // .bind('fileuploadsend', func);
// Callback for successful uploads:
// done: function (e, data) {}, // .bind('fileuploaddone', func);
// Callback for failed (abort or error) uploads:
// fail: function (e, data) {}, // .bind('fileuploadfail', func);
// Callback for completed (success, abort or error) requests:
// always: function (e, data) {}, // .bind('fileuploadalways', func);
// Callback for upload progress events:
// progress: function (e, data) {}, // .bind('fileuploadprogress', func);
// Callback for global upload progress events:
// progressall: function (e, data) {}, // .bind('fileuploadprogressall', func);
// Callback for uploads start, equivalent to the global ajaxStart event:
// start: function (e) {}, // .bind('fileuploadstart', func);
// Callback for uploads stop, equivalent to the global ajaxStop event:
// stop: function (e) {}, // .bind('fileuploadstop', func);
// Callback for change events of the fileInput(s):
// change: function (e, data) {}, // .bind('fileuploadchange', func);
// Callback for paste events to the pasteZone(s):
// paste: function (e, data) {}, // .bind('fileuploadpaste', func);
// Callback for drop events of the dropZone(s):
// drop: function (e, data) {}, // .bind('fileuploaddrop', func);
// Callback for dragover events of the dropZone(s):
// dragover: function (e) {}, // .bind('fileuploaddragover', func);
// Callback for the start of each chunk upload request:
// chunksend: function (e, data) {}, // .bind('fileuploadchunksend', func);
// Callback for successful chunk uploads:
// chunkdone: function (e, data) {}, // .bind('fileuploadchunkdone', func);
// Callback for failed (abort or error) chunk uploads:
// chunkfail: function (e, data) {}, // .bind('fileuploadchunkfail', func);
// Callback for completed (success, abort or error) chunk upload requests:
// chunkalways: function (e, data) {}, // .bind('fileuploadchunkalways', func);
// The plugin options are used as settings object for the ajax calls.
// The following are jQuery ajax settings required for the file uploads:
processData: false,
contentType: false,
cache: false
},
// A list of options that require reinitializing event listeners and/or
// special initialization code:
_specialOptions: [
'fileInput',
'dropZone',
'pasteZone',
'multipart',
'forceIframeTransport'
],
_blobSlice: $.support.blobSlice && function () {
var slice = this.slice || this.webkitSlice || this.mozSlice;
return slice.apply(this, arguments);
},
_BitrateTimer: function () {
this.timestamp = ((Date.now) ? Date.now() : (new Date()).getTime());
this.loaded = 0;
this.bitrate = 0;
this.getBitrate = function (now, loaded, interval) {
var timeDiff = now - this.timestamp;
if (!this.bitrate || !interval || timeDiff > interval) {
this.bitrate = (loaded - this.loaded) * (1000 / timeDiff) * 8;
this.loaded = loaded;
this.timestamp = now;
}
return this.bitrate;
};
},
_isXHRUpload: function (options) {
return !options.forceIframeTransport &&
((!options.multipart && $.support.xhrFileUpload) ||
$.support.xhrFormDataFileUpload);
},
_getFormData: function (options) {
var formData;
if (typeof options.formData === 'function') {
return options.formData(options.form);
}
if ($.isArray(options.formData)) {
return options.formData;
}
if ($.type(options.formData) === 'object') {
formData = [];
$.each(options.formData, function (name, value) {
formData.push({name: name, value: value});
});
return formData;
}
return [];
},
_getTotal: function (files) {
var total = 0;
$.each(files, function (index, file) {
total += file.size || 1;
});
return total;
},
_initProgressObject: function (obj) {
var progress = {
loaded: 0,
total: 0,
bitrate: 0
};
if (obj._progress) {
$.extend(obj._progress, progress);
} else {
obj._progress = progress;
}
},
_initResponseObject: function (obj) {
var prop;
if (obj._response) {
for (prop in obj._response) {
if (obj._response.hasOwnProperty(prop)) {
delete obj._response[prop];
}
}
} else {
obj._response = {};
}
},
_onProgress: function (e, data) {
if (e.lengthComputable) {
var now = ((Date.now) ? Date.now() : (new Date()).getTime()),
loaded;
if (data._time && data.progressInterval &&
(now - data._time < data.progressInterval) &&
e.loaded !== e.total) {
return;
}
data._time = now;
loaded = Math.floor(
e.loaded / e.total * (data.chunkSize || data._progress.total)
) + (data.uploadedBytes || 0);
// Add the difference from the previously loaded state
// to the global loaded counter:
this._progress.loaded += (loaded - data._progress.loaded);
this._progress.bitrate = this._bitrateTimer.getBitrate(
now,
this._progress.loaded,
data.bitrateInterval
);
data._progress.loaded = data.loaded = loaded;
data._progress.bitrate = data.bitrate = data._bitrateTimer.getBitrate(
now,
loaded,
data.bitrateInterval
);
// Trigger a custom progress event with a total data property set
// to the file size(s) of the current upload and a loaded data
// property calculated accordingly:
this._trigger('progress', e, data);
// Trigger a global progress event for all current file uploads,
// including ajax calls queued for sequential file uploads:
this._trigger('progressall', e, this._progress);
}
},
_initProgressListener: function (options) {
var that = this,
xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr();
// Accesss to the native XHR object is required to add event listeners
// for the upload progress event:
if (xhr.upload) {
$(xhr.upload).bind('progress', function (e) {
var oe = e.originalEvent;
// Make sure the progress event properties get copied over:
e.lengthComputable = oe.lengthComputable;
e.loaded = oe.loaded;
e.total = oe.total;
that._onProgress(e, options);
});
options.xhr = function () {
return xhr;
};
}
},
_isInstanceOf: function (type, obj) {
// Cross-frame instanceof check
return Object.prototype.toString.call(obj) === '[object ' + type + ']';
},
_initXHRData: function (options) {
var that = this,
formData,
file = options.files[0],
// Ignore non-multipart setting if not supported:
multipart = options.multipart || !$.support.xhrFileUpload,
paramName = options.paramName[0];
options.headers = options.headers || {};
if (options.contentRange) {
options.headers['Content-Range'] = options.contentRange;
}
if (!multipart || options.blob || !this._isInstanceOf('File', file)) {
options.headers['Content-Disposition'] = 'attachment; filename="' +
encodeURI(file.name) + '"';
}
if (!multipart) {
options.contentType = file.type;
options.data = options.blob || file;
} else if ($.support.xhrFormDataFileUpload) {
if (options.postMessage) {
// window.postMessage does not allow sending FormData
// objects, so we just add the File/Blob objects to
// the formData array and let the postMessage window
// create the FormData object out of this array:
formData = this._getFormData(options);
if (options.blob) {
formData.push({
name: paramName,
value: options.blob
});
} else {
$.each(options.files, function (index, file) {
formData.push({
name: options.paramName[index] || paramName,
value: file
});
});
}
} else {
if (that._isInstanceOf('FormData', options.formData)) {
formData = options.formData;
} else {
formData = new FormData();
$.each(this._getFormData(options), function (index, field) {
formData.append(field.name, field.value);
});
}
if (options.blob) {
formData.append(paramName, options.blob, file.name);
} else {
$.each(options.files, function (index, file) {
// This check allows the tests to run with
// dummy objects:
if (that._isInstanceOf('File', file) ||
that._isInstanceOf('Blob', file)) {
formData.append(
options.paramName[index] || paramName,
file,
file.name
);
}
});
}
}
options.data = formData;
}
// Blob reference is not needed anymore, free memory:
options.blob = null;
},
_initIframeSettings: function (options) {
var targetHost = $('<a></a>').prop('href', options.url).prop('host');
// Setting the dataType to iframe enables the iframe transport:
options.dataType = 'iframe ' + (options.dataType || '');
// The iframe transport accepts a serialized array as form data:
options.formData = this._getFormData(options);
// Add redirect url to form data on cross-domain uploads:
if (options.redirect && targetHost && targetHost !== location.host) {
options.formData.push({
name: options.redirectParamName || 'redirect',
value: options.redirect
});
}
},
_initDataSettings: function (options) {
if (this._isXHRUpload(options)) {
if (!this._chunkedUpload(options, true)) {
if (!options.data) {
this._initXHRData(options);
}
this._initProgressListener(options);
}
if (options.postMessage) {
// Setting the dataType to postmessage enables the
// postMessage transport:
options.dataType = 'postmessage ' + (options.dataType || '');
}
} else {
this._initIframeSettings(options);
}
},
_getParamName: function (options) {
var fileInput = $(options.fileInput),
paramName = options.paramName;
if (!paramName) {
paramName = [];
fileInput.each(function () {
var input = $(this),
name = input.prop('name') || 'files[]',
i = (input.prop('files') || [1]).length;
while (i) {
paramName.push(name);
i -= 1;
}
});
if (!paramName.length) {
paramName = [fileInput.prop('name') || 'files[]'];
}
} else if (!$.isArray(paramName)) {
paramName = [paramName];
}
return paramName;
},
_initFormSettings: function (options) {
// Retrieve missing options from the input field and the
// associated form, if available:
if (!options.form || !options.form.length) {
options.form = $(options.fileInput.prop('form'));
// If the given file input doesn't have an associated form,
// use the default widget file input's form:
if (!options.form.length) {
options.form = $(this.options.fileInput.prop('form'));
}
}
options.paramName = this._getParamName(options);
if (!options.url) {
options.url = options.form.prop('action') || location.href;
}
// The HTTP request method must be "POST" or "PUT":
options.type = (options.type || options.form.prop('method') || '')
.toUpperCase();
if (options.type !== 'POST' && options.type !== 'PUT' &&
options.type !== 'PATCH') {
options.type = 'POST';
}
if (!options.formAcceptCharset) {
options.formAcceptCharset = options.form.attr('accept-charset');
}
},
_getAJAXSettings: function (data) {
var options = $.extend({}, this.options, data);
this._initFormSettings(options);
this._initDataSettings(options);
return options;
},
// jQuery 1.6 doesn't provide .state(),
// while jQuery 1.8+ removed .isRejected() and .isResolved():
_getDeferredState: function (deferred) {
if (deferred.state) {
return deferred.state();
}
if (deferred.isResolved()) {
return 'resolved';
}
if (deferred.isRejected()) {
return 'rejected';
}
return 'pending';
},
// Maps jqXHR callbacks to the equivalent
// methods of the given Promise object:
_enhancePromise: function (promise) {
promise.success = promise.done;
promise.error = promise.fail;
promise.complete = promise.always;
return promise;
},
// Creates and returns a Promise object enhanced with
// the jqXHR methods abort, success, error and complete:
_getXHRPromise: function (resolveOrReject, context, args) {
var dfd = $.Deferred(),
promise = dfd.promise();
context = context || this.options.context || promise;
if (resolveOrReject === true) {
dfd.resolveWith(context, args);
} else if (resolveOrReject === false) {
dfd.rejectWith(context, args);
}
promise.abort = dfd.promise;
return this._enhancePromise(promise);
},
// Adds convenience methods to the data callback argument:
_addConvenienceMethods: function (e, data) {
var that = this,
getPromise = function (data) {
return $.Deferred().resolveWith(that, [data]).promise();
};
data.process = function (resolveFunc, rejectFunc) {
if (resolveFunc || rejectFunc) {
data._processQueue = this._processQueue =
(this._processQueue || getPromise(this))
.pipe(resolveFunc, rejectFunc);
}
return this._processQueue || getPromise(this);
};
data.submit = function () {
if (this.state() !== 'pending') {
data.jqXHR = this.jqXHR =
(that._trigger('submit', e, this) !== false) &&
that._onSend(e, this);
}
return this.jqXHR || that._getXHRPromise();
};
data.abort = function () {
if (this.jqXHR) {
return this.jqXHR.abort();
}
return that._getXHRPromise();
};
data.state = function () {
if (this.jqXHR) {
return that._getDeferredState(this.jqXHR);
}
if (this._processQueue) {
return that._getDeferredState(this._processQueue);
}
};
data.progress = function () {
return this._progress;
};
data.response = function () {
return this._response;
};
},
// Parses the Range header from the server response
// and returns the uploaded bytes:
_getUploadedBytes: function (jqXHR) {
var range = jqXHR.getResponseHeader('Range'),
parts = range && range.split('-'),
upperBytesPos = parts && parts.length > 1 &&
parseInt(parts[1], 10);
return upperBytesPos && upperBytesPos + 1;
},
// Uploads a file in multiple, sequential requests
// by splitting the file up in multiple blob chunks.
// If the second parameter is true, only tests if the file
// should be uploaded in chunks, but does not invoke any
// upload requests:
_chunkedUpload: function (options, testOnly) {
options.uploadedBytes = options.uploadedBytes || 0;
var that = this,
file = options.files[0],
fs = file.size,
ub = options.uploadedBytes,
mcs = options.maxChunkSize || fs,
slice = this._blobSlice,
dfd = $.Deferred(),
promise = dfd.promise(),
jqXHR,
upload;
if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) ||
options.data) {
return false;
}
if (testOnly) {
return true;
}
if (ub >= fs) {
file.error = options.i18n('uploadedBytes');
return this._getXHRPromise(
false,
options.context,
[null, 'error', file.error]
);
}
// The chunk upload method:
upload = function () {
// Clone the options object for each chunk upload:
var o = $.extend({}, options),
currentLoaded = o._progress.loaded;
o.blob = slice.call(
file,
ub,
ub + mcs,
file.type
);
// Store the current chunk size, as the blob itself
// will be dereferenced after data processing:
o.chunkSize = o.blob.size;
// Expose the chunk bytes position range:
o.contentRange = 'bytes ' + ub + '-' +
(ub + o.chunkSize - 1) + '/' + fs;
// Process the upload data (the blob and potential form data):
that._initXHRData(o);
// Add progress listeners for this chunk upload:
that._initProgressListener(o);
jqXHR = ((that._trigger('chunksend', null, o) !== false && $.ajax(o)) ||
that._getXHRPromise(false, o.context))
.done(function (result, textStatus, jqXHR) {
ub = that._getUploadedBytes(jqXHR) ||
(ub + o.chunkSize);
// Create a progress event if no final progress event
// with loaded equaling total has been triggered
// for this chunk:
if (currentLoaded + o.chunkSize - o._progress.loaded) {
that._onProgress($.Event('progress', {
lengthComputable: true,
loaded: ub - o.uploadedBytes,
total: ub - o.uploadedBytes
}), o);
}
options.uploadedBytes = o.uploadedBytes = ub;
o.result = result;
o.textStatus = textStatus;
o.jqXHR = jqXHR;
that._trigger('chunkdone', null, o);
that._trigger('chunkalways', null, o);
if (ub < fs) {
// File upload not yet complete,
// continue with the next chunk:
upload();
} else {
dfd.resolveWith(
o.context,
[result, textStatus, jqXHR]
);
}
})
.fail(function (jqXHR, textStatus, errorThrown) {
o.jqXHR = jqXHR;
o.textStatus = textStatus;
o.errorThrown = errorThrown;
that._trigger('chunkfail', null, o);
that._trigger('chunkalways', null, o);
dfd.rejectWith(
o.context,
[jqXHR, textStatus, errorThrown]
);
});
};
this._enhancePromise(promise);
promise.abort = function () {
return jqXHR.abort();
};
upload();
return promise;
},
_beforeSend: function (e, data) {
if (this._active === 0) {
// the start callback is triggered when an upload starts
// and no other uploads are currently running,
// equivalent to the global ajaxStart event:
this._trigger('start');
// Set timer for global bitrate progress calculation:
this._bitrateTimer = new this._BitrateTimer();
// Reset the global progress values:
this._progress.loaded = this._progress.total = 0;
this._progress.bitrate = 0;
}
// Make sure the container objects for the .response() and
// .progress() methods on the data object are available
// and reset to their initial state:
this._initResponseObject(data);
this._initProgressObject(data);
data._progress.loaded = data.loaded = data.uploadedBytes || 0;
data._progress.total = data.total = this._getTotal(data.files) || 1;
data._progress.bitrate = data.bitrate = 0;
this._active += 1;
// Initialize the global progress values:
this._progress.loaded += data.loaded;
this._progress.total += data.total;
},
_onDone: function (result, textStatus, jqXHR, options) {
var total = options._progress.total,
response = options._response;
if (options._progress.loaded < total) {
// Create a progress event if no final progress event
// with loaded equaling total has been triggered:
this._onProgress($.Event('progress', {
lengthComputable: true,
loaded: total,
total: total
}), options);
}
response.result = options.result = result;
response.textStatus = options.textStatus = textStatus;
response.jqXHR = options.jqXHR = jqXHR;
this._trigger('done', null, options);
},
_onFail: function (jqXHR, textStatus, errorThrown, options) {
var response = options._response;
if (options.recalculateProgress) {
// Remove the failed (error or abort) file upload from
// the global progress calculation:
this._progress.loaded -= options._progress.loaded;
this._progress.total -= options._progress.total;
}
response.jqXHR = options.jqXHR = jqXHR;
response.textStatus = options.textStatus = textStatus;
response.errorThrown = options.errorThrown = errorThrown;
this._trigger('fail', null, options);
},
_onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) {
// jqXHRorResult, textStatus and jqXHRorError are added to the
// options object via done and fail callbacks
this._trigger('always', null, options);
},
_onSend: function (e, data) {
if (!data.submit) {
this._addConvenienceMethods(e, data);
}
var that = this,
jqXHR,
aborted,
slot,
pipe,
options = that._getAJAXSettings(data),
send = function () {
that._sending += 1;
// Set timer for bitrate progress calculation:
options._bitrateTimer = new that._BitrateTimer();
jqXHR = jqXHR || (
((aborted || that._trigger('send', e, options) === false) &&
that._getXHRPromise(false, options.context, aborted)) ||
that._chunkedUpload(options) || $.ajax(options)
).done(function (result, textStatus, jqXHR) {
that._onDone(result, textStatus, jqXHR, options);
}).fail(function (jqXHR, textStatus, errorThrown) {
that._onFail(jqXHR, textStatus, errorThrown, options);
}).always(function (jqXHRorResult, textStatus, jqXHRorError) {
that._onAlways(
jqXHRorResult,
textStatus,
jqXHRorError,
options
);
that._sending -= 1;
that._active -= 1;
if (options.limitConcurrentUploads &&
options.limitConcurrentUploads > that._sending) {
// Start the next queued upload,
// that has not been aborted:
var nextSlot = that._slots.shift();
while (nextSlot) {
if (that._getDeferredState(nextSlot) === 'pending') {
nextSlot.resolve();
break;
}
nextSlot = that._slots.shift();
}
}
if (that._active === 0) {
// The stop callback is triggered when all uploads have
// been completed, equivalent to the global ajaxStop event:
that._trigger('stop');
}
});
return jqXHR;
};
this._beforeSend(e, options);
if (this.options.sequentialUploads ||
(this.options.limitConcurrentUploads &&
this.options.limitConcurrentUploads <= this._sending)) {
if (this.options.limitConcurrentUploads > 1) {
slot = $.Deferred();
this._slots.push(slot);
pipe = slot.pipe(send);
} else {
this._sequence = this._sequence.pipe(send, send);
pipe = this._sequence;
}
// Return the piped Promise object, enhanced with an abort method,
// which is delegated to the jqXHR object of the current upload,
// and jqXHR callbacks mapped to the equivalent Promise methods:
pipe.abort = function () {
aborted = [undefined, 'abort', 'abort'];
if (!jqXHR) {
if (slot) {
slot.rejectWith(options.context, aborted);
}
return send();
}
return jqXHR.abort();
};
return this._enhancePromise(pipe);
}
return send();
},
_onAdd: function (e, data) {
var that = this,
result = true,
options = $.extend({}, this.options, data),
limit = options.limitMultiFileUploads,
paramName = this._getParamName(options),
paramNameSet,
paramNameSlice,
fileSet,
i;
if (!(options.singleFileUploads || limit) ||
!this._isXHRUpload(options)) {
fileSet = [data.files];
paramNameSet = [paramName];
} else if (!options.singleFileUploads && limit) {
fileSet = [];
paramNameSet = [];
for (i = 0; i < data.files.length; i += limit) {
fileSet.push(data.files.slice(i, i + limit));
paramNameSlice = paramName.slice(i, i + limit);
if (!paramNameSlice.length) {
paramNameSlice = paramName;
}
paramNameSet.push(paramNameSlice);
}
} else {
paramNameSet = paramName;
}
data.originalFiles = data.files;
$.each(fileSet || data.files, function (index, element) {
var newData = $.extend({}, data);
newData.files = fileSet ? element : [element];
newData.paramName = paramNameSet[index];
that._initResponseObject(newData);
that._initProgressObject(newData);
that._addConvenienceMethods(e, newData);
result = that._trigger('add', e, newData);
return result;
});
return result;
},
_replaceFileInput: function (input) {
var inputClone = input.clone(true);
$('<form></form>').append(inputClone)[0].reset();
// Detaching allows to insert the fileInput on another form
// without loosing the file input value:
input.after(inputClone).detach();
// Avoid memory leaks with the detached file input:
$.cleanData(input.unbind('remove'));
// Replace the original file input element in the fileInput
// elements set with the clone, which has been copied including
// event handlers:
this.options.fileInput = this.options.fileInput.map(function (i, el) {
if (el === input[0]) {
return inputClone[0];
}
return el;
});
// If the widget has been initialized on the file input itself,
// override this.element with the file input clone:
if (input[0] === this.element[0]) {
this.element = inputClone;
}
},
_handleFileTreeEntry: function (entry, path) {
var that = this,
dfd = $.Deferred(),
errorHandler = function (e) {
if (e && !e.entry) {
e.entry = entry;
}
// Since $.when returns immediately if one
// Deferred is rejected, we use resolve instead.
// This allows valid files and invalid items
// to be returned together in one set:
dfd.resolve([e]);
},
dirReader;
path = path || '';
if (entry.isFile) {
if (entry._file) {
// Workaround for Chrome bug #149735
entry._file.relativePath = path;
dfd.resolve(entry._file);
} else {
entry.file(function (file) {
file.relativePath = path;
dfd.resolve(file);
}, errorHandler);
}
} else if (entry.isDirectory) {
dirReader = entry.createReader();
dirReader.readEntries(function (entries) {
that._handleFileTreeEntries(
entries,
path + entry.name + '/'
).done(function (files) {
dfd.resolve(files);
}).fail(errorHandler);
}, errorHandler);
} else {
// Return an empy list for file system items
// other than files or directories:
dfd.resolve([]);
}
return dfd.promise();
},
_handleFileTreeEntries: function (entries, path) {
var that = this;
return $.when.apply(
$,
$.map(entries, function (entry) {
return that._handleFileTreeEntry(entry, path);
})
).pipe(function () {
return Array.prototype.concat.apply(
[],
arguments
);
});
},
_getDroppedFiles: function (dataTransfer) {
dataTransfer = dataTransfer || {};
var items = dataTransfer.items;
if (items && items.length && (items[0].webkitGetAsEntry ||
items[0].getAsEntry)) {
return this._handleFileTreeEntries(
$.map(items, function (item) {
var entry;
if (item.webkitGetAsEntry) {
entry = item.webkitGetAsEntry();
if (entry) {
// Workaround for Chrome bug #149735:
entry._file = item.getAsFile();
}
return entry;
}
return item.getAsEntry();
})
);
}
return $.Deferred().resolve(
$.makeArray(dataTransfer.files)
).promise();
},
_getSingleFileInputFiles: function (fileInput) {
fileInput = $(fileInput);
var entries = fileInput.prop('webkitEntries') ||
fileInput.prop('entries'),
files,
value;
if (entries && entries.length) {
return this._handleFileTreeEntries(entries);
}
files = $.makeArray(fileInput.prop('files'));
if (!files.length) {
value = fileInput.prop('value');
if (!value) {
return $.Deferred().resolve([]).promise();
}
// If the files property is not available, the browser does not
// support the File API and we add a pseudo File object with
// the input value as name with path information removed:
files = [{name: value.replace(/^.*\\/, '')}];
} else if (files[0].name === undefined && files[0].fileName) {
// File normalization for Safari 4 and Firefox 3:
$.each(files, function (index, file) {
file.name = file.fileName;
file.size = file.fileSize;
});
}
return $.Deferred().resolve(files).promise();
},
_getFileInputFiles: function (fileInput) {
if (!(fileInput instanceof $) || fileInput.length === 1) {
return this._getSingleFileInputFiles(fileInput);
}
return $.when.apply(
$,
$.map(fileInput, this._getSingleFileInputFiles)
).pipe(function () {
return Array.prototype.concat.apply(
[],
arguments
);
});
},
_onChange: function (e) {
var that = this,
data = {
fileInput: $(e.target),
form: $(e.target.form)
};
this._getFileInputFiles(data.fileInput).always(function (files) {
data.files = files;
if (that.options.replaceFileInput) {
that._replaceFileInput(data.fileInput);
}
if (that._trigger('change', e, data) !== false) {
that._onAdd(e, data);
}
});
},
_onPaste: function (e) {
var items = e.originalEvent && e.originalEvent.clipboardData &&
e.originalEvent.clipboardData.items,
data = {files: []};
if (items && items.length) {
$.each(items, function (index, item) {
var file = item.getAsFile && item.getAsFile();
if (file) {
data.files.push(file);
}
});
if (this._trigger('paste', e, data) === false ||
this._onAdd(e, data) === false) {
return false;
}
}
},
_onDrop: function (e) {
e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer;
var that = this,
dataTransfer = e.dataTransfer,
data = {};
if (dataTransfer && dataTransfer.files && dataTransfer.files.length) {
e.preventDefault();
this._getDroppedFiles(dataTransfer).always(function (files) {
data.files = files;
if (that._trigger('drop', e, data) !== false) {
that._onAdd(e, data);
}
});
}
},
_onDragOver: function (e) {
e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer;
var dataTransfer = e.dataTransfer;
if (dataTransfer) {
if (this._trigger('dragover', e) === false) {
return false;
}
if ($.inArray('Files', dataTransfer.types) !== -1) {
dataTransfer.dropEffect = 'copy';
e.preventDefault();
}
}
},
_initEventHandlers: function () {
if (this._isXHRUpload(this.options)) {
this._on(this.options.dropZone, {
dragover: this._onDragOver,
drop: this._onDrop
});
this._on(this.options.pasteZone, {
paste: this._onPaste
});
}
if ($.support.fileInput) {
this._on(this.options.fileInput, {
change: this._onChange
});
}
},
_destroyEventHandlers: function () {
this._off(this.options.dropZone, 'dragover drop');
this._off(this.options.pasteZone, 'paste');
this._off(this.options.fileInput, 'change');
},
_setOption: function (key, value) {
var reinit = $.inArray(key, this._specialOptions) !== -1;
if (reinit) {
this._destroyEventHandlers();
}
this._super(key, value);
if (reinit) {
this._initSpecialOptions();
this._initEventHandlers();
}
},
_initSpecialOptions: function () {
var options = this.options;
if (options.fileInput === undefined) {
options.fileInput = this.element.is('input[type="file"]') ?
this.element : this.element.find('input[type="file"]');
} else if (!(options.fileInput instanceof $)) {
options.fileInput = $(options.fileInput);
}
if (!(options.dropZone instanceof $)) {
options.dropZone = $(options.dropZone);
}
if (!(options.pasteZone instanceof $)) {
options.pasteZone = $(options.pasteZone);
}
},
_getRegExp: function (str) {
var parts = str.split('/'),
modifiers = parts.pop();
parts.shift();
return new RegExp(parts.join('/'), modifiers);
},
_isRegExpOption: function (key, value) {
return key !== 'url' && $.type(value) === 'string' &&
/^\/.*\/[igm]{0,3}$/.test(value);
},
_initDataAttributes: function () {
var that = this,
options = this.options;
// Initialize options set via HTML5 data-attributes:
$.each(
$(this.element[0].cloneNode(false)).data(),
function (key, value) {
if (that._isRegExpOption(key, value)) {
value = that._getRegExp(value);
}
options[key] = value;
}
);
},
_create: function () {
this._initDataAttributes();
this._initSpecialOptions();
this._slots = [];
this._sequence = this._getXHRPromise(true);
this._sending = this._active = 0;
this._initProgressObject(this);
this._initEventHandlers();
},
// This method is exposed to the widget API and allows to query
// the number of active uploads:
active: function () {
return this._active;
},
// This method is exposed to the widget API and allows to query
// the widget upload progress.
// It returns an object with loaded, total and bitrate properties
// for the running uploads:
progress: function () {
return this._progress;
},
// This method is exposed to the widget API and allows adding files
// using the fileupload API. The data parameter accepts an object which
// must have a files property and can contain additional options:
// .fileupload('add', {files: filesList});
add: function (data) {
var that = this;
if (!data || this.options.disabled) {
return;
}
if (data.fileInput && !data.files) {
this._getFileInputFiles(data.fileInput).always(function (files) {
data.files = files;
that._onAdd(null, data);
});
} else {
data.files = $.makeArray(data.files);
this._onAdd(null, data);
}
},
// This method is exposed to the widget API and allows sending files
// using the fileupload API. The data parameter accepts an object which
// must have a files or fileInput property and can contain additional options:
// .fileupload('send', {files: filesList});
// The method returns a Promise object for the file upload call.
send: function (data) {
if (data && !this.options.disabled) {
if (data.fileInput && !data.files) {
var that = this,
dfd = $.Deferred(),
promise = dfd.promise(),
jqXHR,
aborted;
promise.abort = function () {
aborted = true;
if (jqXHR) {
return jqXHR.abort();
}
dfd.reject(null, 'abort', 'abort');
return promise;
};
this._getFileInputFiles(data.fileInput).always(
function (files) {
if (aborted) {
return;
}
data.files = files;
jqXHR = that._onSend(null, data).then(
function (result, textStatus, jqXHR) {
dfd.resolve(result, textStatus, jqXHR);
},
function (jqXHR, textStatus, errorThrown) {
dfd.reject(jqXHR, textStatus, errorThrown);
}
);
}
);
return this._enhancePromise(promise);
}
data.files = $.makeArray(data.files);
if (data.files.length) {
return this._onSend(null, data);
}
}
return this._getXHRPromise(false, data && data.context);
}
});
})); |
// Copyright 2008 The Closure Library Authors. 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.
/**
* @fileoverview Defines the base class for a module. This is used to allow the
* code to be modularized, giving the benefits of lazy loading and loading on
* demand.
*
*/
goog.provide('goog.module.BaseModule');
goog.require('goog.Disposable');
/**
* A basic module object that represents a module of Javascript code that can
* be dynamically loaded.
*
* @constructor
* @extends {goog.Disposable}
*/
goog.module.BaseModule = function() {
goog.Disposable.call(this);
};
goog.inherits(goog.module.BaseModule, goog.Disposable);
/**
* Performs any load-time initialization that the module requires.
* @param {Object} context The module context.
*/
goog.module.BaseModule.prototype.initialize = function(context) {};
|
/*
* Copyright (c) 2012 Dmitri Melikyan
*
* 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.
*/
var nt;
var filterKeys;
var sampleNum;
exports.init = function() {
nt = global.nodetime;
filterKeys = {};
sampleNum = 0;
nt.on('sample', function(sample) {
if(!nt.headless && nt.sessionId) {
collectKeys(undefined, sample, 0);
sampleNum++;
if(sampleNum == 1 || sampleNum == 10) {
sendKeys();
}
}
});
setInterval(function() {
try {
sendKeys();
}
catch(e) {
nt.error(e);
}
}, 60000);
};
var collectKeys = function(key, obj, depth) {
if(depth > 20) return 0;
var isArray = Array.isArray(obj);
for(var prop in obj) {
if(prop.match(/^\_/)) continue;
if(typeof obj[prop] === 'object') {
collectKeys(prop, obj[prop], depth + 1);
}
else {
if(!isArray) {
filterKeys[prop] = true;
}
else {
filterKeys[key] = true;
}
}
}
};
var sendKeys = function() {
var keys = [];
for(var prop in filterKeys) {
keys.push(prop);
}
keys = keys.sort(function(a, b) {
a = a.toLowerCase();
b = b.toLowerCase();
if(a > b) return 1;
if(a < b) return -1;
return 0;
});
if(keys.length > 0) {
nt.agent.send({cmd: 'updateFilterKeys', args: keys});
}
};
var PredicateFilter = function() {
}
exports.PredicateFilter = PredicateFilter;
PredicateFilter.prototype.preparePredicates = function(preds) {
preds.forEach(function(pred) {
try{
pred.valNum = parseFloat(pred.val)
}
catch(err) {
}
try{
if(pred.op === 'match') pred.valRe = new RegExp(pred.val);
if(typeof pred.val === 'string') pred.valLc = pred.val.toLowerCase();
}
catch(err) {
return nt.error(err);
}
});
this.preds = preds;
return true;
}
PredicateFilter.prototype.filter = function(sample) {
var matched = 0;
this.preds.forEach(function(pred) {
matched += walk(pred, sample, 0);
});
return (matched > 0);
};
function walk(pred, obj, depth) {
if(depth > 20) return 0;
var matched = 0;
for(var prop in obj) {
var val = obj[prop];
if(val === undefined || val === null) {
continue;
}
else if(typeof val === 'object') {
matched += walk(pred, val, depth + 1);
}
else if((pred.key === '*' || pred.key === prop) && test(pred, val)) {
matched++;
}
if(matched) break;
}
return matched;
}
function test(pred, val) {
var ret = false;
if(typeof val === 'number') {
if(pred.valNum !== NaN) {
if (pred.op === '==') {
ret = (val == pred.valNum);
}
else if (pred.op === '!=') {
ret = (val != pred.valNum);
}
else if (pred.op === '<') {
ret = (val < pred.valNum);
}
else if (pred.op === '>') {
ret = (val > pred.valNum);
}
}
}
else if(typeof val === 'string') {
if(pred.op === 'match' && pred.valRe) {
ret = pred.valRe.exec(val);
}
else if (pred.op === '==') {
ret = (val.toLowerCase() == pred.valLc);
}
else if (pred.op === '!=') {
ret = (val.toLowerCase() != pred.valLc);
}
}
return ret;
}
|
/*
* Version 0.1.14
* Made By Robin Kuiper
* Skype: RobinKuiper.eu
* Discord: Atheos#1095
* My Discord Server: https://discord.gg/AcC9VME
* Roll20: https://app.roll20.net/users/1226016/robin
* Roll20 Wiki: https://wiki.roll20.net/Script:Concentration
* Roll20 Thread: https://app.roll20.net/forum/post/6364317/script-concentration/?pageforid=6364317#post-6364317
* Github: https://github.com/RobinKuiper/Roll20APIScripts
* Reddit: https://www.reddit.com/user/robinkuiper/
* Patreon: https://patreon.com/robinkuiper
* Paypal.me: https://www.paypal.me/robinkuiper
*/
var Concentration = Concentration || (function() {
'use strict';
let checked = [];
// Styling for the chat responses.
const styles = {
reset: 'padding: 0; margin: 0;',
menu: 'background-color: #fff; border: 1px solid #000; padding: 5px; border-radius: 5px;',
button: 'background-color: #000; border: 1px solid #292929; border-radius: 3px; padding: 5px; color: #fff; text-align: center;',
textButton: 'background-color: transparent; border: none; padding: 0; color: #000; text-decoration: underline',
list: 'list-style: none;',
float: {
right: 'float: right;',
left: 'float: left;'
},
overflow: 'overflow: hidden;',
fullWidth: 'width: 100%;'
},
script_name = 'Concentration',
state_name = 'CONCENTRATION',
markers = ['blue', 'brown', 'green', 'pink', 'purple', 'red', 'yellow', '-', 'all-for-one', 'angel-outfit', 'archery-target', 'arrowed', 'aura', 'back-pain', 'black-flag', 'bleeding-eye', 'bolt-shield', 'broken-heart', 'broken-shield', 'broken-skull', 'chained-heart', 'chemical-bolt', 'cobweb', 'dead', 'death-zone', 'drink-me', 'edge-crack', 'fishing-net', 'fist', 'fluffy-wing', 'flying-flag', 'frozen-orb', 'grab', 'grenade', 'half-haze', 'half-heart', 'interdiction', 'lightning-helix', 'ninja-mask', 'overdrive', 'padlock', 'pummeled', 'radioactive', 'rolling-tomb', 'screaming', 'sentry-gun', 'skull', 'sleepy', 'snail', 'spanner', 'stopwatch','strong', 'three-leaves', 'tread', 'trophy', 'white-tower'],
handleInput = (msg) => {
if(state[state_name].config.auto_add_concentration_marker && msg && msg.rolltemplate && msg.rolltemplate === 'spell' && (msg.content.includes("{{concentration=1}}"))){
handleConcentrationSpellCast(msg);
}
if (msg.type != 'api') return;
// Split the message into command and argument(s)
let args = msg.content.split(' ');
let command = args.shift().substring(1);
let extracommand = args.shift();
let message;
if (command == state[state_name].config.command) {
if(playerIsGM(msg.playerid)){
switch(extracommand){
case 'reset':
state[state_name] = {};
setDefaults(true);
sendConfigMenu(false, '<span style="color: red">The API Library needs to be restarted for this to take effect.</span>');
break;
case 'config':
if(args.length > 0){
let setting = args.shift().split('|');
let key = setting.shift();
let value = (setting[0] === 'true') ? true : (setting[0] === 'false') ? false : setting[0];
state[state_name].config[key] = value;
if(key === 'bar'){
//registerEventHandlers();
message = '<span style="color: red">The API Library needs to be restarted for this to take effect.</span>';
}
}
sendConfigMenu(false, message);
break;
case 'advantage-menu':
sendAdvantageMenu();
break;
case 'toggle-advantage':
let id = args[0];
if(state[state_name].advantages[id]){
state[state_name].advantages[id] = !state[state_name].advantages[id];
}else{
state[state_name].advantages[id] = true;
}
sendAdvantageMenu();
break;
case 'roll':
let represents = args[0],
DC = parseInt(args[1], 10),
con_save_mod = parseInt(args[2], 10),
name = args[3],
target = args[4];
roll(represents, DC, con_save_mod, name, target, false);
break;
case 'advantage':
let represents_a = args[0],
DC_a = parseInt(args[1], 10),
con_save_mod_a = parseInt(args[2], 10),
name_a = args[3],
target_a = args[4];
roll(represents_a, DC_a, con_save_mod_a, name_a, target_a, true);
break;
default:
if(msg.selected && msg.selected.length){
msg.selected.forEach(s => {
let token = getObj(s._type, s._id);
addConcentration(token, msg.playerid, extracommand);
});
return;
}
sendConfigMenu();
break;
}
}else{
if(msg.selected && msg.selected.length){
msg.selected.forEach(s => {
let token = getObj(s._type, s._id);
addConcentration(token, msg.playerid, extracommand);
});
}
}
}
},
addConcentration = (token, playerid, spell) => {
const marker = state[state_name].config.statusmarker
let character = getObj('character', token.get('represents'));
if((token.get('controlledby').split(',').includes(playerid) || token.get('controlledby').split(',').includes('all')) ||
(character && (character.get('controlledby').split(',').includes(playerid) || character.get('controlledby').split(',').includes('all'))) ||
playerIsGM(playerid)){
if(!token.get('status_'+marker)){
let target = state[state_name].config.send_reminder_to;
if(target === 'character'){
target = createWhisperName(character_name);
}else if(target === 'everyone'){
target = ''
}
let message;
if(spell){
message = '<b>'+token.get('name')+'</b> is now concentrating on <b>'+spell+'</b>.';
}else{
message = '<b>'+token.get('name')+'</b> is now concentrating.';
}
makeAndSendMenu(message, '', target);
}
token.set('status_'+marker, !token.get('status_'+marker));
}
},
handleConcentrationSpellCast = (msg) => {
const marker = state[state_name].config.statusmarker
let character_name = msg.content.match(/charname=([^\n{}]*[^"\n{}])/);
character_name = RegExp.$1;
let spell_name = msg.content.match(/name=([^\n{}]*[^"\n{}])/);
spell_name = RegExp.$1;
let player = getObj('player', msg.playerid),
characterid = findObjs({ name: character_name, _type: 'character' }).shift().get('id'),
represented_tokens = findObjs({ represents: characterid, _type: 'graphic' }),
message,
target = state[state_name].config.send_reminder_to;
if(!character_name || !spell_name || !player || !characterid) return;
let search_attributes = {
represents: characterid,
_type: 'graphic',
_pageid: player.get('lastpage')
}
search_attributes['status_'+marker] = true;
let is_concentrating = (findObjs(search_attributes).length > 0);
if(is_concentrating){
message = '<b>'+character_name+'</b> is concentrating already.';
}else{
represented_tokens.forEach(token => {
let attributes = {};
attributes['status_'+marker] = true;
token.set(attributes);
message = '<b>'+character_name+'</b> is now concentrating on <b>'+spell_name+'</b>.';
});
}
if(target === 'character'){
target = createWhisperName(character_name);
}else if(target === 'everyone'){
target = ''
}
makeAndSendMenu(message, '', target);
},
handleStatusMarkerChange = (obj, prev) => {
const marker = state[state_name].config.statusmarker
if(!obj.get('status_'+marker)){
removeMarker(obj.get('represents'));
}
},
handleGraphicChange = (obj, prev) => {
if(checked.includes(obj.get('represents'))){ return false; }
let bar = 'bar'+state[state_name].config.bar+'_value',
target = state[state_name].config.send_reminder_to,
marker = state[state_name].config.statusmarker;
if(prev && obj.get('status_'+marker) && obj.get(bar) < prev[bar]){
let calc_DC = Math.floor((prev[bar] - obj.get(bar))/2),
DC = (calc_DC > 10) ? calc_DC : 10,
con_save_mod = parseInt(getAttrByName(obj.get('represents'), state[state_name].config.bonus_attribute, 'current')) || 0,
chat_text;
if(target === 'character'){
chat_text = "Make a Concentration Check - <b>DC " + DC + "</b>.";
target = createWhisperName(obj.get('name'));
}else if(target === 'everyone'){
chat_text = '<b>'+obj.get('name')+'</b> must make a Concentration Check - <b>DC ' + DC + '</b>.';
target = '';
}else{
chat_text = '<b>'+obj.get('name')+'</b> must make a Concentration Check - <b>DC ' + DC + '</b>.';
target = 'gm';
}
if(state[state_name].config.show_roll_button){
chat_text += '<hr>' + makeButton('Advantage', '!' + state[state_name].config.command + ' advantage ' + obj.get('represents') + ' ' + DC + ' ' + con_save_mod + ' ' + obj.get('name') + ' ' + target, styles.button + styles.float.right);
chat_text += ' ' + makeButton('Roll', '!' + state[state_name].config.command + ' roll ' + obj.get('represents') + ' ' + DC + ' ' + con_save_mod + ' ' + obj.get('name') + ' ' + target, styles.button + styles.float.left);
}
if(state[state_name].config.auto_roll_save){
//&{template:default} {{name='+obj.get('name')+' - Concentration Save}} {{Modifier='+con_save_mod+'}} {{Roll=[[1d20cf<'+(DC-con_save_mod-1)+'cs>'+(DC-con_save_mod-1)+'+'+con_save_mod+']]}} {{DC='+DC+'}}
roll(obj.get('represents'), DC, con_save_mod, obj.get('name'), target, state[state_name].advantages[obj.get('represents')]);
}else{
makeAndSendMenu(chat_text, '', target);
}
let length = checked.push(obj.get('represents'));
setTimeout(() => {
checked.splice(length-1, 1);
}, 1000);
}
},
roll = (represents, DC, con_save_mod, name, target, advantage) => {
sendChat(script_name, '[[1d20cf<'+(DC-con_save_mod-1)+'cs>'+(DC-con_save_mod-1)+'+'+con_save_mod+']]', results => {
let title = 'Concentration Save <br> <b style="font-size: 10pt; color: gray;">'+name+'</b>',
advantageRollResult;
let rollresult = results[0].inlinerolls[0].results.rolls[0].results[0].v;
let result = rollresult;
if(advantage){
advantageRollResult = randomInteger(20);
result = (rollresult <= advantageRollResult) ? advantageRollResult : rollresult;
}
let total = result + con_save_mod;
let success = total >= DC;
let result_text = (success) ? 'Success' : 'Failed',
result_color = (success) ? 'green' : 'red';
let rollResultString = (advantage) ? rollresult + ' / ' + advantageRollResult : rollresult;
let contents = ' \
<table style="width: 100%; text-align: left;"> \
<tr> \
<th>DC</th> \
<td>'+DC+'</td> \
</tr> \
<tr> \
<th>Modifier</th> \
<td>'+con_save_mod+'</td> \
</tr> \
<tr> \
<th>Roll Result</th> \
<td>'+rollResultString+'</td> \
</tr> \
</table> \
<div style="text-align: center"> \
<b style="font-size: 16pt;"> \
<span style="border: 1px solid '+result_color+'; padding-bottom: 2px; padding-top: 4px;">[['+result+'+'+con_save_mod+']]</span><br><br> \
'+result_text+' \
</b> \
</div>'
makeAndSendMenu(contents, title, target);
if(target !== '' && target !== 'gm'){
makeAndSendMenu(contents, title, 'gm');
}
if(!success){
removeMarker(represents);
}
});
},
removeMarker = (represents, type='graphic') => {
findObjs({ type, represents }).forEach(o => {
o.set('status_'+state[state_name].config.statusmarker, false);
});
},
createWhisperName = (name) => {
return name.split(' ').shift();
},
ucFirst = (string) => {
return string.charAt(0).toUpperCase() + string.slice(1);
},
sendConfigMenu = (first, message) => {
let markerDropdown = '?{Marker';
markers.forEach((marker) => {
markerDropdown += '|'+ucFirst(marker).replace('-', ' ')+','+marker
})
markerDropdown += '}';
let markerButton = makeButton(state[state_name].config.statusmarker, '!' + state[state_name].config.command + ' config statusmarker|'+markerDropdown, styles.button + styles.float.right),
commandButton = makeButton('!'+state[state_name].config.command, '!' + state[state_name].config.command + ' config command|?{Command (without !)}', styles.button + styles.float.right),
barButton = makeButton('bar ' + state[state_name].config.bar, '!' + state[state_name].config.command + ' config bar|?{Bar|Bar 1 (green),1|Bar 2 (blue),2|Bar 3 (red),3}', styles.button + styles.float.right),
sendToButton = makeButton(state[state_name].config.send_reminder_to, '!' + state[state_name].config.command + ' config send_reminder_to|?{Send To|Everyone,everyone|Character,character|GM,gm}', styles.button + styles.float.right),
addConMarkerButton = makeButton(state[state_name].config.auto_add_concentration_marker, '!' + state[state_name].config.command + ' config auto_add_concentration_marker|'+!state[state_name].config.auto_add_concentration_marker, styles.button + styles.float.right),
autoRollButton = makeButton(state[state_name].config.auto_roll_save, '!' + state[state_name].config.command + ' config auto_roll_save|'+!state[state_name].config.auto_roll_save, styles.button + styles.float.right),
//advantageButton = makeButton(state[state_name].config.advantage, '!' + state[state_name].config.command + ' config advantage|'+!state[state_name].config.advantage, styles.button + styles.float.right),
bonusAttrButton = makeButton(state[state_name].config.bonus_attribute, '!' + state[state_name].config.command + ' config bonus_attribute|?{Attribute|'+state[state_name].config.bonus_attribute+'}', styles.button + styles.float.right),
showRollButtonButton = makeButton(state[state_name].config.show_roll_button, '!' + state[state_name].config.command + ' config show_roll_button|'+!state[state_name].config.show_roll_button, styles.button + styles.float.right),
listItems = [
'<span style="'+styles.float.left+'">Command:</span> ' + commandButton,
'<span style="'+styles.float.left+'">Statusmarker:</span> ' + markerButton,
'<span style="'+styles.float.left+'">HP Bar:</span> ' + barButton,
'<span style="'+styles.float.left+'">Send Reminder To:</span> ' + sendToButton,
'<span style="'+styles.float.left+'">Auto Add Con. Marker: <p style="font-size: 8pt;">Works only for 5e OGL Sheet.</p></span> ' + addConMarkerButton,
'<span style="'+styles.float.left+'">Auto Roll Save:</span> ' + autoRollButton,
],
resetButton = makeButton('Reset', '!' + state[state_name].config.command + ' reset', styles.button + styles.fullWidth),
title_text = (first) ? script_name + ' First Time Setup' : script_name + ' Config';
/*if(state[state_name].config.auto_roll_save){
listItems.push('<span style="'+styles.float.left+'">Advantage:</span> ' + advantageButton);
}*/
if(state[state_name].config.auto_roll_save){
listItems.push('<span style="'+styles.float.left+'">Bonus Attribute:</span> ' + bonusAttrButton)
}
if(!state[state_name].config.auto_roll_save){
listItems.push('<span style="'+styles.float.left+'">Roll Button:</span> ' + showRollButtonButton);
}
let advantageMenuButton = (state[state_name].config.auto_roll_save) ? makeButton('Advantage Menu', '!' + state[state_name].config.command + ' advantage-menu', styles.button + styles.fullWidth) : '';
message = (message) ? '<p>'+message+'</p>' : '';
let contents = message+makeList(listItems, styles.reset + styles.list + styles.overflow, styles.overflow)+'<br>'+advantageMenuButton+'<hr><p style="font-size: 80%">You can always come back to this config by typing `!'+state[state_name].config.command+' config`.</p><hr>'+resetButton;
makeAndSendMenu(contents, title_text, 'gm');
},
sendAdvantageMenu = () => {
let menu_text = "";
let characters = findObjs({ type: 'character' }).sort((a, b) => {
let nameA = a.get('name').toUpperCase();
let nameB = b.get('name').toUpperCase();
if(nameA < nameB) return -1;
if(nameA > nameB) return 1;
return 0;
});
characters.forEach(character => {
let name = (state[state_name].advantages && state[state_name].advantages[character.get('id')]) ? '<b>'+character.get('name')+'</b>' : character.get('name');
menu_text += makeButton(name, '!' + state[state_name].config.command + ' toggle-advantage ' + character.get('id'), styles.textButton) + '<br>';
});
makeAndSendMenu(menu_text, 'Advantage Menu', 'gm');
},
makeAndSendMenu = (contents, title, whisper, callback) => {
title = (title && title != '') ? makeTitle(title) : '';
whisper = (whisper && whisper !== '') ? '/w ' + whisper + ' ' : '';
sendChat(script_name, whisper + '<div style="'+styles.menu+styles.overflow+'">'+title+contents+'</div>', null, {noarchive:true});
},
makeTitle = (title) => {
return '<h3 style="margin-bottom: 10px;">'+title+'</h3>';
},
makeButton = (title, href, style) => {
return '<a style="'+style+'" href="'+href+'">'+title+'</a>';
},
makeList = (items, listStyle, itemStyle) => {
let list = '<ul style="'+listStyle+'">';
items.forEach((item) => {
list += '<li style="'+itemStyle+'">'+item+'</li>';
});
list += '</ul>';
return list;
},
pre_log = (message) => {
log('---------------------------------------------------------------------------------------------');
if(!message){ return; }
log(message);
log('---------------------------------------------------------------------------------------------');
},
checkInstall = () => {
if(!_.has(state, state_name)){
state[state_name] = state[state_name] || {};
}
setDefaults();
log(script_name + ' Ready! Command: !'+state[state_name].config.command);
if(state[state_name].config.debug){ makeAndSendMenu(script_name + ' Ready! Debug On.', '', 'gm') }
},
registerEventHandlers = () => {
on('chat:message', handleInput);
on('change:graphic:bar'+state[state_name].config.bar+'_value', handleGraphicChange);
on('change:graphic:statusmarkers', handleStatusMarkerChange);
},
setDefaults = (reset) => {
const defaults = {
config: {
command: 'concentration',
statusmarker: 'stopwatch',
bar: 1,
send_reminder_to: 'everyone', // character,gm,
auto_add_concentration_marker: true,
auto_roll_save: true,
advantage: false,
bonus_attribute: 'constitution_save_bonus',
show_roll_button: true
},
advantages: {}
};
if(!state[state_name].config){
state[state_name].config = defaults.config;
}else{
if(!state[state_name].config.hasOwnProperty('command')){
state[state_name].config.command = defaults.config.command;
}
if(!state[state_name].config.hasOwnProperty('statusmarker')){
state[state_name].config.statusmarker = defaults.config.statusmarker;
}
if(!state[state_name].config.hasOwnProperty('bar')){
state[state_name].config.bar = defaults.config.bar;
}
if(!state[state_name].config.hasOwnProperty('send_reminder_to')){
state[state_name].config.send_reminder_to = defaults.config.send_reminder_to;
}
if(!state[state_name].config.hasOwnProperty('auto_add_concentration_marker')){
state[state_name].config.auto_add_concentration_marker = defaults.config.auto_add_concentration_marker;
}
if(!state[state_name].config.hasOwnProperty('auto_roll_save')){
state[state_name].config.auto_roll_save = defaults.config.auto_roll_save;
}
if(!state[state_name].config.hasOwnProperty('advantage')){
state[state_name].config.advantage = defaults.config.advantage;
}
if(!state[state_name].config.hasOwnProperty('bonus_attribute')){
state[state_name].config.bonus_attribute = defaults.config.bonus_attribute;
}
if(!state[state_name].config.hasOwnProperty('show_roll_button')){
state[state_name].config.show_roll_button = defaults.config.show_roll_button;
}
}
if(!state[state_name].advantages){
state[state_name].advantages = defaults.advantages;
}
if(!state[state_name].config.hasOwnProperty('firsttime') && !reset){
sendConfigMenu(true);
state[state_name].config.firsttime = false;
}
};
return {
CheckInstall: checkInstall,
RegisterEventHandlers: registerEventHandlers
}
})();
on('ready',function() {
'use strict';
Concentration.CheckInstall();
Concentration.RegisterEventHandlers();
}); |
Polymer('selection-example', {
itemTapAction: function(e, detail, sender) {
this.$.selection.select(e.target);
},
selectAction: function(e, detail, sender) {
detail.item.classList.toggle('selected', detail.isSelected);
}
});
|
/**
* Browser platform description
*/
SB.createPlatform('browser', {
keys: {
RIGHT: 39,
LEFT: 37,
DOWN: 40,
UP: 38,
RETURN: 27,//esc
EXIT: 46,//delete
TOOLS: 32,//space
FF: 33,//page up
RW: 34,//page down
NEXT: 107,//num+
PREV: 109,//num-
ENTER: 13,
RED: 65,//A
GREEN: 66,//B
YELLOW: 67,//C
BLUE: 68,//D
CH_UP: 221, // ]
CH_DOWN: 219, // [
N0: 48,
N1: 49,
N2: 50,
N3: 51,
N4: 52,
N5: 53,
N6: 54,
N7: 55,
N8: 56,
N9: 57,
PRECH: 45,//ins
SMART: 36,//home
PLAY: 97,//numpad 1
STOP: 98,//numpad 2
PAUSE: 99,//numpad 3
SUBT: 76,//l,
INFO: 73,//i
REC: 82//r
},
detect: function () {
// always true for browser platform
return true;
},
getNativeDUID: function () {
if (navigator.userAgent.indexOf('Chrome') != -1) {
this.DUID = 'CHROMEISFINETOO';
} else {
this.DUID = 'FIREFOXISBEST';
}
return this.DUID;
}
});
|
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
function test0() {
var a = 1;
while(1 && (0 & 1) >= (0 | a)) {
function test0a() { a; }
}
}
test0();
test0();
test0();
WScript.Echo("pass");
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: >
Operator x <= y returns ToString(x) <= ToString(y), if Type(Primitive(x))
is String and Type(Primitive(y)) is String
es5id: 11.8.3_A3.2_T1.2
description: >
Type(Primitive(x)) and Type(Primitive(y)) vary between Object
object and Function object
---*/
//CHECK#1
if (({} <= function(){return 1}) !== ({}.toString() <= function(){return 1}.toString())) {
$ERROR('#1: ({} <= function(){return 1}) === ({}.toString() <= function(){return 1}.toString())');
}
//CHECK#2
if ((function(){return 1} <= {}) !== (function(){return 1}.toString() <= {}.toString())) {
$ERROR('#2: (function(){return 1} <= {}) === (function(){return 1}.toString() <= {}.toString())');
}
//CHECK#3
if ((function(){return 1} <= function(){return 1}) !== (function(){return 1}.toString() <= function(){return 1}.toString())) {
$ERROR('#3: (function(){return 1} <= function(){return 1}) === (function(){return 1}.toString() <= function(){return 1}.toString())');
}
//CHECK#4
if (({} <= {}) !== ({}.toString() <= {}.toString())) {
$ERROR('#4: ({} <= {}) === ({}.toString() <= {}.toString())');
}
|
var _ = require('underscore');
var Backbone = require('backbone');
var GRAPHICS = require('../util/constants').GRAPHICS;
var VisBase = require('../visuals/visBase').VisBase;
var VisEdge = VisBase.extend({
defaults: {
tail: null,
head: null,
animationSpeed: GRAPHICS.defaultAnimationTime,
animationEasing: GRAPHICS.defaultEasing
},
validateAtInit: function() {
var required = ['tail', 'head'];
_.each(required, function(key) {
if (!this.get(key)) {
throw new Error(key + ' is required!');
}
}, this);
},
getID: function() {
return this.get('tail').get('id') + '.' + this.get('head').get('id');
},
initialize: function() {
this.validateAtInit();
// shorthand for the main objects
this.gitVisuals = this.get('gitVisuals');
this.gitEngine = this.get('gitEngine');
this.get('tail').get('outgoingEdges').push(this);
},
remove: function() {
this.removeKeys(['path']);
this.gitVisuals.removeVisEdge(this);
},
genSmoothBezierPathString: function(tail, head) {
var tailPos = tail.getScreenCoords();
var headPos = head.getScreenCoords();
return this.genSmoothBezierPathStringFromCoords(tailPos, headPos);
},
genSmoothBezierPathStringFromCoords: function(tailPos, headPos) {
// we need to generate the path and control points for the bezier. format
// is M(move abs) C (curve to) (control point 1) (control point 2) (final point)
// the control points have to be __below__ to get the curve starting off straight.
var coords = function(pos) {
return String(Math.round(pos.x)) + ',' + String(Math.round(pos.y));
};
var offset = function(pos, dir, delta) {
delta = delta || GRAPHICS.curveControlPointOffset;
return {
x: pos.x,
y: pos.y + delta * dir
};
};
var offset2d = function(pos, x, y) {
return {
x: pos.x + x,
y: pos.y + y
};
};
// first offset tail and head by radii
tailPos = offset(tailPos, -1, this.get('tail').getRadius());
headPos = offset(headPos, 1, this.get('head').getRadius());
var str = '';
// first move to bottom of tail
str += 'M' + coords(tailPos) + ' ';
// start bezier
str += 'C';
// then control points above tail and below head
str += coords(offset(tailPos, -1)) + ' ';
str += coords(offset(headPos, 1)) + ' ';
// now finish
str += coords(headPos);
// arrow head
var delta = GRAPHICS.arrowHeadSize || 10;
str += ' L' + coords(offset2d(headPos, -delta, delta));
str += ' L' + coords(offset2d(headPos, delta, delta));
str += ' L' + coords(headPos);
// then go back, so we can fill correctly
str += 'C';
str += coords(offset(headPos, 1)) + ' ';
str += coords(offset(tailPos, -1)) + ' ';
str += coords(tailPos);
return str;
},
getBezierCurve: function() {
return this.genSmoothBezierPathString(this.get('tail'), this.get('head'));
},
getStrokeColor: function() {
return GRAPHICS.visBranchStrokeColorNone;
},
setOpacity: function(opacity) {
opacity = (opacity === undefined) ? 1 : opacity;
this.get('path').attr({opacity: opacity});
},
genGraphics: function(paper) {
var pathString = this.getBezierCurve();
var path = paper.path(pathString).attr({
'stroke-width': GRAPHICS.visBranchStrokeWidth,
'stroke': this.getStrokeColor(),
'stroke-linecap': 'round',
'stroke-linejoin': 'round',
'fill': this.getStrokeColor()
});
path.toBack();
this.set('path', path);
},
getOpacity: function() {
var stat = this.gitVisuals.getCommitUpstreamStatus(this.get('tail'));
var map = {
'branch': 1,
'head': GRAPHICS.edgeUpstreamHeadOpacity,
'none': GRAPHICS.edgeUpstreamNoneOpacity
};
if (map[stat] === undefined) { throw new Error('bad stat'); }
return map[stat];
},
getAttributes: function() {
var newPath = this.getBezierCurve();
var opacity = this.getOpacity();
return {
path: {
path: newPath,
opacity: opacity
}
};
},
animateUpdatedPath: function(speed, easing) {
var attr = this.getAttributes();
this.animateToAttr(attr, speed, easing);
},
animateFromAttrToAttr: function(fromAttr, toAttr, speed, easing) {
// an animation of 0 is essentially setting the attribute directly
this.animateToAttr(fromAttr, 0);
this.animateToAttr(toAttr, speed, easing);
},
animateToAttr: function(attr, speed, easing) {
if (speed === 0) {
this.get('path').attr(attr.path);
return;
}
this.get('path').toBack();
this.get('path').stop().animate(
attr.path,
speed !== undefined ? speed : this.get('animationSpeed'),
easing || this.get('animationEasing')
);
}
});
var VisEdgeCollection = Backbone.Collection.extend({
model: VisEdge
});
exports.VisEdgeCollection = VisEdgeCollection;
exports.VisEdge = VisEdge;
|
require('../../support/spec_helper');
describe("Cucumber.Ast.Feature", function () {
var Cucumber = requireLib('cucumber');
var scenarioCollection, lastScenario;
var feature, keyword, name, description, uri, line;
beforeEach(function () {
lastScenario = createSpy("Last scenario");
scenarioCollection = {}; // bare objects because we need .length
// which is not available on jasmine spies
spyOnStub(scenarioCollection, 'add');
spyOnStub(scenarioCollection, 'insert');
spyOnStub(scenarioCollection, 'removeAtIndex');
spyOnStub(scenarioCollection, 'indexOf');
spyOnStub(scenarioCollection, 'getLast').andReturn(lastScenario);
spyOnStub(scenarioCollection, 'syncForEach');
spyOnStub(scenarioCollection, 'forEach');
spyOn(Cucumber.Type, 'Collection').andReturn(scenarioCollection);
keyword = createSpy("keyword");
name = createSpy("name");
description = createSpy("description");
uri = createSpy("uri");
line = createSpy("line number");
feature = Cucumber.Ast.Feature(keyword, name, description, uri, line);
});
describe("constructor", function () {
it("creates a new collection to store scenarios", function () {
expect(Cucumber.Type.Collection).toHaveBeenCalled();
});
});
describe("getKeyword()", function () {
it("returns the keyword of the feature", function () {
expect(feature.getKeyword()).toBe(keyword);
});
});
describe("getName()", function () {
it("returns the name of the feature", function () {
expect(feature.getName()).toBe(name);
});
});
describe("getDescription()", function () {
it("returns the description of the feature", function () {
expect(feature.getDescription()).toBe(description);
});
});
describe("getUri()", function () {
it("returns the URI of the feature", function () {
expect(feature.getUri()).toBe(uri);
});
});
describe("getLine()", function () {
it("returns the line number on which the feature starts", function () {
expect(feature.getLine()).toBe(line);
});
});
describe("getBackground() [setBackground()]", function () {
describe("when a background was previously added", function () {
var background;
beforeEach(function () {
background = createSpy("background");
feature.setBackground(background);
});
it("returns the background", function () {
expect(feature.getBackground()).toBe(background);
});
});
describe("when no background was previousyly added", function () {
it("returns nothing", function () {
expect(feature.getBackground()).toBeUndefined();
});
});
});
describe("hasBackground()", function () {
it("returns true when a background was set", function () {
var background = createSpy("background");
feature.setBackground(background);
expect(feature.hasBackground()).toBeTruthy();
});
it("returns false when no background was set", function () {
expect(feature.hasBackground()).toBeFalsy();
});
});
describe("addFeatureElement()", function () {
var scenario, background;
beforeEach(function () {
scenario = createSpyWithStubs("scenario AST element", {setBackground: null});
background = createSpy("scenario background");
spyOn(feature, 'getBackground').andReturn(background);
});
it("sets the background on the scenario", function () {
feature.addFeatureElement(scenario);
expect(scenario.setBackground).toHaveBeenCalledWith(background);
});
it("adds the scenario to the scenarios (collection)", function () {
feature.addFeatureElement(scenario);
expect(scenarioCollection.add).toHaveBeenCalledWith(scenario);
});
});
describe("insertFeatureElement()", function () {
var index, scenario, background;
beforeEach(function () {
index = createSpy("index");
scenario = createSpyWithStubs("scenario AST element", {setBackground: null});
background = createSpy("scenario background");
spyOn(feature, 'getBackground').andReturn(background);
});
it("sets the background on the scenario", function () {
feature.insertFeatureElement(index, scenario);
expect(scenario.setBackground).toHaveBeenCalledWith(background);
});
it("adds the scenario to the scenarios (collection)", function () {
feature.insertFeatureElement(index, scenario);
expect(scenarioCollection.insert).toHaveBeenCalledWith(index, scenario);
});
});
describe("convertScenarioOutlinesToScenarios()", function () {
it ("iterates over the feature elements", function () {
feature.convertScenarioOutlinesToScenarios();
expect(scenarioCollection.syncForEach).toHaveBeenCalled();
expect(scenarioCollection.syncForEach).toHaveBeenCalledWithAFunctionAsNthParameter(1);
});
describe("for each feature element", function () {
var userFunction, featureElement;
beforeEach(function () {
feature.convertScenarioOutlinesToScenarios();
userFunction = scenarioCollection.syncForEach.mostRecentCall.args[0];
featureElement = createSpyWithStubs("feature element", {isScenarioOutline: null});
spyOn(feature, 'convertScenarioOutlineToScenarios');
});
describe("when the feature element is a scenario outline", function () {
beforeEach(function () {
featureElement.isScenarioOutline.andReturn(true);
userFunction (featureElement);
});
it("converts the scenario outline into scenarios", function () {
expect(feature.convertScenarioOutlineToScenarios).toHaveBeenCalledWith(featureElement);
});
});
describe("when the feature element is not a scenario outline", function () {
beforeEach(function () {
featureElement.isScenarioOutline.andReturn(false);
userFunction (featureElement);
});
it("converts the scenario outline into scenarios", function () {
expect(feature.convertScenarioOutlineToScenarios).not.toHaveBeenCalled();
});
});
});
});
describe("convertScenarioOutlineToScenarios()", function () {
var scenarios, scenarioOutlineTags, scenarioOutline, scenarioOutlineIndex;
beforeEach(function () {
scenarios = createSpyWithStubs("scenarios", {syncForEach: null});
scenarioOutlineTags = createSpy("tags");
scenarioOutline = createSpyWithStubs("scenario outline", {buildScenarios: scenarios, getTags: scenarioOutlineTags});
scenarioOutlineIndex = 1;
scenarioCollection.indexOf.andReturn(scenarioOutlineIndex);
feature.convertScenarioOutlineToScenarios(scenarioOutline);
});
it ("builds the scenarios for the scenario outline", function () {
expect(scenarioOutline.buildScenarios).toHaveBeenCalled();
});
it ("gets the index of the scenario outline in the scenario collection", function () {
expect(scenarioCollection.indexOf).toHaveBeenCalledWith(scenarioOutline);
});
it("removes the scenario outline from the scenario collection", function () {
expect(scenarioCollection.removeAtIndex).toHaveBeenCalledWith(scenarioOutlineIndex);
});
it("gets the tags from the scenario outline just once", function () {
expect(scenarioOutline.getTags).toHaveBeenCalledNTimes(1);
});
it ("iterates over the scenarios", function () {
expect(scenarios.syncForEach).toHaveBeenCalled();
expect(scenarios.syncForEach).toHaveBeenCalledWithAFunctionAsNthParameter(1);
});
describe("for each scenario", function () {
var userFunction, scenario, index;
beforeEach(function () {
userFunction = scenarios.syncForEach.mostRecentCall.args[0];
scenario = createSpyWithStubs("scenario", {addTags: null});
index = 2;
spyOn(feature, 'insertFeatureElement');
userFunction (scenario, index);
});
it("adds the scenario outline's tags to the scenario", function () {
expect(scenario.addTags).toHaveBeenCalledWith(scenarioOutlineTags);
});
it("inserts the scenario into the scenario collection", function () {
expect(feature.insertFeatureElement).toHaveBeenCalledWith(scenarioOutlineIndex + index, scenario);
});
});
});
describe("getLastScenario()", function () {
it("gets the last scenario from the collection", function () {
feature.getLastFeatureElement();
expect(scenarioCollection.getLast).toHaveBeenCalled();
});
it("returns the last scenario", function () {
expect(feature.getLastFeatureElement()).toBe(lastScenario);
});
});
describe("hasScenarios()", function () {
beforeEach(function () {
spyOnStub(scenarioCollection, 'length');
});
it("gets the number of scenarios", function () {
feature.hasFeatureElements();
expect(scenarioCollection.length).toHaveBeenCalled();
});
it("is falsy when there are 0 scenarios", function () {
scenarioCollection.length.andReturn(0);
expect(feature.hasFeatureElements()).toBeFalsy();
});
it("is truthy when there is 1 scenario", function () {
scenarioCollection.length.andReturn(1);
expect(feature.hasFeatureElements()).toBeTruthy();
});
it("is truthy when there are more than 1 scenarios", function () {
scenarioCollection.length.andReturn(2);
expect(feature.hasFeatureElements()).toBeTruthy();
});
});
describe("getTags() [addTags()]", function () {
it("returns an empty set when no tags were added", function () {
expect(feature.getTags()).toEqual([]);
});
it("returns the tags", function () {
var tag1 = createSpy("tag 1");
var tag2 = createSpy("tag 2");
var tag3 = createSpy("tag 3");
feature.addTags([tag1, tag2]);
feature.addTags([tag3]);
expect(feature.getTags()).toEqual([tag1, tag2, tag3]);
});
});
describe("acceptVisitor", function () {
var visitor, callback;
beforeEach(function () {
visitor = createSpyWithStubs("visitor", {visitStep: null});
callback = createSpy("callback");
spyOn(feature, 'instructVisitorToVisitBackground');
spyOn(feature, 'instructVisitorToVisitScenarios');
});
it("instructs the visitor to visit the feature background", function () {
feature.acceptVisitor(visitor, callback);
expect(feature.instructVisitorToVisitBackground).toHaveBeenCalledWithValueAsNthParameter(visitor, 1);
expect(feature.instructVisitorToVisitBackground).toHaveBeenCalledWithAFunctionAsNthParameter(2);
});
describe("when the visitor has finished visiting the background", function () {
var featureStepsVisitCallback;
beforeEach(function () {
feature.acceptVisitor(visitor, callback);
featureStepsVisitCallback = feature.instructVisitorToVisitBackground.mostRecentCall.args[1];
});
it("instructs the visitor to visit the feature steps", function () {
featureStepsVisitCallback();
expect(feature.instructVisitorToVisitScenarios).toHaveBeenCalledWith(visitor, callback);
});
});
});
describe("instructVisitorToVisitBackground()", function () {
var visitor, callback;
beforeEach(function () {
visitor = createSpyWithStubs("visitor", {visitBackground: undefined});
callback = createSpy("callback");
spyOn(feature, 'hasBackground');
});
it("checks whether the feature has a background", function () {
feature.instructVisitorToVisitBackground(visitor, callback);
expect(feature.hasBackground).toHaveBeenCalled();
});
describe("when there is a background", function () {
var background;
beforeEach(function () {
background = createSpy("background");
feature.hasBackground.andReturn(true);
spyOn(feature, 'getBackground').andReturn(background);
});
it("gets the background", function () {
feature.instructVisitorToVisitBackground(visitor, callback);
expect(feature.getBackground).toHaveBeenCalled();
});
it("instructs the visitor to visit the background", function () {
feature.instructVisitorToVisitBackground(visitor, callback);
expect(visitor.visitBackground).toHaveBeenCalledWith(background, callback);
});
it("does not call back", function () {
feature.instructVisitorToVisitBackground(visitor, callback);
expect(callback).not.toHaveBeenCalled();
});
});
describe("when there is no background", function () {
beforeEach(function () {
feature.hasBackground.andReturn(false);
});
it("calls back", function () {
feature.instructVisitorToVisitBackground(visitor, callback);
expect(callback).toHaveBeenCalled();
});
});
});
describe("instructVisitorToVisitScenarios()", function () {
var visitor, callback;
beforeEach(function () {
visitor = createSpyWithStubs("Visitor", {visitScenario: null});
callback = createSpy("Callback");
});
it ("iterates over the scenarios with a user function and the callback", function () {
feature.instructVisitorToVisitScenarios(visitor, callback);
expect(scenarioCollection.forEach).toHaveBeenCalled();
expect(scenarioCollection.forEach).toHaveBeenCalledWithAFunctionAsNthParameter(1);
expect(scenarioCollection.forEach).toHaveBeenCalledWithValueAsNthParameter(callback, 2);
});
describe("for each scenario", function () {
var userFunction, scenario, forEachCallback;
beforeEach(function () {
feature.instructVisitorToVisitScenarios(visitor, callback);
userFunction = scenarioCollection.forEach.mostRecentCall.args[0];
scenario = createSpy("A scenario from the collection");
forEachCallback = createSpy("forEach() callback");
});
it("tells the visitor to visit the scenario and call back when finished", function () {
userFunction (scenario, forEachCallback);
expect(visitor.visitScenario).toHaveBeenCalledWith(scenario, forEachCallback);
});
});
});
});
|
/*
* A reply to a screenshot comment made on a review.
*
* When created, this must take a parentObject attribute that points to a
* Review object.
*/
RB.ScreenshotCommentReply = RB.BaseCommentReply.extend({
rspNamespace: 'screenshot_comment'
});
|
define([
"dojo/_base/declare",
"dojo/_base/lang",
"dojo/store/Memory",
"dojo/query",
"dojo/dom-attr",
"dijit/_WidgetBase",
"dijit/_FocusMixin",
"dijit/_TemplatedMixin",
"dijit/form/FilteringSelect"
], function(declare, lang, Store, query, domAttr, _WidgetBase, _FocusMixin, _TemplatedMixin, FilteringSelect){
/*=====
return declare([_WidgetBase, _FocusMixin, _TemplatedMixin], {
// summary:
// This grid bar plugin is to switch pages using select widget.
// grid: [const] gridx.Grid
// The grid widget this plugin works for.
grid: null,
// stepperClass: Function
// The constructor of the select widget
stepperClass: FilteringSelect,
// stepperProps: Object
// The properties passed to select widget when creating it.
stepperProps: null,
refresh: function(){}
});
=====*/
return declare([_WidgetBase, _FocusMixin, _TemplatedMixin], {
templateString: '<div class="gridxDropDownPager"><label class="gridxPagerLabel">${pageLabel}</label></div>',
constructor: function(args){
lang.mixin(this, args.grid.nls);
},
postCreate: function(){
var t = this,
g = t.grid,
c = 'connect',
p = g.pagination;
t[c](p, 'onSwitchPage', '_onSwitchPage');
t[c](p, 'onChangePageSize', 'refresh');
t[c](g.model, 'onSizeChange', 'refresh');
g.pagination.loaded.then(function(){
t.refresh();
//Set initial page after pagination module is ready.
t._onSwitchPage(g.pagination.currentPage());
});
},
//Public-----------------------------------------------------------------------------
grid: null,
stepperClass: FilteringSelect,
stepperProps: null,
refresh: function(){
var t = this, mod = t.module,
items = [],
selectedItem,
p = t.grid.pagination,
pageCount = p.pageCount(),
currentPage = p.currentPage(),
stepper = t._pageStepperSelect,
i, v, item;
for(i = 0; i < pageCount; ++i){
v = i + 1;
item = {
id: v,
label: v,
value: v
};
items.push(item);
if(currentPage == i){
selectedItem = item;
}
}
var store = new Store({data: items});
if(!stepper){
var cls = t.stepperClass,
props = lang.mixin({
store: store,
searchAttr: 'label',
item: selectedItem,
'class': 'gridxPagerStepperWidget',
onChange: function(page){
p.gotoPage(page - 1);
}
}, t.stepperProps || {});
stepper = t._pageStepperSelect = new cls(props);
stepper.placeAt(t.domNode, "last");
stepper.startup();
domAttr.set(query('.gridxPagerLabel', t.domNode)[0], 'for', stepper.id);
}else{
stepper.set('store', store);
stepper.set('value', currentPage + 1);
}
stepper.set('disabled', pageCount <= 1);
},
//Private----------------------------------------------------------------------------
_onSwitchPage: function(page){
this._pageStepperSelect.set('value', page + 1);
}
});
});
|
var should = require('should'),
sinon = require('sinon'),
rewire = require('rewire'),
path = require('path'),
Promise = require('bluebird'),
ampController = rewire('../lib/router'),
errors = require('../../../errors'),
configUtils = require('../../../../test/utils/configUtils'),
themes = require('../../../themes'),
sandbox = sinon.sandbox.create();
// Helper function to prevent unit tests
// from failing via timeout when they
// should just immediately fail
function failTest(done) {
return function (err) {
done(err);
};
}
describe('AMP Controller', function () {
var res,
req,
defaultPath,
setResponseContextStub,
hasTemplateStub;
beforeEach(function () {
hasTemplateStub = sandbox.stub().returns(false);
hasTemplateStub.withArgs('index').returns(true);
sandbox.stub(themes, 'getActive').returns({
hasTemplate: hasTemplateStub
});
res = {
render: sandbox.spy(),
locals: {
context: ['amp', 'post']
}
};
req = {
route: {path: '/'},
query: {r: ''},
params: {},
amp: {}
};
defaultPath = path.join(configUtils.config.get('paths').appRoot, '/core/server/apps/amp/lib/views/amp.hbs');
configUtils.set({
theme: {
permalinks: '/:slug/',
amp: true
}
});
});
afterEach(function () {
sandbox.restore();
configUtils.restore();
});
it('should render default amp page when theme has no amp template', function (done) {
setResponseContextStub = sandbox.stub();
ampController.__set__('setResponseContext', setResponseContextStub);
res.render = function (view) {
view.should.eql(defaultPath);
done();
};
ampController.controller(req, res, failTest(done));
});
it('should render theme amp page when theme has amp template', function (done) {
hasTemplateStub.withArgs('amp').returns(true);
setResponseContextStub = sandbox.stub();
ampController.__set__('setResponseContext', setResponseContextStub);
res.render = function (view) {
view.should.eql('amp');
done();
};
ampController.controller(req, res, failTest(done));
});
it('should render with error when error is passed in', function (done) {
res.error = 'Test Error';
setResponseContextStub = sandbox.stub();
ampController.__set__('setResponseContext', setResponseContextStub);
res.render = function (view, context) {
view.should.eql(defaultPath);
context.should.eql({error: 'Test Error'});
done();
};
ampController.controller(req, res, failTest(done));
});
it('does not render amp page when amp context is missing', function (done) {
var renderSpy;
setResponseContextStub = sandbox.stub();
ampController.__set__('setResponseContext', setResponseContextStub);
res.locals.context = ['post'];
res.render = sandbox.spy(function () {
done();
});
renderSpy = res.render;
ampController.controller(req, res, failTest(done));
renderSpy.called.should.be.false();
});
it('does not render amp page when context is other than amp and post', function (done) {
var renderSpy;
setResponseContextStub = sandbox.stub();
ampController.__set__('setResponseContext', setResponseContextStub);
res.locals.context = ['amp', 'page'];
res.render = sandbox.spy(function () {
done();
});
renderSpy = res.render;
ampController.controller(req, res, failTest(done));
renderSpy.called.should.be.false();
});
});
describe('AMP getPostData', function () {
var res, req, postLookupStub, next;
beforeEach(function () {
res = {
locals: {
relativeUrl: '/welcome-to-ghost/amp/'
}
};
req = {
amp: {
post: {}
}
};
next = function () {};
});
afterEach(function () {
sandbox.restore();
});
it('should successfully get the post data from slug', function (done) {
postLookupStub = sandbox.stub();
postLookupStub.returns(new Promise.resolve({
post: {
id: '1',
slug: 'welcome-to-ghost'
}
}));
ampController.__set__('postLookup', postLookupStub);
ampController.getPostData(req, res, function () {
req.body.post.should.be.eql({
id: '1',
slug: 'welcome-to-ghost'
}
);
done();
});
});
it('should return error if postlookup returns NotFoundError', function (done) {
postLookupStub = sandbox.stub();
postLookupStub.returns(new Promise.reject(new errors.NotFoundError({message: 'not found'})));
ampController.__set__('postLookup', postLookupStub);
ampController.getPostData(req, res, function (err) {
should.exist(err);
should.exist(err.message);
should.exist(err.statusCode);
should.exist(err.errorType);
err.message.should.be.eql('not found');
err.statusCode.should.be.eql(404);
err.errorType.should.be.eql('NotFoundError');
req.body.should.be.eql({});
done();
});
});
it('should return error and if postlookup returns error', function (done) {
postLookupStub = sandbox.stub();
postLookupStub.returns(new Promise.reject('not found'));
ampController.__set__('postLookup', postLookupStub);
ampController.getPostData(req, res, function (err) {
should.exist(err);
err.should.be.eql('not found');
req.body.should.be.eql({});
done();
});
});
});
|
/** PeriodLister Class */
function PeriodDeltaChain(params) {
this.period_root_id = params.period_root_id;
this.date_format = this.set_or_default(params.date_format, '');
this.set_due_date(params.due_date);
this.period_class = this.set_or_default(params.period_class, 'period');
}
PeriodDeltaChain.prototype.refresh = function() {
var current_time = this.due_date;
var format = this.date_format;
var period_selector = '#' + this.period_root_id + ' .' + this.period_class;
var me = this;
jQuery(period_selector).each(function() {
var from_time_node = this.querySelector('.PeriodDeltaChain_FromTime');
var to_time_node = this.querySelector('.PeriodDeltaChain_ToTime');
var hours_value = this.querySelector('.PeriodDeltaChain_Hours').value;
var from_time = moment(current_time, me.date_format);
var to_time = moment(current_time, me.date_format);
jQuery(from_time_node).html(from_time.format(format));
jQuery(to_time_node).html(to_time.add('hours', hours_value).format(format));
current_time = to_time;
});
if (jQuery(period_selector).length < 2) {
jQuery(period_selector + ' a').hide();
} else {
jQuery(period_selector + ' a').show();
}
}
PeriodDeltaChain.prototype.set_due_date = function(new_due_date) {
delete this.due_date;
this.due_date = convert_date(new_due_date);
}
PeriodDeltaChain.prototype.set_or_default = function(value, default_value) {
if (typeof value == 'undefined') {
return default_value;
}
return value;
}
/** Converts date string to an actual Date object. */
function convert_date(due_date) {
if (due_date.indexOf(' ') > -1) {
var arr_date = due_date.split(/[ T]/).filter(function (s) {
return s !== '';
});
due_date = arr_date[0] + ' ' + arr_date[1] + ' ' + arr_date[2];
}
return due_date;
}
|
var test = require("tape")
var add = require("../index.js")
test("add is a function", function (assert) {
assert.equal(typeof add, "function")
assert.end()
})
test("can add numbers", function (assert) {
assert.equal(add(3, 9), 12)
assert.end()
}) |
var parent = require('../../stable/string/match-all');
module.exports = parent;
|
const Combinatorics = require('js-combinatorics');
const widths = [null, 20, 60];
const heights = [null, 40, 80];
const horizontalAlignments = [null, 'left', 'right', 'center'];
const verticalAlignments = [null, 'bottom', 'top', 'center'];
const orients = [null, 'horizontal', 'vertical'];
const caps = [null, 10, 20];
const results = {
bar: {
keys: ['width', 'height', 'horizontalAlign', 'verticalAlign'],
combinations: Combinatorics.cartesianProduct(
widths, // Bar chart needs a width
heights.slice(1),
horizontalAlignments,
verticalAlignments
).toArray()
},
boxPlot: {
keys: ['width', 'orient', 'cap'],
combinations: Combinatorics.cartesianProduct(
widths,
orients,
caps
).toArray()
},
candlestick: {
keys: ['width'],
combinations: Combinatorics.cartesianProduct(
widths
).toArray()
},
errorBar: {
keys: ['width', 'orient'],
combinations: Combinatorics.cartesianProduct(
widths,
orients
).toArray()
},
ohlc: {
keys: ['width', 'orient'],
combinations: Combinatorics.cartesianProduct(
widths,
orients
).toArray()
}
};
module.exports = results;
|
"use strict";
const Utils = require("../../core/Utils");
const RequestQueue = require("./RequestQueue");
const ChainedBucket = require("./ChainedBucket");
class RequestQueueGroup {
constructor(bucketFactory) {
this.queues = {};
this.bucketFactory = bucketFactory || null;
if (!(bucketFactory instanceof BucketFactory)) {
throw new TypeError(
"Param 'bucketFactory' is not an instance of BucketFactory"
);
}
}
get(id) {
if (!this.queues[id]) {
const bucket = (this.bucketFactory && this.bucketFactory.get(id));
this.queues[id] = new RequestQueue(bucket);
}
this.queues[id].id = id;
return this.queues[id];
}
delete(id) {
if (this.bucketFactory)
this.bucketFactory.delete(id);
delete this.queues[id];
}
deleteContaining(id) {
var keys = Object.keys(this.queues);
for (var i = 0, len = keys.length; i < len; i++) {
var key = keys[i];
if (!key || key.indexOf(id) < 0) continue;
this.delete(key);
}
}
}
class BucketFactory {
constructor(manager, size, duration, name, parent) {
this.manager = manager;
this.size = size;
this.duration = duration;
this.name = name;
this.parent = parent || null;
if (!(manager instanceof RequestQueueManager))
throw new TypeError("Param 'manager' is invalid");
if (typeof size !== "number")
throw new TypeError("Param 'size' is not a number");
if (typeof duration !== "number")
throw new TypeError("Param 'duration' is not a number");
if (typeof name !== "string")
throw new TypeError("Param 'name' is not a string");
}
makeName(id) {
return this.name + ":" + id;
}
get(id) {
const parent =
this.parent instanceof BucketFactory ?
this.parent.get(id) :
this.parent;
return this.manager._createBucket(
this.size, this.duration, this.makeName(id), parent
);
}
delete(id) {
delete this.manager.buckets[this.makeName(id)];
}
}
class RequestQueueManager {
constructor(discordie) {
this._discordie = discordie;
this.isBot = true;
this.disabled = false;
this.buckets = {};
this.bucketFactories = {};
// whole API, bucket blocks when client gets a HTTP 429 with global flag
const _bot_global =
this._createBucket(Infinity, 1000, "bot:global");
this.globalBucket = _bot_global;
// msg 10/10s
const _msg =
this._createBucket(10, 10000, "msg", _bot_global);
this.userMessageQueue = new RequestQueue(_msg);
// per-channel bot:msg:dm 10/10s
const _bot_msg_dm =
this._createBucketFactory(10, 10000, "bot:msg:dm", _bot_global);
this.botDirectMessageQueues = new RequestQueueGroup(_bot_msg_dm);
// per-guild bot:msg:server 10/10s
const _bot_msg_server =
this._createBucketFactory(10, 10000, "bot:msg:server", _bot_global);
this.botMessageQueues = new RequestQueueGroup(_bot_msg_server);
// per-guild dmsg 5/1s
const _dmsg =
this._createBucketFactory(5, 1000, "dmsg", _bot_global);
this.messageDeleteQueues = new RequestQueueGroup(_dmsg);
// per-guild bdmsg 1/1s
const _bdmsg =
this._createBucketFactory(1, 1000, "bdmsg", _bot_global);
this.messageBulkDeleteQueues = new RequestQueueGroup(_bdmsg);
// per-guild guild_member 10/10s
const _guild_member =
this._createBucketFactory(10, 10000, "guild_member", _bot_global);
this.guildMemberPatchQueues = new RequestQueueGroup(_guild_member);
// per-guild guild_member_nick 1/1s
const _guild_member_nick =
this._createBucketFactory(1, 1000, "guild_member_nick", _bot_global);
this.guildMemberNickQueues = new RequestQueueGroup(_guild_member_nick);
// all other requests go here with route as key
// bucket size should be set by HTTP headers
const _bot_generic =
this._createBucketFactory(Infinity, 5000, "bot:generic", _bot_global);
this.genericRequestQueues = new RequestQueueGroup(_bot_generic);
discordie.Dispatcher.on("GATEWAY_DISPATCH", e => {
if (!e.data) return;
if (e.type === "READY") {
if (!e.data.user) return;
this.isBot = e.data.user.bot || false;
}
if (e.type === "GUILD_DELETE") {
this._deleteGuildQueues(e.data.id);
}
if (e.type === "CHANNEL_DELETE") {
this._deleteChannelQueues(e.data.id);
}
});
Utils.privatify(this);
}
_reset() {
Object.keys(this.buckets).forEach(k => this.buckets[k].refill());
}
_createBucket(size, duration, name, parent) {
if (!this.buckets[name]) {
this.buckets[name] = new ChainedBucket(size, duration, name, parent);
} else {
this.buckets[name].refill();
}
return this.buckets[name];
}
_createBucketFactory(size, duration, name, parent) {
if (!this.bucketFactories[name]) {
this.bucketFactories[name] =
new BucketFactory(this, size, duration, name, parent);
}
return this.bucketFactories[name];
}
put(request, sendCallback) {
const route = request.path
.replace(/\/\d+$/g, "")
.replace(/\d+/g, ":id");
// convert to route: <- /api/guilds/:guild_id/bans/:user_id
// -> /api/guilds/:id/bans
// <- /api/channels/:channel_id
// -> /api/channels/
const queue = this.genericRequestQueues.get(route);
this._enqueueTo(queue, request, sendCallback);
}
putToRoute(request, route, sendCallback) {
const queue = this.genericRequestQueues.get(route);
this._enqueueTo(queue, request, sendCallback);
}
putMessage(request, channelId, sendCallback) {
const channel = this._discordie._channels.get(channelId);
var queue = this.userMessageQueue;
if (this.isBot && channel) {
if (channel.is_private || !channel.guild_id) {
queue = this.botDirectMessageQueues.get(channelId);
} else {
queue = this.botMessageQueues.get(channel.guild_id);
}
}
this._enqueueTo(queue, request, sendCallback);
}
putDeleteMessage(request, channelId, sendCallback) {
const group = this.messageDeleteQueues;
this._enqueueToGroup(group, request, channelId, sendCallback);
}
putBulkDeleteMessage(request, channelId, sendCallback) {
const group = this.messageBulkDeleteQueues;
this._enqueueToGroup(group, request, channelId, sendCallback);
}
putGuildMemberPatch(request, guildId, sendCallback) {
const queue = this.guildMemberPatchQueues.get(guildId);
this._enqueueTo(queue, request, sendCallback);
}
putGuildMemberNick(request, guildId, sendCallback) {
const queue = this.guildMemberNickQueues.get(guildId);
this._enqueueTo(queue, request, sendCallback);
}
_enqueueToGroup(group, request, channelId, sendCallback) {
const channel = this._discordie._channels.get(channelId);
const guildId = (channel && channel.guild_id) || null;
this._enqueueTo(group.get(guildId), request, sendCallback);
}
_enqueueTo(queue, request, sendCallback) {
if (this.disabled) {
return request.send(sendCallback);
}
queue.enqueue(request, sendCallback);
}
_deleteGuildQueues(guildId) {
const groups = [
this.botMessageQueues,
this.messageDeleteQueues,
this.messageBulkDeleteQueues,
this.guildMemberPatchQueues
];
groups.forEach(g => g.delete(guildId));
this.genericRequestQueues.deleteContaining(guildId);
}
_deleteChannelQueues(channelId) {
this.botDirectMessageQueues.delete(channelId);
this.genericRequestQueues.deleteContaining(channelId);
}
}
module.exports = RequestQueueManager; |
'use strict';
const {
Symbol
} = primordials;
const {
kUpdateTimer,
onStreamRead,
} = require('internal/stream_base_commons');
const { owner_symbol } = require('internal/async_hooks').symbols;
const { Readable } = require('stream');
const kHandle = Symbol('kHandle');
class HeapSnapshotStream extends Readable {
constructor(handle) {
super({ autoDestroy: true });
this[kHandle] = handle;
handle[owner_symbol] = this;
handle.onread = onStreamRead;
}
_read() {
if (this[kHandle])
this[kHandle].readStart();
}
_destroy() {
// Release the references on the handle so that
// it can be garbage collected.
this[kHandle][owner_symbol] = undefined;
this[kHandle] = undefined;
}
[kUpdateTimer]() {
// Does nothing
}
}
module.exports = {
HeapSnapshotStream
};
|
import hasFeature from './has';
export function prop(path) {
return function(state, props) {
const names = path.split('.');
if (!(names[0] in props)) {
throw new Error(`Missing required prop ${names[0]}.`);
}
return names.reduce((p, name) => (p && p[name]), props);
};
}
export function has(featureName) {
return function(_props, _state, browser) {
return hasFeature(featureName, browser);
};
}
|
const {addTable} = require('../../utils');
module.exports = addTable('snippets');
|
var inspector = require('../');
// Custom type schema
var personValidation = {
type: 'object',
properties: {
firstname: { type: 'string', minLength: 1 },
lastname: { type: 'string', minLength: 1 },
age: { type: 'integer', gt: 0, lte: 120 }
}
};
// Custom Validation ($type)
var customValidation = {
// $type will be like type but with an additional possible value "person"
type: function (schema, candidate) {
var result;
// Custom type
if (schema.$type === 'person')
result = inspector.validate(personValidation, candidate);
// Basic type
else
result = inspector.validate({ type: schema.$type }, candidate);
if (!result.valid)
return this.report(result.format());
}
};
// Extend SchemaInspector.Validator
inspector.Validation.extend(customValidation);
var data = {
firstname: ' sebastien ',
lastname: 'chopin ',
age: '21'
};
var schema = { $type: 'person' };
var result = inspector.validate(schema, data);
if (!result.valid)
console.log(result.format()); // Property @.age: must be integer, but is string |
/***** AVAILABLE JAVASCRIPT FUNCTIONS ******/
/* Function: GraphicsApp()
* --------------------------------
* Creates a new GraphicsApp object and returns it.
*
* Parameters: none
*/
function GraphicsApp() {}
/* Function: addButton(buttonName)
* -----------------------------------------------
* Creates and adds a new button to the top area of the webpage. The button
* will display the text buttonName.
*
* Parameters:
* -----------
* buttonName: the text that is displayed on the button.
*/
GraphicsApp.prototype.addButton = function(buttonName, callbackFn) {
var inputDiv = document.getElementById("inputDiv");
var button = document.createElement("BUTTON");
button.textContent = buttonName;
button.onclick = callbackFn;
if (typeof(inputDiv) === "undefined") {
inputDiv = document.getElementsByTagName('body');
}
inputDiv.appendChild(button);
}
/* Function: addTextField()
* -----------------------------
* Creates and adds a new text field to the top area of the webpage.
* Returns the text field object that was added to the page.
*
* Parameters: none
* Returns: the text field that was created.
*/
GraphicsApp.prototype.addTextField = function() {
// Make a new text field
var textField = document.createElement("INPUT");
textField.type = "text";
textField.id = "inputField";
// Append it inside our input div
var inputDiv = document.getElementById("inputDiv");
if (typeof(inputDiv) === "undefined") {
inputDiv = document.getElementsByTagName('body');
}
inputDiv.appendChild(textField);
return textField;
}
/* Function: addCanvas()
* --------------------------
* Creates and adds a new canvas to the center area of the webpage.
*
* Parameters: none
*/
GraphicsApp.prototype.addCanvas = function(width, height) {
setBackground(width,height,0xFFFFFF);
}
/* Function: addTitle(title)
* --------------------------------
* Adds a title with the given text at the top of the page.
*
* Parameters:
* -----------
* title: the text of the title to add.
*/
GraphicsApp.prototype.addTitle = function(title) {
// Set the page title to be equal to the passed in text
var titleElem = document.createElement("TITLE");
titleElem.textContent = title;
var head = document.getElementsByTagName("HEAD")[0];
head.appendChild(titleElem);
// Also create and add an H1 element at the top displaying the passed in text
var h1 = document.createElement("H1");
h1.textContent = title;
var inputDiv = document.getElementById("inputDiv");
var body = document.getElementsByTagName("BODY")[0];
body.insertBefore(h1, inputDiv);
}
/* Function: displayErrorMessage(error)
* --------------------------------
* Displays an error message to the user in red below the text box.
*
* Parameters:
* -----------
* error: the error message to display.
*/
GraphicsApp.prototype.displayErrorMessage = function(error) {
var errorField = document.getElementById("errorField");
errorField.innerHTML = error;
}
/* Function: getCurrentLocation()
* ----------------------------
* Calculates the user's current location, and calls callbackFn, passing
* the user's current latitude and longitude. The provided callbackFn should
* therefore be something like
*
* function callback(latitude, longitude) {
* ...
* }
*
*
* Parameters:
* -----------
* callbackFn: the function that's called once the user's location has been calculated
*/
GraphicsApp.prototype.getCurrentLocation = function(callbackFn) {
// Query the user's location
navigator.geolocation.getCurrentPosition(function(position) {
callbackFn(position.coords.latitude, position.coords.longitude);
});
}
/* Function: fetchWeatherForQuery(query, numDays, successFn, errorFn)
* -------------------------------------------------------------
* Sends a request to the weather API, passing in the given query.
*
* Parameters:
* -----------
* query: a string query of the place the weather should be fetched for.
*
* numDays: the number of days for which you want to get the weather.
*
* successFn: a function that takes a single parameter, the data returned from the API call.
* This function will be called upon success of the API call.
*
* errorFn: a function that takes no parameters. This function will be called upon failure of the API call.
*/
GraphicsApp.prototype.fetchWeatherForQuery = function(query, numDays, successFn, errorFn) {
var url = "http://api.openweathermap.org/data/2.5/forecast/daily?q=" + encodeURIComponent(query) +
"&mode=json&cnt=" + encodeURIComponent(numDays) + "&units=metric";
this.sendWeatherRequestWithURL(url, successFn, errorFn);
}
/* Function: fetchWeatherForCoordinates(latitude, longitude, numDays, successFn, errorFn)
* ----------------------------------------------------------------------------------
* Sends a request to the weather API, passing in the given coordinates.
*
* Parameters:
* -----------
* latitude: the latitude to fetch the weather for.
*
* longitude: the longitude to fetch the weather for.
*
* numDays: the number of days for which you want to get the weather.
*
* successFn: a function that takes a single parameter, the data returned from the API call.
* This function will be called upon success of the API call.
*
* errorFn: a function that takes no parameters. This function will be called upon failure of the API call.
*/
GraphicsApp.prototype.fetchWeatherForCoordinates = function(latitude, longitude, numDays, successFn, errorFn) {
var url = "http://api.openweathermap.org/data/2.5/forecast/daily?lat=" +
encodeURIComponent(latitude) + "&lon=" + encodeURIComponent(longitude) + "&mode=json&cnt=" + encodeURIComponent(numDays) + "&units=metric";
this.sendWeatherRequestWithURL(url, successFn, errorFn);
}
/*******************************************************/
/********* PRIVATE GraphicsApp METHODS ************/
/* Function: sendWeatherRequestWithURL(url, successFn, errorFn)
* ---------------------------------------------------------
* Makes an AJAX (Asynchronous Javascript and XML) GET request to the given URL.
* If the request is unsuccessful, the errorFn callback is called. If successful,
* the weather server will return an array of objects, each representing the weather for
* a day. This function then adds the name of each day to each day object (eg. "Monday") and
* passes the array to the successFn callback.
*
* Parameters:
* -----------
* url: the URL to send the request to.
*
* successFn: the function to execute if a response is successfully returned.
*
* errorFn: the function to execute if the request fails.
*/
GraphicsApp.prototype.sendWeatherRequestWithURL = function(url, successFn, errorFn) {
// The handler for the AJAX requests that call the student's callbacks
var obj = this;
function xhrHandler() {
if (this.readyState != 4) return;
else if (this.status != 200 && errorFn) errorFn();
else {
var data = JSON.parse(this.responseText);
var daysArray = data["list"];
// If there is no data, call the error handler
if (daysArray == null) {
if (errorFn) errorFn();
return;
} else if (!successFn) return;
var cleanedDaysArray = [];
// Get the array of day names this weather data corresponds to
var dayNames = obj.dayNamesStartingToday(daysArray.length);
// Pull out only the relevant weather data and store an object for each
// day inside of cleanedDaysArray
for (var i = 0; i < daysArray.length; i++) {
// Create a new day object with the relevant data inside
var day = {};
day["dayName"] = dayNames[i];
day["tempHigh"] = daysArray[i]["temp"]["max"];
day["tempLow"] = daysArray[i]["temp"]["min"];
day["weatherDescription"] = daysArray[i]["weather"][0]["main"]; // Rain Clouds Clear Snow
day["humidity"] = daysArray[i]["humidity"];
day["windSpeed"] = daysArray[i]["speed"];
// Add it to our days array
cleanedDaysArray.push(day);
}
successFn(cleanedDaysArray);
}
}
// Create and send the request
xhr = new XMLHttpRequest();
xhr.onreadystatechange = xhrHandler;
xhr.open("GET", url);
xhr.send();
}
/* Function: dayNamesStartingToday(numDays)
* -------------------------------------
* Returns an array of length "numDays" containing consecutive
* weekday names starting with today. For example, if today is
* Tuesday, and numDays = 4, then dayNamesStartingToday would return
* ["Tuesday", "Wednesday", "Thursday", "Friday"].
*
* Parameters:
* -----------
* numDays: the number day names to include in the array
*/
GraphicsApp.prototype.dayNamesStartingToday = function(numDays) {
// Get the index of today
var currDate = new Date();
var todayIndex = currDate.getDay();
var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
// Loop around the day names array starting today and add each day name
var daysArray = [];
for (var i = 0; i < numDays; i++) {
// Loop around the day names array (if we get over 6, loop back around)
var index = (todayIndex + i) % 7;
daysArray.push(dayNames[index]);
}
return daysArray;
}
/****************************************/
|
/**
* Module dependencies.
*/
var Emitter = require('emitter');
var render = require('render');
var events = require('events');
var empty = require('empty');
var filter = require('laws-filter');
var template = require('./filter-container');
var o = require('query');
var closest = require('closest');
var classes = require('classes');
function FilterView() {
if (!(this instanceof FilterView)) {
return new FilterView();
};
// Prep event handlers
this.refresh = this.refresh.bind(this);
this.build();
this.switchOn();
}
Emitter(FilterView.prototype);
FilterView.prototype.build = function() {
this.el = render.dom(template, { filter: filter });
};
FilterView.prototype.switchOn = function() {
// View events
this.events = events(this.el, this);
this.events.bind('click #status-filter a.btn', 'onstatusclick');
this.events.bind('click #sort-filter ul li', 'onsortclick');
this.events.bind('click #hide-voted-filter input[name=hide-voted]', 'onhidevotedclick');
// Behavior events
filter.on('change', this.refresh);
}
FilterView.prototype.switchOff = function() {
this.events.unbind();
filter.off('change', this.refresh);
}
FilterView.prototype.refresh = function() {
var old = this.el;
this.switchOff();
this.build();
this.switchOn();
if (old.parentNode) old.parentNode.replaceChild(this.el, old);
old.remove();
var obj = o('li[data-sort="closing-soon"]', this.el);
if (filter.get('status') == 'closed') {
classes(obj).add('hide');
if (filter.get('sort') == 'closing-soon') filter.set('sort', 'newest-first');
} else {
classes(obj).remove('hide');
}
};
FilterView.prototype.onstatusclick = function(ev) {
ev.preventDefault();
var target = ev.delegateTarget || closest(ev.target, '[data-status]', true);
var status = target.getAttribute('data-status');
filter.set('status', status);
}
FilterView.prototype.onsortclick = function(ev) {
ev.preventDefault();
var target = ev.delegateTarget || closest(ev.target, '[data-sort]', true);
var sort = target.getAttribute('data-sort');
filter.set('sort', sort);
}
FilterView.prototype.onhidevotedclick = function(ev) {
ev.preventDefault();
var target = ev.delegateTarget || closest(ev.target, '[type=checkbox]', true);
var checked = !!target.checked;
filter.set('hide-voted', checked);
}
FilterView.prototype.ready = function(fn) {
filter.ready(fn);
filter.ready(this.refresh);
}
FilterView.prototype.render = function(el) {
if (1 === arguments.length) {
// if string, then query element
if ('string' === typeof el) {
el = o(el);
};
// if it's not currently inserted
// at `el`, then append to `el`
if (el !== this.el.parentNode) {
el.appendChild(this.el);
};
// !!!: Should we return different things
// on different conditions?
// Or should we be consistent with
// render returning always `this.el`
return this;
};
return this.el;
}
module.exports = new FilterView(); |
var ModelForm = {
init: function(options)
{
var ops = $.extend(true, this.getDefaultOptions(), options);
Validation.init(ops);
},
getDefaultOptions: function()
{
return {
src: '.form',
isAjax: false,
submitAjax: function(validation)
{
//
},
validate: {
rules: {
name: {
required: true
}
},
messages: messagesOfRules
}
}
}
};
|
import React, { Component } from "react";
import Home from "../components/home/";
import BlankPage2 from "../components/blankPage2";
import { DrawerNavigator } from "react-navigation";
import DrawBar from "../components/DrawBar";
export default (DrawNav = DrawerNavigator(
{
Home: { screen: Home },
BlankPage2: { screen: BlankPage2 }
},
{
contentComponent: props => <DrawBar {...props} />
}
));
|
describe('Demo test with Mocha', function() {
describe('for testing purposes', function() {
before(function(client, done) {
client.globals.test_calls++;
done();
});
after(function(client, done) {
setTimeout(function() {
client.globals.test_calls++;
done();
}, 100);
});
afterEach(function(client, done) {
setTimeout(function() {
client.globals.test_calls++;
done();
}, 100);
});
beforeEach(function(client, done) {
setTimeout(function() {
client.globals.test_calls++;
done();
}, 100);
});
it('demoTestAsyncOne', function(client) {
client.url('http://localhost');
});
it('demoTestAsyncTwo', function(client) {
client.end();
});
});
}); |
;(function (global) {
if ("EventSource" in global) return;
var reTrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;
var EventSource = function (url) {
var eventsource = this,
interval = 500, // polling interval
lastEventId = null,
cache = '';
if (!url || typeof url != 'string') {
throw new SyntaxError('Not enough arguments');
}
this.URL = url;
this.readyState = this.CONNECTING;
this._pollTimer = null;
this._xhr = null;
function pollAgain(interval) {
eventsource._pollTimer = setTimeout(function () {
poll.call(eventsource);
}, interval);
}
function poll() {
try { // force hiding of the error message... insane?
if (eventsource.readyState == eventsource.CLOSED) return;
// NOTE: IE7 and upwards support
var xhr = new XMLHttpRequest();
xhr.open('GET', eventsource.URL, true);
xhr.setRequestHeader('Accept', 'text/event-stream');
xhr.setRequestHeader('Cache-Control', 'no-cache');
// we must make use of this on the server side if we're working with Android - because they don't trigger
// readychange until the server connection is closed
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
if (lastEventId != null) xhr.setRequestHeader('Last-Event-ID', lastEventId);
cache = '';
xhr.timeout = 50000;
xhr.onreadystatechange = function () {
if ((this.readyState == 3 || this.readyState == 4) && this.status == 200) {
// on success
if (eventsource.readyState == eventsource.CONNECTING) {
eventsource.readyState = eventsource.OPEN;
eventsource.dispatchEvent('open', { type: 'open' });
}
var responseText = '';
try {
responseText = this.responseText || '';
} catch (e) {}
// process this.responseText
var parts = responseText.substr(cache.length).split("\n"),
eventType = 'message',
data = [],
i = 0,
line = '';
cache = responseText;
// TODO handle 'event' (for buffer name), retry
for (; i < parts.length; i++) {
line = parts[i].replace(reTrim, '');
if (line.indexOf('event') == 0) {
eventType = line.replace(/event:?\s*/, '');
} else if (line.indexOf('retry') == 0) {
retry = parseInt(line.replace(/retry:?\s*/, ''));
if(!isNaN(retry)) { interval = retry; }
} else if (line.indexOf('data') == 0) {
data.push(line.replace(/data:?\s*/, ''));
} else if (line.indexOf('id:') == 0) {
lastEventId = line.replace(/id:?\s*/, '');
} else if (line.indexOf('id') == 0) { // this resets the id
lastEventId = null;
} else if (line == '') {
if (data.length) {
var event = new MessageEvent(data.join('\n'), eventsource.url, lastEventId);
eventsource.dispatchEvent(eventType, event);
data = [];
eventType = 'message';
}
}
}
if (this.readyState == 4) pollAgain(interval);
// don't need to poll again, because we're long-loading
} else if (eventsource.readyState !== eventsource.CLOSED) {
if (this.readyState == 4) { // and some other status
// dispatch error
eventsource.readyState = eventsource.CONNECTING;
eventsource.dispatchEvent('error', { type: 'error' });
pollAgain(interval);
} else if (this.readyState == 0) { // likely aborted
pollAgain(interval);
} else {
}
}
};
xhr.send();
setTimeout(function () {
if (true || xhr.readyState == 3) xhr.abort();
}, xhr.timeout);
eventsource._xhr = xhr;
} catch (e) { // in an attempt to silence the errors
eventsource.dispatchEvent('error', { type: 'error', data: e.message }); // ???
}
};
poll(); // init now
};
EventSource.prototype = {
close: function () {
// closes the connection - disabling the polling
this.readyState = this.CLOSED;
clearInterval(this._pollTimer);
this._xhr.abort();
},
CONNECTING: 0,
OPEN: 1,
CLOSED: 2,
dispatchEvent: function (type, event) {
var handlers = this['_' + type + 'Handlers'];
if (handlers) {
for (var i = 0; i < handlers.length; i++) {
handlers[i].call(this, event);
}
}
if (this['on' + type]) {
this['on' + type].call(this, event);
}
},
addEventListener: function (type, handler) {
if (!this['_' + type + 'Handlers']) {
this['_' + type + 'Handlers'] = [];
}
this['_' + type + 'Handlers'].push(handler);
},
removeEventListener: function () {
// TODO
},
onerror: null,
onmessage: null,
onopen: null,
readyState: 0,
URL: ''
};
var MessageEvent = function (data, origin, lastEventId) {
this.data = data;
this.origin = origin;
this.lastEventId = lastEventId || '';
};
MessageEvent.prototype = {
data: null,
type: 'message',
lastEventId: '',
origin: ''
};
if ('module' in global) module.exports = EventSource;
global.EventSource = EventSource;
})(this);
|
import { RocketChat } from 'meteor/rocketchat:lib';
import { Random } from 'meteor/random';
import _ from 'underscore';
import s from 'underscore.string';
import hljs from 'highlight.js';
import _marked from 'marked';
const renderer = new _marked.Renderer();
let msg = null;
renderer.code = function(code, lang, escaped) {
if (this.options.highlight) {
const out = this.options.highlight(code, lang);
if (out != null && out !== code) {
escaped = true;
code = out;
}
}
let text = null;
if (!lang) {
text = `<pre><code class="code-colors hljs">${ (escaped ? code : s.escapeHTML(code, true)) }</code></pre>`;
} else {
text = `<pre><code class="code-colors hljs ${ escape(lang, true) }">${ (escaped ? code : s.escapeHTML(code, true)) }</code></pre>`;
}
if (_.isString(msg)) {
return text;
}
const token = `=!=${ Random.id() }=!=`;
msg.tokens.push({
highlight: true,
token,
text
});
return token;
};
renderer.codespan = function(text) {
text = `<code class="code-colors inline">${ text }</code>`;
if (_.isString(msg)) {
return text;
}
const token = `=!=${ Random.id() }=!=`;
msg.tokens.push({
token,
text
});
return token;
};
renderer.blockquote = function(quote) {
return `<blockquote class="background-transparent-darker-before">${ quote }</blockquote>`;
};
const highlight = function(code, lang) {
if (!lang) {
return code;
}
try {
return hljs.highlight(lang, code).value;
} catch (e) {
// Unknown language
return code;
}
};
let gfm = null;
let tables = null;
let breaks = null;
let pedantic = null;
let smartLists = null;
let smartypants = null;
export const marked = (message) => {
msg = message;
if (!msg.tokens) {
msg.tokens = [];
}
if (gfm == null) { gfm = RocketChat.settings.get('Markdown_Marked_GFM'); }
if (tables == null) { tables = RocketChat.settings.get('Markdown_Marked_Tables'); }
if (breaks == null) { breaks = RocketChat.settings.get('Markdown_Marked_Breaks'); }
if (pedantic == null) { pedantic = RocketChat.settings.get('Markdown_Marked_Pedantic'); }
if (smartLists == null) { smartLists = RocketChat.settings.get('Markdown_Marked_SmartLists'); }
if (smartypants == null) { smartypants = RocketChat.settings.get('Markdown_Marked_Smartypants'); }
msg.html = _marked(s.unescapeHTML(msg.html), {
gfm,
tables,
breaks,
pedantic,
smartLists,
smartypants,
renderer,
sanitize: true,
highlight
});
return msg;
};
|
define('lodash/lang/isEqual', ['exports', 'lodash/internal/baseIsEqual', 'lodash/internal/bindCallback'], function (exports, _lodashInternalBaseIsEqual, _lodashInternalBindCallback) {
'use strict';
/**
* Performs a deep comparison between two values to determine if they are
* equivalent. If `customizer` is provided it's invoked to compare values.
* If `customizer` returns `undefined` comparisons are handled by the method
* instead. The `customizer` is bound to `thisArg` and invoked with up to
* three arguments: (value, other [, index|key]).
*
* **Note:** This method supports comparing arrays, booleans, `Date` objects,
* numbers, `Object` objects, regexes, and strings. Objects are compared by
* their own, not inherited, enumerable properties. Functions and DOM nodes
* are **not** supported. Provide a customizer function to extend support
* for comparing other values.
*
* @static
* @memberOf _
* @alias eq
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {Function} [customizer] The function to customize value comparisons.
* @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'user': 'fred' };
* var other = { 'user': 'fred' };
*
* object == other;
* // => false
*
* _.isEqual(object, other);
* // => true
*
* // using a customizer callback
* var array = ['hello', 'goodbye'];
* var other = ['hi', 'goodbye'];
*
* _.isEqual(array, other, function(value, other) {
* if (_.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/)) {
* return true;
* }
* });
* // => true
*/
function isEqual(value, other, customizer, thisArg) {
customizer = typeof customizer == 'function' ? (0, _lodashInternalBindCallback['default'])(customizer, thisArg, 3) : undefined;
var result = customizer ? customizer(value, other) : undefined;
return result === undefined ? (0, _lodashInternalBaseIsEqual['default'])(value, other, customizer) : !!result;
}
exports['default'] = isEqual;
}); |
/*!
* VERSION: 0.2.1
* DATE: 2017-01-17
* UPDATES AND DOCS AT: http://greensock.com
*
* @license Copyright (c) 2008-2017, GreenSock. All rights reserved.
* This work is subject to the terms at http://greensock.com/standard-license or for
* Club GreenSock members, the software agreement that was issued with your membership.
*
* @author: Jack Doyle, [email protected]
**/
var _gsScope = (typeof(module) !== "undefined" && module.exports && typeof(global) !== "undefined") ? global : this || window; //helps ensure compatibility with AMD/RequireJS and CommonJS/Node
(_gsScope._gsQueue || (_gsScope._gsQueue = [])).push( function() {
"use strict";
var _numExp = /(\d|\.)+/g,
_ColorFilter, _ColorMatrixFilter,
_colorProps = ["redMultiplier","greenMultiplier","blueMultiplier","alphaMultiplier","redOffset","greenOffset","blueOffset","alphaOffset"],
_colorLookup = {aqua:[0,255,255],
lime:[0,255,0],
silver:[192,192,192],
black:[0,0,0],
maroon:[128,0,0],
teal:[0,128,128],
blue:[0,0,255],
navy:[0,0,128],
white:[255,255,255],
fuchsia:[255,0,255],
olive:[128,128,0],
yellow:[255,255,0],
orange:[255,165,0],
gray:[128,128,128],
purple:[128,0,128],
green:[0,128,0],
red:[255,0,0],
pink:[255,192,203],
cyan:[0,255,255],
transparent:[255,255,255,0]},
_parseColor = function(color) {
if (color === "" || color == null || color === "none") {
return _colorLookup.transparent;
} else if (_colorLookup[color]) {
return _colorLookup[color];
} else if (typeof(color) === "number") {
return [color >> 16, (color >> 8) & 255, color & 255];
} else if (color.charAt(0) === "#") {
if (color.length === 4) { //for shorthand like #9F0
color = "#" + color.charAt(1) + color.charAt(1) + color.charAt(2) + color.charAt(2) + color.charAt(3) + color.charAt(3);
}
color = parseInt(color.substr(1), 16);
return [color >> 16, (color >> 8) & 255, color & 255];
}
return color.match(_numExp) || _colorLookup.transparent;
},
_parseColorFilter = function(t, v, pg) {
if (!_ColorFilter) {
_ColorFilter = (_gsScope.ColorFilter || _gsScope.createjs.ColorFilter);
if (!_ColorFilter) {
throw("EaselPlugin error: The EaselJS ColorFilter JavaScript file wasn't loaded.");
}
}
var filters = t.filters || [],
i = filters.length,
c, s, e, a, p;
while (--i > -1) {
if (filters[i] instanceof _ColorFilter) {
s = filters[i];
break;
}
}
if (!s) {
s = new _ColorFilter();
filters.push(s);
t.filters = filters;
}
e = s.clone();
if (v.tint != null) {
c = _parseColor(v.tint);
a = (v.tintAmount != null) ? Number(v.tintAmount) : 1;
e.redOffset = Number(c[0]) * a;
e.greenOffset = Number(c[1]) * a;
e.blueOffset = Number(c[2]) * a;
e.redMultiplier = e.greenMultiplier = e.blueMultiplier = 1 - a;
} else {
for (p in v) {
if (p !== "exposure") if (p !== "brightness") {
e[p] = Number(v[p]);
}
}
}
if (v.exposure != null) {
e.redOffset = e.greenOffset = e.blueOffset = 255 * (Number(v.exposure) - 1);
e.redMultiplier = e.greenMultiplier = e.blueMultiplier = 1;
} else if (v.brightness != null) {
a = Number(v.brightness) - 1;
e.redOffset = e.greenOffset = e.blueOffset = (a > 0) ? a * 255 : 0;
e.redMultiplier = e.greenMultiplier = e.blueMultiplier = 1 - Math.abs(a);
}
i = 8;
while (--i > -1) {
p = _colorProps[i];
if (s[p] !== e[p]) {
pg._addTween(s, p, s[p], e[p], "easel_colorFilter");
}
}
pg._overwriteProps.push("easel_colorFilter");
if (!t.cacheID) {
throw("EaselPlugin warning: for filters to display in EaselJS, you must call the object's cache() method first. " + t);
}
},
_idMatrix = [1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],
_lumR = 0.212671,
_lumG = 0.715160,
_lumB = 0.072169,
_applyMatrix = function(m, m2) {
if (!(m instanceof Array) || !(m2 instanceof Array)) {
return m2;
}
var temp = [],
i = 0,
z = 0,
y, x;
for (y = 0; y < 4; y++) {
for (x = 0; x < 5; x++) {
z = (x === 4) ? m[i + 4] : 0;
temp[i + x] = m[i] * m2[x] + m[i+1] * m2[x + 5] + m[i+2] * m2[x + 10] + m[i+3] * m2[x + 15] + z;
}
i += 5;
}
return temp;
},
_setSaturation = function(m, n) {
if (isNaN(n)) {
return m;
}
var inv = 1 - n,
r = inv * _lumR,
g = inv * _lumG,
b = inv * _lumB;
return _applyMatrix([r + n, g, b, 0, 0, r, g + n, b, 0, 0, r, g, b + n, 0, 0, 0, 0, 0, 1, 0], m);
},
_colorize = function(m, color, amount) {
if (isNaN(amount)) {
amount = 1;
}
var c = _parseColor(color),
r = c[0] / 255,
g = c[1] / 255,
b = c[2] / 255,
inv = 1 - amount;
return _applyMatrix([inv + amount * r * _lumR, amount * r * _lumG, amount * r * _lumB, 0, 0, amount * g * _lumR, inv + amount * g * _lumG, amount * g * _lumB, 0, 0, amount * b * _lumR, amount * b * _lumG, inv + amount * b * _lumB, 0, 0, 0, 0, 0, 1, 0], m);
},
_setHue = function(m, n) {
if (isNaN(n)) {
return m;
}
n *= Math.PI / 180;
var c = Math.cos(n),
s = Math.sin(n);
return _applyMatrix([(_lumR + (c * (1 - _lumR))) + (s * (-_lumR)), (_lumG + (c * (-_lumG))) + (s * (-_lumG)), (_lumB + (c * (-_lumB))) + (s * (1 - _lumB)), 0, 0, (_lumR + (c * (-_lumR))) + (s * 0.143), (_lumG + (c * (1 - _lumG))) + (s * 0.14), (_lumB + (c * (-_lumB))) + (s * -0.283), 0, 0, (_lumR + (c * (-_lumR))) + (s * (-(1 - _lumR))), (_lumG + (c * (-_lumG))) + (s * _lumG), (_lumB + (c * (1 - _lumB))) + (s * _lumB), 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1], m);
},
_setContrast = function(m, n) {
if (isNaN(n)) {
return m;
}
n += 0.01;
return _applyMatrix([n,0,0,0,128 * (1 - n), 0,n,0,0,128 * (1 - n), 0,0,n,0,128 * (1 - n), 0,0,0,1,0], m);
},
_parseColorMatrixFilter = function(t, v, pg) {
if (!_ColorMatrixFilter) {
_ColorMatrixFilter = (_gsScope.ColorMatrixFilter || _gsScope.createjs.ColorMatrixFilter);
if (!_ColorMatrixFilter) {
throw("EaselPlugin error: The EaselJS ColorMatrixFilter JavaScript file wasn't loaded.");
}
}
var filters = t.filters || [],
i = filters.length,
matrix, startMatrix, s;
while (--i > -1) {
if (filters[i] instanceof _ColorMatrixFilter) {
s = filters[i];
break;
}
}
if (!s) {
s = new _ColorMatrixFilter(_idMatrix.slice());
filters.push(s);
t.filters = filters;
}
startMatrix = s.matrix;
matrix = _idMatrix.slice();
if (v.colorize != null) {
matrix = _colorize(matrix, v.colorize, Number(v.colorizeAmount));
}
if (v.contrast != null) {
matrix = _setContrast(matrix, Number(v.contrast));
}
if (v.hue != null) {
matrix = _setHue(matrix, Number(v.hue));
}
if (v.saturation != null) {
matrix = _setSaturation(matrix, Number(v.saturation));
}
i = matrix.length;
while (--i > -1) {
if (matrix[i] !== startMatrix[i]) {
pg._addTween(startMatrix, i, startMatrix[i], matrix[i], "easel_colorMatrixFilter");
}
}
pg._overwriteProps.push("easel_colorMatrixFilter");
if (!t.cacheID) {
throw("EaselPlugin warning: for filters to display in EaselJS, you must call the object's cache() method first. " + t);
}
pg._matrix = startMatrix;
};
_gsScope._gsDefine.plugin({
propName: "easel",
priority: -1,
version: "0.2.1",
API: 2,
//called when the tween renders for the first time. This is where initial values should be recorded and any setup routines should run.
init: function(target, value, tween, index) {
this._target = target;
var p, pt, tint, colorMatrix, end, labels, i;
for (p in value) {
end = value[p];
if (typeof(end) === "function") {
end = end(index, target);
}
if (p === "colorFilter" || p === "tint" || p === "tintAmount" || p === "exposure" || p === "brightness") {
if (!tint) {
_parseColorFilter(target, value.colorFilter || value, this);
tint = true;
}
} else if (p === "saturation" || p === "contrast" || p === "hue" || p === "colorize" || p === "colorizeAmount") {
if (!colorMatrix) {
_parseColorMatrixFilter(target, value.colorMatrixFilter || value, this);
colorMatrix = true;
}
} else if (p === "frame") {
this._firstPT = pt = {_next:this._firstPT, t:target, p:"gotoAndStop", s:target.currentFrame, f:true, n:"frame", pr:0, type:0, m:Math.round};
if (typeof(end) === "string" && end.charAt(1) !== "=" && (labels = target.labels)) {
for (i = 0; i < labels.length; i++) {
if (labels[i].label === end) {
end = labels[i].position;
}
}
}
pt.c = (typeof(end) === "number") ? end - pt.s : parseFloat((end+"").split("=").join(""));
if (pt._next) {
pt._next._prev = pt;
}
} else if (target[p] != null) {
this._firstPT = pt = {_next:this._firstPT, t:target, p:p, f:(typeof(target[p]) === "function"), n:p, pr:0, type:0};
pt.s = (!pt.f) ? parseFloat(target[p]) : target[ ((p.indexOf("set") || typeof(target["get" + p.substr(3)]) !== "function") ? p : "get" + p.substr(3)) ]();
pt.c = (typeof(end) === "number") ? end - pt.s : (typeof(end) === "string") ? parseFloat(end.split("=").join("")) : 0;
if (pt._next) {
pt._next._prev = pt;
}
}
}
return true;
},
//called each time the values should be updated, and the ratio gets passed as the only parameter (typically it's a value between 0 and 1, but it can exceed those when using an ease like Elastic.easeOut or Back.easeOut, etc.)
set: function(v) {
var pt = this._firstPT,
min = 0.000001,
val;
while (pt) {
val = pt.c * v + pt.s;
if (pt.m) {
val = pt.m(val, pt.t);
} else if (val < min && val > -min) {
val = 0;
}
if (pt.f) {
pt.t[pt.p](val);
} else {
pt.t[pt.p] = val;
}
pt = pt._next;
}
if (this._target.cacheID) {
this._target.updateCache();
}
}
});
}); if (_gsScope._gsDefine) { _gsScope._gsQueue.pop()(); }
//export to AMD/RequireJS and CommonJS/Node (precursor to full modular build system coming at a later date)
(function(name) {
"use strict";
var getGlobal = function() {
return (_gsScope.GreenSockGlobals || _gsScope)[name];
};
if (typeof(define) === "function" && define.amd) { //AMD
define(["./TweenLite"], getGlobal);
} else if (typeof(module) !== "undefined" && module.exports) { //node
require("./TweenLite.js");
module.exports = getGlobal();
}
}("EaselPlugin")); |
"use strict";import"../parts-3d/Math.js";import"../parts-3d/SVGRenderer.js";import"../parts-3d/Chart.js";import"../parts-3d/Axis.js";import"../parts-3d/Series.js";import"../parts-3d/Column.js";import"../parts-3d/Pie.js";import"../parts-3d/Scatter.js";import"../parts-3d/VMLRenderer.js"; |
/**
Breaks up a long string
@method breakUp
@for Handlebars
**/
Handlebars.registerHelper('breakUp', function(property, hint, options) {
var prop = Ember.Handlebars.get(this, property, options);
if (!prop) return "";
hint = Ember.Handlebars.get(this, hint, options);
return Discourse.Formatter.breakUp(prop, hint);
});
/**
Truncates long strings
@method shorten
@for Handlebars
**/
Handlebars.registerHelper('shorten', function(property, options) {
return Ember.Handlebars.get(this, property, options).substring(0,35);
});
/**
Produces a link to a topic
@method topicLink
@for Handlebars
**/
Handlebars.registerHelper('topicLink', function(property, options) {
var topic = Ember.Handlebars.get(this, property, options),
title = topic.get('fancy_title') || topic.get('title');
return "<a href='" + topic.get('lastUnreadUrl') + "' class='title'>" + title + "</a>";
});
/**
Produces a link to a category given a category object and helper options
@method categoryLinkHTML
@param {Discourse.Category} category to link to
@param {Object} options standard from handlebars
**/
function categoryLinkHTML(category, options) {
var categoryOptions = {};
if (options.hash) {
if (options.hash.allowUncategorized) {
categoryOptions.allowUncategorized = true;
}
if (options.hash.categories) {
categoryOptions.categories = Em.Handlebars.get(this, options.hash.categories, options);
}
}
return new Handlebars.SafeString(Discourse.HTML.categoryLink(category, categoryOptions));
}
/**
Produces a link to a category
@method categoryLink
@for Handlebars
**/
Handlebars.registerHelper('categoryLink', function(property, options) {
return categoryLinkHTML(Ember.Handlebars.get(this, property, options), options);
});
Handlebars.registerHelper('categoryLinkRaw', function(property, options) {
return categoryLinkHTML(property, options);
});
/**
Produces a bound link to a category
@method boundCategoryLink
@for Handlebars
**/
Ember.Handlebars.registerBoundHelper('boundCategoryLink', categoryLinkHTML);
/**
Produces a link to a route with support for i18n on the title
@method titledLinkTo
@for Handlebars
**/
Handlebars.registerHelper('titledLinkTo', function(name, object) {
var options = [].slice.call(arguments, -1)[0];
if (options.hash.titleKey) {
options.hash.title = I18n.t(options.hash.titleKey);
}
if (arguments.length === 3) {
return Ember.Handlebars.helpers.linkTo.call(this, name, object, options);
} else {
return Ember.Handlebars.helpers.linkTo.call(this, name, options);
}
});
/**
Shorten a URL for display by removing common components
@method shortenUrl
@for Handlebars
**/
Handlebars.registerHelper('shortenUrl', function(property, options) {
var url;
url = Ember.Handlebars.get(this, property, options);
// Remove trailing slash if it's a top level URL
if (url.match(/\//g).length === 3) {
url = url.replace(/\/$/, '');
}
url = url.replace(/^https?:\/\//, '');
url = url.replace(/^www\./, '');
return url.substring(0,80);
});
/**
Display a property in lower case
@method lower
@for Handlebars
**/
Handlebars.registerHelper('lower', function(property, options) {
var o;
o = Ember.Handlebars.get(this, property, options);
if (o && typeof o === 'string') {
return o.toLowerCase();
} else {
return "";
}
});
/**
Show an avatar for a user, intelligently making use of available properties
@method avatar
@for Handlebars
**/
Handlebars.registerHelper('avatar', function(user, options) {
if (typeof user === 'string') {
user = Ember.Handlebars.get(this, user, options);
}
if (user) {
var username = Em.get(user, 'username');
if (!username) username = Em.get(user, options.hash.usernamePath);
var avatarTemplate;
var template = options.hash.template;
if (template && template !== 'avatar_template') {
avatarTemplate = Em.get(user, template);
if (!avatarTemplate) avatarTemplate = Em.get(user, 'user.' + template);
}
if (!avatarTemplate) avatarTemplate = Em.get(user, 'avatar_template');
if (!avatarTemplate) avatarTemplate = Em.get(user, 'user.avatar_template');
var title;
if (!options.hash.ignoreTitle) {
// first try to get a title
title = Em.get(user, 'title');
// if there was no title provided
if (!title) {
// try to retrieve a description
var description = Em.get(user, 'description');
// if a description has been provided
if (description && description.length > 0) {
// preprend the username before the description
title = username + " - " + description;
}
}
}
return new Handlebars.SafeString(Discourse.Utilities.avatarImg({
size: options.hash.imageSize,
extraClasses: Em.get(user, 'extras') || options.hash.extraClasses,
title: title || username,
avatarTemplate: avatarTemplate
}));
} else {
return '';
}
});
/**
Bound avatar helper.
Will rerender whenever the "avatar_template" changes.
@method boundAvatar
@for Handlebars
**/
Ember.Handlebars.registerBoundHelper('boundAvatar', function(user, options) {
return new Handlebars.SafeString(Discourse.Utilities.avatarImg({
size: options.hash.imageSize,
avatarTemplate: Em.get(user, options.hash.template || 'avatar_template')
}));
}, 'avatar_template', 'uploaded_avatar_template', 'gravatar_template');
/**
Nicely format a date without a binding since the date doesn't need to change.
@method unboundDate
@for Handlebars
**/
Handlebars.registerHelper('unboundDate', function(property, options) {
var dt = new Date(Ember.Handlebars.get(this, property, options));
return Discourse.Formatter.longDate(dt);
});
/**
Live refreshing age helper
@method unboundDate
@for Handlebars
**/
Handlebars.registerHelper('unboundAge', function(property, options) {
var dt = new Date(Ember.Handlebars.get(this, property, options));
return new Handlebars.SafeString(Discourse.Formatter.autoUpdatingRelativeAge(dt));
});
/**
Live refreshing age helper, with a tooltip showing the date and time
@method unboundAgeWithTooltip
@for Handlebars
**/
Handlebars.registerHelper('unboundAgeWithTooltip', function(property, options) {
var dt = new Date(Ember.Handlebars.get(this, property, options));
return new Handlebars.SafeString(Discourse.Formatter.autoUpdatingRelativeAge(dt, {title: true}));
});
/**
Display a date related to an edit of a post
@method editDate
@for Handlebars
**/
Handlebars.registerHelper('editDate', function(property, options) {
// autoupdating this is going to be painful
var date = new Date(Ember.Handlebars.get(this, property, options));
return new Handlebars.SafeString(Discourse.Formatter.autoUpdatingRelativeAge(date, {format: 'medium', title: true, leaveAgo: true, wrapInSpan: false}));
});
/**
Displays a percentile based on a `percent_rank` field
@method percentile
@for Ember.Handlebars
**/
Ember.Handlebars.registerHelper('percentile', function(property, options) {
var percentile = Ember.Handlebars.get(this, property, options);
return Math.round((1.0 - percentile) * 100);
});
/**
Displays a float nicely
@method float
@for Ember.Handlebars
**/
Ember.Handlebars.registerHelper('float', function(property, options) {
var x = Ember.Handlebars.get(this, property, options);
if (!x) return "0";
if (Math.round(x) === x) return x;
return x.toFixed(3);
});
/**
Display logic for numbers.
@method number
@for Handlebars
**/
Handlebars.registerHelper('number', function(property, options) {
var orig = parseInt(Ember.Handlebars.get(this, property, options), 10);
if (isNaN(orig)) { orig = 0; }
var title = orig;
if (options.hash.numberKey) {
title = I18n.t(options.hash.numberKey, { number: orig });
}
// Round off the thousands to one decimal place
var n = orig;
if (orig > 999 && !options.hash.noTitle) {
n = (orig / 1000).toFixed(1) + "K";
}
var classNames = 'number';
if (options.hash['class']) {
classNames += ' ' + Ember.Handlebars.get(this, options.hash['class'], options);
}
var result = "<span class='" + classNames + "'";
if (n !== title) {
result += " title='" + Handlebars.Utils.escapeExpression(title) + "'";
}
result += ">" + n + "</span>";
return new Handlebars.SafeString(result);
});
/**
Display logic for dates.
@method date
@for Handlebars
**/
Handlebars.registerHelper('date', function(property, options) {
var leaveAgo;
if (property.hash) {
if (property.hash.leaveAgo) {
leaveAgo = property.hash.leaveAgo === "true";
}
if (property.hash.path) {
property = property.hash.path;
}
}
var val = Ember.Handlebars.get(this, property, options);
if (val) {
var date = new Date(val);
return new Handlebars.SafeString(Discourse.Formatter.autoUpdatingRelativeAge(date, {format: 'medium', title: true, leaveAgo: leaveAgo}));
}
});
/**
Look for custom html content in the preload store.
@method customHTML
@for Handlebars
**/
Handlebars.registerHelper('customHTML', function(property) {
var html = PreloadStore.get("customHTML");
if (html && html[property] && html[property].length) {
return new Handlebars.SafeString(html[property]);
}
});
|
'use strict';
const styles = require('./styles');
const permsToString = require('./perms-to-string');
const sizeToString = require('./size-to-string');
const sortFiles = require('./sort-files');
const fs = require('fs');
const path = require('path');
const he = require('he');
const etag = require('../etag');
const url = require('url');
const status = require('../status-handlers');
const supportedIcons = styles.icons;
const css = styles.css;
module.exports = (opts) => {
// opts are parsed by opts.js, defaults already applied
const cache = opts.cache;
const root = path.resolve(opts.root);
const baseDir = opts.baseDir;
const humanReadable = opts.humanReadable;
const hidePermissions = opts.hidePermissions;
const handleError = opts.handleError;
const showDotfiles = opts.showDotfiles;
const si = opts.si;
const weakEtags = opts.weakEtags;
return function middleware(req, res, next) {
// Figure out the path for the file from the given url
const parsed = url.parse(req.url);
const pathname = decodeURIComponent(parsed.pathname);
const dir = path.normalize(
path.join(
root,
path.relative(
path.join('/', baseDir),
pathname
)
)
);
fs.stat(dir, (statErr, stat) => {
if (statErr) {
if (handleError) {
status[500](res, next, { error: statErr });
} else {
next();
}
return;
}
// files are the listing of dir
fs.readdir(dir, (readErr, _files) => {
let files = _files;
if (readErr) {
if (handleError) {
status[500](res, next, { error: readErr });
} else {
next();
}
return;
}
// Optionally exclude dotfiles from directory listing.
if (!showDotfiles) {
files = files.filter(filename => filename.slice(0, 1) !== '.');
}
res.setHeader('content-type', 'text/html');
res.setHeader('etag', etag(stat, weakEtags));
res.setHeader('last-modified', (new Date(stat.mtime)).toUTCString());
res.setHeader('cache-control', cache);
function render(dirs, renderFiles, lolwuts) {
// each entry in the array is a [name, stat] tuple
let html = `${[
'<!doctype html>',
'<html>',
' <head>',
' <meta charset="utf-8">',
' <meta name="viewport" content="width=device-width">',
` <title>Index of ${he.encode(pathname)}</title>`,
` <style type="text/css">${css}</style>`,
' </head>',
' <body>',
`<h1>Index of ${he.encode(pathname)}</h1>`,
].join('\n')}\n`;
html += '<table>';
const failed = false;
const writeRow = (file) => {
// render a row given a [name, stat] tuple
const isDir = file[1].isDirectory && file[1].isDirectory();
let href = `${parsed.pathname.replace(/\/$/, '')}/${encodeURIComponent(file[0])}`;
// append trailing slash and query for dir entry
if (isDir) {
href += `/${he.encode((parsed.search) ? parsed.search : '')}`;
}
const displayName = he.encode(file[0]) + ((isDir) ? '/' : '');
const ext = file[0].split('.').pop();
const classForNonDir = supportedIcons[ext] ? ext : '_page';
const iconClass = `icon-${isDir ? '_blank' : classForNonDir}`;
// TODO: use stylessheets?
html += `${'<tr>' +
'<td><i class="icon '}${iconClass}"></i></td>`;
if (!hidePermissions) {
html += `<td class="perms"><code>(${permsToString(file[1])})</code></td>`;
}
html +=
`<td class="file-size"><code>${sizeToString(file[1], humanReadable, si)}</code></td>` +
`<td class="display-name"><a href="${href}">${displayName}</a></td>` +
'</tr>\n';
};
dirs.sort((a, b) => a[0].toString().localeCompare(b[0].toString())).forEach(writeRow);
renderFiles.sort((a, b) => a.toString().localeCompare(b.toString())).forEach(writeRow);
lolwuts.sort((a, b) => a[0].toString().localeCompare(b[0].toString())).forEach(writeRow);
html += '</table>\n';
html += `<br><address>Node.js ${
process.version
}/ <a href="https://github.com/jfhbrook/node-ecstatic">ecstatic</a> ` +
`server running @ ${
he.encode(req.headers.host || '')}</address>\n` +
'</body></html>'
;
if (!failed) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(html);
}
}
sortFiles(dir, files, (lolwuts, dirs, sortedFiles) => {
// It's possible to get stat errors for all sorts of reasons here.
// Unfortunately, our two choices are to either bail completely,
// or just truck along as though everything's cool. In this case,
// I decided to just tack them on as "??!?" items along with dirs
// and files.
//
// Whatever.
// if it makes sense to, add a .. link
if (path.resolve(dir, '..').slice(0, root.length) === root) {
fs.stat(path.join(dir, '..'), (err, s) => {
if (err) {
if (handleError) {
status[500](res, next, { error: err });
} else {
next();
}
return;
}
dirs.unshift(['..', s]);
render(dirs, sortedFiles, lolwuts);
});
} else {
render(dirs, sortedFiles, lolwuts);
}
});
});
});
};
};
|
'use strict'
const assert = require('assert')
const http = require('http')
const https = require('https')
const { kState, kOptions } = require('./symbols')
const {
codes: { FST_ERR_HTTP2_INVALID_VERSION }
} = require('./errors')
function createServer (options, httpHandler) {
assert(options, 'Missing options')
assert(httpHandler, 'Missing http handler')
var server = null
if (options.serverFactory) {
server = options.serverFactory(httpHandler, options)
} else if (options.https) {
if (options.http2) {
server = http2().createSecureServer(options.https, httpHandler)
} else {
server = https.createServer(options.https, httpHandler)
}
} else if (options.http2) {
server = http2().createServer(httpHandler)
server.on('session', sessionTimeout(options.http2SessionTimeout))
} else {
server = http.createServer(httpHandler)
}
return { server, listen }
// `this` is the Fastify object
function listen () {
const normalizeListenArgs = (args) => {
if (args.length === 0) {
return { port: 0, host: 'localhost' }
}
const cb = typeof args[args.length - 1] === 'function' ? args.pop() : undefined
const options = { cb: cb }
const firstArg = args[0]
const argsLength = args.length
const lastArg = args[argsLength - 1]
/* Deal with listen (options) || (handle[, backlog]) */
if (typeof firstArg === 'object' && firstArg !== null) {
options.backlog = argsLength > 1 ? lastArg : undefined
Object.assign(options, firstArg)
} else if (typeof firstArg === 'string' && isNaN(firstArg)) {
/* Deal with listen (pipe[, backlog]) */
options.path = firstArg
options.backlog = argsLength > 1 ? lastArg : undefined
} else {
/* Deal with listen ([port[, host[, backlog]]]) */
options.port = argsLength >= 1 && firstArg ? firstArg : 0
// This will listen to what localhost is.
// It can be 127.0.0.1 or ::1, depending on the operating system.
// Fixes https://github.com/fastify/fastify/issues/1022.
options.host = argsLength >= 2 && args[1] ? args[1] : 'localhost'
options.backlog = argsLength >= 3 ? args[2] : undefined
}
return options
}
const listenOptions = normalizeListenArgs(Array.from(arguments))
const cb = listenOptions.cb
const wrap = err => {
server.removeListener('error', wrap)
if (!err) {
const address = logServerAddress()
cb(null, address)
} else {
this[kState].listening = false
cb(err, null)
}
}
const listenPromise = (listenOptions) => {
if (this[kState].listening) {
return Promise.reject(new Error('Fastify is already listening'))
}
return this.ready().then(() => {
var errEventHandler
var errEvent = new Promise((resolve, reject) => {
errEventHandler = (err) => {
this[kState].listening = false
reject(err)
}
server.once('error', errEventHandler)
})
var listen = new Promise((resolve, reject) => {
server.listen(listenOptions, () => {
server.removeListener('error', errEventHandler)
resolve(logServerAddress())
})
// we set it afterwards because listen can throw
this[kState].listening = true
})
return Promise.race([
errEvent, // e.g invalid port range error is always emitted before the server listening
listen
])
})
}
const logServerAddress = () => {
var address = server.address()
const isUnixSocket = typeof address === 'string'
if (!isUnixSocket) {
if (address.address.indexOf(':') === -1) {
address = address.address + ':' + address.port
} else {
address = '[' + address.address + ']:' + address.port
}
}
address = (isUnixSocket ? '' : ('http' + (this[kOptions].https ? 's' : '') + '://')) + address
this.log.info('Server listening at ' + address)
return address
}
if (cb === undefined) return listenPromise(listenOptions)
this.ready(err => {
if (err != null) return cb(err)
if (this[kState].listening) {
return cb(new Error('Fastify is already listening'), null)
}
server.once('error', wrap)
server.listen(listenOptions, wrap)
this[kState].listening = true
})
}
}
function http2 () {
try {
return require('http2')
} catch (err) {
throw new FST_ERR_HTTP2_INVALID_VERSION()
}
}
function sessionTimeout (timeout) {
return function (session) {
session.setTimeout(timeout, close)
}
}
function close () {
this.close()
}
module.exports = { createServer }
|
module.exports={title:"LiveChat",slug:"livechat",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>LiveChat</title><path d="'+this.path+'"/></svg>'},path:"M23.849 14.91c-.24 2.94-2.73 5.22-5.7 5.19h-3.15l-6 3.9v-3.9l6-3.9h3.15c.93.03 1.71-.66 1.83-1.59.18-3 .18-6-.06-9-.06-.84-.75-1.47-1.56-1.53-2.04-.09-4.2-.18-6.36-.18s-4.32.06-6.36.21c-.84.06-1.5.69-1.56 1.53-.21 3-.24 6-.06 9 .09.93.9 1.59 1.83 1.56h3.15v3.9h-3.15a5.644 5.644 0 01-5.7-5.19c-.21-3.21-.18-6.39.06-9.6a5.57 5.57 0 015.19-5.1c2.1-.15 4.35-.21 6.6-.21s4.5.06 6.63.24a5.57 5.57 0 015.19 5.1c.21 3.18.24 6.39.03 9.57z",source:"https://livechat.design/",hex:"FFD000",guidelines:"https://livechat.design/",license:void 0}; |
// PhantomJS is missing Function.prototype.bind:
// http://code.google.com/p/phantomjs/issues/detail?id=522
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP && oThis
? this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
|
export default function identity(x) {
return x;
}
|
Subsets and Splits