code
stringlengths 2
1.05M
| repo_name
stringlengths 5
114
| path
stringlengths 4
991
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
---|---|---|---|---|---|
/**
* 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;
| janvt/Ghost | core/server/lib/common/events.js | JavaScript | mit | 911 |
/*! 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)}); | meso-unimpressed/pallet | public/javascripts/jquery-ui/ui/i18n/jquery.ui.datepicker-hy.min.js | JavaScript | mit | 1,126 |
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,
}
| chromakode/react-html-email | src/index.js | JavaScript | mit | 676 |
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();
| georgiy-abbasov/testcafe-hammerhead | src/processing/resources/manifest.js | JavaScript | mit | 1,000 |
/*
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'
});
| chiave/gamp | public_html/ckeditor/plugins/flash/lang/fo.js | JavaScript | mit | 1,374 |
/**
* @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);
});
}
}]);
| mallowigi/angular-filter | src/_filter/collection/map.js | JavaScript | mit | 572 |
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;
}
| workcraft/workcraft | ci/flow-mpsat-g/test.js | JavaScript | mit | 3,041 |
(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("希望能够让更多的获取知识,加油!"); | lenbo-ma/gso | public/javascripts/main.js | JavaScript | mit | 1,797 |
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"
})
);
| synico/springframework | lobtool/src/main/webapp/resources/javascript/dojox/editor/plugins/nls/es/TableDialog.js | JavaScript | mit | 935 |
/* 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);
}
});
| carto-tragsatec/visorCatastroColombia | WebContent/visorcatastrocol/lib/geoext/v3.1.0/src/component/Map.js | JavaScript | mit | 14,751 |
/* @flow */
export default function extractSupportQuery(ruleSet: string): string {
return ruleSet
.split('{')[0]
.slice(9)
.trim()
}
| derek-duncan/fela | packages/fela-utils/src/extractSupportQuery.js | JavaScript | mit | 147 |
// ## 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');
});
| MikeiLL/HealthyHappyHarmony | gulpfile.js | JavaScript | mit | 8,996 |
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');
});
| wedgex/ember-bootstrap-daterange | tests/unit/components/daterange-picker-test.js | JavaScript | mit | 493 |
/* 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.
*
*/
| jrlarsen/AdventuresInJavaScript | Ch04_Functions/listing4.02.js | JavaScript | mit | 1,566 |
'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 }));
}
}); | raskolnikova/infomaps | node_modules/elemental/lib/components/Row.js | JavaScript | mit | 1,695 |
version https://git-lfs.github.com/spec/v1
oid sha256:ba35426ce7731b677aeb9fca46043dc31d9cd6a87abedb15382e4c3bc001b548
size 1760
| yogeshsaroya/new-cdnjs | ajax/libs/dojo/1.7.2/gears.js.uncompressed.js | JavaScript | mit | 129 |
// 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));
};
| rybon/Remocial | node_modules/socketstream/lib/socketstream.js | JavaScript | mit | 4,404 |
"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 | binariedMe/blogging | node_modules/angular2/node_modules/@reactivex/rxjs/dist/cjs/util/isDate.js | JavaScript | mit | 258 |
/**
* # 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;
}); | SvDvorak/stitches | src/js/wrap/modernizr.js | JavaScript | mit | 266 |
/*!
* 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);
}
})();
| Nightsuki/AVDir | theme/admin/static/editor.md/plugins/reference-link-dialog/reference-link-dialog.js | JavaScript | mit | 5,283 |
'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 | binariedMe/blogging | node_modules/angular2/node_modules/@reactivex/rxjs/dist/cjs/operators/publish.js | JavaScript | mit | 623 |
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');
})
}); | ksanaforge/swjzz | index.js | JavaScript | mit | 598 |
;(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();
}
}
});
})();
| aliaraaab/xin-arch | js/app/app.js | JavaScript | mit | 3,178 |
import getDocument from './get-document';
export default function(node) {
const _document = getDocument(node);
return _document.defaultView || window;
}
| DNACodeStudios/ally.js | src/util/get-window.js | JavaScript | mit | 159 |
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 }
]
);
});
});
| rlugojr/bower | test/commands/unregister.js | JavaScript | mit | 2,413 |
"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; | cdnjs/cdnjs | ajax/libs/material-ui/5.0.0-alpha.27/node/Card/Card.js | JavaScript | mit | 3,406 |
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']]]
];
| v8-dox/v8-dox.github.io | e1c9761/html/search/all_4.js | JavaScript | mit | 3,498 |
module.exports = function (app) {
app.get('/', function (req, res) {
if (req.logout) {
req.logout();
}
res.redirect('/');
});
}; | jgable/node-site | server/routes/logout.js | JavaScript | mit | 174 |
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;
});
| sjcobb/nfl-data-muncher | nfl-data-muncher/lib/dijit/BackgroundIframe.js | JavaScript | mit | 3,629 |
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()
}
}
}
};
| unimonkiez/react-cordova-boilerplate | bin/webpack-eslint.js | JavaScript | mit | 355 |
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;
};
| studio666/node-torrent | lib/util.js | JavaScript | mit | 879 |
/* 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'
});
| MustD/a3al | webpack.config.development.js | JavaScript | mit | 1,083 |
export const API_FAIL = 'API_FAIL';
export const SAVE_TIMELINE_FAIL = 'SAVE_TIMELINE_FAIL';
| WikiEducationFoundation/WikiEduDashboard | app/assets/javascripts/constants/api.js | JavaScript | mit | 92 |
/*global GLOBE, Em */
GLOBE.Top10Controller = Em.ArrayController.extend({
needs: ['application'],
relays: [],
actions: {
showRelayDetail: function(fingerprint) {
this.transitionToRoute('relayDetail', fingerprint);
}
}
}); | isislovecruft/globe | src/js/controllers/Top10Controller.js | JavaScript | mit | 266 |
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,
}
| LearnersGuild/echo | src/server/services/gitHubService/index.js | JavaScript | mit | 873 |
/**
* Librerías Javascript
*
* @package Roraima
* @author $Author$ <[email protected]>
* @version SVN: $Id$
*
* @copyright Copyright 2007, Cide S.A.
* @license http://opensource.org/licenses/gpl-2.0.php GPLv2
*/
function codigopadre(){
var codigo=$('cideftit_codpre').value;
if (codigo.length==2){
codigo=codigo+"-";
}
new Ajax.Request(getUrlModuloAjax(),{asynchronous:true, evalScripts:false, onComplete:function(request, json){AjaxJSON(request, json)}, parameters:'ajax=1&codigo='+codigo});
} | cidesa/siga-universitario | web/js/ingresos/ingtitpre.js | JavaScript | gpl-2.0 | 537 |
$(function() {
$('img[data-hover]').hover(function() {
$(this).attr('tmp', $(this).attr('src')).attr('src', $(this).attr('data-hover')).attr('data-hover', $(this).attr('tmp')).removeAttr('tmp');
}).each(function() {
$('<img>').attr('src', $(this).attr('data-hover'));
});;
});
jQuery(document).ready(function ($) {
var options = {
$AutoPlay: true,
$SlideDuration: 800,
$AutoPlayInterval: 2000
};
var jssor_slider1 = new $JssorSlider$('slider1_container', options);
}); | alex789/random | wp-content/themes/randomTheme/js/jquery.js | JavaScript | gpl-2.0 | 528 |
//asteroid clone (core mechanics only)
//arrow keys to move + x to shoot
var bullets;
var asteroids;
var ship;
var shipImage, bulletImage, particleImage;
var MARGIN = 40;
function setup() {
createCanvas(800, 600);
bulletImage = loadImage('assets/asteroids_bullet.png');
shipImage = loadImage('assets/asteroids_ship0001.png');
particleImage = loadImage('assets/asteroids_particle.png');
ship = createSprite(width/2, height/2);
ship.maxSpeed = 6;
ship.friction = 0.98;
ship.setCollider('circle', 0, 0, 20);
ship.addImage('normal', shipImage);
ship.addAnimation('thrust', 'assets/asteroids_ship0002.png', 'assets/asteroids_ship0007.png');
asteroids = new Group();
bullets = new Group();
for(var i = 0; i<8; i++) {
var ang = random(360);
var px = width/2 + 1000 * cos(radians(ang));
var py = height/2+ 1000 * sin(radians(ang));
createAsteroid(3, px, py);
}
}
function draw() {
background(0);
fill(255);
textAlign(CENTER);
text('Controls: Arrow Keys + X', width/2, 20);
for(var i=0; i<allSprites.length; i++) {
var s = allSprites[i];
if(s.position.x<-MARGIN) s.position.x = width+MARGIN;
if(s.position.x>width+MARGIN) s.position.x = -MARGIN;
if(s.position.y<-MARGIN) s.position.y = height+MARGIN;
if(s.position.y>height+MARGIN) s.position.y = -MARGIN;
}
asteroids.overlap(bullets, asteroidHit);
ship.bounce(asteroids);
if(keyDown(LEFT_ARROW))
ship.rotation -= 4;
if(keyDown(RIGHT_ARROW))
ship.rotation += 4;
if(keyDown(UP_ARROW))
{
ship.addSpeed(0.2, ship.rotation);
ship.changeAnimation('thrust');
}
else
ship.changeAnimation('normal');
if(keyWentDown('x'))
{
var bullet = createSprite(ship.position.x, ship.position.y);
bullet.addImage(bulletImage);
bullet.setSpeed(10+ship.getSpeed(), ship.rotation);
bullet.life = 30;
bullets.add(bullet);
}
drawSprites();
}
function createAsteroid(type, x, y) {
var a = createSprite(x, y);
var img = loadImage('assets/asteroid'+floor(random(0, 3))+'.png');
a.addImage(img);
a.setSpeed(2.5-(type/2), random(360));
a.rotationSpeed = 0.5;
//a.debug = true;
a.type = type;
if(type == 2)
a.scale = 0.6;
if(type == 1)
a.scale = 0.3;
a.mass = 2+a.scale;
a.setCollider('circle', 0, 0, 50);
asteroids.add(a);
return a;
}
function asteroidHit(asteroid, bullet) {
var newType = asteroid.type-1;
if(newType>0) {
createAsteroid(newType, asteroid.position.x, asteroid.position.y);
createAsteroid(newType, asteroid.position.x, asteroid.position.y);
}
for(var i=0; i<10; i++) {
var p = createSprite(bullet.position.x, bullet.position.y);
p.addImage(particleImage);
p.setSpeed(random(3, 5), random(360));
p.friction = 0.95;
p.life = 15;
}
bullet.remove();
asteroid.remove();
}
| sabotai/energyDrinkGame | p5.play/examples/asteroids.js | JavaScript | gpl-2.0 | 2,832 |
//>>built
define("dojox/editor/plugins/nls/el/Smiley",({smiley:"Εισαγωγή εικονιδίου συναισθήματος",emoticonSmile:"Χαμόγελο",emoticonLaughing:"Γέλιο",emoticonWink:"Κλείσιμο ματιού",emoticonGrin:"Πλατύ χαμόγελο",emoticonCool:"Άνετος",emoticonAngry:"Θυμωμένος",emoticonHalf:"Μισό",emoticonEyebrow:"Σηκωμένο φρύδι",emoticonFrown:"Συνοφρυωμένος",emoticonShy:"Ντροπαλός",emoticonGoofy:"Χαζόφατσα",emoticonOops:"Έκπληξη",emoticonTongue:"Κοροϊδία",emoticonIdea:"Ιδέα",emoticonYes:"Ναι",emoticonNo:"Όχι",emoticonAngel:"Αγγελούδι",emoticonCrying:"Κλάμα",emoticonHappy:"Ευτυχία"}));
| hariomkumarmth/champaranexpress | wp-content/plugins/dojo/dojox/editor/plugins/nls/el/Smiley.js | JavaScript | gpl-2.0 | 754 |
//>>built
define("dojox/embed/flashVars",["dojo"],function(_1){
_1.deprecated("dojox.embed.flashVars","Will be removed in 2.0","2.0");
var _2={serialize:function(n,o){
var _3=function(_4){
if(typeof _4=="string"){
_4=_4.replace(/;/g,"_sc_");
_4=_4.replace(/\./g,"_pr_");
_4=_4.replace(/\:/g,"_cl_");
}
return _4;
};
var df=dojox.embed.flashVars.serialize;
var _5="";
if(_1.isArray(o)){
for(var i=0;i<o.length;i++){
_5+=df(n+"."+i,_3(o[i]))+";";
}
return _5.replace(/;{2,}/g,";");
}else{
if(_1.isObject(o)){
for(var nm in o){
_5+=df(n+"."+nm,_3(o[nm]))+";";
}
return _5.replace(/;{2,}/g,";");
}
}
return n+":"+o;
}};
_1.setObject("dojox.embed.flashVars",_2);
return _2;
});
| hariomkumarmth/champaranexpress | wp-content/plugins/dojo/dojox/embed/flashVars.js | JavaScript | gpl-2.0 | 705 |
/**
* Created by Stefan on 24.05.14.
*/
(function() {
tinymce.create('tinymce.plugins.Footnotes', {
/**
* Initializes the plugin, this will be executed after the plugin has been created.
* This call is done before the editor instance has finished its initialization so use the onInit event
* of the editor instance to intercept that event.
*
* @param {tinymce.Editor} ed Editor instance that the plugin is initialized in.
* @param {string} url Absolute URL to where the plugin is located.
*/
init : function(ed, url) {
ed.addButton('footnotes', {
title : 'footnotes',
cmd : 'footnotes',
image : url + '/../img/fn-wysiwyg.png'
});
ed.addCommand('footnotes', function() {
jQuery.ajax({
type: 'POST',
url: '/wp-admin/admin-ajax.php',
data: {
action: 'footnotes_getTags'
},
success: function(data, textStatus, XMLHttpRequest){
var l_arr_Tags = JSON.parse(data);
var return_text = l_arr_Tags['start'] + ed.selection.getContent() + l_arr_Tags['end'];
ed.execCommand('insertHTML', true, return_text);
},
error: function(MLHttpRequest, textStatus, errorThrown){
console.log("Error: " + errorThrown);
}
});
});
},
/**
* Creates control instances based in the incomming name. This method is normally not
* needed since the addButton method of the tinymce.Editor class is a more easy way of adding buttons
* but you sometimes need to create more complex controls like listboxes, split buttons etc then this
* method can be used to create those.
*
* @param {String} n Name of the control to create.
* @param {tinymce.ControlManager} cm Control manager to use inorder to create new control.
* @return {tinymce.ui.Control} New control instance or null if no control was created.
*/
createControl : function(n, cm) {
return null;
},
/**
* Returns information about the plugin as a name/value array.
* The current keys are longname, author, authorurl, infourl and version.
*
* @return {Object} Name/value array containing information about the plugin.
*/
getInfo : function() {
return {
longname : 'Inserts the Footnotes short code.',
author : 'ManFisher Medien ManuFaktur',
authorurl : 'http://http://manfisher.net/',
infourl : 'http://wordpress.org/plugins/footnotes/',
version : "1.5.0"
};
}
});
// Register plugin
tinymce.PluginManager.add('footnotes', tinymce.plugins.Footnotes);
})(); | austing/siq | wp-content/plugins/footnotes/js/wysiwyg-editor.js | JavaScript | gpl-2.0 | 3,155 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ZoomOut = exports.ZoomIn = exports.SlideRight = exports.SlideLeft = undefined;
var _slideLeft = require('./slide-left.scss');
var _slideLeft2 = _interopRequireDefault(_slideLeft);
var _slideRight = require('./slide-right.scss');
var _slideRight2 = _interopRequireDefault(_slideRight);
var _zoomIn = require('./zoom-in.scss');
var _zoomIn2 = _interopRequireDefault(_zoomIn);
var _zoomOut = require('./zoom-out.scss');
var _zoomOut2 = _interopRequireDefault(_zoomOut);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.SlideLeft = _slideLeft2.default;
exports.SlideRight = _slideRight2.default;
exports.ZoomIn = _zoomIn2.default;
exports.ZoomOut = _zoomOut2.default; | fonea/velon | themes/frontend/assets/vendor/node_modules/react-toolbox/lib/animations/index.js | JavaScript | gpl-2.0 | 816 |
/*
* Ext JS Library 2.1
* Copyright(c) 2006-2008, Ext JS, LLC.
* [email protected]
*
* http://extjs.com/license
*/
/**
* @class Ext.Component
* @extends Ext.util.Observable
* <p>Base class for all Ext components. All subclasses of Component can automatically participate in the standard
* Ext component lifecycle of creation, rendering and destruction. They also have automatic support for basic hide/show
* and enable/disable behavior. Component allows any subclass to be lazy-rendered into any {@link Ext.Container} and
* to be automatically registered with the {@link Ext.ComponentMgr} so that it can be referenced at any time via
* {@link Ext#getCmp}. All visual widgets that require rendering into a layout should subclass Component (or
* {@link Ext.BoxComponent} if managed box model handling is required).</p>
* <p>Every component has a specific xtype, which is its Ext-specific type name, along with methods for checking the
* xtype like {@link #getXType} and {@link #isXType}. This is the list of all valid xtypes:</p>
* <pre>
xtype Class
------------- ------------------
box Ext.BoxComponent
button Ext.Button
colorpalette Ext.ColorPalette
component Ext.Component
container Ext.Container
cycle Ext.CycleButton
dataview Ext.DataView
datepicker Ext.DatePicker
editor Ext.Editor
editorgrid Ext.grid.EditorGridPanel
grid Ext.grid.GridPanel
paging Ext.PagingToolbar
panel Ext.Panel
progress Ext.ProgressBar
propertygrid Ext.grid.PropertyGrid
slider Ext.Slider
splitbutton Ext.SplitButton
statusbar Ext.StatusBar
tabpanel Ext.TabPanel
treepanel Ext.tree.TreePanel
viewport Ext.Viewport
window Ext.Window
Toolbar components
---------------------------------------
toolbar Ext.Toolbar
tbbutton Ext.Toolbar.Button
tbfill Ext.Toolbar.Fill
tbitem Ext.Toolbar.Item
tbseparator Ext.Toolbar.Separator
tbspacer Ext.Toolbar.Spacer
tbsplit Ext.Toolbar.SplitButton
tbtext Ext.Toolbar.TextItem
Form components
---------------------------------------
form Ext.FormPanel
checkbox Ext.form.Checkbox
combo Ext.form.ComboBox
datefield Ext.form.DateField
field Ext.form.Field
fieldset Ext.form.FieldSet
hidden Ext.form.Hidden
htmleditor Ext.form.HtmlEditor
label Ext.form.Label
numberfield Ext.form.NumberField
radio Ext.form.Radio
textarea Ext.form.TextArea
textfield Ext.form.TextField
timefield Ext.form.TimeField
trigger Ext.form.TriggerField
</pre>
* @constructor
* @param {Ext.Element/String/Object} config The configuration options. If an element is passed, it is set as the internal
* element and its id used as the component id. If a string is passed, it is assumed to be the id of an existing element
* and is used as the component id. Otherwise, it is assumed to be a standard config object and is applied to the component.
*/
Ext.Component = function(config){
config = config || {};
if(config.initialConfig){
if(config.isAction){ // actions
this.baseAction = config;
}
config = config.initialConfig; // component cloning / action set up
}else if(config.tagName || config.dom || typeof config == "string"){ // element object
config = {applyTo: config, id: config.id || config};
}
/**
* This Component's initial configuration specification. Read-only.
* @type Object
* @property initialConfig
*/
this.initialConfig = config;
Ext.apply(this, config);
this.addEvents(
/**
* @event disable
* Fires after the component is disabled.
* @param {Ext.Component} this
*/
'disable',
/**
* @event enable
* Fires after the component is enabled.
* @param {Ext.Component} this
*/
'enable',
/**
* @event beforeshow
* Fires before the component is shown. Return false to stop the show.
* @param {Ext.Component} this
*/
'beforeshow',
/**
* @event show
* Fires after the component is shown.
* @param {Ext.Component} this
*/
'show',
/**
* @event beforehide
* Fires before the component is hidden. Return false to stop the hide.
* @param {Ext.Component} this
*/
'beforehide',
/**
* @event hide
* Fires after the component is hidden.
* @param {Ext.Component} this
*/
'hide',
/**
* @event beforerender
* Fires before the component is rendered. Return false to stop the render.
* @param {Ext.Component} this
*/
'beforerender',
/**
* @event render
* Fires after the component is rendered.
* @param {Ext.Component} this
*/
'render',
/**
* @event beforedestroy
* Fires before the component is destroyed. Return false to stop the destroy.
* @param {Ext.Component} this
*/
'beforedestroy',
/**
* @event destroy
* Fires after the component is destroyed.
* @param {Ext.Component} this
*/
'destroy',
/**
* @event beforestaterestore
* Fires before the state of the component is restored. Return false to stop the restore.
* @param {Ext.Component} this
* @param {Object} state The hash of state values
*/
'beforestaterestore',
/**
* @event staterestore
* Fires after the state of the component is restored.
* @param {Ext.Component} this
* @param {Object} state The hash of state values
*/
'staterestore',
/**
* @event beforestatesave
* Fires before the state of the component is saved to the configured state provider. Return false to stop the save.
* @param {Ext.Component} this
* @param {Object} state The hash of state values
*/
'beforestatesave',
/**
* @event statesave
* Fires after the state of the component is saved to the configured state provider.
* @param {Ext.Component} this
* @param {Object} state The hash of state values
*/
'statesave'
);
this.getId();
Ext.ComponentMgr.register(this);
Ext.Component.superclass.constructor.call(this);
if(this.baseAction){
this.baseAction.addComponent(this);
}
this.initComponent();
if(this.plugins){
if(Ext.isArray(this.plugins)){
for(var i = 0, len = this.plugins.length; i < len; i++){
this.plugins[i].init(this);
}
}else{
this.plugins.init(this);
}
}
if(this.stateful !== false){
this.initState(config);
}
if(this.applyTo){
this.applyToMarkup(this.applyTo);
delete this.applyTo;
}else if(this.renderTo){
this.render(this.renderTo);
delete this.renderTo;
}
};
// private
Ext.Component.AUTO_ID = 1000;
Ext.extend(Ext.Component, Ext.util.Observable, {
/**
* @cfg {String} id
* The unique id of this component (defaults to an auto-assigned id).
*/
/**
* @cfg {String/Object} autoEl
* A tag name or DomHelper spec to create an element with. This is intended to create shorthand
* utility components inline via JSON. It should not be used for higher level components which already create
* their own elements. Example usage:
* <pre><code>
{xtype:'box', autoEl: 'div', cls:'my-class'}
{xtype:'box', autoEl: {tag:'blockquote', html:'autoEl is cool!'}} // with DomHelper
</code></pre>
*/
/**
* @cfg {String} xtype
* The registered xtype to create. This config option is not used when passing
* a config object into a constructor. This config option is used only when
* lazy instantiation is being used, and a child item of a Container is being
* specified not as a fully instantiated Component, but as a <i>Component config
* object</i>. The xtype will be looked up at render time up to determine what
* type of child Component to create.<br><br>
* The predefined xtypes are listed {@link Ext.Component here}.
* <br><br>
* If you subclass Components to create your own Components, you may register
* them using {@link Ext.ComponentMgr#registerType} in order to be able to
* take advantage of lazy instantiation and rendering.
*/
/**
* @cfg {String} cls
* An optional extra CSS class that will be added to this component's Element (defaults to ''). This can be
* useful for adding customized styles to the component or any of its children using standard CSS rules.
*/
/**
* @cfg {String} overCls
* An optional extra CSS class that will be added to this component's Element when the mouse moves
* over the Element, and removed when the mouse moves out. (defaults to ''). This can be
* useful for adding customized "active" or "hover" styles to the component or any of its children using standard CSS rules.
*/
/**
* @cfg {String} style
* A custom style specification to be applied to this component's Element. Should be a valid argument to
* {@link Ext.Element#applyStyles}.
*/
/**
* @cfg {String} ctCls
* An optional extra CSS class that will be added to this component's container (defaults to ''). This can be
* useful for adding customized styles to the container or any of its children using standard CSS rules.
*/
/**
* @cfg {Object/Array} plugins
* An object or array of objects that will provide custom functionality for this component. The only
* requirement for a valid plugin is that it contain an init method that accepts a reference of type Ext.Component.
* When a component is created, if any plugins are available, the component will call the init method on each
* plugin, passing a reference to itself. Each plugin can then call methods or respond to events on the
* component as needed to provide its functionality.
*/
/**
* @cfg {Mixed} applyTo
* The id of the node, a DOM node or an existing Element corresponding to a DIV that is already present in
* the document that specifies some structural markup for this component. When applyTo is used, constituent parts of
* the component can also be specified by id or CSS class name within the main element, and the component being created
* may attempt to create its subcomponents from that markup if applicable. Using this config, a call to render() is
* not required. If applyTo is specified, any value passed for {@link #renderTo} will be ignored and the target
* element's parent node will automatically be used as the component's container.
*/
/**
* @cfg {Mixed} renderTo
* The id of the node, a DOM node or an existing Element that will be the container to render this component into.
* Using this config, a call to render() is not required.
*/
/**
* @cfg {Boolean} stateful
* A flag which causes the Component to attempt to restore the state of internal properties
* from a saved state on startup.<p>
* For state saving to work, the state manager's provider must have been set to an implementation
* of {@link Ext.state.Provider} which overrides the {@link Ext.state.Provider#set set}
* and {@link Ext.state.Provider#get get} methods to save and recall name/value pairs.
* A built-in implementation, {@link Ext.state.CookieProvider} is available.</p>
* <p>To set the state provider for the current page:</p>
* <pre><code>
Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
</code></pre>
* <p>Components attempt to save state when one of the events listed in the {@link #stateEvents}
* configuration fires.</p>
* <p>You can perform extra processing on state save and restore by attaching handlers to the
* {@link #beforestaterestore}, {@link staterestore}, {@link beforestatesave} and {@link statesave} events</p>
*/
/**
* @cfg {String} stateId
* The unique id for this component to use for state management purposes (defaults to the component id).
* <p>See {@link #stateful} for an explanation of saving and restoring Component state.</p>
*/
/* //internal - to be set by subclasses
* @cfg {Array} stateEvents
* An array of events that, when fired, should trigger this component to save its state (defaults to none).
* These can be any types of events supported by this component, including browser or custom events (e.g.,
* ['click', 'customerchange']).
* <p>See {@link #stateful} for an explanation of saving and restoring Component state.</p>
*/
/**
* @cfg {String} disabledClass
* CSS class added to the component when it is disabled (defaults to "x-item-disabled").
*/
disabledClass : "x-item-disabled",
/**
* @cfg {Boolean} allowDomMove
* Whether the component can move the Dom node when rendering (defaults to true).
*/
allowDomMove : true,
/**
* @cfg {Boolean} autoShow
* True if the component should check for hidden classes (e.g. 'x-hidden' or 'x-hide-display') and remove
* them on render (defaults to false).
*/
autoShow : false,
/**
* @cfg {String} hideMode
* How this component should hidden. Supported values are "visibility" (css visibility), "offsets" (negative
* offset position) and "display" (css display) - defaults to "display".
*/
hideMode: 'display',
/**
* @cfg {Boolean} hideParent
* True to hide and show the component's container when hide/show is called on the component, false to hide
* and show the component itself (defaults to false). For example, this can be used as a shortcut for a hide
* button on a window by setting hide:true on the button when adding it to its parent container.
*/
hideParent: false,
/**
* The component's owner {@link Ext.Container} (defaults to undefined, and is set automatically when
* the component is added to a container). Read-only.
* @type Ext.Container
* @property ownerCt
*/
/**
* True if this component is hidden. Read-only.
* @type Boolean
* @property
*/
hidden : false,
/**
* True if this component is disabled. Read-only.
* @type Boolean
* @property
*/
disabled : false,
/**
* True if this component has been rendered. Read-only.
* @type Boolean
* @property
*/
rendered : false,
// private
ctype : "Ext.Component",
// private
actionMode : "el",
// private
getActionEl : function(){
return this[this.actionMode];
},
/* // protected
* Function to be implemented by Component subclasses to be part of standard component initialization flow (it is empty by default).
* <pre><code>
// Traditional constructor:
Ext.Foo = function(config){
// call superclass constructor:
Ext.Foo.superclass.constructor.call(this, config);
this.addEvents({
// add events
});
};
Ext.extend(Ext.Foo, Ext.Bar, {
// class body
}
// initComponent replaces the constructor:
Ext.Foo = Ext.extend(Ext.Bar, {
initComponent : function(){
// call superclass initComponent
Ext.Container.superclass.initComponent.call(this);
this.addEvents({
// add events
});
}
}
</code></pre>
*/
initComponent : Ext.emptyFn,
/**
* If this is a lazy rendering component, render it to its container element.
* @param {Mixed} container (optional) The element this component should be rendered into. If it is being
* applied to existing markup, this should be left off.
* @param {String/Number} position (optional) The element ID or DOM node index within the container <b>before</b>
* which this component will be inserted (defaults to appending to the end of the container)
*/
render : function(container, position){
if(!this.rendered && this.fireEvent("beforerender", this) !== false){
if(!container && this.el){
this.el = Ext.get(this.el);
container = this.el.dom.parentNode;
this.allowDomMove = false;
}
this.container = Ext.get(container);
if(this.ctCls){
this.container.addClass(this.ctCls);
}
this.rendered = true;
if(position !== undefined){
if(typeof position == 'number'){
position = this.container.dom.childNodes[position];
}else{
position = Ext.getDom(position);
}
}
this.onRender(this.container, position || null);
if(this.autoShow){
this.el.removeClass(['x-hidden','x-hide-' + this.hideMode]);
}
if(this.cls){
this.el.addClass(this.cls);
delete this.cls;
}
if(this.style){
this.el.applyStyles(this.style);
delete this.style;
}
this.fireEvent("render", this);
this.afterRender(this.container);
if(this.hidden){
this.hide();
}
if(this.disabled){
this.disable();
}
this.initStateEvents();
}
return this;
},
// private
initState : function(config){
if(Ext.state.Manager){
var state = Ext.state.Manager.get(this.stateId || this.id);
if(state){
if(this.fireEvent('beforestaterestore', this, state) !== false){
this.applyState(state);
this.fireEvent('staterestore', this, state);
}
}
}
},
// private
initStateEvents : function(){
if(this.stateEvents){
for(var i = 0, e; e = this.stateEvents[i]; i++){
this.on(e, this.saveState, this, {delay:100});
}
}
},
// private
applyState : function(state, config){
if(state){
Ext.apply(this, state);
}
},
// private
getState : function(){
return null;
},
// private
saveState : function(){
if(Ext.state.Manager){
var state = this.getState();
if(this.fireEvent('beforestatesave', this, state) !== false){
Ext.state.Manager.set(this.stateId || this.id, state);
this.fireEvent('statesave', this, state);
}
}
},
/**
* Apply this component to existing markup that is valid. With this function, no call to render() is required.
* @param {String/HTMLElement} el
*/
applyToMarkup : function(el){
this.allowDomMove = false;
this.el = Ext.get(el);
this.render(this.el.dom.parentNode);
},
/**
* Adds a CSS class to the component's underlying element.
* @param {string} cls The CSS class name to add
*/
addClass : function(cls){
if(this.el){
this.el.addClass(cls);
}else{
this.cls = this.cls ? this.cls + ' ' + cls : cls;
}
},
/**
* Removes a CSS class from the component's underlying element.
* @param {string} cls The CSS class name to remove
*/
removeClass : function(cls){
if(this.el){
this.el.removeClass(cls);
}else if(this.cls){
this.cls = this.cls.split(' ').remove(cls).join(' ');
}
},
// private
// default function is not really useful
onRender : function(ct, position){
if(this.autoEl){
if(typeof this.autoEl == 'string'){
this.el = document.createElement(this.autoEl);
}else{
var div = document.createElement('div');
Ext.DomHelper.overwrite(div, this.autoEl);
this.el = div.firstChild;
}
if (!this.el.id) {
this.el.id = this.getId();
}
}
if(this.el){
this.el = Ext.get(this.el);
if(this.allowDomMove !== false){
ct.dom.insertBefore(this.el.dom, position);
}
if(this.overCls) {
this.el.addClassOnOver(this.overCls);
}
}
},
// private
getAutoCreate : function(){
var cfg = typeof this.autoCreate == "object" ?
this.autoCreate : Ext.apply({}, this.defaultAutoCreate);
if(this.id && !cfg.id){
cfg.id = this.id;
}
return cfg;
},
// private
afterRender : Ext.emptyFn,
/**
* Destroys this component by purging any event listeners, removing the component's element from the DOM,
* removing the component from its {@link Ext.Container} (if applicable) and unregistering it from
* {@link Ext.ComponentMgr}. Destruction is generally handled automatically by the framework and this method
* should usually not need to be called directly.
*/
destroy : function(){
if(this.fireEvent("beforedestroy", this) !== false){
this.beforeDestroy();
if(this.rendered){
this.el.removeAllListeners();
this.el.remove();
if(this.actionMode == "container"){
this.container.remove();
}
}
this.onDestroy();
Ext.ComponentMgr.unregister(this);
this.fireEvent("destroy", this);
this.purgeListeners();
}
},
// private
beforeDestroy : Ext.emptyFn,
// private
onDestroy : Ext.emptyFn,
/**
* Returns the underlying {@link Ext.Element}.
* @return {Ext.Element} The element
*/
getEl : function(){
return this.el;
},
/**
* Returns the id of this component.
* @return {String}
*/
getId : function(){
return this.id || (this.id = "ext-comp-" + (++Ext.Component.AUTO_ID));
},
/**
* Returns the item id of this component.
* @return {String}
*/
getItemId : function(){
return this.itemId || this.getId();
},
/**
* Try to focus this component.
* @param {Boolean} selectText (optional) If applicable, true to also select the text in this component
* @param {Boolean/Number} delay (optional) Delay the focus this number of milliseconds (true for 10 milliseconds)
* @return {Ext.Component} this
*/
focus : function(selectText, delay){
if(delay){
this.focus.defer(typeof delay == 'number' ? delay : 10, this, [selectText, false]);
return;
}
if(this.rendered){
this.el.focus();
if(selectText === true){
this.el.dom.select();
}
}
return this;
},
// private
blur : function(){
if(this.rendered){
this.el.blur();
}
return this;
},
/**
* Disable this component.
* @return {Ext.Component} this
*/
disable : function(){
if(this.rendered){
this.onDisable();
}
this.disabled = true;
this.fireEvent("disable", this);
return this;
},
// private
onDisable : function(){
this.getActionEl().addClass(this.disabledClass);
this.el.dom.disabled = true;
},
/**
* Enable this component.
* @return {Ext.Component} this
*/
enable : function(){
if(this.rendered){
this.onEnable();
}
this.disabled = false;
this.fireEvent("enable", this);
return this;
},
// private
onEnable : function(){
this.getActionEl().removeClass(this.disabledClass);
this.el.dom.disabled = false;
},
/**
* Convenience function for setting disabled/enabled by boolean.
* @param {Boolean} disabled
*/
setDisabled : function(disabled){
this[disabled ? "disable" : "enable"]();
},
/**
* Show this component.
* @return {Ext.Component} this
*/
show: function(){
if(this.fireEvent("beforeshow", this) !== false){
this.hidden = false;
if(this.autoRender){
this.render(typeof this.autoRender == 'boolean' ? Ext.getBody() : this.autoRender);
}
if(this.rendered){
this.onShow();
}
this.fireEvent("show", this);
}
return this;
},
// private
onShow : function(){
if(this.hideParent){
this.container.removeClass('x-hide-' + this.hideMode);
}else{
this.getActionEl().removeClass('x-hide-' + this.hideMode);
}
},
/**
* Hide this component.
* @return {Ext.Component} this
*/
hide: function(){
if(this.fireEvent("beforehide", this) !== false){
this.hidden = true;
if(this.rendered){
this.onHide();
}
this.fireEvent("hide", this);
}
return this;
},
// private
onHide : function(){
if(this.hideParent){
this.container.addClass('x-hide-' + this.hideMode);
}else{
this.getActionEl().addClass('x-hide-' + this.hideMode);
}
},
/**
* Convenience function to hide or show this component by boolean.
* @param {Boolean} visible True to show, false to hide
* @return {Ext.Component} this
*/
setVisible: function(visible){
if(visible) {
this.show();
}else{
this.hide();
}
return this;
},
/**
* Returns true if this component is visible.
*/
isVisible : function(){
return this.rendered && this.getActionEl().isVisible();
},
/**
* Clone the current component using the original config values passed into this instance by default.
* @param {Object} overrides A new config containing any properties to override in the cloned version.
* An id property can be passed on this object, otherwise one will be generated to avoid duplicates.
* @return {Ext.Component} clone The cloned copy of this component
*/
cloneConfig : function(overrides){
overrides = overrides || {};
var id = overrides.id || Ext.id();
var cfg = Ext.applyIf(overrides, this.initialConfig);
cfg.id = id; // prevent dup id
return new this.constructor(cfg);
},
/**
* Gets the xtype for this component as registered with {@link Ext.ComponentMgr}. For a list of all
* available xtypes, see the {@link Ext.Component} header. Example usage:
* <pre><code>
var t = new Ext.form.TextField();
alert(t.getXType()); // alerts 'textfield'
</code></pre>
* @return {String} The xtype
*/
getXType : function(){
return this.constructor.xtype;
},
/**
* Tests whether or not this component is of a specific xtype. This can test whether this component is descended
* from the xtype (default) or whether it is directly of the xtype specified (shallow = true). For a list of all
* available xtypes, see the {@link Ext.Component} header. Example usage:
* <pre><code>
var t = new Ext.form.TextField();
var isText = t.isXType('textfield'); // true
var isBoxSubclass = t.isXType('box'); // true, descended from BoxComponent
var isBoxInstance = t.isXType('box', true); // false, not a direct BoxComponent instance
</code></pre>
* @param {String} xtype The xtype to check for this component
* @param {Boolean} shallow (optional) False to check whether this component is descended from the xtype (this is
* the default), or true to check whether this component is directly of the specified xtype.
*/
isXType : function(xtype, shallow){
return !shallow ?
('/' + this.getXTypes() + '/').indexOf('/' + xtype + '/') != -1 :
this.constructor.xtype == xtype;
},
/**
* Returns this component's xtype hierarchy as a slash-delimited string. For a list of all
* available xtypes, see the {@link Ext.Component} header. Example usage:
* <pre><code>
var t = new Ext.form.TextField();
alert(t.getXTypes()); // alerts 'component/box/field/textfield'
</pre></code>
* @return {String} The xtype hierarchy string
*/
getXTypes : function(){
var tc = this.constructor;
if(!tc.xtypes){
var c = [], sc = this;
while(sc && sc.constructor.xtype){
c.unshift(sc.constructor.xtype);
sc = sc.constructor.superclass;
}
tc.xtypeChain = c;
tc.xtypes = c.join('/');
}
return tc.xtypes;
},
/**
* Find a container above this component at any level by a custom function. If the passed function returns
* true, the container will be returned. The passed function is called with the arguments (container, this component).
* @param {Function} fcn
* @param {Object} scope (optional)
* @return {Array} Array of Ext.Components
*/
findParentBy: function(fn) {
for (var p = this.ownerCt; (p != null) && !fn(p, this); p = p.ownerCt);
return p || null;
},
/**
* Find a container above this component at any level by xtype or class
* @param {String/Class} xtype The xtype string for a component, or the class of the component directly
* @return {Container} The found container
*/
findParentByType: function(xtype) {
return typeof xtype == 'function' ?
this.findParentBy(function(p){
return p.constructor === xtype;
}) :
this.findParentBy(function(p){
return p.constructor.xtype === xtype;
});
},
// internal function for auto removal of assigned event handlers on destruction
mon : function(item, ename, fn, scope, opt){
if(!this.mons){
this.mons = [];
this.on('beforedestroy', function(){
for(var i= 0, len = this.mons.length; i < len; i++){
var m = this.mons[i];
m.item.un(m.ename, m.fn, m.scope);
}
}, this);
}
this.mons.push({
item: item, ename: ename, fn: fn, scope: scope
});
item.on(ename, fn, scope, opt);
}
});
Ext.reg('component', Ext.Component);
| Kev/maybelater | static/ext-2.1/source/widgets/Component.js | JavaScript | gpl-2.0 | 31,082 |
"use strict";
describe("Services: bigQueryLogging", function() {
beforeEach(module("risevision.common.components.logging"));
var bigQueryLogging, httpResp, forceHttpError, externalLogEventSpy;
beforeEach(module(function($provide) {
$provide.service("$q", function() {return Q;});
$provide.factory("externalLogging", [function () {
return {
logEvent: function(eventName, eventDetails, eventValue,
userId, companyId) {
console.log(eventName, eventDetails, eventValue,userId, companyId);
var deferred = Q.defer();
if (forceHttpError) {
deferred.reject("Http Error");
} else {
deferred.resolve(httpResp);
}
deferred.resolve(httpResp);
return deferred.promise;
}
};
}]);
$provide.factory("userState", [function () {
return {
getUsername: function() {return "user1";},
getSelectedCompanyId: function() {return "company1";}
};
}]);
}));
beforeEach(function() {
inject(function($injector){
forceHttpError = false;
bigQueryLogging = $injector.get("bigQueryLogging");
var externalLogging = $injector.get("externalLogging");
externalLogEventSpy = sinon.spy(externalLogging,"logEvent");
});
});
it("should exist",function() {
expect(bigQueryLogging.logEvent).to.be.a("function");
});
describe("logEvent:", function(){
it("should POST with userId and companyId if not provided",function(done){
bigQueryLogging.logEvent("eventName","details",1).then(function(){
externalLogEventSpy.should.have.been.calledWith("eventName","details",1,"user1","company1");
done();
}).then(null,done);
});
it("should POST with custom userId and companyId",function(done){
bigQueryLogging.logEvent("eventName","details",1, "myUser", "myCompany").then(function(){
externalLogEventSpy.should.have.been.calledWith("eventName","details",1,"myUser","myCompany");
done();
}).then(null,done);
});
it("should handle http error",function(done){
forceHttpError = true;
bigQueryLogging.logEvent("eventName","details",1).then(function(){
done(new Error("Should have rejected"));
},function(){
done();
}).then(null,done);
});
});
});
| Rise-Vision/common-header | test/unit/components/userstate/services/svc-big-query-logging.tests.js | JavaScript | gpl-3.0 | 2,365 |
//>>built
define("dijit/_KeyNavMixin",["dojo/_base/array","dojo/_base/declare","dojo/dom-attr","dojo/keys","dojo/_base/lang","dojo/on","dijit/registry","dijit/_FocusMixin"],function(_1,_2,_3,_4,_5,on,_6,_7){
return _2("dijit._KeyNavMixin",_7,{tabIndex:"0",childSelector:null,postCreate:function(){
this.inherited(arguments);
_3.set(this.domNode,"tabIndex",this.tabIndex);
if(!this._keyNavCodes){
var _8=this._keyNavCodes={};
_8[_4.HOME]=_5.hitch(this,"focusFirstChild");
_8[_4.END]=_5.hitch(this,"focusLastChild");
_8[this.isLeftToRight()?_4.LEFT_ARROW:_4.RIGHT_ARROW]=_5.hitch(this,"_onLeftArrow");
_8[this.isLeftToRight()?_4.RIGHT_ARROW:_4.LEFT_ARROW]=_5.hitch(this,"_onRightArrow");
_8[_4.UP_ARROW]=_5.hitch(this,"_onUpArrow");
_8[_4.DOWN_ARROW]=_5.hitch(this,"_onDownArrow");
}
var _9=this,_a=typeof this.childSelector=="string"?this.childSelector:_5.hitch(this,"childSelector");
this.own(on(this.domNode,"keypress",_5.hitch(this,"_onContainerKeypress")),on(this.domNode,"keydown",_5.hitch(this,"_onContainerKeydown")),on(this.domNode,"focus",_5.hitch(this,"_onContainerFocus")),on(this.containerNode,on.selector(_a,"focusin"),function(_b){
_9._onChildFocus(_6.getEnclosingWidget(this),_b);
}));
},_onLeftArrow:function(){
},_onRightArrow:function(){
},_onUpArrow:function(){
},_onDownArrow:function(){
},focus:function(){
this.focusFirstChild();
},_getFirstFocusableChild:function(){
return this._getNextFocusableChild(null,1);
},_getLastFocusableChild:function(){
return this._getNextFocusableChild(null,-1);
},focusFirstChild:function(){
this.focusChild(this._getFirstFocusableChild());
},focusLastChild:function(){
this.focusChild(this._getLastFocusableChild());
},focusChild:function(_c,_d){
if(!_c){
return;
}
if(this.focusedChild&&_c!==this.focusedChild){
this._onChildBlur(this.focusedChild);
}
_c.set("tabIndex",this.tabIndex);
_c.focus(_d?"end":"start");
},_onContainerFocus:function(_e){
if(_e.target!==this.domNode||this.focusedChild){
return;
}
this.focus();
},_onFocus:function(){
_3.set(this.domNode,"tabIndex","-1");
this.inherited(arguments);
},_onBlur:function(_f){
_3.set(this.domNode,"tabIndex",this.tabIndex);
if(this.focusedChild){
this.focusedChild.set("tabIndex","-1");
this.lastFocusedChild=this.focusedChild;
this._set("focusedChild",null);
}
this.inherited(arguments);
},_onChildFocus:function(_10){
if(_10&&_10!=this.focusedChild){
if(this.focusedChild&&!this.focusedChild._destroyed){
this.focusedChild.set("tabIndex","-1");
}
_10.set("tabIndex",this.tabIndex);
this.lastFocused=_10;
this._set("focusedChild",_10);
}
},_searchString:"",multiCharSearchDuration:1000,onKeyboardSearch:function(_11,evt,_12,_13){
if(_11){
this.focusChild(_11);
}
},_keyboardSearchCompare:function(_14,_15){
var _16=_14.domNode,_17=_14.label||(_16.focusNode?_16.focusNode.label:"")||_16.innerText||_16.textContent||"",_18=_17.replace(/^\s+/,"").substr(0,_15.length).toLowerCase();
return (!!_15.length&&_18==_15)?-1:0;
},_onContainerKeydown:function(evt){
var _19=this._keyNavCodes[evt.keyCode];
if(_19){
_19(evt,this.focusedChild);
evt.stopPropagation();
evt.preventDefault();
this._searchString="";
}else{
if(evt.keyCode==_4.SPACE&&this._searchTimer&&!(evt.ctrlKey||evt.altKey||evt.metaKey)){
evt.stopImmediatePropagation();
evt.preventDefault();
this._keyboardSearch(evt," ");
}
}
},_onContainerKeypress:function(evt){
if(evt.charCode<_4.SPACE||evt.ctrlKey||evt.altKey||evt.metaKey||(evt.charCode==_4.SPACE&&this._searchTimer)){
return;
}
evt.preventDefault();
evt.stopPropagation();
this._keyboardSearch(evt,String.fromCharCode(evt.charCode).toLowerCase());
},_keyboardSearch:function(evt,_1a){
var _1b=null,_1c,_1d=0,_1e=_5.hitch(this,function(){
if(this._searchTimer){
this._searchTimer.remove();
}
this._searchString+=_1a;
var _1f=/^(.)\1*$/.test(this._searchString);
var _20=_1f?1:this._searchString.length;
_1c=this._searchString.substr(0,_20);
this._searchTimer=this.defer(function(){
this._searchTimer=null;
this._searchString="";
},this.multiCharSearchDuration);
var _21=this.focusedChild||null;
if(_20==1||!_21){
_21=this._getNextFocusableChild(_21,1);
if(!_21){
return;
}
}
var _22=_21;
do{
var rc=this._keyboardSearchCompare(_21,_1c);
if(!!rc&&_1d++==0){
_1b=_21;
}
if(rc==-1){
_1d=-1;
break;
}
_21=this._getNextFocusableChild(_21,1);
}while(_21!=_22);
});
_1e();
this.onKeyboardSearch(_1b,evt,_1c,_1d);
},_onChildBlur:function(){
},_getNextFocusableChild:function(_23,dir){
var _24=_23;
do{
if(!_23){
_23=this[dir>0?"_getFirst":"_getLast"]();
if(!_23){
break;
}
}else{
_23=this._getNext(_23,dir);
}
if(_23!=null&&_23!=_24&&_23.isFocusable()){
return _23;
}
}while(_23!=_24);
return null;
},_getFirst:function(){
return null;
},_getLast:function(){
return null;
},_getNext:function(_25,dir){
if(_25){
_25=_25.domNode;
while(_25){
_25=_25[dir<0?"previousSibling":"nextSibling"];
if(_25&&"getAttribute" in _25){
var w=_6.byNode(_25);
if(w){
return w;
}
}
}
}
return null;
}});
});
| cryo3d/cryo3d | static/ThirdParty/dojo-release-1.9.3/dijit/_KeyNavMixin.js | JavaScript | gpl-3.0 | 5,071 |
import PropTypes from 'prop-types';
import React from 'react';
import Icon from 'Components/Icon';
import Link from 'Components/Link/Link';
import { icons } from 'Helpers/Props';
import styles from './ModalContent.css';
function ModalContent(props) {
const {
className,
children,
showCloseButton,
onModalClose,
...otherProps
} = props;
return (
<div
className={className}
{...otherProps}
>
{
showCloseButton &&
<Link
className={styles.closeButton}
onPress={onModalClose}
>
<Icon
name={icons.CLOSE}
size={18}
/>
</Link>
}
{children}
</div>
);
}
ModalContent.propTypes = {
className: PropTypes.string,
children: PropTypes.node,
showCloseButton: PropTypes.bool.isRequired,
onModalClose: PropTypes.func.isRequired
};
ModalContent.defaultProps = {
className: styles.modalContent,
showCloseButton: true
};
export default ModalContent;
| Radarr/Radarr | frontend/src/Components/Modal/ModalContent.js | JavaScript | gpl-3.0 | 1,031 |
"use strict";
tutao.provide('tutao.entity.sys.System');
/**
* @constructor
* @param {Object=} data The json data to store in this entity.
*/
tutao.entity.sys.System = function(data) {
if (data) {
this.updateData(data);
} else {
this.__format = "0";
this.__id = null;
this.__permissions = null;
this._lastInvoiceNbr = null;
this._freeCustomerInfos = null;
this._freeGroup = null;
this._invoiceStatusIndex = null;
this._premiumCustomerInfos = null;
this._premiumGroup = null;
this._registrationDataList = null;
this._starterCustomerInfos = null;
this._starterGroup = null;
this._streamCustomerInfos = null;
this._streamGroup = null;
this._systemAdminGroup = null;
this._systemCustomer = null;
this._systemCustomerInfo = null;
this._systemUserGroup = null;
}
this._entityHelper = new tutao.entity.EntityHelper(this);
this.prototype = tutao.entity.sys.System.prototype;
};
/**
* Updates the data of this entity.
* @param {Object=} data The json data to store in this entity.
*/
tutao.entity.sys.System.prototype.updateData = function(data) {
this.__format = data._format;
this.__id = data._id;
this.__permissions = data._permissions;
this._lastInvoiceNbr = data.lastInvoiceNbr;
this._freeCustomerInfos = data.freeCustomerInfos;
this._freeGroup = data.freeGroup;
this._invoiceStatusIndex = data.invoiceStatusIndex;
this._premiumCustomerInfos = data.premiumCustomerInfos;
this._premiumGroup = data.premiumGroup;
this._registrationDataList = data.registrationDataList;
this._starterCustomerInfos = data.starterCustomerInfos;
this._starterGroup = data.starterGroup;
this._streamCustomerInfos = data.streamCustomerInfos;
this._streamGroup = data.streamGroup;
this._systemAdminGroup = data.systemAdminGroup;
this._systemCustomer = data.systemCustomer;
this._systemCustomerInfo = data.systemCustomerInfo;
this._systemUserGroup = data.systemUserGroup;
};
/**
* The version of the model this type belongs to.
* @const
*/
tutao.entity.sys.System.MODEL_VERSION = '9';
/**
* The url path to the resource.
* @const
*/
tutao.entity.sys.System.PATH = '/rest/sys/system';
/**
* The id of the root instance reference.
* @const
*/
tutao.entity.sys.System.ROOT_INSTANCE_ID = 'A3N5cwAAsQ';
/**
* The generated id type flag.
* @const
*/
tutao.entity.sys.System.GENERATED_ID = true;
/**
* The encrypted flag.
* @const
*/
tutao.entity.sys.System.prototype.ENCRYPTED = false;
/**
* Provides the data of this instances as an object that can be converted to json.
* @return {Object} The json object.
*/
tutao.entity.sys.System.prototype.toJsonData = function() {
return {
_format: this.__format,
_id: this.__id,
_permissions: this.__permissions,
lastInvoiceNbr: this._lastInvoiceNbr,
freeCustomerInfos: this._freeCustomerInfos,
freeGroup: this._freeGroup,
invoiceStatusIndex: this._invoiceStatusIndex,
premiumCustomerInfos: this._premiumCustomerInfos,
premiumGroup: this._premiumGroup,
registrationDataList: this._registrationDataList,
starterCustomerInfos: this._starterCustomerInfos,
starterGroup: this._starterGroup,
streamCustomerInfos: this._streamCustomerInfos,
streamGroup: this._streamGroup,
systemAdminGroup: this._systemAdminGroup,
systemCustomer: this._systemCustomer,
systemCustomerInfo: this._systemCustomerInfo,
systemUserGroup: this._systemUserGroup
};
};
/**
* The id of the System type.
*/
tutao.entity.sys.System.prototype.TYPE_ID = 177;
/**
* The id of the lastInvoiceNbr attribute.
*/
tutao.entity.sys.System.prototype.LASTINVOICENBR_ATTRIBUTE_ID = 591;
/**
* The id of the freeCustomerInfos attribute.
*/
tutao.entity.sys.System.prototype.FREECUSTOMERINFOS_ATTRIBUTE_ID = 183;
/**
* The id of the freeGroup attribute.
*/
tutao.entity.sys.System.prototype.FREEGROUP_ATTRIBUTE_ID = 191;
/**
* The id of the invoiceStatusIndex attribute.
*/
tutao.entity.sys.System.prototype.INVOICESTATUSINDEX_ATTRIBUTE_ID = 829;
/**
* The id of the premiumCustomerInfos attribute.
*/
tutao.entity.sys.System.prototype.PREMIUMCUSTOMERINFOS_ATTRIBUTE_ID = 185;
/**
* The id of the premiumGroup attribute.
*/
tutao.entity.sys.System.prototype.PREMIUMGROUP_ATTRIBUTE_ID = 190;
/**
* The id of the registrationDataList attribute.
*/
tutao.entity.sys.System.prototype.REGISTRATIONDATALIST_ATTRIBUTE_ID = 194;
/**
* The id of the starterCustomerInfos attribute.
*/
tutao.entity.sys.System.prototype.STARTERCUSTOMERINFOS_ATTRIBUTE_ID = 184;
/**
* The id of the starterGroup attribute.
*/
tutao.entity.sys.System.prototype.STARTERGROUP_ATTRIBUTE_ID = 192;
/**
* The id of the streamCustomerInfos attribute.
*/
tutao.entity.sys.System.prototype.STREAMCUSTOMERINFOS_ATTRIBUTE_ID = 186;
/**
* The id of the streamGroup attribute.
*/
tutao.entity.sys.System.prototype.STREAMGROUP_ATTRIBUTE_ID = 193;
/**
* The id of the systemAdminGroup attribute.
*/
tutao.entity.sys.System.prototype.SYSTEMADMINGROUP_ATTRIBUTE_ID = 189;
/**
* The id of the systemCustomer attribute.
*/
tutao.entity.sys.System.prototype.SYSTEMCUSTOMER_ATTRIBUTE_ID = 187;
/**
* The id of the systemCustomerInfo attribute.
*/
tutao.entity.sys.System.prototype.SYSTEMCUSTOMERINFO_ATTRIBUTE_ID = 182;
/**
* The id of the systemUserGroup attribute.
*/
tutao.entity.sys.System.prototype.SYSTEMUSERGROUP_ATTRIBUTE_ID = 188;
/**
* Provides the id of this System.
* @return {string} The id of this System.
*/
tutao.entity.sys.System.prototype.getId = function() {
return this.__id;
};
/**
* Sets the format of this System.
* @param {string} format The format of this System.
*/
tutao.entity.sys.System.prototype.setFormat = function(format) {
this.__format = format;
return this;
};
/**
* Provides the format of this System.
* @return {string} The format of this System.
*/
tutao.entity.sys.System.prototype.getFormat = function() {
return this.__format;
};
/**
* Sets the permissions of this System.
* @param {string} permissions The permissions of this System.
*/
tutao.entity.sys.System.prototype.setPermissions = function(permissions) {
this.__permissions = permissions;
return this;
};
/**
* Provides the permissions of this System.
* @return {string} The permissions of this System.
*/
tutao.entity.sys.System.prototype.getPermissions = function() {
return this.__permissions;
};
/**
* Sets the lastInvoiceNbr of this System.
* @param {string} lastInvoiceNbr The lastInvoiceNbr of this System.
*/
tutao.entity.sys.System.prototype.setLastInvoiceNbr = function(lastInvoiceNbr) {
this._lastInvoiceNbr = lastInvoiceNbr;
return this;
};
/**
* Provides the lastInvoiceNbr of this System.
* @return {string} The lastInvoiceNbr of this System.
*/
tutao.entity.sys.System.prototype.getLastInvoiceNbr = function() {
return this._lastInvoiceNbr;
};
/**
* Sets the freeCustomerInfos of this System.
* @param {string} freeCustomerInfos The freeCustomerInfos of this System.
*/
tutao.entity.sys.System.prototype.setFreeCustomerInfos = function(freeCustomerInfos) {
this._freeCustomerInfos = freeCustomerInfos;
return this;
};
/**
* Provides the freeCustomerInfos of this System.
* @return {string} The freeCustomerInfos of this System.
*/
tutao.entity.sys.System.prototype.getFreeCustomerInfos = function() {
return this._freeCustomerInfos;
};
/**
* Sets the freeGroup of this System.
* @param {string} freeGroup The freeGroup of this System.
*/
tutao.entity.sys.System.prototype.setFreeGroup = function(freeGroup) {
this._freeGroup = freeGroup;
return this;
};
/**
* Provides the freeGroup of this System.
* @return {string} The freeGroup of this System.
*/
tutao.entity.sys.System.prototype.getFreeGroup = function() {
return this._freeGroup;
};
/**
* Loads the freeGroup of this System.
* @return {Promise.<tutao.entity.sys.Group>} Resolves to the loaded freeGroup of this System or an exception if the loading failed.
*/
tutao.entity.sys.System.prototype.loadFreeGroup = function() {
return tutao.entity.sys.Group.load(this._freeGroup);
};
/**
* Sets the invoiceStatusIndex of this System.
* @param {string} invoiceStatusIndex The invoiceStatusIndex of this System.
*/
tutao.entity.sys.System.prototype.setInvoiceStatusIndex = function(invoiceStatusIndex) {
this._invoiceStatusIndex = invoiceStatusIndex;
return this;
};
/**
* Provides the invoiceStatusIndex of this System.
* @return {string} The invoiceStatusIndex of this System.
*/
tutao.entity.sys.System.prototype.getInvoiceStatusIndex = function() {
return this._invoiceStatusIndex;
};
/**
* Loads the invoiceStatusIndex of this System.
* @return {Promise.<tutao.entity.sys.InvoiceStatusIndex>} Resolves to the loaded invoiceStatusIndex of this System or an exception if the loading failed.
*/
tutao.entity.sys.System.prototype.loadInvoiceStatusIndex = function() {
return tutao.entity.sys.InvoiceStatusIndex.load(this._invoiceStatusIndex);
};
/**
* Sets the premiumCustomerInfos of this System.
* @param {string} premiumCustomerInfos The premiumCustomerInfos of this System.
*/
tutao.entity.sys.System.prototype.setPremiumCustomerInfos = function(premiumCustomerInfos) {
this._premiumCustomerInfos = premiumCustomerInfos;
return this;
};
/**
* Provides the premiumCustomerInfos of this System.
* @return {string} The premiumCustomerInfos of this System.
*/
tutao.entity.sys.System.prototype.getPremiumCustomerInfos = function() {
return this._premiumCustomerInfos;
};
/**
* Sets the premiumGroup of this System.
* @param {string} premiumGroup The premiumGroup of this System.
*/
tutao.entity.sys.System.prototype.setPremiumGroup = function(premiumGroup) {
this._premiumGroup = premiumGroup;
return this;
};
/**
* Provides the premiumGroup of this System.
* @return {string} The premiumGroup of this System.
*/
tutao.entity.sys.System.prototype.getPremiumGroup = function() {
return this._premiumGroup;
};
/**
* Loads the premiumGroup of this System.
* @return {Promise.<tutao.entity.sys.Group>} Resolves to the loaded premiumGroup of this System or an exception if the loading failed.
*/
tutao.entity.sys.System.prototype.loadPremiumGroup = function() {
return tutao.entity.sys.Group.load(this._premiumGroup);
};
/**
* Sets the registrationDataList of this System.
* @param {string} registrationDataList The registrationDataList of this System.
*/
tutao.entity.sys.System.prototype.setRegistrationDataList = function(registrationDataList) {
this._registrationDataList = registrationDataList;
return this;
};
/**
* Provides the registrationDataList of this System.
* @return {string} The registrationDataList of this System.
*/
tutao.entity.sys.System.prototype.getRegistrationDataList = function() {
return this._registrationDataList;
};
/**
* Sets the starterCustomerInfos of this System.
* @param {string} starterCustomerInfos The starterCustomerInfos of this System.
*/
tutao.entity.sys.System.prototype.setStarterCustomerInfos = function(starterCustomerInfos) {
this._starterCustomerInfos = starterCustomerInfos;
return this;
};
/**
* Provides the starterCustomerInfos of this System.
* @return {string} The starterCustomerInfos of this System.
*/
tutao.entity.sys.System.prototype.getStarterCustomerInfos = function() {
return this._starterCustomerInfos;
};
/**
* Sets the starterGroup of this System.
* @param {string} starterGroup The starterGroup of this System.
*/
tutao.entity.sys.System.prototype.setStarterGroup = function(starterGroup) {
this._starterGroup = starterGroup;
return this;
};
/**
* Provides the starterGroup of this System.
* @return {string} The starterGroup of this System.
*/
tutao.entity.sys.System.prototype.getStarterGroup = function() {
return this._starterGroup;
};
/**
* Loads the starterGroup of this System.
* @return {Promise.<tutao.entity.sys.Group>} Resolves to the loaded starterGroup of this System or an exception if the loading failed.
*/
tutao.entity.sys.System.prototype.loadStarterGroup = function() {
return tutao.entity.sys.Group.load(this._starterGroup);
};
/**
* Sets the streamCustomerInfos of this System.
* @param {string} streamCustomerInfos The streamCustomerInfos of this System.
*/
tutao.entity.sys.System.prototype.setStreamCustomerInfos = function(streamCustomerInfos) {
this._streamCustomerInfos = streamCustomerInfos;
return this;
};
/**
* Provides the streamCustomerInfos of this System.
* @return {string} The streamCustomerInfos of this System.
*/
tutao.entity.sys.System.prototype.getStreamCustomerInfos = function() {
return this._streamCustomerInfos;
};
/**
* Sets the streamGroup of this System.
* @param {string} streamGroup The streamGroup of this System.
*/
tutao.entity.sys.System.prototype.setStreamGroup = function(streamGroup) {
this._streamGroup = streamGroup;
return this;
};
/**
* Provides the streamGroup of this System.
* @return {string} The streamGroup of this System.
*/
tutao.entity.sys.System.prototype.getStreamGroup = function() {
return this._streamGroup;
};
/**
* Loads the streamGroup of this System.
* @return {Promise.<tutao.entity.sys.Group>} Resolves to the loaded streamGroup of this System or an exception if the loading failed.
*/
tutao.entity.sys.System.prototype.loadStreamGroup = function() {
return tutao.entity.sys.Group.load(this._streamGroup);
};
/**
* Sets the systemAdminGroup of this System.
* @param {string} systemAdminGroup The systemAdminGroup of this System.
*/
tutao.entity.sys.System.prototype.setSystemAdminGroup = function(systemAdminGroup) {
this._systemAdminGroup = systemAdminGroup;
return this;
};
/**
* Provides the systemAdminGroup of this System.
* @return {string} The systemAdminGroup of this System.
*/
tutao.entity.sys.System.prototype.getSystemAdminGroup = function() {
return this._systemAdminGroup;
};
/**
* Loads the systemAdminGroup of this System.
* @return {Promise.<tutao.entity.sys.Group>} Resolves to the loaded systemAdminGroup of this System or an exception if the loading failed.
*/
tutao.entity.sys.System.prototype.loadSystemAdminGroup = function() {
return tutao.entity.sys.Group.load(this._systemAdminGroup);
};
/**
* Sets the systemCustomer of this System.
* @param {string} systemCustomer The systemCustomer of this System.
*/
tutao.entity.sys.System.prototype.setSystemCustomer = function(systemCustomer) {
this._systemCustomer = systemCustomer;
return this;
};
/**
* Provides the systemCustomer of this System.
* @return {string} The systemCustomer of this System.
*/
tutao.entity.sys.System.prototype.getSystemCustomer = function() {
return this._systemCustomer;
};
/**
* Loads the systemCustomer of this System.
* @return {Promise.<tutao.entity.sys.Customer>} Resolves to the loaded systemCustomer of this System or an exception if the loading failed.
*/
tutao.entity.sys.System.prototype.loadSystemCustomer = function() {
return tutao.entity.sys.Customer.load(this._systemCustomer);
};
/**
* Sets the systemCustomerInfo of this System.
* @param {string} systemCustomerInfo The systemCustomerInfo of this System.
*/
tutao.entity.sys.System.prototype.setSystemCustomerInfo = function(systemCustomerInfo) {
this._systemCustomerInfo = systemCustomerInfo;
return this;
};
/**
* Provides the systemCustomerInfo of this System.
* @return {string} The systemCustomerInfo of this System.
*/
tutao.entity.sys.System.prototype.getSystemCustomerInfo = function() {
return this._systemCustomerInfo;
};
/**
* Sets the systemUserGroup of this System.
* @param {string} systemUserGroup The systemUserGroup of this System.
*/
tutao.entity.sys.System.prototype.setSystemUserGroup = function(systemUserGroup) {
this._systemUserGroup = systemUserGroup;
return this;
};
/**
* Provides the systemUserGroup of this System.
* @return {string} The systemUserGroup of this System.
*/
tutao.entity.sys.System.prototype.getSystemUserGroup = function() {
return this._systemUserGroup;
};
/**
* Loads the systemUserGroup of this System.
* @return {Promise.<tutao.entity.sys.Group>} Resolves to the loaded systemUserGroup of this System or an exception if the loading failed.
*/
tutao.entity.sys.System.prototype.loadSystemUserGroup = function() {
return tutao.entity.sys.Group.load(this._systemUserGroup);
};
/**
* Loads a System from the server.
* @param {string} id The id of the System.
* @return {Promise.<tutao.entity.sys.System>} Resolves to the System or an exception if the loading failed.
*/
tutao.entity.sys.System.load = function(id) {
return tutao.locator.entityRestClient.getElement(tutao.entity.sys.System, tutao.entity.sys.System.PATH, id, null, {"v" : 9}, tutao.entity.EntityHelper.createAuthHeaders()).then(function(entity) {
return entity;
});
};
/**
* Loads multiple Systems from the server.
* @param {Array.<string>} ids The ids of the Systems to load.
* @return {Promise.<Array.<tutao.entity.sys.System>>} Resolves to an array of System or rejects with an exception if the loading failed.
*/
tutao.entity.sys.System.loadMultiple = function(ids) {
return tutao.locator.entityRestClient.getElements(tutao.entity.sys.System, tutao.entity.sys.System.PATH, ids, {"v": 9}, tutao.entity.EntityHelper.createAuthHeaders()).then(function(entities) {
return entities;
});
};
/**
* Register a function that is called as soon as any attribute of the entity has changed. If this listener
* was already registered it is not registered again.
* @param {function(Object,*=)} listener. The listener function. When called it gets the entity and the given id as arguments.
* @param {*=} id. An optional value that is just passed-through to the listener.
*/
tutao.entity.sys.System.prototype.registerObserver = function(listener, id) {
this._entityHelper.registerObserver(listener, id);
};
/**
* Removes a registered listener function if it was registered before.
* @param {function(Object)} listener. The listener to unregister.
*/
tutao.entity.sys.System.prototype.unregisterObserver = function(listener) {
this._entityHelper.unregisterObserver(listener);
};
/**
* Provides the entity helper of this entity.
* @return {tutao.entity.EntityHelper} The entity helper.
*/
tutao.entity.sys.System.prototype.getEntityHelper = function() {
return this._entityHelper;
};
| msoftware/tutanota-1 | web/js/generated/entity/sys/System.js | JavaScript | gpl-3.0 | 18,395 |
/*
Input Mask plugin extensions
http://github.com/RobinHerbots/jquery.inputmask
Copyright (c) 2010 - 2014 Robin Herbots
Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
Version: 0.0.0
Optional extensions on the jquery.inputmask base
*/
(function ($) {
//extra definitions
$.extend($.inputmask.defaults.definitions, {
'A': {
validator: "[A-Za-z]",
cardinality: 1,
casing: "upper" //auto uppercasing
},
'#': {
validator: "[A-Za-z\u0410-\u044F\u0401\u04510-9]",
cardinality: 1,
casing: "upper"
}
});
$.extend($.inputmask.defaults.aliases, {
'url': {
mask: "ir",
placeholder: "",
separator: "",
defaultPrefix: "http://",
regex: {
urlpre1: new RegExp("[fh]"),
urlpre2: new RegExp("(ft|ht)"),
urlpre3: new RegExp("(ftp|htt)"),
urlpre4: new RegExp("(ftp:|http|ftps)"),
urlpre5: new RegExp("(ftp:/|ftps:|http:|https)"),
urlpre6: new RegExp("(ftp://|ftps:/|http:/|https:)"),
urlpre7: new RegExp("(ftp://|ftps://|http://|https:/)"),
urlpre8: new RegExp("(ftp://|ftps://|http://|https://)")
},
definitions: {
'i': {
validator: function (chrs, buffer, pos, strict, opts) {
return true;
},
cardinality: 8,
prevalidator: (function () {
var result = [], prefixLimit = 8;
for (var i = 0; i < prefixLimit; i++) {
result[i] = (function () {
var j = i;
return {
validator: function (chrs, buffer, pos, strict, opts) {
if (opts.regex["urlpre" + (j + 1)]) {
var tmp = chrs, k;
if (((j + 1) - chrs.length) > 0) {
tmp = buffer.join('').substring(0, ((j + 1) - chrs.length)) + "" + tmp;
}
var isValid = opts.regex["urlpre" + (j + 1)].test(tmp);
if (!strict && !isValid) {
pos = pos - j;
for (k = 0; k < opts.defaultPrefix.length; k++) {
buffer[pos] = opts.defaultPrefix[k]; pos++;
}
for (k = 0; k < tmp.length - 1; k++) {
buffer[pos] = tmp[k]; pos++;
}
return { "pos": pos };
}
return isValid;
} else {
return false;
}
}, cardinality: j
};
})();
}
return result;
})()
},
"r": {
validator: ".",
cardinality: 50
}
},
insertMode: false,
autoUnmask: false
},
"ip": { //ip-address mask
mask: "i[i[i]].i[i[i]].i[i[i]].i[i[i]]",
definitions: {
'i': {
validator: function (chrs, buffer, pos, strict, opts) {
if (pos - 1 > -1 && buffer[pos - 1] != ".") {
chrs = buffer[pos - 1] + chrs;
if (pos - 2 > -1 && buffer[pos - 2] != ".") {
chrs = buffer[pos - 2] + chrs;
} else chrs = "0" + chrs;
} else chrs = "00" + chrs;
return new RegExp("25[0-5]|2[0-4][0-9]|[01][0-9][0-9]").test(chrs);
},
cardinality: 1
}
}
},
"email": {
mask: "*{1,20}[.*{1,20}][.*{1,20}][.*{1,20}]@*{1,20}.*{2,6}[.*{1,2}]",
greedy: false
}
});
})(jQuery);
| anex/web_mask_field | static/lib/jquery.inputmask.extensions.js | JavaScript | gpl-3.0 | 4,746 |
/*
* Ext JS Library 1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* [email protected]
*
* http://www.extjs.com/license
*/
/*
* Simplified Chinese translation
* By DavidHu
* 09 April 2007
*/
Ext.UpdateManager.defaults.indicatorText = '<div class="loading-indicator">加载中...</div>';
if(Ext.View){
Ext.View.prototype.emptyText = "";
}
if(Ext.grid.Grid){
Ext.grid.Grid.prototype.ddText = "{0} 选择行";
}
if(Ext.TabPanelItem){
Ext.TabPanelItem.prototype.closeText = "关闭";
}
if(Ext.form.Field){
Ext.form.Field.prototype.invalidText = "输入值非法";
}
Date.monthNames = [
"一月",
"二月",
"三月",
"四月",
"五月",
"六月",
"七月",
"八月",
"九月",
"十月",
"十一月",
"十二月"
];
Date.dayNames = [
"周日",
"周一",
"周二",
"周三",
"周四",
"周五",
"周六"
];
if(Ext.MessageBox){
Ext.MessageBox.buttonText = {
ok : "确定",
cancel : "取消",
yes : "是",
no : "否"
};
}
if(Ext.util.Format){
Ext.util.Format.date = function(v, format){
if(!v) return "";
if(!(v instanceof Date)) v = new Date(Date.parse(v));
return v.dateFormat(format || "y年m月d日");
};
}
if(Ext.DatePicker){
Ext.apply(Ext.DatePicker.prototype, {
todayText : "今天",
minText : "日期在最小日期之前",
maxText : "日期在最大日期之后",
disabledDaysText : "",
disabledDatesText : "",
monthNames : Date.monthNames,
dayNames : Date.dayNames,
nextText : '下月 (Control+Right)',
prevText : '上月 (Control+Left)',
monthYearText : '选择一个月 (Control+Up/Down 来改变年)',
todayTip : "{0} (Spacebar)",
format : "y年m月d日"
});
}
if(Ext.PagingToolbar){
Ext.apply(Ext.PagingToolbar.prototype, {
beforePageText : "页",
afterPageText : "of {0}",
firstText : "第一页",
prevText : "前一页",
nextText : "下一页",
lastText : "最后页",
refreshText : "刷新",
displayMsg : "显示 {0} - {1} of {2}",
emptyMsg : '没有数据需要显示'
});
}
if(Ext.form.TextField){
Ext.apply(Ext.form.TextField.prototype, {
minLengthText : "该输入项的最小长度是 {0}",
maxLengthText : "该输入项的最大长度是 {0}",
blankText : "该输入项为必输项",
regexText : "",
emptyText : null
});
}
if(Ext.form.NumberField){
Ext.apply(Ext.form.NumberField.prototype, {
minText : "该输入项的最小值是 {0}",
maxText : "该输入项的最大值是 {0}",
nanText : "{0} 不是有效数值"
});
}
if(Ext.form.DateField){
Ext.apply(Ext.form.DateField.prototype, {
disabledDaysText : "禁用",
disabledDatesText : "禁用",
minText : "该输入项的日期必须在 {0} 之后",
maxText : "该输入项的日期必须在 {0} 之前",
invalidText : "{0} 是无效的日期 - 必须符合格式: {1}",
format : "y年m月d日"
});
}
if(Ext.form.ComboBox){
Ext.apply(Ext.form.ComboBox.prototype, {
loadingText : "加载...",
valueNotFoundText : undefined
});
}
if(Ext.form.VTypes){
Ext.apply(Ext.form.VTypes, {
emailText : '该输入项必须是电子邮件地址,格式如: "[email protected]"',
urlText : '该输入项必须是URL地址,格式如: "http:/'+'/www.domain.com"',
alphaText : '该输入项只能包含字符和_',
alphanumText : '该输入项只能包含字符,数字和_'
});
}
if(Ext.grid.GridView){
Ext.apply(Ext.grid.GridView.prototype, {
sortAscText : "正序",
sortDescText : "逆序",
lockText : "锁列",
unlockText : "解锁列",
columnsText : "列"
});
}
if(Ext.grid.PropertyColumnModel){
Ext.apply(Ext.grid.PropertyColumnModel.prototype, {
nameText : "名称",
valueText : "值",
dateFormat : "y年m月d日"
});
}
if(Ext.SplitLayoutRegion){
Ext.apply(Ext.SplitLayoutRegion.prototype, {
splitTip : "拖动来改变尺寸.",
collapsibleSplitTip : "拖动来改变尺寸. 双击隐藏."
});
}
| jeffreyhynes-360training/tarantula | app/assets/javascripts/ext/source/locale/ext-lang-zh_CN.js | JavaScript | gpl-3.0 | 4,566 |
/*!
* FileInput Danish Translations
*
* This file must be loaded after 'fileinput.js'. Patterns in braces '{}', or
* any HTML markup tags in the messages must not be converted or translated.
*
* @see http://github.com/kartik-v/bootstrap-fileinput
*
* NOTE: this file must be saved in UTF-8 encoding.
*/
(function ($) {
"use strict";
$.fn.fileinputLocales['da'] = {
fileSingle: 'fil',
filePlural: 'filer',
browseLabel: 'Browse …',
removeLabel: 'Fjern',
removeTitle: 'Fjern valgte filer',
cancelLabel: 'Fortryd',
cancelTitle: 'Afbryd nuværende upload',
uploadLabel: 'Upload',
uploadTitle: 'Upload valgte filer',
msgNo: 'Ingen',
msgNoFilesSelected: '',
msgCancelled: 'aflyst',
msgZoomModalHeading: 'Detaljeret visning',
msgSizeTooLarge: 'Fil "{name}" (<b>{size} KB</b>) er større end de tilladte <b>{maxSize} KB</b>.',
msgFilesTooLess: 'Du skal mindst vælge <b>{n}</b> {files} til upload.',
msgFilesTooMany: '<b>({n})</b> filer valgt til upload, men maks. <b>{m}</b> er tilladt.',
msgFileNotFound: 'Filen "{name}" blev ikke fundet!',
msgFileSecured: 'Sikkerhedsrestriktioner forhindrer læsning af "{name}".',
msgFileNotReadable: 'Filen "{name}" kan ikke indlæses.',
msgFilePreviewAborted: 'Filpreview annulleret for "{name}".',
msgFilePreviewError: 'Der skete en fejl under læsningen af filen "{name}".',
msgInvalidFileType: 'Ukendt type for filen "{name}". Kun "{types}" kan bruges.',
msgInvalidFileExtension: 'Ukendt filtype for filen "{name}". Kun "{extensions}" filer kan bruges.',
msgUploadAborted: 'Filupload annulleret',
msgUploadThreshold: 'Processing...',
msgValidationError: 'Validering Fejl',
msgLoading: 'Henter fil {index} af {files} …',
msgProgress: 'Henter fil {index} af {files} - {name} - {percent}% færdiggjort.',
msgSelected: '{n} {files} valgt',
msgFoldersNotAllowed: 'Drag & drop kun filer! {n} mappe(r) sprunget over.',
msgImageWidthSmall: 'Bredden af billedet "{name}" skal være på mindst {size} px.',
msgImageHeightSmall: 'Højden af billedet "{name}" skal være på mindst {size} px.',
msgImageWidthLarge: 'Bredden af billedet "{name}" må ikke være over {size} px.',
msgImageHeightLarge: 'Højden af billedet "{name}" må ikke være over {size} px.',
msgImageResizeError: 'Kunne ikke få billedets dimensioner for at ændre størrelsen.',
msgImageResizeException: 'Fejl ved at ændre størrelsen på billedet.<pre>{errors}</pre>',
dropZoneTitle: 'Drag & drop filer her …',
dropZoneClickTitle: '<br>(or click to select {files})',
fileActionSettings: {
removeTitle: 'Fjern fil',
uploadTitle: 'Upload fil',
zoomTitle: 'Se detaljer',
dragTitle: 'Move / Rearrange',
indicatorNewTitle: 'Ikke uploadet endnu',
indicatorSuccessTitle: 'Uploadet',
indicatorErrorTitle: 'Upload fejl',
indicatorLoadingTitle: 'Uploader ...'
},
previewZoomButtonTitles: {
prev: 'View previous file',
next: 'View next file',
toggleheader: 'Toggle header',
fullscreen: 'Toggle full screen',
borderless: 'Toggle borderless mode',
close: 'Close detailed preview'
}
};
})(window.jQuery); | ur13l/LaPurisimaWeb | public/js/locales/da.js | JavaScript | gpl-3.0 | 3,695 |
var searchData=
[
['kx122_5f2g',['KX122_2G',['../dc/da9/kx122_8h.html#af0d84feead3d8dc9e026be1d8bed0f1e',1,'kx122.h']]],
['kx122_5f4g',['KX122_4G',['../dc/da9/kx122_8h.html#a5f3b389fa7f60e02322cac6c4b9f339a',1,'kx122.h']]],
['kx122_5f8g',['KX122_8G',['../dc/da9/kx122_8h.html#a12e207bb6e2fdeffb820224db888f9dc',1,'kx122.h']]],
['kx122_5fcntl1',['KX122_CNTL1',['../dc/da9/kx122_8h.html#a4fffe24184e19f859cc6c02c656c8ce4',1,'kx122.h']]],
['kx122_5fdr_5f0_5f781',['KX122_DR_0_781',['../dc/da9/kx122_8h.html#a0319e862ee374690ae7dfb0717bb1dfd',1,'kx122.h']]],
['kx122_5fdr_5f100',['KX122_DR_100',['../dc/da9/kx122_8h.html#a275a5b72764c688de9aa98b1d5076e4e',1,'kx122.h']]],
['kx122_5fdr_5f12800',['KX122_DR_12800',['../dc/da9/kx122_8h.html#aa8ef7cb915b1abd59924422788c0ef7a',1,'kx122.h']]],
['kx122_5fdr_5f12_5f5',['KX122_DR_12_5',['../dc/da9/kx122_8h.html#a34e7f6a9af7ccb8dcc9bb5bb34131a08',1,'kx122.h']]],
['kx122_5fdr_5f1600',['KX122_DR_1600',['../dc/da9/kx122_8h.html#ac6a179cf0f2b1911fe4d65737732bf0d',1,'kx122.h']]],
['kx122_5fdr_5f1_5f563',['KX122_DR_1_563',['../dc/da9/kx122_8h.html#a23aad4d05060d1afd6a453c26431a3cb',1,'kx122.h']]],
['kx122_5fdr_5f200',['KX122_DR_200',['../dc/da9/kx122_8h.html#a22ebbc85157c95079b91cab687fc6d0b',1,'kx122.h']]],
['kx122_5fdr_5f25',['KX122_DR_25',['../dc/da9/kx122_8h.html#a932af84331610f47c60142a27cdd3421',1,'kx122.h']]],
['kx122_5fdr_5f25600',['KX122_DR_25600',['../dc/da9/kx122_8h.html#a4f424c130057f84cee9e9126386e923c',1,'kx122.h']]],
['kx122_5fdr_5f3200',['KX122_DR_3200',['../dc/da9/kx122_8h.html#a0777ff2a5a3f2a93d46562191b34405d',1,'kx122.h']]],
['kx122_5fdr_5f3_5f125',['KX122_DR_3_125',['../dc/da9/kx122_8h.html#a48d03458d6bbeb649a03a837dae7929e',1,'kx122.h']]],
['kx122_5fdr_5f400',['KX122_DR_400',['../dc/da9/kx122_8h.html#aa1076e1ba7ae01c96f065aed3d89f13e',1,'kx122.h']]],
['kx122_5fdr_5f50',['KX122_DR_50',['../dc/da9/kx122_8h.html#a3060fc2a1896d4db386523edb737a44d',1,'kx122.h']]],
['kx122_5fdr_5f6400',['KX122_DR_6400',['../dc/da9/kx122_8h.html#a8bbcf184c30b2e6c7eebed3f7e45682b',1,'kx122.h']]],
['kx122_5fdr_5f6_5f25',['KX122_DR_6_25',['../dc/da9/kx122_8h.html#a748031bcffef53ad282f00945b196bba',1,'kx122.h']]],
['kx122_5fdr_5f800',['KX122_DR_800',['../dc/da9/kx122_8h.html#a56cd31b6f4367c011c50f959c3e006b9',1,'kx122.h']]],
['kx122_5fget_5facc',['KX122_GET_ACC',['../dc/da9/kx122_8h.html#a415133c10bf125dad0d0e034e70772a4',1,'kx122.h']]],
['kx122_5fhi_5fres',['KX122_HI_RES',['../dc/da9/kx122_8h.html#a65cdd764d4d8e40be9fbeb613aca3f3c',1,'kx122.h']]],
['kx122_5fi_5fam_5fwho',['KX122_I_AM_WHO',['../dc/da9/kx122_8h.html#a8544881f7237865ee2ecf9c86a16e08d',1,'kx122.h']]],
['kx122_5fiir_5fbypass',['KX122_IIR_BYPASS',['../dc/da9/kx122_8h.html#a773c47865ef87893a37a1d7935c12acb',1,'kx122.h']]],
['kx122_5flow_5fres',['KX122_LOW_RES',['../dc/da9/kx122_8h.html#af7fe1205860d5457e83399b407511fae',1,'kx122.h']]],
['kx122_5flpro',['KX122_LPRO',['../dc/da9/kx122_8h.html#a7b5ea1826de68ad7b2617d14032d8811',1,'kx122.h']]],
['kx122_5fodcntl',['KX122_ODCNTL',['../dc/da9/kx122_8h.html#a4ea4d67c6d8d383b6ffd7d0a6708895a',1,'kx122.h']]],
['kx122_5foperate',['KX122_OPERATE',['../dc/da9/kx122_8h.html#a97b4de8580216654f6084e7427a71c56',1,'kx122.h']]],
['kx122_5fosa0',['KX122_OSA0',['../dc/da9/kx122_8h.html#a2c14e4e0871b3ea59803722c5922ddaf',1,'kx122.h']]],
['kx122_5fosa1',['KX122_OSA1',['../dc/da9/kx122_8h.html#a121d007772ffbb8fc249e80bbf330922',1,'kx122.h']]],
['kx122_5fosa2',['KX122_OSA2',['../dc/da9/kx122_8h.html#a4e555798b4f4badd96c7fb4e15c49cb8',1,'kx122.h']]],
['kx122_5fosa3',['KX122_OSA3',['../dc/da9/kx122_8h.html#a19632641b85af57d38a0ecd01844b074',1,'kx122.h']]],
['kx122_5fwhoami',['KX122_WHOAMI',['../dc/da9/kx122_8h.html#ada9e4dc9fb0f7ec496d361a1ea9231c7',1,'kx122.h']]],
['kx122_5fxout_5fh',['KX122_XOUT_H',['../dc/da9/kx122_8h.html#ac9c1a3296f9cc3beb0e15d9639139ff3',1,'kx122.h']]],
['kx122_5fxout_5fl',['KX122_XOUT_L',['../dc/da9/kx122_8h.html#a06d2e8966f6b649ae4f4eec76085f3f8',1,'kx122.h']]],
['kx122_5fyout_5fh',['KX122_YOUT_H',['../dc/da9/kx122_8h.html#a8a64a08dc4c99f7d30cf55743c251d7c',1,'kx122.h']]],
['kx122_5fyout_5fl',['KX122_YOUT_L',['../dc/da9/kx122_8h.html#af2557e15a78c186779ccfd895d196cc1',1,'kx122.h']]],
['kx122_5fzout_5fh',['KX122_ZOUT_H',['../dc/da9/kx122_8h.html#ad703c8ca503e7ca5fac2f31f0fe867e1',1,'kx122.h']]],
['kx122_5fzout_5fl',['KX122_ZOUT_L',['../dc/da9/kx122_8h.html#a53ba5843eaddbc2629ff7341990fbca8',1,'kx122.h']]]
];
| gratefulfrog/SPI | RPI/Python/serialApp/DOC/Dox/html/search/defines_7.js | JavaScript | gpl-3.0 | 4,491 |
/*
Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
//>>built
define("dojo/cldr/nls/nl/number",{"group":".","percentSign":"%","exponential":"E","scientificFormat":"#E0","percentFormat":"#,##0%","list":";","infinity":"∞","minusSign":"-","decimal":",","nan":"NaN","perMille":"‰","decimalFormat":"#,##0.###","currencyFormat":"¤ #,##0.00;¤ #,##0.00-","plusSign":"+","decimalFormat-long":"000 biljoen","decimalFormat-short":"000 bln'.'"});
| cryo3d/cryo3d | static/ThirdParty/dojo-release-1.9.3/dojo/cldr/nls/nl/number.js | JavaScript | gpl-3.0 | 596 |
import fs from 'fs';
import path from 'path';
import Wxr from 'wxr';
import Base from './base';
const NOT_SAFE_IN_XML = /[^\x09\x0A\x0D\x20-\xFF\x85\xA0-\uD7FF\uE000-\uFDCF\uFDE0-\uFFFD]/gm;
export default class extends Base {
constructor(...args) {
super(...args);
this.outputFile = path.join(think.RUNTIME_PATH, 'output_wordpress.xml');
}
async run() {
let importer = new Wxr();
let posts = await this.getPosts();
for(let post of posts) {
post.content = post.content.replace(NOT_SAFE_IN_XML, '');
post.summary = post.summary.replace(NOT_SAFE_IN_XML, '');
importer.addPost({
id: post.id,
title: post.title,
date: think.datetime(post.create_time),
contentEncoded: post.content,
excerptEncoded: post.summary,
categories: post.cate
})
}
let cateList = await this.model('cate').select();
for(let cate of cateList) {
importer.addCategory({
id: cate.id,
title: cate.name,
slug: cate.pathname
});
}
try {
fs.writeFileSync(
this.outputFile,
importer.stringify()
)
return this.outputFile;
} catch (e) {
throw new Error(e);
}
}
}
| Genffy/Blog.Genffy | src/admin/service/export/wordpress.js | JavaScript | gpl-3.0 | 1,230 |
/* webui functions */
function model_server(data) {
var self = this;
$.extend(self, data);
self.mem_utilization = ko.computed(function() {
return '{0} / {1}'.format(parseInt(self.memory), self.java_xmx);
})
self.capacity = ko.computed(function() {
return '{0} / {1}'.format(self.players_online, self.max_players);
})
self.overextended = ko.computed(function() {
try {
return parseInt(self.memory) > parseInt(self.java_xmx)
} catch (err) {
return false;
}
})
self.online_pct = ko.computed(function() {
return parseInt((self.players_online / self.max_players) * 100)
})
self.memory_pct = ko.computed(function() {
return parseInt((parseInt(self.memory) / parseInt(self.java_xmx)) * 100)
})
if (self.eula == null)
self.eula_ok = true;
else if (self.eula.toLowerCase() == 'false')
self.eula_ok = false;
else
self.eula_ok = true;
}
function model_property(server_name, option, value, section, new_prop) {
var self = this;
self.option = ko.observable(option);
self.val = ko.observable(value);
self.section = ko.observable(section);
self.success = ko.observable(null);
self.newly_created = ko.observable(new_prop || false);
self.type = 'textbox';
self.check_type = function(option, section) {
if (section) {
var fixed = [
{section: 'java', option: 'java_debug', type: 'truefalse'},
{section: 'onreboot', option: 'restore', type: 'truefalse'},
{section: 'onreboot', option: 'start', type: 'truefalse'},
{section: 'crontabs', option: 'archive_interval', type: 'interval'},
{section: 'crontabs', option: 'backup_interval', type: 'interval'},
{section: 'crontabs', option: 'restart_interval', type: 'interval'}
]
$.each(fixed, function(i,v) {
if (v.section == section && v.option == option){
self.type = v.type;
self.id = v.id;
return false;
}
})
} else {
var fixed = [
{option: 'pvp', type: 'truefalse'},
{option: 'allow-nether', type: 'truefalse'},
{option: 'spawn-animals', type: 'truefalse'},
{option: 'enable-query', type: 'truefalse'},
{option: 'generate-structures', type: 'truefalse'},
{option: 'hardcore', type: 'truefalse'},
{option: 'allow-flight', type: 'truefalse'},
{option: 'online-mode', type: 'truefalse'},
{option: 'spawn-monsters', type: 'truefalse'},
{option: 'force-gamemode', type: 'truefalse'},
{option: 'spawn-npcs', type: 'truefalse'},
{option: 'snooper-enabled', type: 'truefalse'},
{option: 'white-list', type: 'truefalse'},
{option: 'enable-rcon', type: 'truefalse'},
{option: 'announce-player-achievements', type: 'truefalse'},
{option: 'enable-command-block', type: 'truefalse'}
]
$.each(fixed, function(i,v) {
if (v.option == option){
self.type = v.type;
return false;
}
})
}
if (self.type == 'truefalse') {
if (self.val().toLowerCase() == 'true')
self.val(true);
else
self.val(false);
}
}
self.toggle = function(model, eventobj) {
$(eventobj.currentTarget).find('input').iCheck('destroy');
if (self.val() == true) {
$(eventobj.currentTarget).find('input').iCheck('uncheck');
self.val(false);
} else if (self.val() == false) {
var target = $(eventobj.currentTarget).find('input');
$(target).iCheck({
checkboxClass: 'icheckbox_minimal-grey',
radioClass: 'iradio_minimal-grey',
increaseArea: '40%' // optional
});
$(target).iCheck('check');
self.val(true);
}
}
self.change_select = function(model, eventobj) {
var new_value = $(eventobj.currentTarget).val();
var params = {
server_name: server_name,
cmd: 'modify_config',
option: self.option(),
value: new_value,
section: self.section()
}
$.getJSON('/server', params)
}
self.val.subscribe(function(value) {
function flash_success(data) {
if (data.result == 'success') {
self.newly_created(false);
self.success(true);
setTimeout(function() {self.success(null)}, 5000)
} else {
self.success(false);
}
}
function flash_failure(data) {
self.success(false);
}
var params = {
server_name: server_name,
cmd: 'modify_config',
option: self.option(),
value: self.val(),
section: self.section()
}
$.getJSON('/server', params).then(flash_success, flash_failure)
}, self)
self.check_type(option, section);
self.id = '{0}_{1}'.format((section ? section : ''), option);
}
function model_logline(str) {
var self = this;
self.timestamp = '';
self.entry = ansi_up.ansi_to_html(ansi_up.linkify(ansi_up.escape_for_html(str)));
}
function model_profile(data) {
var self = this;
$.extend(self, data);
self.description = ko.observable(self.desc);
self.success = ko.observable(null);
self.description.subscribe(function(value) {
var params = {
cmd: 'modify_profile',
option: 'desc',
value: self.description(),
section: self.profile
}
$.getJSON('/host', params)
}, self)
}
function webui() {
var self = this;
self.server = ko.observable({});
self.page = ko.observable();
self.profile = ko.observable({});
self.server.extend({ notify: 'always' });
self.page.extend({ notify: 'always' });
self.refresh_rate = 100;
self.refresh_loadavg = 2000;
self.dashboard = {
whoami: ko.observable(''),
group: ko.observable(),
groups: ko.observableArray([]),
memfree: ko.observable(),
uptime: ko.observable(),
servers_up: ko.observable(0),
disk_usage: ko.observable(),
disk_usage_pct: ko.observable(),
pc_permissions: ko.observable(),
pc_group: ko.observable(),
git_hash: ko.observable(),
stock_profiles: ko.observableArray([]),
base_directory: ko.observable()
}
self.logs = {
reversed: ko.observable(true)
}
self.load_averages = {
one: [0],
five: [0],
fifteen: [0],
autorefresh: ko.observable(true),
options: {
series: {
lines: {
show: true,
fill: .3
},
shadowSize: 0
},
yaxis: {
min: 0,
max: 1,
axisLabel: "Load Average for last minute",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 3
},
xaxis: { min: 0, max: 30, show: false },
grid: {
borderWidth: 0,
hoverable: false
},
legend: {
labelBoxBorderColor: "#858585",
position: "ne"
}
}
}
self.vmdata = {
pings: ko.observableArray(),
archives: ko.observableArray(),
increments: ko.observableArray(),
importable: ko.observableArray(),
profiles: ko.observableArray(),
sp: ko.observableArray(),
sc: ko.observableArray(),
logs: ko.observableArray()
}
self.import_information = ko.observable();
self.profile_type = ko.observable();
self.summary = {
backup: {
most_recent: ko.computed(function() {
try { return self.vmdata.increments()[0].timestamp } catch (e) { return 'None' }
}),
first: ko.computed(function() {
try { return self.vmdata.increments()[self.vmdata.increments().length-1].timestamp } catch (e) { return 'None' }
}),
cumulative: ko.computed(function() {
try { return self.vmdata.increments()[self.vmdata.increments().length-1].cumulative_size } catch (e) { return '0 MB' }
})
},
archive: {
most_recent: ko.computed(function() {
try { return self.vmdata.archives()[0].friendly_timestamp } catch (e) { return 'None' }
}),
first: ko.computed(function() {
try { return self.vmdata.archives()[self.vmdata.archives().length-1].friendly_timestamp } catch (e) { return 'None' }
}),
cumulative: ko.computed(function() {
return bytes_to_mb(self.vmdata.archives().sum('size'))
})
},
owner: ko.observable(''),
group: ko.observable(''),
du_cwd: ko.observable(0),
du_bwd: ko.observable(0),
du_awd: ko.observable(0)
}
self.pruning = {
increments: {
user_input: ko.observable(''),
remove_count: ko.observable(0),
step: '',
space_reclaimed: ko.observable(0.0)
},
archives: {
user_input: ko.observable(),
filename: ko.observable(),
remove_count: ko.observable(0),
archives_to_delete: '',
space_reclaimed: ko.observable(0.0)
},
profiles: {
profile: ko.observable()
}
}
/* beginning root functions */
self.save_state = function() {
var state_to_save = {
page: self.page(),
server: JSON.stringify(self.server()),
profile: self.profile()
}
history.pushState(state_to_save, 'MineOS Web UI');
}
self.restore_state = function(state) {
var server = new model_server(JSON.parse(state.server));
$('.container-fluid').hide();
if ($.isEmptyObject(server)) {
self.server({})
$('#dashboard').show();
} else {
self.server(server);
self.page(state.page);
$('.container-fluid').hide();
$('#{0}'.format(self.page())).show();
}
}
self.toggle_loadaverages = function() {
if (self.load_averages.autorefresh())
self.load_averages.autorefresh(false);
else {
self.load_averages.autorefresh(true);
self.redraw.chart();
}
}
self.reset_logs = function() {
self.vmdata.logs([]);
$.getJSON('/logs', {server_name: self.server().server_name, reset: true}).then(self.refresh.logs);
}
self.select_server = function(model) {
self.server(model);
if (self.page() == 'dashboard')
self.show_page('server_status');
else
self.ajax.refresh(null);
}
self.select_profile = function(model) {
self.profile(model);
self.show_page('profile_view');
}
self.new_property = function(vm, event) {
var config = $(event.target).data('config');
if (config == 'sp') {
self.vmdata.sp.push(new model_property(self.server().server_name, null, null, null, true))
} else if (config == 'sc') {
self.vmdata.sc.push(new model_property(self.server().server_name, null, null, null, true))
}
}
self.show_page = function(vm, event) {
try {
self.page($(event.currentTarget).data('page'));
} catch (e) {
self.page(vm);
}
$('.container-fluid').hide();
$('#{0}'.format(self.page())).show();
self.save_state();
}
self.extract_required = function(required, element, vm) {
var params = {};
$.each(required, function(i,v) {
//checks if required param in DOM element
//then falls back to vm
var required_param = v.replace(/\s/g, '');
if (required_param in $(element).data())
params[required_param] = $(element).data(required_param);
else if (required_param in vm)
params[required_param] = vm[required_param];
})
return params;
}
self.remember_import = function(model, eventobj) {
var target = $(eventobj.currentTarget);
var params = {
path: model['path'],
filename: model['filename']
}
$.extend(params, self.extract_required(['path','filename'], target, model));
self.import_information(params);
}
self.import_server = function(vm, eventobj) {
var params = self.import_information();
params['server_name'] = $('#import_server_modal').find('input[name="newname"]').val();
$.getJSON('/import_server', params).then(self.ajax.received, self.ajax.lost)
.then(self.show_page('dashboard'));
}
self.prune_archives = function(vm, eventobj) {
var params = {
cmd: 'prune_archives',
server_name: self.server().server_name,
filename: self.pruning.archives.archives_to_delete
}
$.getJSON('/server', params).then(self.ajax.received, self.ajax.lost)
.then(function() {self.ajax.refresh(null)});
}
self.prune_increments = function(vm, eventobj) {
var params = {
cmd: 'prune',
server_name: self.server().server_name,
step: self.pruning.increments.step
}
$.getJSON('/server', params).then(self.ajax.received, self.ajax.lost)
.then(function() {self.ajax.refresh(null)});
}
self.remember_profile = function(model, eventobj) {
self.pruning.profiles.profile(model.profile);
}
self.prune_profile = function(vm, eventobj) {
var params = {
cmd: 'remove_profile',
profile: self.pruning.profiles.profile
}
$.getJSON('/host', params).then(self.ajax.received, self.ajax.lost)
.then(function() {self.ajax.refresh(null)});
}
self.delete_server = function(vm, eventobj) {
var params = {
server_name: self.server().server_name
}
var unchecked = $('#delete_confirmations input[type=checkbox]').filter(function(i,v) {
return !$(v).prop('checked');
})
if (unchecked.length == 0) {
$.getJSON('/delete_server', params)
.then(self.ajax.received, self.ajax.lost)
.done(function(){ self.show_page('dashboard') },
function(){})
} else {
$.gritter.add({
text: 'No action taken; must confirm all content will be deleted to continue.',
sticky: false,
time: '3000',
class_name: 'gritter-warning'
});
}
}
self.change_group = function(vm, eventobj) {
var params = {
group: $(eventobj.currentTarget).val(),
server_name: self.server().server_name
}
$.getJSON('/change_group', params).then(self.ajax.received, self.ajax.lost)
}
self.change_pc_group = function(vm, eventobj) {
var params = {
group: $(eventobj.currentTarget).val()
}
$.getJSON('/change_pc_group', params).then(self.ajax.received, self.ajax.lost)
}
self.command = function(vm, eventobj) {
var target = $(eventobj.currentTarget);
var cmd = $(target).data('cmd');
var required = $(target).data('required').split(',');
var params = {cmd: cmd};
$.extend(params, self.extract_required(required, target, vm));
if (required.indexOf('force') >= 0)
params['force'] = true;
//console.log(params)
var refresh_time = parseInt($(target).data('refresh'));
if (required.indexOf('server_name') >= 0) {
$.extend(params, {server_name: self.server().server_name});
$.getJSON('/server', params).then(self.ajax.received, self.ajax.lost)
.then(function() {self.ajax.refresh(refresh_time)});
} else {
$.getJSON('/host', params).then(self.ajax.received, self.ajax.lost)
.then(function() {self.ajax.refresh(refresh_time)});
}
}
self.page.subscribe(function(page){
var server_name = self.server().server_name;
var params = {server_name: server_name};
switch(page) {
case 'dashboard':
$.getJSON('/vm/status').then(self.refresh.pings);
$.getJSON('/vm/dashboard').then(self.refresh.dashboard).then(self.redraw.gauges);
self.redraw.chart();
break;
case 'backup_list':
$.getJSON('/vm/increments', params).then(self.refresh.increments);
break;
case 'archive_list':
$.getJSON('/vm/archives', params).then(self.refresh.archives);
break;
case 'server_status':
$.getJSON('/vm/status').then(self.refresh.pings).then(self.redraw.gauges);
$.getJSON('/vm/increments', params).then(self.refresh.increments);
$.getJSON('/vm/archives', params).then(self.refresh.archives);
$.getJSON('/vm/server_summary', params).then(self.refresh.summary);
setTimeout(function() {
$('#delete_server input[type="checkbox"]').not('.nostyle').iCheck({
checkboxClass: 'icheckbox_minimal-grey',
radioClass: 'iradio_minimal-grey',
increaseArea: '40%' // optional
});
}, 500)
break;
case 'profiles':
$.getJSON('/vm/profiles').then(self.refresh.profiles);
break;
case 'profile_view':
$.getJSON('/vm/profiles').then(self.refresh.profiles);
break;
case 'create_server':
$.getJSON('/vm/profiles').then(self.refresh.profiles);
break;
case 'server_properties':
$.getJSON('/server', $.extend({}, params, {'cmd': 'sp'})).then(self.refresh.sp);
break;
case 'server_config':
$.getJSON('/server', $.extend({}, params, {'cmd': 'sc'})).then(self.refresh.sc);
break;
case 'importable':
$.getJSON('/vm/importable', {}).then(self.refresh.importable);
break;
case 'console':
$.getJSON('/logs', params).then(self.refresh.logs);
break;
default:
break;
}
})
self.pruning.archives.user_input.subscribe(function(new_value) {
var clone = self.vmdata.archives().slice(0).reverse();
var match;
var reclaimed = 0.0;
$.each(clone, function(i,v) {
if (v.friendly_timestamp == new_value) {
match = i;
self.pruning.archives.filename(v.filename);
return false;
}
reclaimed += v.size;
})
if (!match){
self.pruning.archives.remove_count(0);
self.pruning.archives.space_reclaimed(0.0);
self.pruning.archives.archives_to_delete = '';
} else {
var hits = clone.slice(0,match).map(function(e) { return e.filename });
self.pruning.archives.remove_count(hits.length);
self.pruning.archives.space_reclaimed(bytes_to_mb(reclaimed));
self.pruning.archives.archives_to_delete = hits.join(' ');
}
})
self.pruning.increments.user_input.subscribe(function(new_value){
var clone = self.vmdata.increments().slice(0).reverse();
var match;
var reclaimed = 0.0;
$.each(clone, function(i,v) {
if (v.timestamp == new_value || v.step == new_value) {
match = i;
self.pruning.increments.step = v.step;
return false;
}
if (v.increment_size.slice(-2) == 'KB')
reclaimed += parseFloat(v.increment_size) / 1000;
else
reclaimed += parseFloat(v.increment_size);
})
if (!match){
self.pruning.increments.remove_count(0);
self.pruning.increments.space_reclaimed(0);
self.pruning.increments.step = '';
} else {
self.pruning.increments.remove_count(clone.slice(0,match).length);
self.pruning.increments.space_reclaimed(reclaimed);
}
})
/* form submissions */
self.create_server = function(form) {
var server_name = $(form).find('input[name="server_name"]').val();
var group = $(form).find('select[name=group]').val();
var step1 = $(form).find('fieldset#step1 :input').filter(function() {
return ($(this).val() ? true : false);
})
var step2 = $(form).find('fieldset#step2 :input').filter(function() {
return ($(this).val() ? true : false);
})
var step3 = $(form).find('fieldset#step3 :input').filter(function() {
return ($(this).val() ? true : false);
})
var sp = {};
$.each($(step2).serialize().split('&'), function(i,v) {
sp[v.split('=')[0]] = v.split('=')[1];
})
var sc = {};
$.each(step3, function(i,v) {
input = $(v);
section = input.data('section');
if (!(section in sc))
sc[section] = {};
if ($(input).is(':checkbox')) {
sc[section][input.attr('name')] = $(input).is(':checked');
} else{
sc[section][input.attr('name')] = input.val();
}
})
params = {
'server_name': server_name,
'sp': JSON.stringify(sp),
'sc': JSON.stringify(sc),
'group': group
}
$.getJSON('/create', params)
.then(self.ajax.received, self.ajax.lost)
.done(function() {
self.show_page('dashboard');
},function(){
});
}
self.console_command = function(form) {
var user_input = $(form).find('input[name=console_command]');
params = {
cmd: user_input.val(),
server_name: self.server().server_name
}
$.getJSON('/server', params)
.then(self.ajax.received, self.ajax.lost).then(function() {
self.ajax.refresh(null);
user_input.val('');
});
}
self.define_profile = function(form) {
var step1 = $(form).find('fieldset :input').filter(function() {
return ($(this).val() ? true : false);
})
var properties = {};
$(step1).each(function() {
properties[ $(this).attr('name') ] = $(this).val();
})
var props = $(form).find('input[name="tags"]').map(function(i,v) {
return $(this).val();
});
properties['ignore'] = (props.length > 0) ? props.get().join(' ') : '';
delete properties.tags;
params = {
'cmd': 'define_profile',
'profile_dict': JSON.stringify(properties),
}
$.getJSON('/host', params)
.then(self.ajax.received, self.ajax.lost)
.done(function() {
self.show_page('profiles');
},function(){
});
}
/* promises */
self.ajax = {
received: function(data) {
$.gritter.add({
text: (data.payload) ? data.payload : '{0} [{1}]'.format(data.cmd, data.result),
sticky: false,
time: '3000',
class_name: 'gritter-{0}'.format(data.result)
});
console.log(data);
if (data.result == 'success')
return $.Deferred().resolve().promise();
else
return $.Deferred().reject().promise();
},
lost: function(data) {
$.gritter.add({
text: data.payload || 'Server did not respond to request',
time: '4000',
class_name: 'gritter-warning'
});
console.log(data);
return $.Deferred().reject().promise();
},
refresh: function(time) {
setTimeout(self.page.valueHasMutated, time || self.refresh_rate)
}
}
self.refresh = {
dashboard: function(data) {
self.dashboard.uptime(seconds_to_days(data.uptime));
self.dashboard.memfree(data.memfree);
self.dashboard.whoami(data.whoami);
self.dashboard.group(data.group);
self.dashboard.disk_usage(data.df);
self.dashboard.disk_usage_pct((str_to_bytes(self.dashboard.disk_usage().used) /
str_to_bytes(self.dashboard.disk_usage().total) * 100).toFixed(1));
self.dashboard.groups(data.groups);
self.dashboard.pc_permissions(data.pc_permissions);
self.dashboard.pc_group(data.pc_group);
self.dashboard.git_hash(data.git_hash);
self.dashboard.stock_profiles(data.stock_profiles);
self.dashboard.base_directory(data.base_directory);
$('#pc_group option').filter(function () {
return $(this).val() == data.pc_group
}).prop('selected', true);
},
pings: function(data) {
self.vmdata.pings.removeAll();
self.dashboard.servers_up(0);
$.each(data.ascending_by('server_name'), function(i,v) {
self.vmdata.pings.push( new model_server(v) );
if (self.server().server_name == v.server_name)
self.server(new model_server(v));
if (v.up)
self.dashboard.servers_up(self.dashboard.servers_up()+1)
})
},
archives: function(data) {
self.vmdata.archives(data.ascending_by('timestamp').reverse());
$("input#prune_archive_input").autocomplete({
source: self.vmdata.archives().map(function(i) {
return i.friendly_timestamp
})
});
},
increments: function(data) {
self.vmdata.increments(data);
$("input#prune_increment_input").autocomplete({
source: self.vmdata.increments().map(function(i) {
return i.timestamp
})
});
},
summary: function(data) {
self.summary.owner(data.owner);
self.summary.group(data.group);
self.summary.du_cwd(bytes_to_mb(data.du_cwd));
setTimeout(function() {
$('#available_groups option').filter(function () {
return $(this).val() == self.summary.group()
}).prop('selected', true)}, 50)
},
profiles: function(data) {
self.vmdata.profiles.removeAll();
$.each(data, function(i,v) {
self.vmdata.profiles.push( new model_profile(v) );
if (self.profile().profile == v.profile)
self.profile(new model_profile(v));
})
self.vmdata.profiles(self.vmdata.profiles().ascending_by('profile'));
},
sp: function(data) {
self.vmdata.sp.removeAll();
$.each(data.payload, function(option, value) {
self.vmdata.sp.push( new model_property(self.server().server_name, option, value) )
})
self.vmdata.sp(self.vmdata.sp().ascending_by('option'));
$('table#table_properties input[type="checkbox"]').not('.nostyle').iCheck({
checkboxClass: 'icheckbox_minimal-grey',
radioClass: 'iradio_minimal-grey',
increaseArea: '40%' // optional
});
},
sc: function(data) {
self.vmdata.sc.removeAll();
$.each(data.payload, function(section, option_value_pair){
$.each(option_value_pair, function(option, value){
self.vmdata.sc.push(new model_property(self.server().server_name, option, value, section))
})
})
self.vmdata.sc(self.vmdata.sc().ascending_by('section'));
$('table#table_config input[type="checkbox"]').not('.nostyle').iCheck({
checkboxClass: 'icheckbox_minimal-grey',
radioClass: 'iradio_minimal-grey',
increaseArea: '40%' // optional
});
setTimeout(function() {
$.each(self.vmdata.sc(), function(i,v) {
if (v.type == 'interval'){
$('#{0}_{1} option'.format(v.section(), v.option())).filter(function () {
return $(this).val() == v.val()
}).prop('selected', true)
}
})
}, 50)
},
importable: function(data) {
self.vmdata.importable(data.ascending_by('filename'));
},
logs: function(data) {
if (!data.payload.length) {
self.reset_logs();
} else {
$.each(data.payload, function(i,v) {
if (!v.match(/\[INFO\] \/127.0.0.1:\d+ lost connection/) && !v.match(/\[SEVERE\] Reached end of stream for \/127.0.0.1/))
self.vmdata.logs.push(new model_logline(v));
})
}
}
}
/* redraw functions */
self.judge_severity = function(percent) {
var colors = ['green', 'yellow', 'orange', 'red'];
var thresholds = [0, 60, 75, 90];
var gauge_color = colors[0];
for (var i=0; i < colors.length; i++)
gauge_color = (parseInt(percent) >= thresholds[i] ? colors[i] : gauge_color)
return gauge_color;
}
self.redraw = {
gauges: function() {
$('#{0} .gauge'.format(self.page())).easyPieChart({
barColor: $color[self.judge_severity( $(this).data('percent') )],
scaleColor: false,
trackColor: '#999',
lineCap: 'butt',
lineWidth: 4,
size: 50,
animate: 1000
});
},
chart: function() {
function rerender(data) {
function enumerate(arr) {
var res = [];
for (var i = 0; i < arr.length; ++i)
res.push([i, arr[i]])
return res;
}
self.load_averages.one.push(data[0])
self.load_averages.five.push(data[1])
self.load_averages.fifteen.push(data[2])
while (self.load_averages.one.length > (self.load_averages.options.xaxis.max + 1)){
self.load_averages.one.splice(0,1)
self.load_averages.five.splice(0,1)
self.load_averages.fifteen.splice(0,1)
}
//colors http://www.jqueryflottutorial.com/tester-4.html
var dataset = [
{ label: "fifteen", data: enumerate(self.load_averages['fifteen']), color: "#0077FF" },
{ label: "five", data: enumerate(self.load_averages['five']), color: "#ED7B00" },
{ label: "one", data: enumerate(self.load_averages['one']), color: "#E8E800" }
]
self.load_averages.options.yaxis.max = Math.max(
self.load_averages.one.max(),
self.load_averages.five.max(),
self.load_averages.fifteen.max()) || 1;
var plot = $.plot($("#load_averages"), dataset, self.load_averages.options);
plot.draw();
}
function update() {
if (self.page() != 'dashboard' || !self.load_averages.autorefresh()) {
self.load_averages.one.push.apply(self.load_averages.one, [0,0,0])
self.load_averages.five.push.apply(self.load_averages.five, [0,0,0])
self.load_averages.fifteen.push.apply(self.load_averages.fifteen, [0,0,0])
return
}
$.getJSON('/vm/loadavg').then(rerender);
setTimeout(update, self.refresh_loadavg);
}
update();
}
}
/* viewmodel startup */
self.show_page('dashboard');
}
/* prototypes */
String.prototype.format = String.prototype.f = function() {
var s = this,
i = arguments.length;
while (i--) { s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);}
return s;
};
Array.prototype.max = function () {
return Math.max.apply(Math, this);
};
Array.prototype.ascending_by = function(param) {
return this.sort(function(a, b) {return a[param] == b[param] ? 0 : (a[param] < b[param] ? -1 : 1) })
}
Array.prototype.sum = function(param) {
var total = 0;
for (var i=0; i < this.length; i++)
total += this[i][param]
return total;
}
function seconds_to_days(seconds){
var numdays = Math.floor(seconds / 86400);
var numhours = Math.floor((seconds % 86400) / 3600);
var numminutes = Math.floor(((seconds % 86400) % 3600) / 60);
var numseconds = ((seconds % 86400) % 3600) % 60;
return numdays + " days " + ('0' + numhours).slice(-2) + ":" + ('0' + numminutes).slice(-2) + ":" + ('0' + numseconds).slice(-2);
}
function seconds_to_time(seconds) {
function zero_pad(number){
if (number.toString().length == 1)
return '0' + number;
else
return number;
}
var hours = Math.floor(seconds / (60 * 60));
var divisor_for_minutes = seconds % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);
var divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);
return '{0}:{1}:{2}'.format(hours, zero_pad(minutes), zero_pad(seconds));
}
function str_to_bytes(str) {
if (str.substr(-1) == 'T')
return parseFloat(str) * Math.pow(10,12);
else if (str.substr(-1) == 'G')
return parseFloat(str) * Math.pow(10,9);
else if (str.substr(-1) == 'M')
return parseFloat(str) * Math.pow(10,6);
else if (str.substr(-1) == 'K')
return parseFloat(str) * Math.pow(10,3);
else
return parseFloat(str);
}
function bytes_to_mb(bytes){
//http://stackoverflow.com/a/18650828
if (bytes == 0)
return '0B';
else if (bytes < 1024)
return bytes + 'B';
var k = 1024;
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var i = Math.floor(Math.log(bytes) / Math.log(k));
return (bytes / Math.pow(k, i)).toPrecision(3) + sizes[i];
}
| koderiter/mineos | html/js/scriptin.js | JavaScript | gpl-3.0 | 30,637 |
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-26989160-4', '3scape.me');
ga('require', 'displayfeatures');
ga('require', 'linkid', 'linkid.js');
ga('send', 'pageview');
| kmcurry/3Scape | public/js/google.js | JavaScript | gpl-3.0 | 453 |
$(document).ready(function(){
$('#countdown').countdown( {date: '19 april 2013 16:24:00'} );
}); | gengjian1203/GoldAbacus | vendor/countdown/ext.js | JavaScript | gpl-3.0 | 99 |
odoo.define('website_forum.tour_forum', function (require) {
'use strict';
var core = require('web.core');
var Tour = require('web.Tour');
var _t = core._t;
Tour.register({
id: 'question',
name: _t("Create a question"),
steps: [
{
title: _t("Create a Question!"),
content: _t("Let's go through the first steps to create a new question."),
popover: { next: _t("Start Tutorial"), end: _t("Skip It") },
},
{
title: _t("Add Content"),
element: '#oe_main_menu_navbar a[data-action=new_page]',
placement: 'bottom',
content: _t("Use this button to create a new forum like any other document (page, menu, products, event, ...)."),
popover: { fixed: true },
},
{
title: _t("New Forum"),
element: 'a[data-action=new_forum]',
placement: 'left',
content: _t("Select this menu item to create a new forum."),
popover: { fixed: true },
},
{
title: _t("Forum Name"),
element: '.modal #editor_new_forum input[type=text]',
sampleText:'New Forum',
placement: 'right',
content: _t("Enter a name for your new forum."),
},
{
title: _t("Create Forum"),
waitNot: ".modal #editor_new_forum input[type=text]:propValue('')",
element: '.modal button.btn-primary',
placement: 'right',
content: _t("Click <em>Continue</em> to create the forum."),
},
{
title: _t("New Forum Created"),
waitNot: '.modal:visible',
content: _t("This page contains all the information related to the new forum."),
popover: { next: _t("Continue") },
},
{
title: _t("Ask a Question"),
element: '.btn-block a:first',
placement: 'left',
content: _t("Ask the question in this forum by clicking on the button."),
},
{
title: _t("Question Title"),
element: 'input[name=post_name]',
sampleText:'First Question Title',
placement: 'top',
content: _t("Give your question title."),
},
{
title: _t("Question"),
waitNot: "input[name=post_name]:propValue('')",
element: '.note-editable p',
sampleText: 'First Question',
placement: 'top',
content: _t("Put your question here."),
},
{
title: _t("Give Tag"),
waitNot: '.note-editable p:containsExact("<br>")',
element: '.select2-choices',
placement: 'top',
content: _t("Insert tags related to your question."),
},
{
title: _t("Post Question"),
waitNot: "input[id=s2id_autogen2]:propValue('Tags')",
element: 'button:contains("Post Your Question")',
placement: 'bottom',
content: _t("Click to post your question."),
},
{
title: _t("New Question Created"),
waitFor: '.fa-star',
content: _t("This page contains the newly created questions."),
popover: { next: _t("Continue") },
},
{
title: _t("Answer"),
element: '.note-editable p',
sampleText: 'First Answer',
placement: 'top',
content: _t("Put your answer here."),
},
{
title: _t("Post Answer"),
waitNot: '.note-editable p:containsExact("<br>")',
element: 'button:contains("Post Answer")',
placement: 'bottom',
content: _t("Click to post your answer."),
},
{
title: _t("Answer Posted"),
waitFor: '.fa-check-circle',
content: _t("This page contains the newly created questions and its answers."),
popover: { next: _t("Continue") },
},
{
title: _t("Accept Answer"),
element: 'a[data-karma="20"]:first',
placement: 'right',
content: _t("Click here to accept this answer."),
},
{
title: _t("Congratulations"),
waitFor: '.oe_answer_true',
content: _t("Congratulations! You just created and post your first question and answer."),
popover: { next: _t("Close Tutorial") },
},
]
});
});
| akhmadMizkat/odoo | addons/website_forum/static/src/js/website_tour_forum.js | JavaScript | gpl-3.0 | 4,695 |
tutao.provide('tutao.tutanota.ctrl.lang.ja');
tutao.tutanota.ctrl.lang.ja.writing_direction = "ltr";
tutao.tutanota.ctrl.lang.ja.id = "ja";
tutao.tutanota.ctrl.lang.ja.keys = {
"account_label": "ユーザー",
"activate_action": "有効にする",
"address_label": "アドレス",
"add_action": "追加する",
"adminEmailSettings_action": "メール",
"adminMessages_action": "表示されたメッセージ",
"adminUserList_action": "ユーザー管理",
"afterRegistration_msg": "アカウントが作成されました。ログインして楽しみましょう。",
"archive_action": "アーカイブ",
"backTologin_action": "ログインに戻る",
"back_action": "前",
"bcc_label": "Bcc",
"birthday_alt": "生年月日",
"cancel_action": "キャンセルする",
"captchaDisplay_label": "キャプチャ",
"changeNotificationMailLanguage_msg": "通知メールの言語:",
"comment_label": "コメント",
"community_label": "コミュニティ",
"company_label": "会社",
"company_placeholder": "会社",
"confidentialMail_alt": "このメールはエンドツーエンドで暗号化され、送信されました。",
"confidential_action": "親展",
"contactImage_alt": "画像",
"contacts_alt": "連絡先",
"contacts_label": "連絡先",
"createAccountInvalidCaptcha_msg": "申し訳ありませんが、回答が間違っています。もう一度やり直して下さい。",
"createAccountRunning_msg": "アカウントを作成しています...",
"custom_label": "カスタム",
"db_label": "データベース",
"defaultExternalDelivery_label": "デフォルトの送信設定",
"defaultSenderMailAddress_label": "デフォルトの送信元",
"deleteAccountWait_msg": "アカウントを削除しています...",
"deleteContact_msg": "この連絡先を本当に削除しますか?",
"deleteMail_msg": "新規メールを送信せずに削除しますか?",
"deleteTrash_action": "すべて削除",
"delete_action": "削除",
"dev_label": "開発者",
"discardContactChangesFor_msg": "{1}の連絡先の変更を破棄しますか?",
"editFolder_action": "編集",
"editUser_label": "ユーザーを編集する",
"email_label": "Eメール",
"enterPresharedPassword_msg": "送信者と共有しているパスワードを入力して下さい。",
"errorNotification_label": "エラー通知",
"export_action": "エクスポートする",
"externalNotificationMailBody3_msg": "暗号化メールを表示する",
"facebook_label": "Facebook",
"fax_label": "ファックス",
"finished_msg": "完了しました。",
"folderNameCreate_label": "新しいフォルダーを作成する",
"folderNameNeutral_msg": "フォルダ名を入力して下さい。",
"folderTitle_label": "フォルダ",
"goodPassphrase_action": "良いパスワードにするには?",
"help_label": "ヘルプを見る:",
"importCsvInvalid_msg": "",
"importCsv_label": "CSVデータをインポートする",
"import_action": "インポートする",
"invalidLink_msg": "申し訳ありません、このリンクは無効です。",
"invalidPassword_msg": "無効なパスワードです。もう一度確認して下さい。",
"invalidRecipients_msg": "受信者欄の無効なメールアドレスを修正して下さい。",
"invitationMailSubject_msg": "Tutanotaで私たちのプライバシーを取り戻そう!",
"invite_alt": "招待",
"invite_label": "招待",
"languageAlbanian_label": "アルバニア語",
"languageArabic_label": "アラビア語",
"languageBulgarian_label": "ブルガリア語",
"languageChineseSimplified_label": "中国語, 簡体字",
"languageCroatian_label": "クロアチア語",
"languageDutch_label": "オランダ語",
"languageEnglish_label": "英語",
"languageFinnish_label": "フィンランド語",
"languageFrench_label": "フランス語",
"languageGerman_label": "ドイツ語",
"languageGreek_label": "ギリシャ語",
"languageItalian_label": "イタリア語",
"languageLithuanian_label": "リトアニア語",
"languageMacedonian_label": "マケドニア語",
"languagePolish_label": "ポーランド語",
"languagePortugeseBrazil_label": "ポルトガル語, ブラジル",
"languagePortugesePortugal_label": "ポルトガル語, ポルトガル",
"languageRomanian_label": "ルーマニア語",
"languageRussian_label": "ロシア語",
"languageSerbian_label": "セルビア語",
"languageSpanish_label": "スペイン語",
"languageTurkish_label": "トルコ語",
"lastName_placeholder": "姓",
"linkedin_label": "LinkedIn",
"loading_msg": "読み込み中",
"loginNameInfoAdmin_msg": "任意: ユーザー名",
"login_action": "ログイン",
"login_msg": "ログインする。",
"logout_alt": "ログアウト",
"logout_label": "ログアウト",
"logs_label": "ログ",
"mailAddressAliases_label": "メールエイリアス",
"mailAddressNA_msg": "このメールアドレスは利用できません。",
"meDativ_label": "自分",
"meNominative_label": "自分",
"mobileNumberValidFormat_msg": "フォーマット OK.",
"monthNames_label": [
"1月",
"2月",
"3月",
"4月",
"5月",
"6月",
"7月",
"8月",
"9月",
"10月",
"11月",
"12月"
],
"move_action": "移動する",
"newMails_msg": "Tutanotaの新着メールを受信しました。",
"noConnection_msg": "あなたはオフラインです。Tutanotaに接続できませんでした。",
"noContact_msg": "連絡先が1つも選択されていません。",
"notificationMailSignatureSubject_msg": "{1}からの機密メール",
"notificationMailSignature_label": "サイン",
"ok_action": "OK",
"oldBrowser_msg": "申し訳ありませんが、あなたは古いブラウザをご利用中です。以下のいずれかのブラウザの最新バージョンにアップグレードして下さい:",
"other_label": "その他",
"password1InvalidUnsecure_msg": "このパスワードは安全性に問題があります。",
"passwords_label": "パスワード",
"passwordTransmission_label": "パスワードの送信",
"passwordWrongInvalid_msg": "パスワードが間違っています。",
"password_label": "パスワード",
"presharedPasswordAndStrength_msg": "パスワードの強さ",
"preSharedPasswordNeeded_label": "各外部受信者用の承認パスワードを入力して下さい。",
"privacyLink_label": "プライバシーポリシー",
"registrationSubHeadline2_msg": "登録情報を入力して下さい。(ステップ2/2)",
"removeAddress_alt": "このアドレスを削除する",
"removePhoneNumber_alt": "",
"removeRecipient_alt": "受信者を削除する",
"rename_action": "名前の変更",
"replyAll_action": "全員に返信",
"saved_msg": "保存が完了しました!",
"savePassword_label": "保存",
"save_action": "保存",
"selectAddress_label": "Eメールアドレスを選択して下さい",
"sendMail_alt": "このアドレス宛にメールを送る",
"send_action": "送信する",
"sentMails_alt": "送信済みメール",
"sent_action": "送信完了",
"settings_label": "設定",
"showAddress_alt": "この住所をGoogleマップで表示する",
"showAttachment_label": "添付を表示する",
"showInAddressBook_alt": "連絡先を編集する",
"storageCapacityNoLimit_label": "制限なし",
"subject_label": "件名",
"terms_label": "確認",
"title_placeholder": "件名",
"tooBigAttachment_msg": "次のファイルは全体サイズが25MBを超えるため添付できません:",
"unsecureMailSendFailureSubject_msg": "メールを送信できませんでした",
"unsupportedBrowser_msg": "申し訳ありませんが、ご利用のブラウザは対応していません。以下のいずれかのブラウザをご利用下さい。",
"welcomeMailSubject_msg": "安心して下さい: あなたのデータのプライバシーは保たれています。",
"work_label": "仕事",
"xing_label": "XING"
}; | msoftware/tutanota-1 | web/js/ctrl/lang/ja.js | JavaScript | gpl-3.0 | 8,146 |
'use strict';var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc);
switch (arguments.length) {
case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target);
case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0);
case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc);
}
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var di_1 = require('angular2/src/core/di');
var serializer_1 = require('angular2/src/web_workers/shared/serializer');
var messaging_api_1 = require('angular2/src/web_workers/shared/messaging_api');
var xhr_1 = require('angular2/src/core/compiler/xhr');
var service_message_broker_1 = require('angular2/src/web_workers/shared/service_message_broker');
var bind_1 = require('./bind');
var MessageBasedXHRImpl = (function () {
function MessageBasedXHRImpl(_brokerFactory, _xhr) {
this._brokerFactory = _brokerFactory;
this._xhr = _xhr;
}
MessageBasedXHRImpl.prototype.start = function () {
var broker = this._brokerFactory.createMessageBroker(messaging_api_1.XHR_CHANNEL);
broker.registerMethod("get", [serializer_1.PRIMITIVE], bind_1.bind(this._xhr.get, this._xhr), serializer_1.PRIMITIVE);
};
MessageBasedXHRImpl = __decorate([
di_1.Injectable(),
__metadata('design:paramtypes', [service_message_broker_1.ServiceMessageBrokerFactory, xhr_1.XHR])
], MessageBasedXHRImpl);
return MessageBasedXHRImpl;
})();
exports.MessageBasedXHRImpl = MessageBasedXHRImpl;
//# sourceMappingURL=xhr_impl.js.map | NodeVision/NodeVision | node_modules/angular2/src/web_workers/ui/xhr_impl.js | JavaScript | gpl-3.0 | 1,947 |
define("ghost-admin/templates/components/gh-subscribers-table", ["exports"], function (exports) {
exports["default"] = Ember.HTMLBars.template((function () {
var child0 = (function () {
var child0 = (function () {
var child0 = (function () {
var child0 = (function () {
return {
meta: {
"fragmentReason": false,
"revision": "[email protected]",
"loc": {
"source": null,
"start": {
"line": 6,
"column": 12
},
"end": {
"line": 8,
"column": 12
}
},
"moduleName": "ghost-admin/templates/components/gh-subscribers-table.hbs"
},
isEmpty: false,
arity: 0,
cachedFragment: null,
hasRendered: false,
buildFragment: function buildFragment(dom) {
var el0 = dom.createDocumentFragment();
var el1 = dom.createTextNode(" Loading...\n");
dom.appendChild(el0, el1);
return el0;
},
buildRenderNodes: function buildRenderNodes() {
return [];
},
statements: [],
locals: [],
templates: []
};
})();
return {
meta: {
"fragmentReason": false,
"revision": "[email protected]",
"loc": {
"source": null,
"start": {
"line": 5,
"column": 8
},
"end": {
"line": 9,
"column": 8
}
},
"moduleName": "ghost-admin/templates/components/gh-subscribers-table.hbs"
},
isEmpty: false,
arity: 0,
cachedFragment: null,
hasRendered: false,
buildFragment: function buildFragment(dom) {
var el0 = dom.createDocumentFragment();
var el1 = dom.createComment("");
dom.appendChild(el0, el1);
return el0;
},
buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) {
var morphs = new Array(1);
morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement);
dom.insertBoundary(fragment, 0);
dom.insertBoundary(fragment, null);
return morphs;
},
statements: [["block", "body.loader", [], [], 0, null, ["loc", [null, [6, 12], [8, 28]]]]],
locals: [],
templates: [child0]
};
})();
var child1 = (function () {
var child0 = (function () {
var child0 = (function () {
return {
meta: {
"fragmentReason": false,
"revision": "[email protected]",
"loc": {
"source": null,
"start": {
"line": 11,
"column": 16
},
"end": {
"line": 13,
"column": 16
}
},
"moduleName": "ghost-admin/templates/components/gh-subscribers-table.hbs"
},
isEmpty: false,
arity: 0,
cachedFragment: null,
hasRendered: false,
buildFragment: function buildFragment(dom) {
var el0 = dom.createDocumentFragment();
var el1 = dom.createTextNode(" No subscribers found.\n");
dom.appendChild(el0, el1);
return el0;
},
buildRenderNodes: function buildRenderNodes() {
return [];
},
statements: [],
locals: [],
templates: []
};
})();
return {
meta: {
"fragmentReason": false,
"revision": "[email protected]",
"loc": {
"source": null,
"start": {
"line": 10,
"column": 12
},
"end": {
"line": 14,
"column": 12
}
},
"moduleName": "ghost-admin/templates/components/gh-subscribers-table.hbs"
},
isEmpty: false,
arity: 0,
cachedFragment: null,
hasRendered: false,
buildFragment: function buildFragment(dom) {
var el0 = dom.createDocumentFragment();
var el1 = dom.createComment("");
dom.appendChild(el0, el1);
return el0;
},
buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) {
var morphs = new Array(1);
morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement);
dom.insertBoundary(fragment, 0);
dom.insertBoundary(fragment, null);
return morphs;
},
statements: [["block", "body.no-data", [], [], 0, null, ["loc", [null, [11, 16], [13, 33]]]]],
locals: [],
templates: [child0]
};
})();
return {
meta: {
"fragmentReason": false,
"revision": "[email protected]",
"loc": {
"source": null,
"start": {
"line": 9,
"column": 8
},
"end": {
"line": 15,
"column": 8
}
},
"moduleName": "ghost-admin/templates/components/gh-subscribers-table.hbs"
},
isEmpty: false,
arity: 0,
cachedFragment: null,
hasRendered: false,
buildFragment: function buildFragment(dom) {
var el0 = dom.createDocumentFragment();
var el1 = dom.createComment("");
dom.appendChild(el0, el1);
return el0;
},
buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) {
var morphs = new Array(1);
morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement);
dom.insertBoundary(fragment, 0);
dom.insertBoundary(fragment, null);
return morphs;
},
statements: [["block", "if", [["get", "table.isEmpty", ["loc", [null, [10, 18], [10, 31]]]]], [], 0, null, ["loc", [null, [10, 12], [14, 19]]]]],
locals: [],
templates: [child0]
};
})();
return {
meta: {
"fragmentReason": false,
"revision": "[email protected]",
"loc": {
"source": null,
"start": {
"line": 4,
"column": 4
},
"end": {
"line": 16,
"column": 4
}
},
"moduleName": "ghost-admin/templates/components/gh-subscribers-table.hbs"
},
isEmpty: false,
arity: 1,
cachedFragment: null,
hasRendered: false,
buildFragment: function buildFragment(dom) {
var el0 = dom.createDocumentFragment();
var el1 = dom.createComment("");
dom.appendChild(el0, el1);
return el0;
},
buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) {
var morphs = new Array(1);
morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement);
dom.insertBoundary(fragment, 0);
dom.insertBoundary(fragment, null);
return morphs;
},
statements: [["block", "if", [["get", "isLoading", ["loc", [null, [5, 14], [5, 23]]]]], [], 0, 1, ["loc", [null, [5, 8], [15, 15]]]]],
locals: ["body"],
templates: [child0, child1]
};
})();
return {
meta: {
"fragmentReason": {
"name": "missing-wrapper",
"problems": ["wrong-type", "multiple-nodes"]
},
"revision": "[email protected]",
"loc": {
"source": null,
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 17,
"column": 0
}
},
"moduleName": "ghost-admin/templates/components/gh-subscribers-table.hbs"
},
isEmpty: false,
arity: 1,
cachedFragment: null,
hasRendered: false,
buildFragment: function buildFragment(dom) {
var el0 = dom.createDocumentFragment();
var el1 = dom.createTextNode(" ");
dom.appendChild(el0, el1);
var el1 = dom.createComment("");
dom.appendChild(el0, el1);
var el1 = dom.createTextNode("\n\n");
dom.appendChild(el0, el1);
var el1 = dom.createComment("");
dom.appendChild(el0, el1);
return el0;
},
buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) {
var morphs = new Array(2);
morphs[0] = dom.createMorphAt(fragment, 1, 1, contextualElement);
morphs[1] = dom.createMorphAt(fragment, 3, 3, contextualElement);
dom.insertBoundary(fragment, null);
return morphs;
},
statements: [["inline", "t.head", [], ["onColumnClick", ["subexpr", "action", [["get", "sortByColumn", ["loc", [null, [2, 35], [2, 47]]]]], [], ["loc", [null, [2, 27], [2, 48]]]], "iconAscending", "icon-ascending", "iconDescending", "icon-descending"], ["loc", [null, [2, 4], [2, 114]]]], ["block", "t.body", [], ["canSelect", false, "tableActions", ["subexpr", "hash", [], ["delete", ["subexpr", "action", [["get", "delete", ["loc", [null, [4, 64], [4, 70]]]]], [], ["loc", [null, [4, 56], [4, 71]]]]], ["loc", [null, [4, 43], [4, 72]]]]], 0, null, ["loc", [null, [4, 4], [16, 15]]]]],
locals: ["t"],
templates: [child0]
};
})();
return {
meta: {
"fragmentReason": {
"name": "missing-wrapper",
"problems": ["wrong-type"]
},
"revision": "[email protected]",
"loc": {
"source": null,
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 18,
"column": 0
}
},
"moduleName": "ghost-admin/templates/components/gh-subscribers-table.hbs"
},
isEmpty: false,
arity: 0,
cachedFragment: null,
hasRendered: false,
buildFragment: function buildFragment(dom) {
var el0 = dom.createDocumentFragment();
var el1 = dom.createComment("");
dom.appendChild(el0, el1);
return el0;
},
buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) {
var morphs = new Array(1);
morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement);
dom.insertBoundary(fragment, 0);
dom.insertBoundary(fragment, null);
return morphs;
},
statements: [["block", "gh-light-table", [["get", "table", ["loc", [null, [1, 18], [1, 23]]]]], ["scrollContainer", ".subscribers-table", "scrollBuffer", 100, "onScrolledToBottom", ["subexpr", "action", ["onScrolledToBottom"], [], ["loc", [null, [1, 97], [1, 126]]]]], 0, null, ["loc", [null, [1, 0], [17, 19]]]]],
locals: [],
templates: [child0]
};
})());
}); | Elektro1776/latestEarthables | core/client/tmp/broccoli_persistent_filterbabel-output_path-OKbFKF1N.tmp/ghost-admin/templates/components/gh-subscribers-table.js | JavaScript | gpl-3.0 | 12,139 |
// ┌────────────────────────────────────────────────────────────────────┐ \\
// │ Raphaël 2.1.2 - JavaScript Vector Library │ \\
// ├────────────────────────────────────────────────────────────────────┤ \\
// │ Copyright © 2008-2012 Dmitry Baranovskiy (http://raphaeljs.com) │ \\
// │ Copyright © 2008-2012 Sencha Labs (http://sencha.com) │ \\
// ├────────────────────────────────────────────────────────────────────┤ \\
// │ Licensed under the MIT (http://raphaeljs.com/license.html) license.│ \\
// └────────────────────────────────────────────────────────────────────┘ \\
// Copyright (c) 2013 Adobe Systems Incorporated. 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.
// ┌────────────────────────────────────────────────────────────┐ \\
// │ Eve 0.4.2 - JavaScript Events Library │ \\
// ├────────────────────────────────────────────────────────────┤ \\
// │ Author Dmitry Baranovskiy (http://dmitry.baranovskiy.com/) │ \\
// └────────────────────────────────────────────────────────────┘ \\
(function (glob) {
var version = "0.4.2",
has = "hasOwnProperty",
separator = /[\.\/]/,
wildcard = "*",
fun = function () {},
numsort = function (a, b) {
return a - b;
},
current_event,
stop,
events = {n: {}},
/*\
* eve
[ method ]
* Fires event with given `name`, given scope and other parameters.
> Arguments
- name (string) name of the *event*, dot (`.`) or slash (`/`) separated
- scope (object) context for the event handlers
- varargs (...) the rest of arguments will be sent to event handlers
= (object) array of returned values from the listeners
\*/
eve = function (name, scope) {
name = String(name);
var e = events,
oldstop = stop,
args = Array.prototype.slice.call(arguments, 2),
listeners = eve.listeners(name),
z = 0,
f = false,
l,
indexed = [],
queue = {},
out = [],
ce = current_event,
errors = [];
current_event = name;
stop = 0;
for (var i = 0, ii = listeners.length; i < ii; i++) if ("zIndex" in listeners[i]) {
indexed.push(listeners[i].zIndex);
if (listeners[i].zIndex < 0) {
queue[listeners[i].zIndex] = listeners[i];
}
}
indexed.sort(numsort);
while (indexed[z] < 0) {
l = queue[indexed[z++]];
out.push(l.apply(scope, args));
if (stop) {
stop = oldstop;
return out;
}
}
for (i = 0; i < ii; i++) {
l = listeners[i];
if ("zIndex" in l) {
if (l.zIndex == indexed[z]) {
out.push(l.apply(scope, args));
if (stop) {
break;
}
do {
z++;
l = queue[indexed[z]];
l && out.push(l.apply(scope, args));
if (stop) {
break;
}
} while (l)
} else {
queue[l.zIndex] = l;
}
} else {
out.push(l.apply(scope, args));
if (stop) {
break;
}
}
}
stop = oldstop;
current_event = ce;
return out.length ? out : null;
};
// Undocumented. Debug only.
eve._events = events;
/*\
* eve.listeners
[ method ]
* Internal method which gives you array of all event handlers that will be triggered by the given `name`.
> Arguments
- name (string) name of the event, dot (`.`) or slash (`/`) separated
= (array) array of event handlers
\*/
eve.listeners = function (name) {
var names = name.split(separator),
e = events,
item,
items,
k,
i,
ii,
j,
jj,
nes,
es = [e],
out = [];
for (i = 0, ii = names.length; i < ii; i++) {
nes = [];
for (j = 0, jj = es.length; j < jj; j++) {
e = es[j].n;
items = [e[names[i]], e[wildcard]];
k = 2;
while (k--) {
item = items[k];
if (item) {
nes.push(item);
out = out.concat(item.f || []);
}
}
}
es = nes;
}
return out;
};
/*\
* eve.on
[ method ]
**
* Binds given event handler with a given name. You can use wildcards “`*`” for the names:
| eve.on("*.under.*", f);
| eve("mouse.under.floor"); // triggers f
* Use @eve to trigger the listener.
**
> Arguments
**
- name (string) name of the event, dot (`.`) or slash (`/`) separated, with optional wildcards
- f (function) event handler function
**
= (function) returned function accepts a single numeric parameter that represents z-index of the handler. It is an optional feature and only used when you need to ensure that some subset of handlers will be invoked in a given order, despite of the order of assignment.
> Example:
| eve.on("mouse", eatIt)(2);
| eve.on("mouse", scream);
| eve.on("mouse", catchIt)(1);
* This will ensure that `catchIt()` function will be called before `eatIt()`.
*
* If you want to put your handler before non-indexed handlers, specify a negative value.
* Note: I assume most of the time you don’t need to worry about z-index, but it’s nice to have this feature “just in case”.
\*/
eve.on = function (name, f) {
name = String(name);
if (typeof f != "function") {
return function () {};
}
var names = name.split(separator),
e = events;
for (var i = 0, ii = names.length; i < ii; i++) {
e = e.n;
e = e.hasOwnProperty(names[i]) && e[names[i]] || (e[names[i]] = {n: {}});
}
e.f = e.f || [];
for (i = 0, ii = e.f.length; i < ii; i++) if (e.f[i] == f) {
return fun;
}
e.f.push(f);
return function (zIndex) {
if (+zIndex == +zIndex) {
f.zIndex = +zIndex;
}
};
};
/*\
* eve.f
[ method ]
**
* Returns function that will fire given event with optional arguments.
* Arguments that will be passed to the result function will be also
* concated to the list of final arguments.
| el.onclick = eve.f("click", 1, 2);
| eve.on("click", function (a, b, c) {
| console.log(a, b, c); // 1, 2, [event object]
| });
> Arguments
- event (string) event name
- varargs (…) and any other arguments
= (function) possible event handler function
\*/
eve.f = function (event) {
var attrs = [].slice.call(arguments, 1);
return function () {
eve.apply(null, [event, null].concat(attrs).concat([].slice.call(arguments, 0)));
};
};
/*\
* eve.stop
[ method ]
**
* Is used inside an event handler to stop the event, preventing any subsequent listeners from firing.
\*/
eve.stop = function () {
stop = 1;
};
/*\
* eve.nt
[ method ]
**
* Could be used inside event handler to figure out actual name of the event.
**
> Arguments
**
- subname (string) #optional subname of the event
**
= (string) name of the event, if `subname` is not specified
* or
= (boolean) `true`, if current event’s name contains `subname`
\*/
eve.nt = function (subname) {
if (subname) {
return new RegExp("(?:\\.|\\/|^)" + subname + "(?:\\.|\\/|$)").test(current_event);
}
return current_event;
};
/*\
* eve.nts
[ method ]
**
* Could be used inside event handler to figure out actual name of the event.
**
**
= (array) names of the event
\*/
eve.nts = function () {
return current_event.split(separator);
};
/*\
* eve.off
[ method ]
**
* Removes given function from the list of event listeners assigned to given name.
* If no arguments specified all the events will be cleared.
**
> Arguments
**
- name (string) name of the event, dot (`.`) or slash (`/`) separated, with optional wildcards
- f (function) event handler function
\*/
/*\
* eve.unbind
[ method ]
**
* See @eve.off
\*/
eve.off = eve.unbind = function (name, f) {
if (!name) {
eve._events = events = {n: {}};
return;
}
var names = name.split(separator),
e,
key,
splice,
i, ii, j, jj,
cur = [events];
for (i = 0, ii = names.length; i < ii; i++) {
for (j = 0; j < cur.length; j += splice.length - 2) {
splice = [j, 1];
e = cur[j].n;
if (names[i] != wildcard) {
if (e[names[i]]) {
splice.push(e[names[i]]);
}
} else {
for (key in e) if (e[has](key)) {
splice.push(e[key]);
}
}
cur.splice.apply(cur, splice);
}
}
for (i = 0, ii = cur.length; i < ii; i++) {
e = cur[i];
while (e.n) {
if (f) {
if (e.f) {
for (j = 0, jj = e.f.length; j < jj; j++) if (e.f[j] == f) {
e.f.splice(j, 1);
break;
}
!e.f.length && delete e.f;
}
for (key in e.n) if (e.n[has](key) && e.n[key].f) {
var funcs = e.n[key].f;
for (j = 0, jj = funcs.length; j < jj; j++) if (funcs[j] == f) {
funcs.splice(j, 1);
break;
}
!funcs.length && delete e.n[key].f;
}
} else {
delete e.f;
for (key in e.n) if (e.n[has](key) && e.n[key].f) {
delete e.n[key].f;
}
}
e = e.n;
}
}
};
/*\
* eve.once
[ method ]
**
* Binds given event handler with a given name to only run once then unbind itself.
| eve.once("login", f);
| eve("login"); // triggers f
| eve("login"); // no listeners
* Use @eve to trigger the listener.
**
> Arguments
**
- name (string) name of the event, dot (`.`) or slash (`/`) separated, with optional wildcards
- f (function) event handler function
**
= (function) same return function as @eve.on
\*/
eve.once = function (name, f) {
var f2 = function () {
eve.unbind(name, f2);
return f.apply(this, arguments);
};
return eve.on(name, f2);
};
/*\
* eve.version
[ property (string) ]
**
* Current version of the library.
\*/
eve.version = version;
eve.toString = function () {
return "You are running Eve " + version;
};
(typeof module != "undefined" && module.exports) ? (module.exports = eve) : (typeof define != "undefined" ? (define("eve", [], function() { return eve; })) : (glob.eve = eve));
})(window || this);
// ┌─────────────────────────────────────────────────────────────────────┐ \\
// │ "Raphaël 2.1.2" - JavaScript Vector Library │ \\
// ├─────────────────────────────────────────────────────────────────────┤ \\
// │ Copyright (c) 2008-2011 Dmitry Baranovskiy (http://raphaeljs.com) │ \\
// │ Copyright (c) 2008-2011 Sencha Labs (http://sencha.com) │ \\
// │ Licensed under the MIT (http://raphaeljs.com/license.html) license. │ \\
// └─────────────────────────────────────────────────────────────────────┘ \\
(function (glob, factory) {
// AMD support
if (typeof define === "function" && define.amd) {
// Define as an anonymous module
define(["eve"], function( eve ) {
return factory(glob, eve);
});
} else {
// Browser globals (glob is window)
// Raphael adds itself to window
factory(glob, glob.eve);
}
}(this, function (window, eve) {
/*\
* Raphael
[ method ]
**
* Creates a canvas object on which to draw.
* You must do this first, as all future calls to drawing methods
* from this instance will be bound to this canvas.
> Parameters
**
- container (HTMLElement|string) DOM element or its ID which is going to be a parent for drawing surface
- width (number)
- height (number)
- callback (function) #optional callback function which is going to be executed in the context of newly created paper
* or
- x (number)
- y (number)
- width (number)
- height (number)
- callback (function) #optional callback function which is going to be executed in the context of newly created paper
* or
- all (array) (first 3 or 4 elements in the array are equal to [containerID, width, height] or [x, y, width, height]. The rest are element descriptions in format {type: type, <attributes>}). See @Paper.add.
- callback (function) #optional callback function which is going to be executed in the context of newly created paper
* or
- onReadyCallback (function) function that is going to be called on DOM ready event. You can also subscribe to this event via Eve’s “DOMLoad” event. In this case method returns `undefined`.
= (object) @Paper
> Usage
| // Each of the following examples create a canvas
| // that is 320px wide by 200px high.
| // Canvas is created at the viewport’s 10,50 coordinate.
| var paper = Raphael(10, 50, 320, 200);
| // Canvas is created at the top left corner of the #notepad element
| // (or its top right corner in dir="rtl" elements)
| var paper = Raphael(document.getElementById("notepad"), 320, 200);
| // Same as above
| var paper = Raphael("notepad", 320, 200);
| // Image dump
| var set = Raphael(["notepad", 320, 200, {
| type: "rect",
| x: 10,
| y: 10,
| width: 25,
| height: 25,
| stroke: "#f00"
| }, {
| type: "text",
| x: 30,
| y: 40,
| text: "Dump"
| }]);
\*/
function R(first) {
if (R.is(first, "function")) {
return loaded ? first() : eve.on("raphael.DOMload", first);
} else if (R.is(first, array)) {
return R._engine.create[apply](R, first.splice(0, 3 + R.is(first[0], nu))).add(first);
} else {
var args = Array.prototype.slice.call(arguments, 0);
if (R.is(args[args.length - 1], "function")) {
var f = args.pop();
return loaded ? f.call(R._engine.create[apply](R, args)) : eve.on("raphael.DOMload", function () {
f.call(R._engine.create[apply](R, args));
});
} else {
return R._engine.create[apply](R, arguments);
}
}
}
R.version = "2.1.2";
R.eve = eve;
var loaded,
separator = /[, ]+/,
elements = {circle: 1, rect: 1, path: 1, ellipse: 1, text: 1, image: 1},
formatrg = /\{(\d+)\}/g,
proto = "prototype",
has = "hasOwnProperty",
g = {
doc: document,
win: window
},
oldRaphael = {
was: Object.prototype[has].call(g.win, "Raphael"),
is: g.win.Raphael
},
Paper = function () {
/*\
* Paper.ca
[ property (object) ]
**
* Shortcut for @Paper.customAttributes
\*/
/*\
* Paper.customAttributes
[ property (object) ]
**
* If you have a set of attributes that you would like to represent
* as a function of some number you can do it easily with custom attributes:
> Usage
| paper.customAttributes.hue = function (num) {
| num = num % 1;
| return {fill: "hsb(" + num + ", 0.75, 1)"};
| };
| // Custom attribute “hue” will change fill
| // to be given hue with fixed saturation and brightness.
| // Now you can use it like this:
| var c = paper.circle(10, 10, 10).attr({hue: .45});
| // or even like this:
| c.animate({hue: 1}, 1e3);
|
| // You could also create custom attribute
| // with multiple parameters:
| paper.customAttributes.hsb = function (h, s, b) {
| return {fill: "hsb(" + [h, s, b].join(",") + ")"};
| };
| c.attr({hsb: "0.5 .8 1"});
| c.animate({hsb: [1, 0, 0.5]}, 1e3);
\*/
this.ca = this.customAttributes = {};
},
paperproto,
appendChild = "appendChild",
apply = "apply",
concat = "concat",
supportsTouch = ('ontouchstart' in g.win) || g.win.DocumentTouch && g.doc instanceof DocumentTouch, //taken from Modernizr touch test
E = "",
S = " ",
Str = String,
split = "split",
events = "click dblclick mousedown mousemove mouseout mouseover mouseup touchstart touchmove touchend touchcancel"[split](S),
touchMap = {
mousedown: "touchstart",
mousemove: "touchmove",
mouseup: "touchend"
},
lowerCase = Str.prototype.toLowerCase,
math = Math,
mmax = math.max,
mmin = math.min,
abs = math.abs,
pow = math.pow,
PI = math.PI,
nu = "number",
string = "string",
array = "array",
toString = "toString",
fillString = "fill",
objectToString = Object.prototype.toString,
paper = {},
push = "push",
ISURL = R._ISURL = /^url\(['"]?([^\)]+?)['"]?\)$/i,
colourRegExp = /^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+%?(?:\s*,\s*[\d\.]+%?)?)\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\))\s*$/i,
isnan = {"NaN": 1, "Infinity": 1, "-Infinity": 1},
bezierrg = /^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/,
round = math.round,
setAttribute = "setAttribute",
toFloat = parseFloat,
toInt = parseInt,
upperCase = Str.prototype.toUpperCase,
availableAttrs = R._availableAttrs = {
"arrow-end": "none",
"arrow-start": "none",
blur: 0,
"clip-rect": "0 0 1e9 1e9",
cursor: "default",
cx: 0,
cy: 0,
fill: "#fff",
"fill-opacity": 1,
font: '10px "Arial"',
"font-family": '"Arial"',
"font-size": "10",
"font-style": "normal",
"font-weight": 400,
gradient: 0,
height: 0,
href: "http://raphaeljs.com/",
"letter-spacing": 0,
opacity: 1,
path: "M0,0",
r: 0,
rx: 0,
ry: 0,
src: "",
stroke: "#000",
"stroke-dasharray": "",
"stroke-linecap": "butt",
"stroke-linejoin": "butt",
"stroke-miterlimit": 0,
"stroke-opacity": 1,
"stroke-width": 1,
target: "_blank",
"text-anchor": "middle",
title: "Raphael",
transform: "",
width: 0,
x: 0,
y: 0
},
availableAnimAttrs = R._availableAnimAttrs = {
blur: nu,
"clip-rect": "csv",
cx: nu,
cy: nu,
fill: "colour",
"fill-opacity": nu,
"font-size": nu,
height: nu,
opacity: nu,
path: "path",
r: nu,
rx: nu,
ry: nu,
stroke: "colour",
"stroke-opacity": nu,
"stroke-width": nu,
transform: "transform",
width: nu,
x: nu,
y: nu
},
whitespace = /[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]/g,
commaSpaces = /[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*/,
hsrg = {hs: 1, rg: 1},
p2s = /,?([achlmqrstvxz]),?/gi,
pathCommand = /([achlmrqstvz])[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*)+)/ig,
tCommand = /([rstm])[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*)+)/ig,
pathValues = /(-?\d*\.?\d*(?:e[\-+]?\d+)?)[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*/ig,
radial_gradient = R._radial_gradient = /^r(?:\(([^,]+?)[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*([^\)]+?)\))?/,
eldata = {},
sortByKey = function (a, b) {
return a.key - b.key;
},
sortByNumber = function (a, b) {
return toFloat(a) - toFloat(b);
},
fun = function () {},
pipe = function (x) {
return x;
},
rectPath = R._rectPath = function (x, y, w, h, r) {
if (r) {
return [["M", x + r, y], ["l", w - r * 2, 0], ["a", r, r, 0, 0, 1, r, r], ["l", 0, h - r * 2], ["a", r, r, 0, 0, 1, -r, r], ["l", r * 2 - w, 0], ["a", r, r, 0, 0, 1, -r, -r], ["l", 0, r * 2 - h], ["a", r, r, 0, 0, 1, r, -r], ["z"]];
}
return [["M", x, y], ["l", w, 0], ["l", 0, h], ["l", -w, 0], ["z"]];
},
ellipsePath = function (x, y, rx, ry) {
if (ry == null) {
ry = rx;
}
return [["M", x, y], ["m", 0, -ry], ["a", rx, ry, 0, 1, 1, 0, 2 * ry], ["a", rx, ry, 0, 1, 1, 0, -2 * ry], ["z"]];
},
getPath = R._getPath = {
path: function (el) {
return el.attr("path");
},
circle: function (el) {
var a = el.attrs;
return ellipsePath(a.cx, a.cy, a.r);
},
ellipse: function (el) {
var a = el.attrs;
return ellipsePath(a.cx, a.cy, a.rx, a.ry);
},
rect: function (el) {
var a = el.attrs;
return rectPath(a.x, a.y, a.width, a.height, a.r);
},
image: function (el) {
var a = el.attrs;
return rectPath(a.x, a.y, a.width, a.height);
},
text: function (el) {
var bbox = el._getBBox();
return rectPath(bbox.x, bbox.y, bbox.width, bbox.height);
},
set : function(el) {
var bbox = el._getBBox();
return rectPath(bbox.x, bbox.y, bbox.width, bbox.height);
}
},
/*\
* Raphael.mapPath
[ method ]
**
* Transform the path string with given matrix.
> Parameters
- path (string) path string
- matrix (object) see @Matrix
= (string) transformed path string
\*/
mapPath = R.mapPath = function (path, matrix) {
if (!matrix) {
return path;
}
var x, y, i, j, ii, jj, pathi;
path = path2curve(path);
for (i = 0, ii = path.length; i < ii; i++) {
pathi = path[i];
for (j = 1, jj = pathi.length; j < jj; j += 2) {
x = matrix.x(pathi[j], pathi[j + 1]);
y = matrix.y(pathi[j], pathi[j + 1]);
pathi[j] = x;
pathi[j + 1] = y;
}
}
return path;
};
R._g = g;
/*\
* Raphael.type
[ property (string) ]
**
* Can be “SVG”, “VML” or empty, depending on browser support.
\*/
R.type = (g.win.SVGAngle || g.doc.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") ? "SVG" : "VML");
if (R.type == "VML") {
var d = g.doc.createElement("div"),
b;
d.innerHTML = '<v:shape adj="1"/>';
b = d.firstChild;
b.style.behavior = "url(#default#VML)";
if (!(b && typeof b.adj == "object")) {
return (R.type = E);
}
d = null;
}
/*\
* Raphael.svg
[ property (boolean) ]
**
* `true` if browser supports SVG.
\*/
/*\
* Raphael.vml
[ property (boolean) ]
**
* `true` if browser supports VML.
\*/
R.svg = !(R.vml = R.type == "VML");
R._Paper = Paper;
/*\
* Raphael.fn
[ property (object) ]
**
* You can add your own method to the canvas. For example if you want to draw a pie chart,
* you can create your own pie chart function and ship it as a Raphaël plugin. To do this
* you need to extend the `Raphael.fn` object. You should modify the `fn` object before a
* Raphaël instance is created, otherwise it will take no effect. Please note that the
* ability for namespaced plugins was removed in Raphael 2.0. It is up to the plugin to
* ensure any namespacing ensures proper context.
> Usage
| Raphael.fn.arrow = function (x1, y1, x2, y2, size) {
| return this.path( ... );
| };
| // or create namespace
| Raphael.fn.mystuff = {
| arrow: function () {…},
| star: function () {…},
| // etc…
| };
| var paper = Raphael(10, 10, 630, 480);
| // then use it
| paper.arrow(10, 10, 30, 30, 5).attr({fill: "#f00"});
| paper.mystuff.arrow();
| paper.mystuff.star();
\*/
R.fn = paperproto = Paper.prototype = R.prototype;
R._id = 0;
R._oid = 0;
/*\
* Raphael.is
[ method ]
**
* Handfull replacement for `typeof` operator.
> Parameters
- o (…) any object or primitive
- type (string) name of the type, i.e. “string”, “function”, “number”, etc.
= (boolean) is given value is of given type
\*/
R.is = function (o, type) {
type = lowerCase.call(type);
if (type == "finite") {
return !isnan[has](+o);
}
if (type == "array") {
return o instanceof Array;
}
return (type == "null" && o === null) ||
(type == typeof o && o !== null) ||
(type == "object" && o === Object(o)) ||
(type == "array" && Array.isArray && Array.isArray(o)) ||
objectToString.call(o).slice(8, -1).toLowerCase() == type;
};
function clone(obj) {
if (typeof obj == "function" || Object(obj) !== obj) {
return obj;
}
var res = new obj.constructor;
for (var key in obj) if (obj[has](key)) {
res[key] = clone(obj[key]);
}
return res;
}
/*\
* Raphael.angle
[ method ]
**
* Returns angle between two or three points
> Parameters
- x1 (number) x coord of first point
- y1 (number) y coord of first point
- x2 (number) x coord of second point
- y2 (number) y coord of second point
- x3 (number) #optional x coord of third point
- y3 (number) #optional y coord of third point
= (number) angle in degrees.
\*/
R.angle = function (x1, y1, x2, y2, x3, y3) {
if (x3 == null) {
var x = x1 - x2,
y = y1 - y2;
if (!x && !y) {
return 0;
}
return (180 + math.atan2(-y, -x) * 180 / PI + 360) % 360;
} else {
return R.angle(x1, y1, x3, y3) - R.angle(x2, y2, x3, y3);
}
};
/*\
* Raphael.rad
[ method ]
**
* Transform angle to radians
> Parameters
- deg (number) angle in degrees
= (number) angle in radians.
\*/
R.rad = function (deg) {
return deg % 360 * PI / 180;
};
/*\
* Raphael.deg
[ method ]
**
* Transform angle to degrees
> Parameters
- deg (number) angle in radians
= (number) angle in degrees.
\*/
R.deg = function (rad) {
return rad * 180 / PI % 360;
};
/*\
* Raphael.snapTo
[ method ]
**
* Snaps given value to given grid.
> Parameters
- values (array|number) given array of values or step of the grid
- value (number) value to adjust
- tolerance (number) #optional tolerance for snapping. Default is `10`.
= (number) adjusted value.
\*/
R.snapTo = function (values, value, tolerance) {
tolerance = R.is(tolerance, "finite") ? tolerance : 10;
if (R.is(values, array)) {
var i = values.length;
while (i--) if (abs(values[i] - value) <= tolerance) {
return values[i];
}
} else {
values = +values;
var rem = value % values;
if (rem < tolerance) {
return value - rem;
}
if (rem > values - tolerance) {
return value - rem + values;
}
}
return value;
};
/*\
* Raphael.createUUID
[ method ]
**
* Returns RFC4122, version 4 ID
\*/
var createUUID = R.createUUID = (function (uuidRegEx, uuidReplacer) {
return function () {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(uuidRegEx, uuidReplacer).toUpperCase();
};
})(/[xy]/g, function (c) {
var r = math.random() * 16 | 0,
v = c == "x" ? r : (r & 3 | 8);
return v.toString(16);
});
/*\
* Raphael.setWindow
[ method ]
**
* Used when you need to draw in `<iframe>`. Switched window to the iframe one.
> Parameters
- newwin (window) new window object
\*/
R.setWindow = function (newwin) {
eve("raphael.setWindow", R, g.win, newwin);
g.win = newwin;
g.doc = g.win.document;
if (R._engine.initWin) {
R._engine.initWin(g.win);
}
};
var toHex = function (color) {
if (R.vml) {
// http://dean.edwards.name/weblog/2009/10/convert-any-colour-value-to-hex-in-msie/
var trim = /^\s+|\s+$/g;
var bod;
try {
var docum = new ActiveXObject("htmlfile");
docum.write("<body>");
docum.close();
bod = docum.body;
} catch(e) {
bod = createPopup().document.body;
}
var range = bod.createTextRange();
toHex = cacher(function (color) {
try {
bod.style.color = Str(color).replace(trim, E);
var value = range.queryCommandValue("ForeColor");
value = ((value & 255) << 16) | (value & 65280) | ((value & 16711680) >>> 16);
return "#" + ("000000" + value.toString(16)).slice(-6);
} catch(e) {
return "none";
}
});
} else {
var i = g.doc.createElement("i");
i.title = "Rapha\xebl Colour Picker";
i.style.display = "none";
g.doc.body.appendChild(i);
toHex = cacher(function (color) {
i.style.color = color;
return g.doc.defaultView.getComputedStyle(i, E).getPropertyValue("color");
});
}
return toHex(color);
},
hsbtoString = function () {
return "hsb(" + [this.h, this.s, this.b] + ")";
},
hsltoString = function () {
return "hsl(" + [this.h, this.s, this.l] + ")";
},
rgbtoString = function () {
return this.hex;
},
prepareRGB = function (r, g, b) {
if (g == null && R.is(r, "object") && "r" in r && "g" in r && "b" in r) {
b = r.b;
g = r.g;
r = r.r;
}
if (g == null && R.is(r, string)) {
var clr = R.getRGB(r);
r = clr.r;
g = clr.g;
b = clr.b;
}
if (r > 1 || g > 1 || b > 1) {
r /= 255;
g /= 255;
b /= 255;
}
return [r, g, b];
},
packageRGB = function (r, g, b, o) {
r *= 255;
g *= 255;
b *= 255;
var rgb = {
r: r,
g: g,
b: b,
hex: R.rgb(r, g, b),
toString: rgbtoString
};
R.is(o, "finite") && (rgb.opacity = o);
return rgb;
};
/*\
* Raphael.color
[ method ]
**
* Parses the color string and returns object with all values for the given color.
> Parameters
- clr (string) color string in one of the supported formats (see @Raphael.getRGB)
= (object) Combined RGB & HSB object in format:
o {
o r (number) red,
o g (number) green,
o b (number) blue,
o hex (string) color in HTML/CSS format: #••••••,
o error (boolean) `true` if string can’t be parsed,
o h (number) hue,
o s (number) saturation,
o v (number) value (brightness),
o l (number) lightness
o }
\*/
R.color = function (clr) {
var rgb;
if (R.is(clr, "object") && "h" in clr && "s" in clr && "b" in clr) {
rgb = R.hsb2rgb(clr);
clr.r = rgb.r;
clr.g = rgb.g;
clr.b = rgb.b;
clr.hex = rgb.hex;
} else if (R.is(clr, "object") && "h" in clr && "s" in clr && "l" in clr) {
rgb = R.hsl2rgb(clr);
clr.r = rgb.r;
clr.g = rgb.g;
clr.b = rgb.b;
clr.hex = rgb.hex;
} else {
if (R.is(clr, "string")) {
clr = R.getRGB(clr);
}
if (R.is(clr, "object") && "r" in clr && "g" in clr && "b" in clr) {
rgb = R.rgb2hsl(clr);
clr.h = rgb.h;
clr.s = rgb.s;
clr.l = rgb.l;
rgb = R.rgb2hsb(clr);
clr.v = rgb.b;
} else {
clr = {hex: "none"};
clr.r = clr.g = clr.b = clr.h = clr.s = clr.v = clr.l = -1;
}
}
clr.toString = rgbtoString;
return clr;
};
/*\
* Raphael.hsb2rgb
[ method ]
**
* Converts HSB values to RGB object.
> Parameters
- h (number) hue
- s (number) saturation
- v (number) value or brightness
= (object) RGB object in format:
o {
o r (number) red,
o g (number) green,
o b (number) blue,
o hex (string) color in HTML/CSS format: #••••••
o }
\*/
R.hsb2rgb = function (h, s, v, o) {
if (this.is(h, "object") && "h" in h && "s" in h && "b" in h) {
v = h.b;
s = h.s;
h = h.h;
o = h.o;
}
h *= 360;
var R, G, B, X, C;
h = (h % 360) / 60;
C = v * s;
X = C * (1 - abs(h % 2 - 1));
R = G = B = v - C;
h = ~~h;
R += [C, X, 0, 0, X, C][h];
G += [X, C, C, X, 0, 0][h];
B += [0, 0, X, C, C, X][h];
return packageRGB(R, G, B, o);
};
/*\
* Raphael.hsl2rgb
[ method ]
**
* Converts HSL values to RGB object.
> Parameters
- h (number) hue
- s (number) saturation
- l (number) luminosity
= (object) RGB object in format:
o {
o r (number) red,
o g (number) green,
o b (number) blue,
o hex (string) color in HTML/CSS format: #••••••
o }
\*/
R.hsl2rgb = function (h, s, l, o) {
if (this.is(h, "object") && "h" in h && "s" in h && "l" in h) {
l = h.l;
s = h.s;
h = h.h;
}
if (h > 1 || s > 1 || l > 1) {
h /= 360;
s /= 100;
l /= 100;
}
h *= 360;
var R, G, B, X, C;
h = (h % 360) / 60;
C = 2 * s * (l < .5 ? l : 1 - l);
X = C * (1 - abs(h % 2 - 1));
R = G = B = l - C / 2;
h = ~~h;
R += [C, X, 0, 0, X, C][h];
G += [X, C, C, X, 0, 0][h];
B += [0, 0, X, C, C, X][h];
return packageRGB(R, G, B, o);
};
/*\
* Raphael.rgb2hsb
[ method ]
**
* Converts RGB values to HSB object.
> Parameters
- r (number) red
- g (number) green
- b (number) blue
= (object) HSB object in format:
o {
o h (number) hue
o s (number) saturation
o b (number) brightness
o }
\*/
R.rgb2hsb = function (r, g, b) {
b = prepareRGB(r, g, b);
r = b[0];
g = b[1];
b = b[2];
var H, S, V, C;
V = mmax(r, g, b);
C = V - mmin(r, g, b);
H = (C == 0 ? null :
V == r ? (g - b) / C :
V == g ? (b - r) / C + 2 :
(r - g) / C + 4
);
H = ((H + 360) % 6) * 60 / 360;
S = C == 0 ? 0 : C / V;
return {h: H, s: S, b: V, toString: hsbtoString};
};
/*\
* Raphael.rgb2hsl
[ method ]
**
* Converts RGB values to HSL object.
> Parameters
- r (number) red
- g (number) green
- b (number) blue
= (object) HSL object in format:
o {
o h (number) hue
o s (number) saturation
o l (number) luminosity
o }
\*/
R.rgb2hsl = function (r, g, b) {
b = prepareRGB(r, g, b);
r = b[0];
g = b[1];
b = b[2];
var H, S, L, M, m, C;
M = mmax(r, g, b);
m = mmin(r, g, b);
C = M - m;
H = (C == 0 ? null :
M == r ? (g - b) / C :
M == g ? (b - r) / C + 2 :
(r - g) / C + 4);
H = ((H + 360) % 6) * 60 / 360;
L = (M + m) / 2;
S = (C == 0 ? 0 :
L < .5 ? C / (2 * L) :
C / (2 - 2 * L));
return {h: H, s: S, l: L, toString: hsltoString};
};
R._path2string = function () {
return this.join(",").replace(p2s, "$1");
};
function repush(array, item) {
for (var i = 0, ii = array.length; i < ii; i++) if (array[i] === item) {
return array.push(array.splice(i, 1)[0]);
}
}
function cacher(f, scope, postprocessor) {
function newf() {
var arg = Array.prototype.slice.call(arguments, 0),
args = arg.join("\u2400"),
cache = newf.cache = newf.cache || {},
count = newf.count = newf.count || [];
if (cache[has](args)) {
repush(count, args);
return postprocessor ? postprocessor(cache[args]) : cache[args];
}
count.length >= 1e3 && delete cache[count.shift()];
count.push(args);
cache[args] = f[apply](scope, arg);
return postprocessor ? postprocessor(cache[args]) : cache[args];
}
return newf;
}
var preload = R._preload = function (src, f) {
var img = g.doc.createElement("img");
img.style.cssText = "position:absolute;left:-9999em;top:-9999em";
img.onload = function () {
f.call(this);
this.onload = null;
g.doc.body.removeChild(this);
};
img.onerror = function () {
g.doc.body.removeChild(this);
};
g.doc.body.appendChild(img);
img.src = src;
};
function clrToString() {
return this.hex;
}
/*\
* Raphael.getRGB
[ method ]
**
* Parses colour string as RGB object
> Parameters
- colour (string) colour string in one of formats:
# <ul>
# <li>Colour name (“<code>red</code>”, “<code>green</code>”, “<code>cornflowerblue</code>”, etc)</li>
# <li>#••• — shortened HTML colour: (“<code>#000</code>”, “<code>#fc0</code>”, etc)</li>
# <li>#•••••• — full length HTML colour: (“<code>#000000</code>”, “<code>#bd2300</code>”)</li>
# <li>rgb(•••, •••, •••) — red, green and blue channels’ values: (“<code>rgb(200, 100, 0)</code>”)</li>
# <li>rgb(•••%, •••%, •••%) — same as above, but in %: (“<code>rgb(100%, 175%, 0%)</code>”)</li>
# <li>hsb(•••, •••, •••) — hue, saturation and brightness values: (“<code>hsb(0.5, 0.25, 1)</code>”)</li>
# <li>hsb(•••%, •••%, •••%) — same as above, but in %</li>
# <li>hsl(•••, •••, •••) — same as hsb</li>
# <li>hsl(•••%, •••%, •••%) — same as hsb</li>
# </ul>
= (object) RGB object in format:
o {
o r (number) red,
o g (number) green,
o b (number) blue
o hex (string) color in HTML/CSS format: #••••••,
o error (boolean) true if string can’t be parsed
o }
\*/
R.getRGB = cacher(function (colour) {
if (!colour || !!((colour = Str(colour)).indexOf("-") + 1)) {
return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: clrToString};
}
if (colour == "none") {
return {r: -1, g: -1, b: -1, hex: "none", toString: clrToString};
}
!(hsrg[has](colour.toLowerCase().substring(0, 2)) || colour.charAt() == "#") && (colour = toHex(colour));
var res,
red,
green,
blue,
opacity,
t,
values,
rgb = colour.match(colourRegExp);
if (rgb) {
if (rgb[2]) {
blue = toInt(rgb[2].substring(5), 16);
green = toInt(rgb[2].substring(3, 5), 16);
red = toInt(rgb[2].substring(1, 3), 16);
}
if (rgb[3]) {
blue = toInt((t = rgb[3].charAt(3)) + t, 16);
green = toInt((t = rgb[3].charAt(2)) + t, 16);
red = toInt((t = rgb[3].charAt(1)) + t, 16);
}
if (rgb[4]) {
values = rgb[4][split](commaSpaces);
red = toFloat(values[0]);
values[0].slice(-1) == "%" && (red *= 2.55);
green = toFloat(values[1]);
values[1].slice(-1) == "%" && (green *= 2.55);
blue = toFloat(values[2]);
values[2].slice(-1) == "%" && (blue *= 2.55);
rgb[1].toLowerCase().slice(0, 4) == "rgba" && (opacity = toFloat(values[3]));
values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
}
if (rgb[5]) {
values = rgb[5][split](commaSpaces);
red = toFloat(values[0]);
values[0].slice(-1) == "%" && (red *= 2.55);
green = toFloat(values[1]);
values[1].slice(-1) == "%" && (green *= 2.55);
blue = toFloat(values[2]);
values[2].slice(-1) == "%" && (blue *= 2.55);
(values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
rgb[1].toLowerCase().slice(0, 4) == "hsba" && (opacity = toFloat(values[3]));
values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
return R.hsb2rgb(red, green, blue, opacity);
}
if (rgb[6]) {
values = rgb[6][split](commaSpaces);
red = toFloat(values[0]);
values[0].slice(-1) == "%" && (red *= 2.55);
green = toFloat(values[1]);
values[1].slice(-1) == "%" && (green *= 2.55);
blue = toFloat(values[2]);
values[2].slice(-1) == "%" && (blue *= 2.55);
(values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
rgb[1].toLowerCase().slice(0, 4) == "hsla" && (opacity = toFloat(values[3]));
values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
return R.hsl2rgb(red, green, blue, opacity);
}
rgb = {r: red, g: green, b: blue, toString: clrToString};
rgb.hex = "#" + (16777216 | blue | (green << 8) | (red << 16)).toString(16).slice(1);
R.is(opacity, "finite") && (rgb.opacity = opacity);
return rgb;
}
return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: clrToString};
}, R);
/*\
* Raphael.hsb
[ method ]
**
* Converts HSB values to hex representation of the colour.
> Parameters
- h (number) hue
- s (number) saturation
- b (number) value or brightness
= (string) hex representation of the colour.
\*/
R.hsb = cacher(function (h, s, b) {
return R.hsb2rgb(h, s, b).hex;
});
/*\
* Raphael.hsl
[ method ]
**
* Converts HSL values to hex representation of the colour.
> Parameters
- h (number) hue
- s (number) saturation
- l (number) luminosity
= (string) hex representation of the colour.
\*/
R.hsl = cacher(function (h, s, l) {
return R.hsl2rgb(h, s, l).hex;
});
/*\
* Raphael.rgb
[ method ]
**
* Converts RGB values to hex representation of the colour.
> Parameters
- r (number) red
- g (number) green
- b (number) blue
= (string) hex representation of the colour.
\*/
R.rgb = cacher(function (r, g, b) {
return "#" + (16777216 | b | (g << 8) | (r << 16)).toString(16).slice(1);
});
/*\
* Raphael.getColor
[ method ]
**
* On each call returns next colour in the spectrum. To reset it back to red call @Raphael.getColor.reset
> Parameters
- value (number) #optional brightness, default is `0.75`
= (string) hex representation of the colour.
\*/
R.getColor = function (value) {
var start = this.getColor.start = this.getColor.start || {h: 0, s: 1, b: value || .75},
rgb = this.hsb2rgb(start.h, start.s, start.b);
start.h += .075;
if (start.h > 1) {
start.h = 0;
start.s -= .2;
start.s <= 0 && (this.getColor.start = {h: 0, s: 1, b: start.b});
}
return rgb.hex;
};
/*\
* Raphael.getColor.reset
[ method ]
**
* Resets spectrum position for @Raphael.getColor back to red.
\*/
R.getColor.reset = function () {
delete this.start;
};
// http://schepers.cc/getting-to-the-point
function catmullRom2bezier(crp, z) {
var d = [];
for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) {
var p = [
{x: +crp[i - 2], y: +crp[i - 1]},
{x: +crp[i], y: +crp[i + 1]},
{x: +crp[i + 2], y: +crp[i + 3]},
{x: +crp[i + 4], y: +crp[i + 5]}
];
if (z) {
if (!i) {
p[0] = {x: +crp[iLen - 2], y: +crp[iLen - 1]};
} else if (iLen - 4 == i) {
p[3] = {x: +crp[0], y: +crp[1]};
} else if (iLen - 2 == i) {
p[2] = {x: +crp[0], y: +crp[1]};
p[3] = {x: +crp[2], y: +crp[3]};
}
} else {
if (iLen - 4 == i) {
p[3] = p[2];
} else if (!i) {
p[0] = {x: +crp[i], y: +crp[i + 1]};
}
}
d.push(["C",
(-p[0].x + 6 * p[1].x + p[2].x) / 6,
(-p[0].y + 6 * p[1].y + p[2].y) / 6,
(p[1].x + 6 * p[2].x - p[3].x) / 6,
(p[1].y + 6*p[2].y - p[3].y) / 6,
p[2].x,
p[2].y
]);
}
return d;
}
/*\
* Raphael.parsePathString
[ method ]
**
* Utility method
**
* Parses given path string into an array of arrays of path segments.
> Parameters
- pathString (string|array) path string or array of segments (in the last case it will be returned straight away)
= (array) array of segments.
\*/
R.parsePathString = function (pathString) {
if (!pathString) {
return null;
}
var pth = paths(pathString);
if (pth.arr) {
return pathClone(pth.arr);
}
var paramCounts = {a: 7, c: 6, h: 1, l: 2, m: 2, r: 4, q: 4, s: 4, t: 2, v: 1, z: 0},
data = [];
if (R.is(pathString, array) && R.is(pathString[0], array)) { // rough assumption
data = pathClone(pathString);
}
if (!data.length) {
Str(pathString).replace(pathCommand, function (a, b, c) {
var params = [],
name = b.toLowerCase();
c.replace(pathValues, function (a, b) {
b && params.push(+b);
});
if (name == "m" && params.length > 2) {
data.push([b][concat](params.splice(0, 2)));
name = "l";
b = b == "m" ? "l" : "L";
}
if (name == "r") {
data.push([b][concat](params));
} else while (params.length >= paramCounts[name]) {
data.push([b][concat](params.splice(0, paramCounts[name])));
if (!paramCounts[name]) {
break;
}
}
});
}
data.toString = R._path2string;
pth.arr = pathClone(data);
return data;
};
/*\
* Raphael.parseTransformString
[ method ]
**
* Utility method
**
* Parses given path string into an array of transformations.
> Parameters
- TString (string|array) transform string or array of transformations (in the last case it will be returned straight away)
= (array) array of transformations.
\*/
R.parseTransformString = cacher(function (TString) {
if (!TString) {
return null;
}
var paramCounts = {r: 3, s: 4, t: 2, m: 6},
data = [];
if (R.is(TString, array) && R.is(TString[0], array)) { // rough assumption
data = pathClone(TString);
}
if (!data.length) {
Str(TString).replace(tCommand, function (a, b, c) {
var params = [],
name = lowerCase.call(b);
c.replace(pathValues, function (a, b) {
b && params.push(+b);
});
data.push([b][concat](params));
});
}
data.toString = R._path2string;
return data;
});
// PATHS
var paths = function (ps) {
var p = paths.ps = paths.ps || {};
if (p[ps]) {
p[ps].sleep = 100;
} else {
p[ps] = {
sleep: 100
};
}
setTimeout(function () {
for (var key in p) if (p[has](key) && key != ps) {
p[key].sleep--;
!p[key].sleep && delete p[key];
}
});
return p[ps];
};
/*\
* Raphael.findDotsAtSegment
[ method ]
**
* Utility method
**
* Find dot coordinates on the given cubic bezier curve at the given t.
> Parameters
- p1x (number) x of the first point of the curve
- p1y (number) y of the first point of the curve
- c1x (number) x of the first anchor of the curve
- c1y (number) y of the first anchor of the curve
- c2x (number) x of the second anchor of the curve
- c2y (number) y of the second anchor of the curve
- p2x (number) x of the second point of the curve
- p2y (number) y of the second point of the curve
- t (number) position on the curve (0..1)
= (object) point information in format:
o {
o x: (number) x coordinate of the point
o y: (number) y coordinate of the point
o m: {
o x: (number) x coordinate of the left anchor
o y: (number) y coordinate of the left anchor
o }
o n: {
o x: (number) x coordinate of the right anchor
o y: (number) y coordinate of the right anchor
o }
o start: {
o x: (number) x coordinate of the start of the curve
o y: (number) y coordinate of the start of the curve
o }
o end: {
o x: (number) x coordinate of the end of the curve
o y: (number) y coordinate of the end of the curve
o }
o alpha: (number) angle of the curve derivative at the point
o }
\*/
R.findDotsAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
var t1 = 1 - t,
t13 = pow(t1, 3),
t12 = pow(t1, 2),
t2 = t * t,
t3 = t2 * t,
x = t13 * p1x + t12 * 3 * t * c1x + t1 * 3 * t * t * c2x + t3 * p2x,
y = t13 * p1y + t12 * 3 * t * c1y + t1 * 3 * t * t * c2y + t3 * p2y,
mx = p1x + 2 * t * (c1x - p1x) + t2 * (c2x - 2 * c1x + p1x),
my = p1y + 2 * t * (c1y - p1y) + t2 * (c2y - 2 * c1y + p1y),
nx = c1x + 2 * t * (c2x - c1x) + t2 * (p2x - 2 * c2x + c1x),
ny = c1y + 2 * t * (c2y - c1y) + t2 * (p2y - 2 * c2y + c1y),
ax = t1 * p1x + t * c1x,
ay = t1 * p1y + t * c1y,
cx = t1 * c2x + t * p2x,
cy = t1 * c2y + t * p2y,
alpha = (90 - math.atan2(mx - nx, my - ny) * 180 / PI);
(mx > nx || my < ny) && (alpha += 180);
return {
x: x,
y: y,
m: {x: mx, y: my},
n: {x: nx, y: ny},
start: {x: ax, y: ay},
end: {x: cx, y: cy},
alpha: alpha
};
};
/*\
* Raphael.bezierBBox
[ method ]
**
* Utility method
**
* Return bounding box of a given cubic bezier curve
> Parameters
- p1x (number) x of the first point of the curve
- p1y (number) y of the first point of the curve
- c1x (number) x of the first anchor of the curve
- c1y (number) y of the first anchor of the curve
- c2x (number) x of the second anchor of the curve
- c2y (number) y of the second anchor of the curve
- p2x (number) x of the second point of the curve
- p2y (number) y of the second point of the curve
* or
- bez (array) array of six points for bezier curve
= (object) point information in format:
o {
o min: {
o x: (number) x coordinate of the left point
o y: (number) y coordinate of the top point
o }
o max: {
o x: (number) x coordinate of the right point
o y: (number) y coordinate of the bottom point
o }
o }
\*/
R.bezierBBox = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) {
if (!R.is(p1x, "array")) {
p1x = [p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y];
}
var bbox = curveDim.apply(null, p1x);
return {
x: bbox.min.x,
y: bbox.min.y,
x2: bbox.max.x,
y2: bbox.max.y,
width: bbox.max.x - bbox.min.x,
height: bbox.max.y - bbox.min.y
};
};
/*\
* Raphael.isPointInsideBBox
[ method ]
**
* Utility method
**
* Returns `true` if given point is inside bounding boxes.
> Parameters
- bbox (string) bounding box
- x (string) x coordinate of the point
- y (string) y coordinate of the point
= (boolean) `true` if point inside
\*/
R.isPointInsideBBox = function (bbox, x, y) {
return x >= bbox.x && x <= bbox.x2 && y >= bbox.y && y <= bbox.y2;
};
/*\
* Raphael.isBBoxIntersect
[ method ]
**
* Utility method
**
* Returns `true` if two bounding boxes intersect
> Parameters
- bbox1 (string) first bounding box
- bbox2 (string) second bounding box
= (boolean) `true` if they intersect
\*/
R.isBBoxIntersect = function (bbox1, bbox2) {
var i = R.isPointInsideBBox;
return i(bbox2, bbox1.x, bbox1.y)
|| i(bbox2, bbox1.x2, bbox1.y)
|| i(bbox2, bbox1.x, bbox1.y2)
|| i(bbox2, bbox1.x2, bbox1.y2)
|| i(bbox1, bbox2.x, bbox2.y)
|| i(bbox1, bbox2.x2, bbox2.y)
|| i(bbox1, bbox2.x, bbox2.y2)
|| i(bbox1, bbox2.x2, bbox2.y2)
|| (bbox1.x < bbox2.x2 && bbox1.x > bbox2.x || bbox2.x < bbox1.x2 && bbox2.x > bbox1.x)
&& (bbox1.y < bbox2.y2 && bbox1.y > bbox2.y || bbox2.y < bbox1.y2 && bbox2.y > bbox1.y);
};
function base3(t, p1, p2, p3, p4) {
var t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4,
t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3;
return t * t2 - 3 * p1 + 3 * p2;
}
function bezlen(x1, y1, x2, y2, x3, y3, x4, y4, z) {
if (z == null) {
z = 1;
}
z = z > 1 ? 1 : z < 0 ? 0 : z;
var z2 = z / 2,
n = 12,
Tvalues = [-0.1252,0.1252,-0.3678,0.3678,-0.5873,0.5873,-0.7699,0.7699,-0.9041,0.9041,-0.9816,0.9816],
Cvalues = [0.2491,0.2491,0.2335,0.2335,0.2032,0.2032,0.1601,0.1601,0.1069,0.1069,0.0472,0.0472],
sum = 0;
for (var i = 0; i < n; i++) {
var ct = z2 * Tvalues[i] + z2,
xbase = base3(ct, x1, x2, x3, x4),
ybase = base3(ct, y1, y2, y3, y4),
comb = xbase * xbase + ybase * ybase;
sum += Cvalues[i] * math.sqrt(comb);
}
return z2 * sum;
}
function getTatLen(x1, y1, x2, y2, x3, y3, x4, y4, ll) {
if (ll < 0 || bezlen(x1, y1, x2, y2, x3, y3, x4, y4) < ll) {
return;
}
var t = 1,
step = t / 2,
t2 = t - step,
l,
e = .01;
l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2);
while (abs(l - ll) > e) {
step /= 2;
t2 += (l < ll ? 1 : -1) * step;
l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2);
}
return t2;
}
function intersect(x1, y1, x2, y2, x3, y3, x4, y4) {
if (
mmax(x1, x2) < mmin(x3, x4) ||
mmin(x1, x2) > mmax(x3, x4) ||
mmax(y1, y2) < mmin(y3, y4) ||
mmin(y1, y2) > mmax(y3, y4)
) {
return;
}
var nx = (x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4),
ny = (x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4),
denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
if (!denominator) {
return;
}
var px = nx / denominator,
py = ny / denominator,
px2 = +px.toFixed(2),
py2 = +py.toFixed(2);
if (
px2 < +mmin(x1, x2).toFixed(2) ||
px2 > +mmax(x1, x2).toFixed(2) ||
px2 < +mmin(x3, x4).toFixed(2) ||
px2 > +mmax(x3, x4).toFixed(2) ||
py2 < +mmin(y1, y2).toFixed(2) ||
py2 > +mmax(y1, y2).toFixed(2) ||
py2 < +mmin(y3, y4).toFixed(2) ||
py2 > +mmax(y3, y4).toFixed(2)
) {
return;
}
return {x: px, y: py};
}
function inter(bez1, bez2) {
return interHelper(bez1, bez2);
}
function interCount(bez1, bez2) {
return interHelper(bez1, bez2, 1);
}
function interHelper(bez1, bez2, justCount) {
var bbox1 = R.bezierBBox(bez1),
bbox2 = R.bezierBBox(bez2);
if (!R.isBBoxIntersect(bbox1, bbox2)) {
return justCount ? 0 : [];
}
var l1 = bezlen.apply(0, bez1),
l2 = bezlen.apply(0, bez2),
n1 = mmax(~~(l1 / 5), 1),
n2 = mmax(~~(l2 / 5), 1),
dots1 = [],
dots2 = [],
xy = {},
res = justCount ? 0 : [];
for (var i = 0; i < n1 + 1; i++) {
var p = R.findDotsAtSegment.apply(R, bez1.concat(i / n1));
dots1.push({x: p.x, y: p.y, t: i / n1});
}
for (i = 0; i < n2 + 1; i++) {
p = R.findDotsAtSegment.apply(R, bez2.concat(i / n2));
dots2.push({x: p.x, y: p.y, t: i / n2});
}
for (i = 0; i < n1; i++) {
for (var j = 0; j < n2; j++) {
var di = dots1[i],
di1 = dots1[i + 1],
dj = dots2[j],
dj1 = dots2[j + 1],
ci = abs(di1.x - di.x) < .001 ? "y" : "x",
cj = abs(dj1.x - dj.x) < .001 ? "y" : "x",
is = intersect(di.x, di.y, di1.x, di1.y, dj.x, dj.y, dj1.x, dj1.y);
if (is) {
if (xy[is.x.toFixed(4)] == is.y.toFixed(4)) {
continue;
}
xy[is.x.toFixed(4)] = is.y.toFixed(4);
var t1 = di.t + abs((is[ci] - di[ci]) / (di1[ci] - di[ci])) * (di1.t - di.t),
t2 = dj.t + abs((is[cj] - dj[cj]) / (dj1[cj] - dj[cj])) * (dj1.t - dj.t);
if (t1 >= 0 && t1 <= 1.001 && t2 >= 0 && t2 <= 1.001) {
if (justCount) {
res++;
} else {
res.push({
x: is.x,
y: is.y,
t1: mmin(t1, 1),
t2: mmin(t2, 1)
});
}
}
}
}
}
return res;
}
/*\
* Raphael.pathIntersection
[ method ]
**
* Utility method
**
* Finds intersections of two paths
> Parameters
- path1 (string) path string
- path2 (string) path string
= (array) dots of intersection
o [
o {
o x: (number) x coordinate of the point
o y: (number) y coordinate of the point
o t1: (number) t value for segment of path1
o t2: (number) t value for segment of path2
o segment1: (number) order number for segment of path1
o segment2: (number) order number for segment of path2
o bez1: (array) eight coordinates representing beziér curve for the segment of path1
o bez2: (array) eight coordinates representing beziér curve for the segment of path2
o }
o ]
\*/
R.pathIntersection = function (path1, path2) {
return interPathHelper(path1, path2);
};
R.pathIntersectionNumber = function (path1, path2) {
return interPathHelper(path1, path2, 1);
};
function interPathHelper(path1, path2, justCount) {
path1 = R._path2curve(path1);
path2 = R._path2curve(path2);
var x1, y1, x2, y2, x1m, y1m, x2m, y2m, bez1, bez2,
res = justCount ? 0 : [];
for (var i = 0, ii = path1.length; i < ii; i++) {
var pi = path1[i];
if (pi[0] == "M") {
x1 = x1m = pi[1];
y1 = y1m = pi[2];
} else {
if (pi[0] == "C") {
bez1 = [x1, y1].concat(pi.slice(1));
x1 = bez1[6];
y1 = bez1[7];
} else {
bez1 = [x1, y1, x1, y1, x1m, y1m, x1m, y1m];
x1 = x1m;
y1 = y1m;
}
for (var j = 0, jj = path2.length; j < jj; j++) {
var pj = path2[j];
if (pj[0] == "M") {
x2 = x2m = pj[1];
y2 = y2m = pj[2];
} else {
if (pj[0] == "C") {
bez2 = [x2, y2].concat(pj.slice(1));
x2 = bez2[6];
y2 = bez2[7];
} else {
bez2 = [x2, y2, x2, y2, x2m, y2m, x2m, y2m];
x2 = x2m;
y2 = y2m;
}
var intr = interHelper(bez1, bez2, justCount);
if (justCount) {
res += intr;
} else {
for (var k = 0, kk = intr.length; k < kk; k++) {
intr[k].segment1 = i;
intr[k].segment2 = j;
intr[k].bez1 = bez1;
intr[k].bez2 = bez2;
}
res = res.concat(intr);
}
}
}
}
}
return res;
}
/*\
* Raphael.isPointInsidePath
[ method ]
**
* Utility method
**
* Returns `true` if given point is inside a given closed path.
> Parameters
- path (string) path string
- x (number) x of the point
- y (number) y of the point
= (boolean) true, if point is inside the path
\*/
R.isPointInsidePath = function (path, x, y) {
var bbox = R.pathBBox(path);
return R.isPointInsideBBox(bbox, x, y) &&
interPathHelper(path, [["M", x, y], ["H", bbox.x2 + 10]], 1) % 2 == 1;
};
R._removedFactory = function (methodname) {
return function () {
eve("raphael.log", null, "Rapha\xebl: you are calling to method \u201c" + methodname + "\u201d of removed object", methodname);
};
};
/*\
* Raphael.pathBBox
[ method ]
**
* Utility method
**
* Return bounding box of a given path
> Parameters
- path (string) path string
= (object) bounding box
o {
o x: (number) x coordinate of the left top point of the box
o y: (number) y coordinate of the left top point of the box
o x2: (number) x coordinate of the right bottom point of the box
o y2: (number) y coordinate of the right bottom point of the box
o width: (number) width of the box
o height: (number) height of the box
o cx: (number) x coordinate of the center of the box
o cy: (number) y coordinate of the center of the box
o }
\*/
var pathDimensions = R.pathBBox = function (path) {
var pth = paths(path);
if (pth.bbox) {
return clone(pth.bbox);
}
if (!path) {
return {x: 0, y: 0, width: 0, height: 0, x2: 0, y2: 0};
}
path = path2curve(path);
var x = 0,
y = 0,
X = [],
Y = [],
p;
for (var i = 0, ii = path.length; i < ii; i++) {
p = path[i];
if (p[0] == "M") {
x = p[1];
y = p[2];
X.push(x);
Y.push(y);
} else {
var dim = curveDim(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
X = X[concat](dim.min.x, dim.max.x);
Y = Y[concat](dim.min.y, dim.max.y);
x = p[5];
y = p[6];
}
}
var xmin = mmin[apply](0, X),
ymin = mmin[apply](0, Y),
xmax = mmax[apply](0, X),
ymax = mmax[apply](0, Y),
width = xmax - xmin,
height = ymax - ymin,
bb = {
x: xmin,
y: ymin,
x2: xmax,
y2: ymax,
width: width,
height: height,
cx: xmin + width / 2,
cy: ymin + height / 2
};
pth.bbox = clone(bb);
return bb;
},
pathClone = function (pathArray) {
var res = clone(pathArray);
res.toString = R._path2string;
return res;
},
pathToRelative = R._pathToRelative = function (pathArray) {
var pth = paths(pathArray);
if (pth.rel) {
return pathClone(pth.rel);
}
if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
pathArray = R.parsePathString(pathArray);
}
var res = [],
x = 0,
y = 0,
mx = 0,
my = 0,
start = 0;
if (pathArray[0][0] == "M") {
x = pathArray[0][1];
y = pathArray[0][2];
mx = x;
my = y;
start++;
res.push(["M", x, y]);
}
for (var i = start, ii = pathArray.length; i < ii; i++) {
var r = res[i] = [],
pa = pathArray[i];
if (pa[0] != lowerCase.call(pa[0])) {
r[0] = lowerCase.call(pa[0]);
switch (r[0]) {
case "a":
r[1] = pa[1];
r[2] = pa[2];
r[3] = pa[3];
r[4] = pa[4];
r[5] = pa[5];
r[6] = +(pa[6] - x).toFixed(3);
r[7] = +(pa[7] - y).toFixed(3);
break;
case "v":
r[1] = +(pa[1] - y).toFixed(3);
break;
case "m":
mx = pa[1];
my = pa[2];
default:
for (var j = 1, jj = pa.length; j < jj; j++) {
r[j] = +(pa[j] - ((j % 2) ? x : y)).toFixed(3);
}
}
} else {
r = res[i] = [];
if (pa[0] == "m") {
mx = pa[1] + x;
my = pa[2] + y;
}
for (var k = 0, kk = pa.length; k < kk; k++) {
res[i][k] = pa[k];
}
}
var len = res[i].length;
switch (res[i][0]) {
case "z":
x = mx;
y = my;
break;
case "h":
x += +res[i][len - 1];
break;
case "v":
y += +res[i][len - 1];
break;
default:
x += +res[i][len - 2];
y += +res[i][len - 1];
}
}
res.toString = R._path2string;
pth.rel = pathClone(res);
return res;
},
pathToAbsolute = R._pathToAbsolute = function (pathArray) {
var pth = paths(pathArray);
if (pth.abs) {
return pathClone(pth.abs);
}
if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
pathArray = R.parsePathString(pathArray);
}
if (!pathArray || !pathArray.length) {
return [["M", 0, 0]];
}
var res = [],
x = 0,
y = 0,
mx = 0,
my = 0,
start = 0;
if (pathArray[0][0] == "M") {
x = +pathArray[0][1];
y = +pathArray[0][2];
mx = x;
my = y;
start++;
res[0] = ["M", x, y];
}
var crz = pathArray.length == 3 && pathArray[0][0] == "M" && pathArray[1][0].toUpperCase() == "R" && pathArray[2][0].toUpperCase() == "Z";
for (var r, pa, i = start, ii = pathArray.length; i < ii; i++) {
res.push(r = []);
pa = pathArray[i];
if (pa[0] != upperCase.call(pa[0])) {
r[0] = upperCase.call(pa[0]);
switch (r[0]) {
case "A":
r[1] = pa[1];
r[2] = pa[2];
r[3] = pa[3];
r[4] = pa[4];
r[5] = pa[5];
r[6] = +(pa[6] + x);
r[7] = +(pa[7] + y);
break;
case "V":
r[1] = +pa[1] + y;
break;
case "H":
r[1] = +pa[1] + x;
break;
case "R":
var dots = [x, y][concat](pa.slice(1));
for (var j = 2, jj = dots.length; j < jj; j++) {
dots[j] = +dots[j] + x;
dots[++j] = +dots[j] + y;
}
res.pop();
res = res[concat](catmullRom2bezier(dots, crz));
break;
case "M":
mx = +pa[1] + x;
my = +pa[2] + y;
default:
for (j = 1, jj = pa.length; j < jj; j++) {
r[j] = +pa[j] + ((j % 2) ? x : y);
}
}
} else if (pa[0] == "R") {
dots = [x, y][concat](pa.slice(1));
res.pop();
res = res[concat](catmullRom2bezier(dots, crz));
r = ["R"][concat](pa.slice(-2));
} else {
for (var k = 0, kk = pa.length; k < kk; k++) {
r[k] = pa[k];
}
}
switch (r[0]) {
case "Z":
x = mx;
y = my;
break;
case "H":
x = r[1];
break;
case "V":
y = r[1];
break;
case "M":
mx = r[r.length - 2];
my = r[r.length - 1];
default:
x = r[r.length - 2];
y = r[r.length - 1];
}
}
res.toString = R._path2string;
pth.abs = pathClone(res);
return res;
},
l2c = function (x1, y1, x2, y2) {
return [x1, y1, x2, y2, x2, y2];
},
q2c = function (x1, y1, ax, ay, x2, y2) {
var _13 = 1 / 3,
_23 = 2 / 3;
return [
_13 * x1 + _23 * ax,
_13 * y1 + _23 * ay,
_13 * x2 + _23 * ax,
_13 * y2 + _23 * ay,
x2,
y2
];
},
a2c = function (x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) {
// for more information of where this math came from visit:
// http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
var _120 = PI * 120 / 180,
rad = PI / 180 * (+angle || 0),
res = [],
xy,
rotate = cacher(function (x, y, rad) {
var X = x * math.cos(rad) - y * math.sin(rad),
Y = x * math.sin(rad) + y * math.cos(rad);
return {x: X, y: Y};
});
if (!recursive) {
xy = rotate(x1, y1, -rad);
x1 = xy.x;
y1 = xy.y;
xy = rotate(x2, y2, -rad);
x2 = xy.x;
y2 = xy.y;
var cos = math.cos(PI / 180 * angle),
sin = math.sin(PI / 180 * angle),
x = (x1 - x2) / 2,
y = (y1 - y2) / 2;
var h = (x * x) / (rx * rx) + (y * y) / (ry * ry);
if (h > 1) {
h = math.sqrt(h);
rx = h * rx;
ry = h * ry;
}
var rx2 = rx * rx,
ry2 = ry * ry,
k = (large_arc_flag == sweep_flag ? -1 : 1) *
math.sqrt(abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))),
cx = k * rx * y / ry + (x1 + x2) / 2,
cy = k * -ry * x / rx + (y1 + y2) / 2,
f1 = math.asin(((y1 - cy) / ry).toFixed(9)),
f2 = math.asin(((y2 - cy) / ry).toFixed(9));
f1 = x1 < cx ? PI - f1 : f1;
f2 = x2 < cx ? PI - f2 : f2;
f1 < 0 && (f1 = PI * 2 + f1);
f2 < 0 && (f2 = PI * 2 + f2);
if (sweep_flag && f1 > f2) {
f1 = f1 - PI * 2;
}
if (!sweep_flag && f2 > f1) {
f2 = f2 - PI * 2;
}
} else {
f1 = recursive[0];
f2 = recursive[1];
cx = recursive[2];
cy = recursive[3];
}
var df = f2 - f1;
if (abs(df) > _120) {
var f2old = f2,
x2old = x2,
y2old = y2;
f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1);
x2 = cx + rx * math.cos(f2);
y2 = cy + ry * math.sin(f2);
res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]);
}
df = f2 - f1;
var c1 = math.cos(f1),
s1 = math.sin(f1),
c2 = math.cos(f2),
s2 = math.sin(f2),
t = math.tan(df / 4),
hx = 4 / 3 * rx * t,
hy = 4 / 3 * ry * t,
m1 = [x1, y1],
m2 = [x1 + hx * s1, y1 - hy * c1],
m3 = [x2 + hx * s2, y2 - hy * c2],
m4 = [x2, y2];
m2[0] = 2 * m1[0] - m2[0];
m2[1] = 2 * m1[1] - m2[1];
if (recursive) {
return [m2, m3, m4][concat](res);
} else {
res = [m2, m3, m4][concat](res).join()[split](",");
var newres = [];
for (var i = 0, ii = res.length; i < ii; i++) {
newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x;
}
return newres;
}
},
findDotAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
var t1 = 1 - t;
return {
x: pow(t1, 3) * p1x + pow(t1, 2) * 3 * t * c1x + t1 * 3 * t * t * c2x + pow(t, 3) * p2x,
y: pow(t1, 3) * p1y + pow(t1, 2) * 3 * t * c1y + t1 * 3 * t * t * c2y + pow(t, 3) * p2y
};
},
curveDim = cacher(function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) {
var a = (c2x - 2 * c1x + p1x) - (p2x - 2 * c2x + c1x),
b = 2 * (c1x - p1x) - 2 * (c2x - c1x),
c = p1x - c1x,
t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a,
t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a,
y = [p1y, p2y],
x = [p1x, p2x],
dot;
abs(t1) > "1e12" && (t1 = .5);
abs(t2) > "1e12" && (t2 = .5);
if (t1 > 0 && t1 < 1) {
dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
x.push(dot.x);
y.push(dot.y);
}
if (t2 > 0 && t2 < 1) {
dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
x.push(dot.x);
y.push(dot.y);
}
a = (c2y - 2 * c1y + p1y) - (p2y - 2 * c2y + c1y);
b = 2 * (c1y - p1y) - 2 * (c2y - c1y);
c = p1y - c1y;
t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a;
t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a;
abs(t1) > "1e12" && (t1 = .5);
abs(t2) > "1e12" && (t2 = .5);
if (t1 > 0 && t1 < 1) {
dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
x.push(dot.x);
y.push(dot.y);
}
if (t2 > 0 && t2 < 1) {
dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
x.push(dot.x);
y.push(dot.y);
}
return {
min: {x: mmin[apply](0, x), y: mmin[apply](0, y)},
max: {x: mmax[apply](0, x), y: mmax[apply](0, y)}
};
}),
path2curve = R._path2curve = cacher(function (path, path2) {
var pth = !path2 && paths(path);
if (!path2 && pth.curve) {
return pathClone(pth.curve);
}
var p = pathToAbsolute(path),
p2 = path2 && pathToAbsolute(path2),
attrs = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
attrs2 = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
processPath = function (path, d, pcom) {
var nx, ny, tq = {T:1, Q:1};
if (!path) {
return ["C", d.x, d.y, d.x, d.y, d.x, d.y];
}
!(path[0] in tq) && (d.qx = d.qy = null);
switch (path[0]) {
case "M":
d.X = path[1];
d.Y = path[2];
break;
case "A":
path = ["C"][concat](a2c[apply](0, [d.x, d.y][concat](path.slice(1))));
break;
case "S":
if (pcom == "C" || pcom == "S") { // In "S" case we have to take into account, if the previous command is C/S.
nx = d.x * 2 - d.bx; // And reflect the previous
ny = d.y * 2 - d.by; // command's control point relative to the current point.
}
else { // or some else or nothing
nx = d.x;
ny = d.y;
}
path = ["C", nx, ny][concat](path.slice(1));
break;
case "T":
if (pcom == "Q" || pcom == "T") { // In "T" case we have to take into account, if the previous command is Q/T.
d.qx = d.x * 2 - d.qx; // And make a reflection similar
d.qy = d.y * 2 - d.qy; // to case "S".
}
else { // or something else or nothing
d.qx = d.x;
d.qy = d.y;
}
path = ["C"][concat](q2c(d.x, d.y, d.qx, d.qy, path[1], path[2]));
break;
case "Q":
d.qx = path[1];
d.qy = path[2];
path = ["C"][concat](q2c(d.x, d.y, path[1], path[2], path[3], path[4]));
break;
case "L":
path = ["C"][concat](l2c(d.x, d.y, path[1], path[2]));
break;
case "H":
path = ["C"][concat](l2c(d.x, d.y, path[1], d.y));
break;
case "V":
path = ["C"][concat](l2c(d.x, d.y, d.x, path[1]));
break;
case "Z":
path = ["C"][concat](l2c(d.x, d.y, d.X, d.Y));
break;
}
return path;
},
fixArc = function (pp, i) {
if (pp[i].length > 7) {
pp[i].shift();
var pi = pp[i];
while (pi.length) {
pp.splice(i++, 0, ["C"][concat](pi.splice(0, 6)));
}
pp.splice(i, 1);
ii = mmax(p.length, p2 && p2.length || 0);
}
},
fixM = function (path1, path2, a1, a2, i) {
if (path1 && path2 && path1[i][0] == "M" && path2[i][0] != "M") {
path2.splice(i, 0, ["M", a2.x, a2.y]);
a1.bx = 0;
a1.by = 0;
a1.x = path1[i][1];
a1.y = path1[i][2];
ii = mmax(p.length, p2 && p2.length || 0);
}
};
for (var i = 0, ii = mmax(p.length, p2 && p2.length || 0); i < ii; i++) {
p[i] = processPath(p[i], attrs);
fixArc(p, i);
p2 && (p2[i] = processPath(p2[i], attrs2));
p2 && fixArc(p2, i);
fixM(p, p2, attrs, attrs2, i);
fixM(p2, p, attrs2, attrs, i);
var seg = p[i],
seg2 = p2 && p2[i],
seglen = seg.length,
seg2len = p2 && seg2.length;
attrs.x = seg[seglen - 2];
attrs.y = seg[seglen - 1];
attrs.bx = toFloat(seg[seglen - 4]) || attrs.x;
attrs.by = toFloat(seg[seglen - 3]) || attrs.y;
attrs2.bx = p2 && (toFloat(seg2[seg2len - 4]) || attrs2.x);
attrs2.by = p2 && (toFloat(seg2[seg2len - 3]) || attrs2.y);
attrs2.x = p2 && seg2[seg2len - 2];
attrs2.y = p2 && seg2[seg2len - 1];
}
if (!p2) {
pth.curve = pathClone(p);
}
return p2 ? [p, p2] : p;
}, null, pathClone),
parseDots = R._parseDots = cacher(function (gradient) {
var dots = [];
for (var i = 0, ii = gradient.length; i < ii; i++) {
var dot = {},
par = gradient[i].match(/^([^:]*):?([\d\.]*)/);
dot.color = R.getRGB(par[1]);
if (dot.color.error) {
return null;
}
dot.color = dot.color.hex;
par[2] && (dot.offset = par[2] + "%");
dots.push(dot);
}
for (i = 1, ii = dots.length - 1; i < ii; i++) {
if (!dots[i].offset) {
var start = toFloat(dots[i - 1].offset || 0),
end = 0;
for (var j = i + 1; j < ii; j++) {
if (dots[j].offset) {
end = dots[j].offset;
break;
}
}
if (!end) {
end = 100;
j = ii;
}
end = toFloat(end);
var d = (end - start) / (j - i + 1);
for (; i < j; i++) {
start += d;
dots[i].offset = start + "%";
}
}
}
return dots;
}),
tear = R._tear = function (el, paper) {
el == paper.top && (paper.top = el.prev);
el == paper.bottom && (paper.bottom = el.next);
el.next && (el.next.prev = el.prev);
el.prev && (el.prev.next = el.next);
},
tofront = R._tofront = function (el, paper) {
if (paper.top === el) {
return;
}
tear(el, paper);
el.next = null;
el.prev = paper.top;
paper.top.next = el;
paper.top = el;
},
toback = R._toback = function (el, paper) {
if (paper.bottom === el) {
return;
}
tear(el, paper);
el.next = paper.bottom;
el.prev = null;
paper.bottom.prev = el;
paper.bottom = el;
},
insertafter = R._insertafter = function (el, el2, paper) {
tear(el, paper);
el2 == paper.top && (paper.top = el);
el2.next && (el2.next.prev = el);
el.next = el2.next;
el.prev = el2;
el2.next = el;
},
insertbefore = R._insertbefore = function (el, el2, paper) {
tear(el, paper);
el2 == paper.bottom && (paper.bottom = el);
el2.prev && (el2.prev.next = el);
el.prev = el2.prev;
el2.prev = el;
el.next = el2;
},
/*\
* Raphael.toMatrix
[ method ]
**
* Utility method
**
* Returns matrix of transformations applied to a given path
> Parameters
- path (string) path string
- transform (string|array) transformation string
= (object) @Matrix
\*/
toMatrix = R.toMatrix = function (path, transform) {
var bb = pathDimensions(path),
el = {
_: {
transform: E
},
getBBox: function () {
return bb;
}
};
extractTransform(el, transform);
return el.matrix;
},
/*\
* Raphael.transformPath
[ method ]
**
* Utility method
**
* Returns path transformed by a given transformation
> Parameters
- path (string) path string
- transform (string|array) transformation string
= (string) path
\*/
transformPath = R.transformPath = function (path, transform) {
return mapPath(path, toMatrix(path, transform));
},
extractTransform = R._extractTransform = function (el, tstr) {
if (tstr == null) {
return el._.transform;
}
tstr = Str(tstr).replace(/\.{3}|\u2026/g, el._.transform || E);
var tdata = R.parseTransformString(tstr),
deg = 0,
dx = 0,
dy = 0,
sx = 1,
sy = 1,
_ = el._,
m = new Matrix;
_.transform = tdata || [];
if (tdata) {
for (var i = 0, ii = tdata.length; i < ii; i++) {
var t = tdata[i],
tlen = t.length,
command = Str(t[0]).toLowerCase(),
absolute = t[0] != command,
inver = absolute ? m.invert() : 0,
x1,
y1,
x2,
y2,
bb;
if (command == "t" && tlen == 3) {
if (absolute) {
x1 = inver.x(0, 0);
y1 = inver.y(0, 0);
x2 = inver.x(t[1], t[2]);
y2 = inver.y(t[1], t[2]);
m.translate(x2 - x1, y2 - y1);
} else {
m.translate(t[1], t[2]);
}
} else if (command == "r") {
if (tlen == 2) {
bb = bb || el.getBBox(1);
m.rotate(t[1], bb.x + bb.width / 2, bb.y + bb.height / 2);
deg += t[1];
} else if (tlen == 4) {
if (absolute) {
x2 = inver.x(t[2], t[3]);
y2 = inver.y(t[2], t[3]);
m.rotate(t[1], x2, y2);
} else {
m.rotate(t[1], t[2], t[3]);
}
deg += t[1];
}
} else if (command == "s") {
if (tlen == 2 || tlen == 3) {
bb = bb || el.getBBox(1);
m.scale(t[1], t[tlen - 1], bb.x + bb.width / 2, bb.y + bb.height / 2);
sx *= t[1];
sy *= t[tlen - 1];
} else if (tlen == 5) {
if (absolute) {
x2 = inver.x(t[3], t[4]);
y2 = inver.y(t[3], t[4]);
m.scale(t[1], t[2], x2, y2);
} else {
m.scale(t[1], t[2], t[3], t[4]);
}
sx *= t[1];
sy *= t[2];
}
} else if (command == "m" && tlen == 7) {
m.add(t[1], t[2], t[3], t[4], t[5], t[6]);
}
_.dirtyT = 1;
el.matrix = m;
}
}
/*\
* Element.matrix
[ property (object) ]
**
* Keeps @Matrix object, which represents element transformation
\*/
el.matrix = m;
_.sx = sx;
_.sy = sy;
_.deg = deg;
_.dx = dx = m.e;
_.dy = dy = m.f;
if (sx == 1 && sy == 1 && !deg && _.bbox) {
_.bbox.x += +dx;
_.bbox.y += +dy;
} else {
_.dirtyT = 1;
}
},
getEmpty = function (item) {
var l = item[0];
switch (l.toLowerCase()) {
case "t": return [l, 0, 0];
case "m": return [l, 1, 0, 0, 1, 0, 0];
case "r": if (item.length == 4) {
return [l, 0, item[2], item[3]];
} else {
return [l, 0];
}
case "s": if (item.length == 5) {
return [l, 1, 1, item[3], item[4]];
} else if (item.length == 3) {
return [l, 1, 1];
} else {
return [l, 1];
}
}
},
equaliseTransform = R._equaliseTransform = function (t1, t2) {
t2 = Str(t2).replace(/\.{3}|\u2026/g, t1);
t1 = R.parseTransformString(t1) || [];
t2 = R.parseTransformString(t2) || [];
var maxlength = mmax(t1.length, t2.length),
from = [],
to = [],
i = 0, j, jj,
tt1, tt2;
for (; i < maxlength; i++) {
tt1 = t1[i] || getEmpty(t2[i]);
tt2 = t2[i] || getEmpty(tt1);
if ((tt1[0] != tt2[0]) ||
(tt1[0].toLowerCase() == "r" && (tt1[2] != tt2[2] || tt1[3] != tt2[3])) ||
(tt1[0].toLowerCase() == "s" && (tt1[3] != tt2[3] || tt1[4] != tt2[4]))
) {
return;
}
from[i] = [];
to[i] = [];
for (j = 0, jj = mmax(tt1.length, tt2.length); j < jj; j++) {
j in tt1 && (from[i][j] = tt1[j]);
j in tt2 && (to[i][j] = tt2[j]);
}
}
return {
from: from,
to: to
};
};
R._getContainer = function (x, y, w, h) {
var container;
container = h == null && !R.is(x, "object") ? g.doc.getElementById(x) : x;
if (container == null) {
return;
}
if (container.tagName) {
if (y == null) {
return {
container: container,
width: container.style.pixelWidth || container.offsetWidth,
height: container.style.pixelHeight || container.offsetHeight
};
} else {
return {
container: container,
width: y,
height: w
};
}
}
return {
container: 1,
x: x,
y: y,
width: w,
height: h
};
};
/*\
* Raphael.pathToRelative
[ method ]
**
* Utility method
**
* Converts path to relative form
> Parameters
- pathString (string|array) path string or array of segments
= (array) array of segments.
\*/
R.pathToRelative = pathToRelative;
R._engine = {};
/*\
* Raphael.path2curve
[ method ]
**
* Utility method
**
* Converts path to a new path where all segments are cubic bezier curves.
> Parameters
- pathString (string|array) path string or array of segments
= (array) array of segments.
\*/
R.path2curve = path2curve;
/*\
* Raphael.matrix
[ method ]
**
* Utility method
**
* Returns matrix based on given parameters.
> Parameters
- a (number)
- b (number)
- c (number)
- d (number)
- e (number)
- f (number)
= (object) @Matrix
\*/
R.matrix = function (a, b, c, d, e, f) {
return new Matrix(a, b, c, d, e, f);
};
function Matrix(a, b, c, d, e, f) {
if (a != null) {
this.a = +a;
this.b = +b;
this.c = +c;
this.d = +d;
this.e = +e;
this.f = +f;
} else {
this.a = 1;
this.b = 0;
this.c = 0;
this.d = 1;
this.e = 0;
this.f = 0;
}
}
(function (matrixproto) {
/*\
* Matrix.add
[ method ]
**
* Adds given matrix to existing one.
> Parameters
- a (number)
- b (number)
- c (number)
- d (number)
- e (number)
- f (number)
or
- matrix (object) @Matrix
\*/
matrixproto.add = function (a, b, c, d, e, f) {
var out = [[], [], []],
m = [[this.a, this.c, this.e], [this.b, this.d, this.f], [0, 0, 1]],
matrix = [[a, c, e], [b, d, f], [0, 0, 1]],
x, y, z, res;
if (a && a instanceof Matrix) {
matrix = [[a.a, a.c, a.e], [a.b, a.d, a.f], [0, 0, 1]];
}
for (x = 0; x < 3; x++) {
for (y = 0; y < 3; y++) {
res = 0;
for (z = 0; z < 3; z++) {
res += m[x][z] * matrix[z][y];
}
out[x][y] = res;
}
}
this.a = out[0][0];
this.b = out[1][0];
this.c = out[0][1];
this.d = out[1][1];
this.e = out[0][2];
this.f = out[1][2];
};
/*\
* Matrix.invert
[ method ]
**
* Returns inverted version of the matrix
= (object) @Matrix
\*/
matrixproto.invert = function () {
var me = this,
x = me.a * me.d - me.b * me.c;
return new Matrix(me.d / x, -me.b / x, -me.c / x, me.a / x, (me.c * me.f - me.d * me.e) / x, (me.b * me.e - me.a * me.f) / x);
};
/*\
* Matrix.clone
[ method ]
**
* Returns copy of the matrix
= (object) @Matrix
\*/
matrixproto.clone = function () {
return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f);
};
/*\
* Matrix.translate
[ method ]
**
* Translate the matrix
> Parameters
- x (number)
- y (number)
\*/
matrixproto.translate = function (x, y) {
this.add(1, 0, 0, 1, x, y);
};
/*\
* Matrix.scale
[ method ]
**
* Scales the matrix
> Parameters
- x (number)
- y (number) #optional
- cx (number) #optional
- cy (number) #optional
\*/
matrixproto.scale = function (x, y, cx, cy) {
y == null && (y = x);
(cx || cy) && this.add(1, 0, 0, 1, cx, cy);
this.add(x, 0, 0, y, 0, 0);
(cx || cy) && this.add(1, 0, 0, 1, -cx, -cy);
};
/*\
* Matrix.rotate
[ method ]
**
* Rotates the matrix
> Parameters
- a (number)
- x (number)
- y (number)
\*/
matrixproto.rotate = function (a, x, y) {
a = R.rad(a);
x = x || 0;
y = y || 0;
var cos = +math.cos(a).toFixed(9),
sin = +math.sin(a).toFixed(9);
this.add(cos, sin, -sin, cos, x, y);
this.add(1, 0, 0, 1, -x, -y);
};
/*\
* Matrix.x
[ method ]
**
* Return x coordinate for given point after transformation described by the matrix. See also @Matrix.y
> Parameters
- x (number)
- y (number)
= (number) x
\*/
matrixproto.x = function (x, y) {
return x * this.a + y * this.c + this.e;
};
/*\
* Matrix.y
[ method ]
**
* Return y coordinate for given point after transformation described by the matrix. See also @Matrix.x
> Parameters
- x (number)
- y (number)
= (number) y
\*/
matrixproto.y = function (x, y) {
return x * this.b + y * this.d + this.f;
};
matrixproto.get = function (i) {
return +this[Str.fromCharCode(97 + i)].toFixed(4);
};
matrixproto.toString = function () {
return R.svg ?
"matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")" :
[this.get(0), this.get(2), this.get(1), this.get(3), 0, 0].join();
};
matrixproto.toFilter = function () {
return "progid:DXImageTransform.Microsoft.Matrix(M11=" + this.get(0) +
", M12=" + this.get(2) + ", M21=" + this.get(1) + ", M22=" + this.get(3) +
", Dx=" + this.get(4) + ", Dy=" + this.get(5) + ", sizingmethod='auto expand')";
};
matrixproto.offset = function () {
return [this.e.toFixed(4), this.f.toFixed(4)];
};
function norm(a) {
return a[0] * a[0] + a[1] * a[1];
}
function normalize(a) {
var mag = math.sqrt(norm(a));
a[0] && (a[0] /= mag);
a[1] && (a[1] /= mag);
}
/*\
* Matrix.split
[ method ]
**
* Splits matrix into primitive transformations
= (object) in format:
o dx (number) translation by x
o dy (number) translation by y
o scalex (number) scale by x
o scaley (number) scale by y
o shear (number) shear
o rotate (number) rotation in deg
o isSimple (boolean) could it be represented via simple transformations
\*/
matrixproto.split = function () {
var out = {};
// translation
out.dx = this.e;
out.dy = this.f;
// scale and shear
var row = [[this.a, this.c], [this.b, this.d]];
out.scalex = math.sqrt(norm(row[0]));
normalize(row[0]);
out.shear = row[0][0] * row[1][0] + row[0][1] * row[1][1];
row[1] = [row[1][0] - row[0][0] * out.shear, row[1][1] - row[0][1] * out.shear];
out.scaley = math.sqrt(norm(row[1]));
normalize(row[1]);
out.shear /= out.scaley;
// rotation
var sin = -row[0][1],
cos = row[1][1];
if (cos < 0) {
out.rotate = R.deg(math.acos(cos));
if (sin < 0) {
out.rotate = 360 - out.rotate;
}
} else {
out.rotate = R.deg(math.asin(sin));
}
out.isSimple = !+out.shear.toFixed(9) && (out.scalex.toFixed(9) == out.scaley.toFixed(9) || !out.rotate);
out.isSuperSimple = !+out.shear.toFixed(9) && out.scalex.toFixed(9) == out.scaley.toFixed(9) && !out.rotate;
out.noRotation = !+out.shear.toFixed(9) && !out.rotate;
return out;
};
/*\
* Matrix.toTransformString
[ method ]
**
* Return transform string that represents given matrix
= (string) transform string
\*/
matrixproto.toTransformString = function (shorter) {
var s = shorter || this[split]();
if (s.isSimple) {
s.scalex = +s.scalex.toFixed(4);
s.scaley = +s.scaley.toFixed(4);
s.rotate = +s.rotate.toFixed(4);
return (s.dx || s.dy ? "t" + [s.dx, s.dy] : E) +
(s.scalex != 1 || s.scaley != 1 ? "s" + [s.scalex, s.scaley, 0, 0] : E) +
(s.rotate ? "r" + [s.rotate, 0, 0] : E);
} else {
return "m" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)];
}
};
})(Matrix.prototype);
// WebKit rendering bug workaround method
var version = navigator.userAgent.match(/Version\/(.*?)\s/) || navigator.userAgent.match(/Chrome\/(\d+)/);
if ((navigator.vendor == "Apple Computer, Inc.") && (version && version[1] < 4 || navigator.platform.slice(0, 2) == "iP") ||
(navigator.vendor == "Google Inc." && version && version[1] < 8)) {
/*\
* Paper.safari
[ method ]
**
* There is an inconvenient rendering bug in Safari (WebKit):
* sometimes the rendering should be forced.
* This method should help with dealing with this bug.
\*/
paperproto.safari = function () {
var rect = this.rect(-99, -99, this.width + 99, this.height + 99).attr({stroke: "none"});
setTimeout(function () {rect.remove();});
};
} else {
paperproto.safari = fun;
}
var preventDefault = function () {
this.returnValue = false;
},
preventTouch = function () {
return this.originalEvent.preventDefault();
},
stopPropagation = function () {
this.cancelBubble = true;
},
stopTouch = function () {
return this.originalEvent.stopPropagation();
},
getEventPosition = function (e) {
var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft;
return {
x: e.clientX + scrollX,
y: e.clientY + scrollY
};
},
addEvent = (function () {
if (g.doc.addEventListener) {
return function (obj, type, fn, element) {
var f = function (e) {
var pos = getEventPosition(e);
return fn.call(element, e, pos.x, pos.y);
};
obj.addEventListener(type, f, false);
if (supportsTouch && touchMap[type]) {
var _f = function (e) {
var pos = getEventPosition(e),
olde = e;
for (var i = 0, ii = e.targetTouches && e.targetTouches.length; i < ii; i++) {
if (e.targetTouches[i].target == obj) {
e = e.targetTouches[i];
e.originalEvent = olde;
e.preventDefault = preventTouch;
e.stopPropagation = stopTouch;
break;
}
}
return fn.call(element, e, pos.x, pos.y);
};
obj.addEventListener(touchMap[type], _f, false);
}
return function () {
obj.removeEventListener(type, f, false);
if (supportsTouch && touchMap[type])
obj.removeEventListener(touchMap[type], f, false);
return true;
};
};
} else if (g.doc.attachEvent) {
return function (obj, type, fn, element) {
var f = function (e) {
e = e || g.win.event;
var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
x = e.clientX + scrollX,
y = e.clientY + scrollY;
e.preventDefault = e.preventDefault || preventDefault;
e.stopPropagation = e.stopPropagation || stopPropagation;
return fn.call(element, e, x, y);
};
obj.attachEvent("on" + type, f);
var detacher = function () {
obj.detachEvent("on" + type, f);
return true;
};
return detacher;
};
}
})(),
drag = [],
dragMove = function (e) {
var x = e.clientX,
y = e.clientY,
scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
dragi,
j = drag.length;
while (j--) {
dragi = drag[j];
if (supportsTouch && e.touches) {
var i = e.touches.length,
touch;
while (i--) {
touch = e.touches[i];
if (touch.identifier == dragi.el._drag.id) {
x = touch.clientX;
y = touch.clientY;
(e.originalEvent ? e.originalEvent : e).preventDefault();
break;
}
}
} else {
e.preventDefault();
}
var node = dragi.el.node,
o,
next = node.nextSibling,
parent = node.parentNode,
display = node.style.display;
g.win.opera && parent.removeChild(node);
node.style.display = "none";
o = dragi.el.paper.getElementByPoint(x, y);
node.style.display = display;
g.win.opera && (next ? parent.insertBefore(node, next) : parent.appendChild(node));
o && eve("raphael.drag.over." + dragi.el.id, dragi.el, o);
x += scrollX;
y += scrollY;
eve("raphael.drag.move." + dragi.el.id, dragi.move_scope || dragi.el, x - dragi.el._drag.x, y - dragi.el._drag.y, x, y, e);
}
},
dragUp = function (e) {
R.unmousemove(dragMove).unmouseup(dragUp);
var i = drag.length,
dragi;
while (i--) {
dragi = drag[i];
dragi.el._drag = {};
eve("raphael.drag.end." + dragi.el.id, dragi.end_scope || dragi.start_scope || dragi.move_scope || dragi.el, e);
}
drag = [];
},
/*\
* Raphael.el
[ property (object) ]
**
* You can add your own method to elements. This is usefull when you want to hack default functionality or
* want to wrap some common transformation or attributes in one method. In difference to canvas methods,
* you can redefine element method at any time. Expending element methods wouldn’t affect set.
> Usage
| Raphael.el.red = function () {
| this.attr({fill: "#f00"});
| };
| // then use it
| paper.circle(100, 100, 20).red();
\*/
elproto = R.el = {};
/*\
* Element.click
[ method ]
**
* Adds event handler for click for the element.
> Parameters
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.unclick
[ method ]
**
* Removes event handler for click for the element.
> Parameters
- handler (function) #optional handler for the event
= (object) @Element
\*/
/*\
* Element.dblclick
[ method ]
**
* Adds event handler for double click for the element.
> Parameters
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.undblclick
[ method ]
**
* Removes event handler for double click for the element.
> Parameters
- handler (function) #optional handler for the event
= (object) @Element
\*/
/*\
* Element.mousedown
[ method ]
**
* Adds event handler for mousedown for the element.
> Parameters
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.unmousedown
[ method ]
**
* Removes event handler for mousedown for the element.
> Parameters
- handler (function) #optional handler for the event
= (object) @Element
\*/
/*\
* Element.mousemove
[ method ]
**
* Adds event handler for mousemove for the element.
> Parameters
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.unmousemove
[ method ]
**
* Removes event handler for mousemove for the element.
> Parameters
- handler (function) #optional handler for the event
= (object) @Element
\*/
/*\
* Element.mouseout
[ method ]
**
* Adds event handler for mouseout for the element.
> Parameters
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.unmouseout
[ method ]
**
* Removes event handler for mouseout for the element.
> Parameters
- handler (function) #optional handler for the event
= (object) @Element
\*/
/*\
* Element.mouseover
[ method ]
**
* Adds event handler for mouseover for the element.
> Parameters
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.unmouseover
[ method ]
**
* Removes event handler for mouseover for the element.
> Parameters
- handler (function) #optional handler for the event
= (object) @Element
\*/
/*\
* Element.mouseup
[ method ]
**
* Adds event handler for mouseup for the element.
> Parameters
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.unmouseup
[ method ]
**
* Removes event handler for mouseup for the element.
> Parameters
- handler (function) #optional handler for the event
= (object) @Element
\*/
/*\
* Element.touchstart
[ method ]
**
* Adds event handler for touchstart for the element.
> Parameters
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.untouchstart
[ method ]
**
* Removes event handler for touchstart for the element.
> Parameters
- handler (function) #optional handler for the event
= (object) @Element
\*/
/*\
* Element.touchmove
[ method ]
**
* Adds event handler for touchmove for the element.
> Parameters
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.untouchmove
[ method ]
**
* Removes event handler for touchmove for the element.
> Parameters
- handler (function) #optional handler for the event
= (object) @Element
\*/
/*\
* Element.touchend
[ method ]
**
* Adds event handler for touchend for the element.
> Parameters
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.untouchend
[ method ]
**
* Removes event handler for touchend for the element.
> Parameters
- handler (function) #optional handler for the event
= (object) @Element
\*/
/*\
* Element.touchcancel
[ method ]
**
* Adds event handler for touchcancel for the element.
> Parameters
- handler (function) handler for the event
= (object) @Element
\*/
/*\
* Element.untouchcancel
[ method ]
**
* Removes event handler for touchcancel for the element.
> Parameters
- handler (function) #optional handler for the event
= (object) @Element
\*/
for (var i = events.length; i--;) {
(function (eventName) {
R[eventName] = elproto[eventName] = function (fn, scope) {
if (R.is(fn, "function")) {
this.events = this.events || [];
this.events.push({name: eventName, f: fn, unbind: addEvent(this.shape || this.node || g.doc, eventName, fn, scope || this)});
}
return this;
};
R["un" + eventName] = elproto["un" + eventName] = function (fn) {
var events = this.events || [],
l = events.length;
while (l--){
if (events[l].name == eventName && (R.is(fn, "undefined") || events[l].f == fn)) {
events[l].unbind();
events.splice(l, 1);
!events.length && delete this.events;
}
}
return this;
};
})(events[i]);
}
/*\
* Element.data
[ method ]
**
* Adds or retrieves given value asociated with given key.
**
* See also @Element.removeData
> Parameters
- key (string) key to store data
- value (any) #optional value to store
= (object) @Element
* or, if value is not specified:
= (any) value
* or, if key and value are not specified:
= (object) Key/value pairs for all the data associated with the element.
> Usage
| for (var i = 0, i < 5, i++) {
| paper.circle(10 + 15 * i, 10, 10)
| .attr({fill: "#000"})
| .data("i", i)
| .click(function () {
| alert(this.data("i"));
| });
| }
\*/
elproto.data = function (key, value) {
var data = eldata[this.id] = eldata[this.id] || {};
if (arguments.length == 0) {
return data;
}
if (arguments.length == 1) {
if (R.is(key, "object")) {
for (var i in key) if (key[has](i)) {
this.data(i, key[i]);
}
return this;
}
eve("raphael.data.get." + this.id, this, data[key], key);
return data[key];
}
data[key] = value;
eve("raphael.data.set." + this.id, this, value, key);
return this;
};
/*\
* Element.removeData
[ method ]
**
* Removes value associated with an element by given key.
* If key is not provided, removes all the data of the element.
> Parameters
- key (string) #optional key
= (object) @Element
\*/
elproto.removeData = function (key) {
if (key == null) {
eldata[this.id] = {};
} else {
eldata[this.id] && delete eldata[this.id][key];
}
return this;
};
/*\
* Element.getData
[ method ]
**
* Retrieves the element data
= (object) data
\*/
elproto.getData = function () {
return clone(eldata[this.id] || {});
};
/*\
* Element.hover
[ method ]
**
* Adds event handlers for hover for the element.
> Parameters
- f_in (function) handler for hover in
- f_out (function) handler for hover out
- icontext (object) #optional context for hover in handler
- ocontext (object) #optional context for hover out handler
= (object) @Element
\*/
elproto.hover = function (f_in, f_out, scope_in, scope_out) {
return this.mouseover(f_in, scope_in).mouseout(f_out, scope_out || scope_in);
};
/*\
* Element.unhover
[ method ]
**
* Removes event handlers for hover for the element.
> Parameters
- f_in (function) handler for hover in
- f_out (function) handler for hover out
= (object) @Element
\*/
elproto.unhover = function (f_in, f_out) {
return this.unmouseover(f_in).unmouseout(f_out);
};
var draggable = [];
/*\
* Element.drag
[ method ]
**
* Adds event handlers for drag of the element.
> Parameters
- onmove (function) handler for moving
- onstart (function) handler for drag start
- onend (function) handler for drag end
- mcontext (object) #optional context for moving handler
- scontext (object) #optional context for drag start handler
- econtext (object) #optional context for drag end handler
* Additionaly following `drag` events will be triggered: `drag.start.<id>` on start,
* `drag.end.<id>` on end and `drag.move.<id>` on every move. When element will be dragged over another element
* `drag.over.<id>` will be fired as well.
*
* Start event and start handler will be called in specified context or in context of the element with following parameters:
o x (number) x position of the mouse
o y (number) y position of the mouse
o event (object) DOM event object
* Move event and move handler will be called in specified context or in context of the element with following parameters:
o dx (number) shift by x from the start point
o dy (number) shift by y from the start point
o x (number) x position of the mouse
o y (number) y position of the mouse
o event (object) DOM event object
* End event and end handler will be called in specified context or in context of the element with following parameters:
o event (object) DOM event object
= (object) @Element
\*/
elproto.drag = function (onmove, onstart, onend, move_scope, start_scope, end_scope) {
function start(e) {
(e.originalEvent || e).preventDefault();
var x = e.clientX,
y = e.clientY,
scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft;
this._drag.id = e.identifier;
if (supportsTouch && e.touches) {
var i = e.touches.length, touch;
while (i--) {
touch = e.touches[i];
this._drag.id = touch.identifier;
if (touch.identifier == this._drag.id) {
x = touch.clientX;
y = touch.clientY;
break;
}
}
}
this._drag.x = x + scrollX;
this._drag.y = y + scrollY;
!drag.length && R.mousemove(dragMove).mouseup(dragUp);
drag.push({el: this, move_scope: move_scope, start_scope: start_scope, end_scope: end_scope});
onstart && eve.on("raphael.drag.start." + this.id, onstart);
onmove && eve.on("raphael.drag.move." + this.id, onmove);
onend && eve.on("raphael.drag.end." + this.id, onend);
eve("raphael.drag.start." + this.id, start_scope || move_scope || this, e.clientX + scrollX, e.clientY + scrollY, e);
}
this._drag = {};
draggable.push({el: this, start: start});
this.mousedown(start);
return this;
};
/*\
* Element.onDragOver
[ method ]
**
* Shortcut for assigning event handler for `drag.over.<id>` event, where id is id of the element (see @Element.id).
> Parameters
- f (function) handler for event, first argument would be the element you are dragging over
\*/
elproto.onDragOver = function (f) {
f ? eve.on("raphael.drag.over." + this.id, f) : eve.unbind("raphael.drag.over." + this.id);
};
/*\
* Element.undrag
[ method ]
**
* Removes all drag event handlers from given element.
\*/
elproto.undrag = function () {
var i = draggable.length;
while (i--) if (draggable[i].el == this) {
this.unmousedown(draggable[i].start);
draggable.splice(i, 1);
eve.unbind("raphael.drag.*." + this.id);
}
!draggable.length && R.unmousemove(dragMove).unmouseup(dragUp);
drag = [];
};
/*\
* Paper.circle
[ method ]
**
* Draws a circle.
**
> Parameters
**
- x (number) x coordinate of the centre
- y (number) y coordinate of the centre
- r (number) radius
= (object) Raphaël element object with type “circle”
**
> Usage
| var c = paper.circle(50, 50, 40);
\*/
paperproto.circle = function (x, y, r) {
var out = R._engine.circle(this, x || 0, y || 0, r || 0);
this.__set__ && this.__set__.push(out);
return out;
};
/*\
* Paper.rect
[ method ]
*
* Draws a rectangle.
**
> Parameters
**
- x (number) x coordinate of the top left corner
- y (number) y coordinate of the top left corner
- width (number) width
- height (number) height
- r (number) #optional radius for rounded corners, default is 0
= (object) Raphaël element object with type “rect”
**
> Usage
| // regular rectangle
| var c = paper.rect(10, 10, 50, 50);
| // rectangle with rounded corners
| var c = paper.rect(40, 40, 50, 50, 10);
\*/
paperproto.rect = function (x, y, w, h, r) {
var out = R._engine.rect(this, x || 0, y || 0, w || 0, h || 0, r || 0);
this.__set__ && this.__set__.push(out);
return out;
};
/*\
* Paper.ellipse
[ method ]
**
* Draws an ellipse.
**
> Parameters
**
- x (number) x coordinate of the centre
- y (number) y coordinate of the centre
- rx (number) horizontal radius
- ry (number) vertical radius
= (object) Raphaël element object with type “ellipse”
**
> Usage
| var c = paper.ellipse(50, 50, 40, 20);
\*/
paperproto.ellipse = function (x, y, rx, ry) {
var out = R._engine.ellipse(this, x || 0, y || 0, rx || 0, ry || 0);
this.__set__ && this.__set__.push(out);
return out;
};
/*\
* Paper.path
[ method ]
**
* Creates a path element by given path data string.
> Parameters
- pathString (string) #optional path string in SVG format.
* Path string consists of one-letter commands, followed by comma seprarated arguments in numercal form. Example:
| "M10,20L30,40"
* Here we can see two commands: “M”, with arguments `(10, 20)` and “L” with arguments `(30, 40)`. Upper case letter mean command is absolute, lower case—relative.
*
# <p>Here is short list of commands available, for more details see <a href="http://www.w3.org/TR/SVG/paths.html#PathData" title="Details of a path's data attribute's format are described in the SVG specification.">SVG path string format</a>.</p>
# <table><thead><tr><th>Command</th><th>Name</th><th>Parameters</th></tr></thead><tbody>
# <tr><td>M</td><td>moveto</td><td>(x y)+</td></tr>
# <tr><td>Z</td><td>closepath</td><td>(none)</td></tr>
# <tr><td>L</td><td>lineto</td><td>(x y)+</td></tr>
# <tr><td>H</td><td>horizontal lineto</td><td>x+</td></tr>
# <tr><td>V</td><td>vertical lineto</td><td>y+</td></tr>
# <tr><td>C</td><td>curveto</td><td>(x1 y1 x2 y2 x y)+</td></tr>
# <tr><td>S</td><td>smooth curveto</td><td>(x2 y2 x y)+</td></tr>
# <tr><td>Q</td><td>quadratic Bézier curveto</td><td>(x1 y1 x y)+</td></tr>
# <tr><td>T</td><td>smooth quadratic Bézier curveto</td><td>(x y)+</td></tr>
# <tr><td>A</td><td>elliptical arc</td><td>(rx ry x-axis-rotation large-arc-flag sweep-flag x y)+</td></tr>
# <tr><td>R</td><td><a href="http://en.wikipedia.org/wiki/Catmull–Rom_spline#Catmull.E2.80.93Rom_spline">Catmull-Rom curveto</a>*</td><td>x1 y1 (x y)+</td></tr></tbody></table>
* * “Catmull-Rom curveto” is a not standard SVG command and added in 2.0 to make life easier.
* Note: there is a special case when path consist of just three commands: “M10,10R…z”. In this case path will smoothly connects to its beginning.
> Usage
| var c = paper.path("M10 10L90 90");
| // draw a diagonal line:
| // move to 10,10, line to 90,90
* For example of path strings, check out these icons: http://raphaeljs.com/icons/
\*/
paperproto.path = function (pathString) {
pathString && !R.is(pathString, string) && !R.is(pathString[0], array) && (pathString += E);
var out = R._engine.path(R.format[apply](R, arguments), this);
this.__set__ && this.__set__.push(out);
return out;
};
/*\
* Paper.image
[ method ]
**
* Embeds an image into the surface.
**
> Parameters
**
- src (string) URI of the source image
- x (number) x coordinate position
- y (number) y coordinate position
- width (number) width of the image
- height (number) height of the image
= (object) Raphaël element object with type “image”
**
> Usage
| var c = paper.image("apple.png", 10, 10, 80, 80);
\*/
paperproto.image = function (src, x, y, w, h) {
var out = R._engine.image(this, src || "about:blank", x || 0, y || 0, w || 0, h || 0);
this.__set__ && this.__set__.push(out);
return out;
};
/*\
* Paper.text
[ method ]
**
* Draws a text string. If you need line breaks, put “\n” in the string.
**
> Parameters
**
- x (number) x coordinate position
- y (number) y coordinate position
- text (string) The text string to draw
= (object) Raphaël element object with type “text”
**
> Usage
| var t = paper.text(50, 50, "Raphaël\nkicks\nbutt!");
\*/
paperproto.text = function (x, y, text) {
var out = R._engine.text(this, x || 0, y || 0, Str(text));
this.__set__ && this.__set__.push(out);
return out;
};
/*\
* Paper.set
[ method ]
**
* Creates array-like object to keep and operate several elements at once.
* Warning: it doesn’t create any elements for itself in the page, it just groups existing elements.
* Sets act as pseudo elements — all methods available to an element can be used on a set.
= (object) array-like object that represents set of elements
**
> Usage
| var st = paper.set();
| st.push(
| paper.circle(10, 10, 5),
| paper.circle(30, 10, 5)
| );
| st.attr({fill: "red"}); // changes the fill of both circles
\*/
paperproto.set = function (itemsArray) {
!R.is(itemsArray, "array") && (itemsArray = Array.prototype.splice.call(arguments, 0, arguments.length));
var out = new Set(itemsArray);
this.__set__ && this.__set__.push(out);
out["paper"] = this;
out["type"] = "set";
return out;
};
/*\
* Paper.setStart
[ method ]
**
* Creates @Paper.set. All elements that will be created after calling this method and before calling
* @Paper.setFinish will be added to the set.
**
> Usage
| paper.setStart();
| paper.circle(10, 10, 5),
| paper.circle(30, 10, 5)
| var st = paper.setFinish();
| st.attr({fill: "red"}); // changes the fill of both circles
\*/
paperproto.setStart = function (set) {
this.__set__ = set || this.set();
};
/*\
* Paper.setFinish
[ method ]
**
* See @Paper.setStart. This method finishes catching and returns resulting set.
**
= (object) set
\*/
paperproto.setFinish = function (set) {
var out = this.__set__;
delete this.__set__;
return out;
};
/*\
* Paper.setSize
[ method ]
**
* If you need to change dimensions of the canvas call this method
**
> Parameters
**
- width (number) new width of the canvas
- height (number) new height of the canvas
\*/
paperproto.setSize = function (width, height) {
return R._engine.setSize.call(this, width, height);
};
/*\
* Paper.setViewBox
[ method ]
**
* Sets the view box of the paper. Practically it gives you ability to zoom and pan whole paper surface by
* specifying new boundaries.
**
> Parameters
**
- x (number) new x position, default is `0`
- y (number) new y position, default is `0`
- w (number) new width of the canvas
- h (number) new height of the canvas
- fit (boolean) `true` if you want graphics to fit into new boundary box
\*/
paperproto.setViewBox = function (x, y, w, h, fit) {
return R._engine.setViewBox.call(this, x, y, w, h, fit);
};
/*\
* Paper.top
[ property ]
**
* Points to the topmost element on the paper
\*/
/*\
* Paper.bottom
[ property ]
**
* Points to the bottom element on the paper
\*/
paperproto.top = paperproto.bottom = null;
/*\
* Paper.raphael
[ property ]
**
* Points to the @Raphael object/function
\*/
paperproto.raphael = R;
var getOffset = function (elem) {
var box = elem.getBoundingClientRect(),
doc = elem.ownerDocument,
body = doc.body,
docElem = doc.documentElement,
clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
top = box.top + (g.win.pageYOffset || docElem.scrollTop || body.scrollTop ) - clientTop,
left = box.left + (g.win.pageXOffset || docElem.scrollLeft || body.scrollLeft) - clientLeft;
return {
y: top,
x: left
};
};
/*\
* Paper.getElementByPoint
[ method ]
**
* Returns you topmost element under given point.
**
= (object) Raphaël element object
> Parameters
**
- x (number) x coordinate from the top left corner of the window
- y (number) y coordinate from the top left corner of the window
> Usage
| paper.getElementByPoint(mouseX, mouseY).attr({stroke: "#f00"});
\*/
paperproto.getElementByPoint = function (x, y) {
var paper = this,
svg = paper.canvas,
target = g.doc.elementFromPoint(x, y);
if (g.win.opera && target.tagName == "svg") {
var so = getOffset(svg),
sr = svg.createSVGRect();
sr.x = x - so.x;
sr.y = y - so.y;
sr.width = sr.height = 1;
var hits = svg.getIntersectionList(sr, null);
if (hits.length) {
target = hits[hits.length - 1];
}
}
if (!target) {
return null;
}
while (target.parentNode && target != svg.parentNode && !target.raphael) {
target = target.parentNode;
}
target == paper.canvas.parentNode && (target = svg);
target = target && target.raphael ? paper.getById(target.raphaelid) : null;
return target;
};
/*\
* Paper.getElementsByBBox
[ method ]
**
* Returns set of elements that have an intersecting bounding box
**
> Parameters
**
- bbox (object) bbox to check with
= (object) @Set
\*/
paperproto.getElementsByBBox = function (bbox) {
var set = this.set();
this.forEach(function (el) {
if (R.isBBoxIntersect(el.getBBox(), bbox)) {
set.push(el);
}
});
return set;
};
/*\
* Paper.getById
[ method ]
**
* Returns you element by its internal ID.
**
> Parameters
**
- id (number) id
= (object) Raphaël element object
\*/
paperproto.getById = function (id) {
var bot = this.bottom;
while (bot) {
if (bot.id == id) {
return bot;
}
bot = bot.next;
}
return null;
};
/*\
* Paper.forEach
[ method ]
**
* Executes given function for each element on the paper
*
* If callback function returns `false` it will stop loop running.
**
> Parameters
**
- callback (function) function to run
- thisArg (object) context object for the callback
= (object) Paper object
> Usage
| paper.forEach(function (el) {
| el.attr({ stroke: "blue" });
| });
\*/
paperproto.forEach = function (callback, thisArg) {
var bot = this.bottom;
while (bot) {
if (callback.call(thisArg, bot) === false) {
return this;
}
bot = bot.next;
}
return this;
};
/*\
* Paper.getElementsByPoint
[ method ]
**
* Returns set of elements that have common point inside
**
> Parameters
**
- x (number) x coordinate of the point
- y (number) y coordinate of the point
= (object) @Set
\*/
paperproto.getElementsByPoint = function (x, y) {
var set = this.set();
this.forEach(function (el) {
if (el.isPointInside(x, y)) {
set.push(el);
}
});
return set;
};
function x_y() {
return this.x + S + this.y;
}
function x_y_w_h() {
return this.x + S + this.y + S + this.width + " \xd7 " + this.height;
}
/*\
* Element.isPointInside
[ method ]
**
* Determine if given point is inside this element’s shape
**
> Parameters
**
- x (number) x coordinate of the point
- y (number) y coordinate of the point
= (boolean) `true` if point inside the shape
\*/
elproto.isPointInside = function (x, y) {
var rp = this.realPath = getPath[this.type](this);
if (this.attr('transform') && this.attr('transform').length) {
rp = R.transformPath(rp, this.attr('transform'));
}
return R.isPointInsidePath(rp, x, y);
};
/*\
* Element.getBBox
[ method ]
**
* Return bounding box for a given element
**
> Parameters
**
- isWithoutTransform (boolean) flag, `true` if you want to have bounding box before transformations. Default is `false`.
= (object) Bounding box object:
o {
o x: (number) top left corner x
o y: (number) top left corner y
o x2: (number) bottom right corner x
o y2: (number) bottom right corner y
o width: (number) width
o height: (number) height
o }
\*/
elproto.getBBox = function (isWithoutTransform) {
if (this.removed) {
return {};
}
var _ = this._;
if (isWithoutTransform) {
if (_.dirty || !_.bboxwt) {
this.realPath = getPath[this.type](this);
_.bboxwt = pathDimensions(this.realPath);
_.bboxwt.toString = x_y_w_h;
_.dirty = 0;
}
return _.bboxwt;
}
if (_.dirty || _.dirtyT || !_.bbox) {
if (_.dirty || !this.realPath) {
_.bboxwt = 0;
this.realPath = getPath[this.type](this);
}
_.bbox = pathDimensions(mapPath(this.realPath, this.matrix));
_.bbox.toString = x_y_w_h;
_.dirty = _.dirtyT = 0;
}
return _.bbox;
};
/*\
* Element.clone
[ method ]
**
= (object) clone of a given element
**
\*/
elproto.clone = function () {
if (this.removed) {
return null;
}
var out = this.paper[this.type]().attr(this.attr());
this.__set__ && this.__set__.push(out);
return out;
};
/*\
* Element.glow
[ method ]
**
* Return set of elements that create glow-like effect around given element. See @Paper.set.
*
* Note: Glow is not connected to the element. If you change element attributes it won’t adjust itself.
**
> Parameters
**
- glow (object) #optional parameters object with all properties optional:
o {
o width (number) size of the glow, default is `10`
o fill (boolean) will it be filled, default is `false`
o opacity (number) opacity, default is `0.5`
o offsetx (number) horizontal offset, default is `0`
o offsety (number) vertical offset, default is `0`
o color (string) glow colour, default is `black`
o }
= (object) @Paper.set of elements that represents glow
\*/
elproto.glow = function (glow) {
if (this.type == "text") {
return null;
}
glow = glow || {};
var s = {
width: (glow.width || 10) + (+this.attr("stroke-width") || 1),
fill: glow.fill || false,
opacity: glow.opacity || .5,
offsetx: glow.offsetx || 0,
offsety: glow.offsety || 0,
color: glow.color || "#000"
},
c = s.width / 2,
r = this.paper,
out = r.set(),
path = this.realPath || getPath[this.type](this);
path = this.matrix ? mapPath(path, this.matrix) : path;
for (var i = 1; i < c + 1; i++) {
out.push(r.path(path).attr({
stroke: s.color,
fill: s.fill ? s.color : "none",
"stroke-linejoin": "round",
"stroke-linecap": "round",
"stroke-width": +(s.width / c * i).toFixed(3),
opacity: +(s.opacity / c).toFixed(3)
}));
}
return out.insertBefore(this).translate(s.offsetx, s.offsety);
};
var curveslengths = {},
getPointAtSegmentLength = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length) {
if (length == null) {
return bezlen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y);
} else {
return R.findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, getTatLen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length));
}
},
getLengthFactory = function (istotal, subpath) {
return function (path, length, onlystart) {
path = path2curve(path);
var x, y, p, l, sp = "", subpaths = {}, point,
len = 0;
for (var i = 0, ii = path.length; i < ii; i++) {
p = path[i];
if (p[0] == "M") {
x = +p[1];
y = +p[2];
} else {
l = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
if (len + l > length) {
if (subpath && !subpaths.start) {
point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
sp += ["C" + point.start.x, point.start.y, point.m.x, point.m.y, point.x, point.y];
if (onlystart) {return sp;}
subpaths.start = sp;
sp = ["M" + point.x, point.y + "C" + point.n.x, point.n.y, point.end.x, point.end.y, p[5], p[6]].join();
len += l;
x = +p[5];
y = +p[6];
continue;
}
if (!istotal && !subpath) {
point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
return {x: point.x, y: point.y, alpha: point.alpha};
}
}
len += l;
x = +p[5];
y = +p[6];
}
sp += p.shift() + p;
}
subpaths.end = sp;
point = istotal ? len : subpath ? subpaths : R.findDotsAtSegment(x, y, p[0], p[1], p[2], p[3], p[4], p[5], 1);
point.alpha && (point = {x: point.x, y: point.y, alpha: point.alpha});
return point;
};
};
var getTotalLength = getLengthFactory(1),
getPointAtLength = getLengthFactory(),
getSubpathsAtLength = getLengthFactory(0, 1);
/*\
* Raphael.getTotalLength
[ method ]
**
* Returns length of the given path in pixels.
**
> Parameters
**
- path (string) SVG path string.
**
= (number) length.
\*/
R.getTotalLength = getTotalLength;
/*\
* Raphael.getPointAtLength
[ method ]
**
* Return coordinates of the point located at the given length on the given path.
**
> Parameters
**
- path (string) SVG path string
- length (number)
**
= (object) representation of the point:
o {
o x: (number) x coordinate
o y: (number) y coordinate
o alpha: (number) angle of derivative
o }
\*/
R.getPointAtLength = getPointAtLength;
/*\
* Raphael.getSubpath
[ method ]
**
* Return subpath of a given path from given length to given length.
**
> Parameters
**
- path (string) SVG path string
- from (number) position of the start of the segment
- to (number) position of the end of the segment
**
= (string) pathstring for the segment
\*/
R.getSubpath = function (path, from, to) {
if (this.getTotalLength(path) - to < 1e-6) {
return getSubpathsAtLength(path, from).end;
}
var a = getSubpathsAtLength(path, to, 1);
return from ? getSubpathsAtLength(a, from).end : a;
};
/*\
* Element.getTotalLength
[ method ]
**
* Returns length of the path in pixels. Only works for element of “path” type.
= (number) length.
\*/
elproto.getTotalLength = function () {
var path = this.getPath();
if (!path) {
return;
}
if (this.node.getTotalLength) {
return this.node.getTotalLength();
}
return getTotalLength(path);
};
/*\
* Element.getPointAtLength
[ method ]
**
* Return coordinates of the point located at the given length on the given path. Only works for element of “path” type.
**
> Parameters
**
- length (number)
**
= (object) representation of the point:
o {
o x: (number) x coordinate
o y: (number) y coordinate
o alpha: (number) angle of derivative
o }
\*/
elproto.getPointAtLength = function (length) {
var path = this.getPath();
if (!path) {
return;
}
return getPointAtLength(path, length);
};
/*\
* Element.getPath
[ method ]
**
* Returns path of the element. Only works for elements of “path” type and simple elements like circle.
= (object) path
**
\*/
elproto.getPath = function () {
var path,
getPath = R._getPath[this.type];
if (this.type == "text" || this.type == "set") {
return;
}
if (getPath) {
path = getPath(this);
}
return path;
};
/*\
* Element.getSubpath
[ method ]
**
* Return subpath of a given element from given length to given length. Only works for element of “path” type.
**
> Parameters
**
- from (number) position of the start of the segment
- to (number) position of the end of the segment
**
= (string) pathstring for the segment
\*/
elproto.getSubpath = function (from, to) {
var path = this.getPath();
if (!path) {
return;
}
return R.getSubpath(path, from, to);
};
/*\
* Raphael.easing_formulas
[ property ]
**
* Object that contains easing formulas for animation. You could extend it with your own. By default it has following list of easing:
# <ul>
# <li>“linear”</li>
# <li>“<” or “easeIn” or “ease-in”</li>
# <li>“>” or “easeOut” or “ease-out”</li>
# <li>“<>” or “easeInOut” or “ease-in-out”</li>
# <li>“backIn” or “back-in”</li>
# <li>“backOut” or “back-out”</li>
# <li>“elastic”</li>
# <li>“bounce”</li>
# </ul>
# <p>See also <a href="http://raphaeljs.com/easing.html">Easing demo</a>.</p>
\*/
var ef = R.easing_formulas = {
linear: function (n) {
return n;
},
"<": function (n) {
return pow(n, 1.7);
},
">": function (n) {
return pow(n, .48);
},
"<>": function (n) {
var q = .48 - n / 1.04,
Q = math.sqrt(.1734 + q * q),
x = Q - q,
X = pow(abs(x), 1 / 3) * (x < 0 ? -1 : 1),
y = -Q - q,
Y = pow(abs(y), 1 / 3) * (y < 0 ? -1 : 1),
t = X + Y + .5;
return (1 - t) * 3 * t * t + t * t * t;
},
backIn: function (n) {
var s = 1.70158;
return n * n * ((s + 1) * n - s);
},
backOut: function (n) {
n = n - 1;
var s = 1.70158;
return n * n * ((s + 1) * n + s) + 1;
},
elastic: function (n) {
if (n == !!n) {
return n;
}
return pow(2, -10 * n) * math.sin((n - .075) * (2 * PI) / .3) + 1;
},
bounce: function (n) {
var s = 7.5625,
p = 2.75,
l;
if (n < (1 / p)) {
l = s * n * n;
} else {
if (n < (2 / p)) {
n -= (1.5 / p);
l = s * n * n + .75;
} else {
if (n < (2.5 / p)) {
n -= (2.25 / p);
l = s * n * n + .9375;
} else {
n -= (2.625 / p);
l = s * n * n + .984375;
}
}
}
return l;
}
};
ef.easeIn = ef["ease-in"] = ef["<"];
ef.easeOut = ef["ease-out"] = ef[">"];
ef.easeInOut = ef["ease-in-out"] = ef["<>"];
ef["back-in"] = ef.backIn;
ef["back-out"] = ef.backOut;
var animationElements = [],
requestAnimFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
setTimeout(callback, 16);
},
animation = function () {
var Now = +new Date,
l = 0;
for (; l < animationElements.length; l++) {
var e = animationElements[l];
if (e.el.removed || e.paused) {
continue;
}
var time = Now - e.start,
ms = e.ms,
easing = e.easing,
from = e.from,
diff = e.diff,
to = e.to,
t = e.t,
that = e.el,
set = {},
now,
init = {},
key;
if (e.initstatus) {
time = (e.initstatus * e.anim.top - e.prev) / (e.percent - e.prev) * ms;
e.status = e.initstatus;
delete e.initstatus;
e.stop && animationElements.splice(l--, 1);
} else {
e.status = (e.prev + (e.percent - e.prev) * (time / ms)) / e.anim.top;
}
if (time < 0) {
continue;
}
if (time < ms) {
var pos = easing(time / ms);
for (var attr in from) if (from[has](attr)) {
switch (availableAnimAttrs[attr]) {
case nu:
now = +from[attr] + pos * ms * diff[attr];
break;
case "colour":
now = "rgb(" + [
upto255(round(from[attr].r + pos * ms * diff[attr].r)),
upto255(round(from[attr].g + pos * ms * diff[attr].g)),
upto255(round(from[attr].b + pos * ms * diff[attr].b))
].join(",") + ")";
break;
case "path":
now = [];
for (var i = 0, ii = from[attr].length; i < ii; i++) {
now[i] = [from[attr][i][0]];
for (var j = 1, jj = from[attr][i].length; j < jj; j++) {
now[i][j] = +from[attr][i][j] + pos * ms * diff[attr][i][j];
}
now[i] = now[i].join(S);
}
now = now.join(S);
break;
case "transform":
if (diff[attr].real) {
now = [];
for (i = 0, ii = from[attr].length; i < ii; i++) {
now[i] = [from[attr][i][0]];
for (j = 1, jj = from[attr][i].length; j < jj; j++) {
now[i][j] = from[attr][i][j] + pos * ms * diff[attr][i][j];
}
}
} else {
var get = function (i) {
return +from[attr][i] + pos * ms * diff[attr][i];
};
// now = [["r", get(2), 0, 0], ["t", get(3), get(4)], ["s", get(0), get(1), 0, 0]];
now = [["m", get(0), get(1), get(2), get(3), get(4), get(5)]];
}
break;
case "csv":
if (attr == "clip-rect") {
now = [];
i = 4;
while (i--) {
now[i] = +from[attr][i] + pos * ms * diff[attr][i];
}
}
break;
default:
var from2 = [][concat](from[attr]);
now = [];
i = that.paper.customAttributes[attr].length;
while (i--) {
now[i] = +from2[i] + pos * ms * diff[attr][i];
}
break;
}
set[attr] = now;
}
that.attr(set);
(function (id, that, anim) {
setTimeout(function () {
eve("raphael.anim.frame." + id, that, anim);
});
})(that.id, that, e.anim);
} else {
(function(f, el, a) {
setTimeout(function() {
eve("raphael.anim.frame." + el.id, el, a);
eve("raphael.anim.finish." + el.id, el, a);
R.is(f, "function") && f.call(el);
});
})(e.callback, that, e.anim);
that.attr(to);
animationElements.splice(l--, 1);
if (e.repeat > 1 && !e.next) {
for (key in to) if (to[has](key)) {
init[key] = e.totalOrigin[key];
}
e.el.attr(init);
runAnimation(e.anim, e.el, e.anim.percents[0], null, e.totalOrigin, e.repeat - 1);
}
if (e.next && !e.stop) {
runAnimation(e.anim, e.el, e.next, null, e.totalOrigin, e.repeat);
}
}
}
R.svg && that && that.paper && that.paper.safari();
animationElements.length && requestAnimFrame(animation);
},
upto255 = function (color) {
return color > 255 ? 255 : color < 0 ? 0 : color;
};
/*\
* Element.animateWith
[ method ]
**
* Acts similar to @Element.animate, but ensure that given animation runs in sync with another given element.
**
> Parameters
**
- el (object) element to sync with
- anim (object) animation to sync with
- params (object) #optional final attributes for the element, see also @Element.attr
- ms (number) #optional number of milliseconds for animation to run
- easing (string) #optional easing type. Accept on of @Raphael.easing_formulas or CSS format: `cubic‐bezier(XX, XX, XX, XX)`
- callback (function) #optional callback function. Will be called at the end of animation.
* or
- element (object) element to sync with
- anim (object) animation to sync with
- animation (object) #optional animation object, see @Raphael.animation
**
= (object) original element
\*/
elproto.animateWith = function (el, anim, params, ms, easing, callback) {
var element = this;
if (element.removed) {
callback && callback.call(element);
return element;
}
var a = params instanceof Animation ? params : R.animation(params, ms, easing, callback),
x, y;
runAnimation(a, element, a.percents[0], null, element.attr());
for (var i = 0, ii = animationElements.length; i < ii; i++) {
if (animationElements[i].anim == anim && animationElements[i].el == el) {
animationElements[ii - 1].start = animationElements[i].start;
break;
}
}
return element;
//
//
// var a = params ? R.animation(params, ms, easing, callback) : anim,
// status = element.status(anim);
// return this.animate(a).status(a, status * anim.ms / a.ms);
};
function CubicBezierAtTime(t, p1x, p1y, p2x, p2y, duration) {
var cx = 3 * p1x,
bx = 3 * (p2x - p1x) - cx,
ax = 1 - cx - bx,
cy = 3 * p1y,
by = 3 * (p2y - p1y) - cy,
ay = 1 - cy - by;
function sampleCurveX(t) {
return ((ax * t + bx) * t + cx) * t;
}
function solve(x, epsilon) {
var t = solveCurveX(x, epsilon);
return ((ay * t + by) * t + cy) * t;
}
function solveCurveX(x, epsilon) {
var t0, t1, t2, x2, d2, i;
for(t2 = x, i = 0; i < 8; i++) {
x2 = sampleCurveX(t2) - x;
if (abs(x2) < epsilon) {
return t2;
}
d2 = (3 * ax * t2 + 2 * bx) * t2 + cx;
if (abs(d2) < 1e-6) {
break;
}
t2 = t2 - x2 / d2;
}
t0 = 0;
t1 = 1;
t2 = x;
if (t2 < t0) {
return t0;
}
if (t2 > t1) {
return t1;
}
while (t0 < t1) {
x2 = sampleCurveX(t2);
if (abs(x2 - x) < epsilon) {
return t2;
}
if (x > x2) {
t0 = t2;
} else {
t1 = t2;
}
t2 = (t1 - t0) / 2 + t0;
}
return t2;
}
return solve(t, 1 / (200 * duration));
}
elproto.onAnimation = function (f) {
f ? eve.on("raphael.anim.frame." + this.id, f) : eve.unbind("raphael.anim.frame." + this.id);
return this;
};
function Animation(anim, ms) {
var percents = [],
newAnim = {};
this.ms = ms;
this.times = 1;
if (anim) {
for (var attr in anim) if (anim[has](attr)) {
newAnim[toFloat(attr)] = anim[attr];
percents.push(toFloat(attr));
}
percents.sort(sortByNumber);
}
this.anim = newAnim;
this.top = percents[percents.length - 1];
this.percents = percents;
}
/*\
* Animation.delay
[ method ]
**
* Creates a copy of existing animation object with given delay.
**
> Parameters
**
- delay (number) number of ms to pass between animation start and actual animation
**
= (object) new altered Animation object
| var anim = Raphael.animation({cx: 10, cy: 20}, 2e3);
| circle1.animate(anim); // run the given animation immediately
| circle2.animate(anim.delay(500)); // run the given animation after 500 ms
\*/
Animation.prototype.delay = function (delay) {
var a = new Animation(this.anim, this.ms);
a.times = this.times;
a.del = +delay || 0;
return a;
};
/*\
* Animation.repeat
[ method ]
**
* Creates a copy of existing animation object with given repetition.
**
> Parameters
**
- repeat (number) number iterations of animation. For infinite animation pass `Infinity`
**
= (object) new altered Animation object
\*/
Animation.prototype.repeat = function (times) {
var a = new Animation(this.anim, this.ms);
a.del = this.del;
a.times = math.floor(mmax(times, 0)) || 1;
return a;
};
function runAnimation(anim, element, percent, status, totalOrigin, times) {
percent = toFloat(percent);
var params,
isInAnim,
isInAnimSet,
percents = [],
next,
prev,
timestamp,
ms = anim.ms,
from = {},
to = {},
diff = {};
if (status) {
for (i = 0, ii = animationElements.length; i < ii; i++) {
var e = animationElements[i];
if (e.el.id == element.id && e.anim == anim) {
if (e.percent != percent) {
animationElements.splice(i, 1);
isInAnimSet = 1;
} else {
isInAnim = e;
}
element.attr(e.totalOrigin);
break;
}
}
} else {
status = +to; // NaN
}
for (var i = 0, ii = anim.percents.length; i < ii; i++) {
if (anim.percents[i] == percent || anim.percents[i] > status * anim.top) {
percent = anim.percents[i];
prev = anim.percents[i - 1] || 0;
ms = ms / anim.top * (percent - prev);
next = anim.percents[i + 1];
params = anim.anim[percent];
break;
} else if (status) {
element.attr(anim.anim[anim.percents[i]]);
}
}
if (!params) {
return;
}
if (!isInAnim) {
for (var attr in params) if (params[has](attr)) {
if (availableAnimAttrs[has](attr) || element.paper.customAttributes[has](attr)) {
from[attr] = element.attr(attr);
(from[attr] == null) && (from[attr] = availableAttrs[attr]);
to[attr] = params[attr];
switch (availableAnimAttrs[attr]) {
case nu:
diff[attr] = (to[attr] - from[attr]) / ms;
break;
case "colour":
from[attr] = R.getRGB(from[attr]);
var toColour = R.getRGB(to[attr]);
diff[attr] = {
r: (toColour.r - from[attr].r) / ms,
g: (toColour.g - from[attr].g) / ms,
b: (toColour.b - from[attr].b) / ms
};
break;
case "path":
var pathes = path2curve(from[attr], to[attr]),
toPath = pathes[1];
from[attr] = pathes[0];
diff[attr] = [];
for (i = 0, ii = from[attr].length; i < ii; i++) {
diff[attr][i] = [0];
for (var j = 1, jj = from[attr][i].length; j < jj; j++) {
diff[attr][i][j] = (toPath[i][j] - from[attr][i][j]) / ms;
}
}
break;
case "transform":
var _ = element._,
eq = equaliseTransform(_[attr], to[attr]);
if (eq) {
from[attr] = eq.from;
to[attr] = eq.to;
diff[attr] = [];
diff[attr].real = true;
for (i = 0, ii = from[attr].length; i < ii; i++) {
diff[attr][i] = [from[attr][i][0]];
for (j = 1, jj = from[attr][i].length; j < jj; j++) {
diff[attr][i][j] = (to[attr][i][j] - from[attr][i][j]) / ms;
}
}
} else {
var m = (element.matrix || new Matrix),
to2 = {
_: {transform: _.transform},
getBBox: function () {
return element.getBBox(1);
}
};
from[attr] = [
m.a,
m.b,
m.c,
m.d,
m.e,
m.f
];
extractTransform(to2, to[attr]);
to[attr] = to2._.transform;
diff[attr] = [
(to2.matrix.a - m.a) / ms,
(to2.matrix.b - m.b) / ms,
(to2.matrix.c - m.c) / ms,
(to2.matrix.d - m.d) / ms,
(to2.matrix.e - m.e) / ms,
(to2.matrix.f - m.f) / ms
];
// from[attr] = [_.sx, _.sy, _.deg, _.dx, _.dy];
// var to2 = {_:{}, getBBox: function () { return element.getBBox(); }};
// extractTransform(to2, to[attr]);
// diff[attr] = [
// (to2._.sx - _.sx) / ms,
// (to2._.sy - _.sy) / ms,
// (to2._.deg - _.deg) / ms,
// (to2._.dx - _.dx) / ms,
// (to2._.dy - _.dy) / ms
// ];
}
break;
case "csv":
var values = Str(params[attr])[split](separator),
from2 = Str(from[attr])[split](separator);
if (attr == "clip-rect") {
from[attr] = from2;
diff[attr] = [];
i = from2.length;
while (i--) {
diff[attr][i] = (values[i] - from[attr][i]) / ms;
}
}
to[attr] = values;
break;
default:
values = [][concat](params[attr]);
from2 = [][concat](from[attr]);
diff[attr] = [];
i = element.paper.customAttributes[attr].length;
while (i--) {
diff[attr][i] = ((values[i] || 0) - (from2[i] || 0)) / ms;
}
break;
}
}
}
var easing = params.easing,
easyeasy = R.easing_formulas[easing];
if (!easyeasy) {
easyeasy = Str(easing).match(bezierrg);
if (easyeasy && easyeasy.length == 5) {
var curve = easyeasy;
easyeasy = function (t) {
return CubicBezierAtTime(t, +curve[1], +curve[2], +curve[3], +curve[4], ms);
};
} else {
easyeasy = pipe;
}
}
timestamp = params.start || anim.start || +new Date;
e = {
anim: anim,
percent: percent,
timestamp: timestamp,
start: timestamp + (anim.del || 0),
status: 0,
initstatus: status || 0,
stop: false,
ms: ms,
easing: easyeasy,
from: from,
diff: diff,
to: to,
el: element,
callback: params.callback,
prev: prev,
next: next,
repeat: times || anim.times,
origin: element.attr(),
totalOrigin: totalOrigin
};
animationElements.push(e);
if (status && !isInAnim && !isInAnimSet) {
e.stop = true;
e.start = new Date - ms * status;
if (animationElements.length == 1) {
return animation();
}
}
if (isInAnimSet) {
e.start = new Date - e.ms * status;
}
animationElements.length == 1 && requestAnimFrame(animation);
} else {
isInAnim.initstatus = status;
isInAnim.start = new Date - isInAnim.ms * status;
}
eve("raphael.anim.start." + element.id, element, anim);
}
/*\
* Raphael.animation
[ method ]
**
* Creates an animation object that can be passed to the @Element.animate or @Element.animateWith methods.
* See also @Animation.delay and @Animation.repeat methods.
**
> Parameters
**
- params (object) final attributes for the element, see also @Element.attr
- ms (number) number of milliseconds for animation to run
- easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic‐bezier(XX, XX, XX, XX)`
- callback (function) #optional callback function. Will be called at the end of animation.
**
= (object) @Animation
\*/
R.animation = function (params, ms, easing, callback) {
if (params instanceof Animation) {
return params;
}
if (R.is(easing, "function") || !easing) {
callback = callback || easing || null;
easing = null;
}
params = Object(params);
ms = +ms || 0;
var p = {},
json,
attr;
for (attr in params) if (params[has](attr) && toFloat(attr) != attr && toFloat(attr) + "%" != attr) {
json = true;
p[attr] = params[attr];
}
if (!json) {
return new Animation(params, ms);
} else {
easing && (p.easing = easing);
callback && (p.callback = callback);
return new Animation({100: p}, ms);
}
};
/*\
* Element.animate
[ method ]
**
* Creates and starts animation for given element.
**
> Parameters
**
- params (object) final attributes for the element, see also @Element.attr
- ms (number) number of milliseconds for animation to run
- easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic‐bezier(XX, XX, XX, XX)`
- callback (function) #optional callback function. Will be called at the end of animation.
* or
- animation (object) animation object, see @Raphael.animation
**
= (object) original element
\*/
elproto.animate = function (params, ms, easing, callback) {
var element = this;
if (element.removed) {
callback && callback.call(element);
return element;
}
var anim = params instanceof Animation ? params : R.animation(params, ms, easing, callback);
runAnimation(anim, element, anim.percents[0], null, element.attr());
return element;
};
/*\
* Element.setTime
[ method ]
**
* Sets the status of animation of the element in milliseconds. Similar to @Element.status method.
**
> Parameters
**
- anim (object) animation object
- value (number) number of milliseconds from the beginning of the animation
**
= (object) original element if `value` is specified
* Note, that during animation following events are triggered:
*
* On each animation frame event `anim.frame.<id>`, on start `anim.start.<id>` and on end `anim.finish.<id>`.
\*/
elproto.setTime = function (anim, value) {
if (anim && value != null) {
this.status(anim, mmin(value, anim.ms) / anim.ms);
}
return this;
};
/*\
* Element.status
[ method ]
**
* Gets or sets the status of animation of the element.
**
> Parameters
**
- anim (object) #optional animation object
- value (number) #optional 0 – 1. If specified, method works like a setter and sets the status of a given animation to the value. This will cause animation to jump to the given position.
**
= (number) status
* or
= (array) status if `anim` is not specified. Array of objects in format:
o {
o anim: (object) animation object
o status: (number) status
o }
* or
= (object) original element if `value` is specified
\*/
elproto.status = function (anim, value) {
var out = [],
i = 0,
len,
e;
if (value != null) {
runAnimation(anim, this, -1, mmin(value, 1));
return this;
} else {
len = animationElements.length;
for (; i < len; i++) {
e = animationElements[i];
if (e.el.id == this.id && (!anim || e.anim == anim)) {
if (anim) {
return e.status;
}
out.push({
anim: e.anim,
status: e.status
});
}
}
if (anim) {
return 0;
}
return out;
}
};
/*\
* Element.pause
[ method ]
**
* Stops animation of the element with ability to resume it later on.
**
> Parameters
**
- anim (object) #optional animation object
**
= (object) original element
\*/
elproto.pause = function (anim) {
for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
if (eve("raphael.anim.pause." + this.id, this, animationElements[i].anim) !== false) {
animationElements[i].paused = true;
}
}
return this;
};
/*\
* Element.resume
[ method ]
**
* Resumes animation if it was paused with @Element.pause method.
**
> Parameters
**
- anim (object) #optional animation object
**
= (object) original element
\*/
elproto.resume = function (anim) {
for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
var e = animationElements[i];
if (eve("raphael.anim.resume." + this.id, this, e.anim) !== false) {
delete e.paused;
this.status(e.anim, e.status);
}
}
return this;
};
/*\
* Element.stop
[ method ]
**
* Stops animation of the element.
**
> Parameters
**
- anim (object) #optional animation object
**
= (object) original element
\*/
elproto.stop = function (anim) {
for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
if (eve("raphael.anim.stop." + this.id, this, animationElements[i].anim) !== false) {
animationElements.splice(i--, 1);
}
}
return this;
};
function stopAnimation(paper) {
for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.paper == paper) {
animationElements.splice(i--, 1);
}
}
eve.on("raphael.remove", stopAnimation);
eve.on("raphael.clear", stopAnimation);
elproto.toString = function () {
return "Rapha\xebl\u2019s object";
};
// Set
var Set = function (items) {
this.items = [];
this.length = 0;
this.type = "set";
if (items) {
for (var i = 0, ii = items.length; i < ii; i++) {
if (items[i] && (items[i].constructor == elproto.constructor || items[i].constructor == Set)) {
this[this.items.length] = this.items[this.items.length] = items[i];
this.length++;
}
}
}
},
setproto = Set.prototype;
/*\
* Set.push
[ method ]
**
* Adds each argument to the current set.
= (object) original element
\*/
setproto.push = function () {
var item,
len;
for (var i = 0, ii = arguments.length; i < ii; i++) {
item = arguments[i];
if (item && (item.constructor == elproto.constructor || item.constructor == Set)) {
len = this.items.length;
this[len] = this.items[len] = item;
this.length++;
}
}
return this;
};
/*\
* Set.pop
[ method ]
**
* Removes last element and returns it.
= (object) element
\*/
setproto.pop = function () {
this.length && delete this[this.length--];
return this.items.pop();
};
/*\
* Set.forEach
[ method ]
**
* Executes given function for each element in the set.
*
* If function returns `false` it will stop loop running.
**
> Parameters
**
- callback (function) function to run
- thisArg (object) context object for the callback
= (object) Set object
\*/
setproto.forEach = function (callback, thisArg) {
for (var i = 0, ii = this.items.length; i < ii; i++) {
if (callback.call(thisArg, this.items[i], i) === false) {
return this;
}
}
return this;
};
for (var method in elproto) if (elproto[has](method)) {
setproto[method] = (function (methodname) {
return function () {
var arg = arguments;
return this.forEach(function (el) {
el[methodname][apply](el, arg);
});
};
})(method);
}
setproto.attr = function (name, value) {
if (name && R.is(name, array) && R.is(name[0], "object")) {
for (var j = 0, jj = name.length; j < jj; j++) {
this.items[j].attr(name[j]);
}
} else {
for (var i = 0, ii = this.items.length; i < ii; i++) {
this.items[i].attr(name, value);
}
}
return this;
};
/*\
* Set.clear
[ method ]
**
* Removeds all elements from the set
\*/
setproto.clear = function () {
while (this.length) {
this.pop();
}
};
/*\
* Set.splice
[ method ]
**
* Removes given element from the set
**
> Parameters
**
- index (number) position of the deletion
- count (number) number of element to remove
- insertion… (object) #optional elements to insert
= (object) set elements that were deleted
\*/
setproto.splice = function (index, count, insertion) {
index = index < 0 ? mmax(this.length + index, 0) : index;
count = mmax(0, mmin(this.length - index, count));
var tail = [],
todel = [],
args = [],
i;
for (i = 2; i < arguments.length; i++) {
args.push(arguments[i]);
}
for (i = 0; i < count; i++) {
todel.push(this[index + i]);
}
for (; i < this.length - index; i++) {
tail.push(this[index + i]);
}
var arglen = args.length;
for (i = 0; i < arglen + tail.length; i++) {
this.items[index + i] = this[index + i] = i < arglen ? args[i] : tail[i - arglen];
}
i = this.items.length = this.length -= count - arglen;
while (this[i]) {
delete this[i++];
}
return new Set(todel);
};
/*\
* Set.exclude
[ method ]
**
* Removes given element from the set
**
> Parameters
**
- element (object) element to remove
= (boolean) `true` if object was found & removed from the set
\*/
setproto.exclude = function (el) {
for (var i = 0, ii = this.length; i < ii; i++) if (this[i] == el) {
this.splice(i, 1);
return true;
}
};
setproto.animate = function (params, ms, easing, callback) {
(R.is(easing, "function") || !easing) && (callback = easing || null);
var len = this.items.length,
i = len,
item,
set = this,
collector;
if (!len) {
return this;
}
callback && (collector = function () {
!--len && callback.call(set);
});
easing = R.is(easing, string) ? easing : collector;
var anim = R.animation(params, ms, easing, collector);
item = this.items[--i].animate(anim);
while (i--) {
this.items[i] && !this.items[i].removed && this.items[i].animateWith(item, anim, anim);
(this.items[i] && !this.items[i].removed) || len--;
}
return this;
};
setproto.insertAfter = function (el) {
var i = this.items.length;
while (i--) {
this.items[i].insertAfter(el);
}
return this;
};
setproto.getBBox = function () {
var x = [],
y = [],
x2 = [],
y2 = [];
for (var i = this.items.length; i--;) if (!this.items[i].removed) {
var box = this.items[i].getBBox();
x.push(box.x);
y.push(box.y);
x2.push(box.x + box.width);
y2.push(box.y + box.height);
}
x = mmin[apply](0, x);
y = mmin[apply](0, y);
x2 = mmax[apply](0, x2);
y2 = mmax[apply](0, y2);
return {
x: x,
y: y,
x2: x2,
y2: y2,
width: x2 - x,
height: y2 - y
};
};
setproto.clone = function (s) {
s = this.paper.set();
for (var i = 0, ii = this.items.length; i < ii; i++) {
s.push(this.items[i].clone());
}
return s;
};
setproto.toString = function () {
return "Rapha\xebl\u2018s set";
};
setproto.glow = function(glowConfig) {
var ret = this.paper.set();
this.forEach(function(shape, index){
var g = shape.glow(glowConfig);
if(g != null){
g.forEach(function(shape2, index2){
ret.push(shape2);
});
}
});
return ret;
};
/*\
* Set.isPointInside
[ method ]
**
* Determine if given point is inside this set’s elements
**
> Parameters
**
- x (number) x coordinate of the point
- y (number) y coordinate of the point
= (boolean) `true` if point is inside any of the set's elements
\*/
setproto.isPointInside = function (x, y) {
var isPointInside = false;
this.forEach(function (el) {
if (el.isPointInside(x, y)) {
isPointInside = true;
return false; // stop loop
}
});
return isPointInside;
};
/*\
* Raphael.registerFont
[ method ]
**
* Adds given font to the registered set of fonts for Raphaël. Should be used as an internal call from within Cufón’s font file.
* Returns original parameter, so it could be used with chaining.
# <a href="http://wiki.github.com/sorccu/cufon/about">More about Cufón and how to convert your font form TTF, OTF, etc to JavaScript file.</a>
**
> Parameters
**
- font (object) the font to register
= (object) the font you passed in
> Usage
| Cufon.registerFont(Raphael.registerFont({…}));
\*/
R.registerFont = function (font) {
if (!font.face) {
return font;
}
this.fonts = this.fonts || {};
var fontcopy = {
w: font.w,
face: {},
glyphs: {}
},
family = font.face["font-family"];
for (var prop in font.face) if (font.face[has](prop)) {
fontcopy.face[prop] = font.face[prop];
}
if (this.fonts[family]) {
this.fonts[family].push(fontcopy);
} else {
this.fonts[family] = [fontcopy];
}
if (!font.svg) {
fontcopy.face["units-per-em"] = toInt(font.face["units-per-em"], 10);
for (var glyph in font.glyphs) if (font.glyphs[has](glyph)) {
var path = font.glyphs[glyph];
fontcopy.glyphs[glyph] = {
w: path.w,
k: {},
d: path.d && "M" + path.d.replace(/[mlcxtrv]/g, function (command) {
return {l: "L", c: "C", x: "z", t: "m", r: "l", v: "c"}[command] || "M";
}) + "z"
};
if (path.k) {
for (var k in path.k) if (path[has](k)) {
fontcopy.glyphs[glyph].k[k] = path.k[k];
}
}
}
}
return font;
};
/*\
* Paper.getFont
[ method ]
**
* Finds font object in the registered fonts by given parameters. You could specify only one word from the font name, like “Myriad” for “Myriad Pro”.
**
> Parameters
**
- family (string) font family name or any word from it
- weight (string) #optional font weight
- style (string) #optional font style
- stretch (string) #optional font stretch
= (object) the font object
> Usage
| paper.print(100, 100, "Test string", paper.getFont("Times", 800), 30);
\*/
paperproto.getFont = function (family, weight, style, stretch) {
stretch = stretch || "normal";
style = style || "normal";
weight = +weight || {normal: 400, bold: 700, lighter: 300, bolder: 800}[weight] || 400;
if (!R.fonts) {
return;
}
var font = R.fonts[family];
if (!font) {
var name = new RegExp("(^|\\s)" + family.replace(/[^\w\d\s+!~.:_-]/g, E) + "(\\s|$)", "i");
for (var fontName in R.fonts) if (R.fonts[has](fontName)) {
if (name.test(fontName)) {
font = R.fonts[fontName];
break;
}
}
}
var thefont;
if (font) {
for (var i = 0, ii = font.length; i < ii; i++) {
thefont = font[i];
if (thefont.face["font-weight"] == weight && (thefont.face["font-style"] == style || !thefont.face["font-style"]) && thefont.face["font-stretch"] == stretch) {
break;
}
}
}
return thefont;
};
/*\
* Paper.print
[ method ]
**
* Creates path that represent given text written using given font at given position with given size.
* Result of the method is path element that contains whole text as a separate path.
**
> Parameters
**
- x (number) x position of the text
- y (number) y position of the text
- string (string) text to print
- font (object) font object, see @Paper.getFont
- size (number) #optional size of the font, default is `16`
- origin (string) #optional could be `"baseline"` or `"middle"`, default is `"middle"`
- letter_spacing (number) #optional number in range `-1..1`, default is `0`
- line_spacing (number) #optional number in range `1..3`, default is `1`
= (object) resulting path element, which consist of all letters
> Usage
| var txt = r.print(10, 50, "print", r.getFont("Museo"), 30).attr({fill: "#fff"});
\*/
paperproto.print = function (x, y, string, font, size, origin, letter_spacing, line_spacing) {
origin = origin || "middle"; // baseline|middle
letter_spacing = mmax(mmin(letter_spacing || 0, 1), -1);
line_spacing = mmax(mmin(line_spacing || 1, 3), 1);
var letters = Str(string)[split](E),
shift = 0,
notfirst = 0,
path = E,
scale;
R.is(font, "string") && (font = this.getFont(font));
if (font) {
scale = (size || 16) / font.face["units-per-em"];
var bb = font.face.bbox[split](separator),
top = +bb[0],
lineHeight = bb[3] - bb[1],
shifty = 0,
height = +bb[1] + (origin == "baseline" ? lineHeight + (+font.face.descent) : lineHeight / 2);
for (var i = 0, ii = letters.length; i < ii; i++) {
if (letters[i] == "\n") {
shift = 0;
curr = 0;
notfirst = 0;
shifty += lineHeight * line_spacing;
} else {
var prev = notfirst && font.glyphs[letters[i - 1]] || {},
curr = font.glyphs[letters[i]];
shift += notfirst ? (prev.w || font.w) + (prev.k && prev.k[letters[i]] || 0) + (font.w * letter_spacing) : 0;
notfirst = 1;
}
if (curr && curr.d) {
path += R.transformPath(curr.d, ["t", shift * scale, shifty * scale, "s", scale, scale, top, height, "t", (x - top) / scale, (y - height) / scale]);
}
}
}
return this.path(path).attr({
fill: "#000",
stroke: "none"
});
};
/*\
* Paper.add
[ method ]
**
* Imports elements in JSON array in format `{type: type, <attributes>}`
**
> Parameters
**
- json (array)
= (object) resulting set of imported elements
> Usage
| paper.add([
| {
| type: "circle",
| cx: 10,
| cy: 10,
| r: 5
| },
| {
| type: "rect",
| x: 10,
| y: 10,
| width: 10,
| height: 10,
| fill: "#fc0"
| }
| ]);
\*/
paperproto.add = function (json) {
if (R.is(json, "array")) {
var res = this.set(),
i = 0,
ii = json.length,
j;
for (; i < ii; i++) {
j = json[i] || {};
elements[has](j.type) && res.push(this[j.type]().attr(j));
}
}
return res;
};
/*\
* Raphael.format
[ method ]
**
* Simple format function. Replaces construction of type “`{<number>}`” to the corresponding argument.
**
> Parameters
**
- token (string) string to format
- … (string) rest of arguments will be treated as parameters for replacement
= (string) formated string
> Usage
| var x = 10,
| y = 20,
| width = 40,
| height = 50;
| // this will draw a rectangular shape equivalent to "M10,20h40v50h-40z"
| paper.path(Raphael.format("M{0},{1}h{2}v{3}h{4}z", x, y, width, height, -width));
\*/
R.format = function (token, params) {
var args = R.is(params, array) ? [0][concat](params) : arguments;
token && R.is(token, string) && args.length - 1 && (token = token.replace(formatrg, function (str, i) {
return args[++i] == null ? E : args[i];
}));
return token || E;
};
/*\
* Raphael.fullfill
[ method ]
**
* A little bit more advanced format function than @Raphael.format. Replaces construction of type “`{<name>}`” to the corresponding argument.
**
> Parameters
**
- token (string) string to format
- json (object) object which properties will be used as a replacement
= (string) formated string
> Usage
| // this will draw a rectangular shape equivalent to "M10,20h40v50h-40z"
| paper.path(Raphael.fullfill("M{x},{y}h{dim.width}v{dim.height}h{dim['negative width']}z", {
| x: 10,
| y: 20,
| dim: {
| width: 40,
| height: 50,
| "negative width": -40
| }
| }));
\*/
R.fullfill = (function () {
var tokenRegex = /\{([^\}]+)\}/g,
objNotationRegex = /(?:(?:^|\.)(.+?)(?=\[|\.|$|\()|\[('|")(.+?)\2\])(\(\))?/g, // matches .xxxxx or ["xxxxx"] to run over object properties
replacer = function (all, key, obj) {
var res = obj;
key.replace(objNotationRegex, function (all, name, quote, quotedName, isFunc) {
name = name || quotedName;
if (res) {
if (name in res) {
res = res[name];
}
typeof res == "function" && isFunc && (res = res());
}
});
res = (res == null || res == obj ? all : res) + "";
return res;
};
return function (str, obj) {
return String(str).replace(tokenRegex, function (all, key) {
return replacer(all, key, obj);
});
};
})();
/*\
* Raphael.ninja
[ method ]
**
* If you want to leave no trace of Raphaël (Well, Raphaël creates only one global variable `Raphael`, but anyway.) You can use `ninja` method.
* Beware, that in this case plugins could stop working, because they are depending on global variable existance.
**
= (object) Raphael object
> Usage
| (function (local_raphael) {
| var paper = local_raphael(10, 10, 320, 200);
| …
| })(Raphael.ninja());
\*/
R.ninja = function () {
oldRaphael.was ? (g.win.Raphael = oldRaphael.is) : delete Raphael;
return R;
};
/*\
* Raphael.st
[ property (object) ]
**
* You can add your own method to elements and sets. It is wise to add a set method for each element method
* you added, so you will be able to call the same method on sets too.
**
* See also @Raphael.el.
> Usage
| Raphael.el.red = function () {
| this.attr({fill: "#f00"});
| };
| Raphael.st.red = function () {
| this.forEach(function (el) {
| el.red();
| });
| };
| // then use it
| paper.set(paper.circle(100, 100, 20), paper.circle(110, 100, 20)).red();
\*/
R.st = setproto;
// Firefox <3.6 fix: http://webreflection.blogspot.com/2009/11/195-chars-to-help-lazy-loading.html
(function (doc, loaded, f) {
if (doc.readyState == null && doc.addEventListener){
doc.addEventListener(loaded, f = function () {
doc.removeEventListener(loaded, f, false);
doc.readyState = "complete";
}, false);
doc.readyState = "loading";
}
function isLoaded() {
(/in/).test(doc.readyState) ? setTimeout(isLoaded, 9) : R.eve("raphael.DOMload");
}
isLoaded();
})(document, "DOMContentLoaded");
eve.on("raphael.DOMload", function () {
loaded = true;
});
// ┌─────────────────────────────────────────────────────────────────────┐ \\
// │ Raphaël - JavaScript Vector Library │ \\
// ├─────────────────────────────────────────────────────────────────────┤ \\
// │ SVG Module │ \\
// ├─────────────────────────────────────────────────────────────────────┤ \\
// │ Copyright (c) 2008-2011 Dmitry Baranovskiy (http://raphaeljs.com) │ \\
// │ Copyright (c) 2008-2011 Sencha Labs (http://sencha.com) │ \\
// │ Licensed under the MIT (http://raphaeljs.com/license.html) license. │ \\
// └─────────────────────────────────────────────────────────────────────┘ \\
(function(){
if (!R.svg) {
return;
}
var has = "hasOwnProperty",
Str = String,
toFloat = parseFloat,
toInt = parseInt,
math = Math,
mmax = math.max,
abs = math.abs,
pow = math.pow,
separator = /[, ]+/,
eve = R.eve,
E = "",
S = " ";
var xlink = "http://www.w3.org/1999/xlink",
markers = {
block: "M5,0 0,2.5 5,5z",
classic: "M5,0 0,2.5 5,5 3.5,3 3.5,2z",
diamond: "M2.5,0 5,2.5 2.5,5 0,2.5z",
open: "M6,1 1,3.5 6,6",
oval: "M2.5,0A2.5,2.5,0,0,1,2.5,5 2.5,2.5,0,0,1,2.5,0z"
},
markerCounter = {};
R.toString = function () {
return "Your browser supports SVG.\nYou are running Rapha\xebl " + this.version;
};
var $ = function (el, attr) {
if (attr) {
if (typeof el == "string") {
el = $(el);
}
for (var key in attr) if (attr[has](key)) {
if (key.substring(0, 6) == "xlink:") {
el.setAttributeNS(xlink, key.substring(6), Str(attr[key]));
} else {
el.setAttribute(key, Str(attr[key]));
}
}
} else {
el = R._g.doc.createElementNS("http://www.w3.org/2000/svg", el);
el.style && (el.style.webkitTapHighlightColor = "rgba(0,0,0,0)");
}
return el;
},
addGradientFill = function (element, gradient) {
var type = "linear",
id = element.id + gradient,
fx = .5, fy = .5,
o = element.node,
SVG = element.paper,
s = o.style,
el = R._g.doc.getElementById(id);
if (!el) {
gradient = Str(gradient).replace(R._radial_gradient, function (all, _fx, _fy) {
type = "radial";
if (_fx && _fy) {
fx = toFloat(_fx);
fy = toFloat(_fy);
var dir = ((fy > .5) * 2 - 1);
pow(fx - .5, 2) + pow(fy - .5, 2) > .25 &&
(fy = math.sqrt(.25 - pow(fx - .5, 2)) * dir + .5) &&
fy != .5 &&
(fy = fy.toFixed(5) - 1e-5 * dir);
}
return E;
});
gradient = gradient.split(/\s*\-\s*/);
if (type == "linear") {
var angle = gradient.shift();
angle = -toFloat(angle);
if (isNaN(angle)) {
return null;
}
var vector = [0, 0, math.cos(R.rad(angle)), math.sin(R.rad(angle))],
max = 1 / (mmax(abs(vector[2]), abs(vector[3])) || 1);
vector[2] *= max;
vector[3] *= max;
if (vector[2] < 0) {
vector[0] = -vector[2];
vector[2] = 0;
}
if (vector[3] < 0) {
vector[1] = -vector[3];
vector[3] = 0;
}
}
var dots = R._parseDots(gradient);
if (!dots) {
return null;
}
id = id.replace(/[\(\)\s,\xb0#]/g, "_");
if (element.gradient && id != element.gradient.id) {
SVG.defs.removeChild(element.gradient);
delete element.gradient;
}
if (!element.gradient) {
el = $(type + "Gradient", {id: id});
element.gradient = el;
$(el, type == "radial" ? {
fx: fx,
fy: fy
} : {
x1: vector[0],
y1: vector[1],
x2: vector[2],
y2: vector[3],
gradientTransform: element.matrix.invert()
});
SVG.defs.appendChild(el);
for (var i = 0, ii = dots.length; i < ii; i++) {
el.appendChild($("stop", {
offset: dots[i].offset ? dots[i].offset : i ? "100%" : "0%",
"stop-color": dots[i].color || "#fff"
}));
}
}
}
$(o, {
fill: "url(#" + id + ")",
opacity: 1,
"fill-opacity": 1
});
s.fill = E;
s.opacity = 1;
s.fillOpacity = 1;
return 1;
},
updatePosition = function (o) {
var bbox = o.getBBox(1);
$(o.pattern, {patternTransform: o.matrix.invert() + " translate(" + bbox.x + "," + bbox.y + ")"});
},
addArrow = function (o, value, isEnd) {
if (o.type == "path") {
var values = Str(value).toLowerCase().split("-"),
p = o.paper,
se = isEnd ? "end" : "start",
node = o.node,
attrs = o.attrs,
stroke = attrs["stroke-width"],
i = values.length,
type = "classic",
from,
to,
dx,
refX,
attr,
w = 3,
h = 3,
t = 5;
while (i--) {
switch (values[i]) {
case "block":
case "classic":
case "oval":
case "diamond":
case "open":
case "none":
type = values[i];
break;
case "wide": h = 5; break;
case "narrow": h = 2; break;
case "long": w = 5; break;
case "short": w = 2; break;
}
}
if (type == "open") {
w += 2;
h += 2;
t += 2;
dx = 1;
refX = isEnd ? 4 : 1;
attr = {
fill: "none",
stroke: attrs.stroke
};
} else {
refX = dx = w / 2;
attr = {
fill: attrs.stroke,
stroke: "none"
};
}
if (o._.arrows) {
if (isEnd) {
o._.arrows.endPath && markerCounter[o._.arrows.endPath]--;
o._.arrows.endMarker && markerCounter[o._.arrows.endMarker]--;
} else {
o._.arrows.startPath && markerCounter[o._.arrows.startPath]--;
o._.arrows.startMarker && markerCounter[o._.arrows.startMarker]--;
}
} else {
o._.arrows = {};
}
if (type != "none") {
var pathId = "raphael-marker-" + type,
markerId = "raphael-marker-" + se + type + w + h;
if (!R._g.doc.getElementById(pathId)) {
p.defs.appendChild($($("path"), {
"stroke-linecap": "round",
d: markers[type],
id: pathId
}));
markerCounter[pathId] = 1;
} else {
markerCounter[pathId]++;
}
var marker = R._g.doc.getElementById(markerId),
use;
if (!marker) {
marker = $($("marker"), {
id: markerId,
markerHeight: h,
markerWidth: w,
orient: "auto",
refX: refX,
refY: h / 2
});
use = $($("use"), {
"xlink:href": "#" + pathId,
transform: (isEnd ? "rotate(180 " + w / 2 + " " + h / 2 + ") " : E) + "scale(" + w / t + "," + h / t + ")",
"stroke-width": (1 / ((w / t + h / t) / 2)).toFixed(4)
});
marker.appendChild(use);
p.defs.appendChild(marker);
markerCounter[markerId] = 1;
} else {
markerCounter[markerId]++;
use = marker.getElementsByTagName("use")[0];
}
$(use, attr);
var delta = dx * (type != "diamond" && type != "oval");
if (isEnd) {
from = o._.arrows.startdx * stroke || 0;
to = R.getTotalLength(attrs.path) - delta * stroke;
} else {
from = delta * stroke;
to = R.getTotalLength(attrs.path) - (o._.arrows.enddx * stroke || 0);
}
attr = {};
attr["marker-" + se] = "url(#" + markerId + ")";
if (to || from) {
attr.d = R.getSubpath(attrs.path, from, to);
}
$(node, attr);
o._.arrows[se + "Path"] = pathId;
o._.arrows[se + "Marker"] = markerId;
o._.arrows[se + "dx"] = delta;
o._.arrows[se + "Type"] = type;
o._.arrows[se + "String"] = value;
} else {
if (isEnd) {
from = o._.arrows.startdx * stroke || 0;
to = R.getTotalLength(attrs.path) - from;
} else {
from = 0;
to = R.getTotalLength(attrs.path) - (o._.arrows.enddx * stroke || 0);
}
o._.arrows[se + "Path"] && $(node, {d: R.getSubpath(attrs.path, from, to)});
delete o._.arrows[se + "Path"];
delete o._.arrows[se + "Marker"];
delete o._.arrows[se + "dx"];
delete o._.arrows[se + "Type"];
delete o._.arrows[se + "String"];
}
for (attr in markerCounter) if (markerCounter[has](attr) && !markerCounter[attr]) {
var item = R._g.doc.getElementById(attr);
item && item.parentNode.removeChild(item);
}
}
},
dasharray = {
"": [0],
"none": [0],
"-": [3, 1],
".": [1, 1],
"-.": [3, 1, 1, 1],
"-..": [3, 1, 1, 1, 1, 1],
". ": [1, 3],
"- ": [4, 3],
"--": [8, 3],
"- .": [4, 3, 1, 3],
"--.": [8, 3, 1, 3],
"--..": [8, 3, 1, 3, 1, 3]
},
addDashes = function (o, value, params) {
value = dasharray[Str(value).toLowerCase()];
if (value) {
var width = o.attrs["stroke-width"] || "1",
butt = {round: width, square: width, butt: 0}[o.attrs["stroke-linecap"] || params["stroke-linecap"]] || 0,
dashes = [],
i = value.length;
while (i--) {
dashes[i] = value[i] * width + ((i % 2) ? 1 : -1) * butt;
}
$(o.node, {"stroke-dasharray": dashes.join(",")});
}
},
setFillAndStroke = function (o, params) {
var node = o.node,
attrs = o.attrs,
vis = node.style.visibility;
node.style.visibility = "hidden";
for (var att in params) {
if (params[has](att)) {
if (!R._availableAttrs[has](att)) {
continue;
}
var value = params[att];
attrs[att] = value;
switch (att) {
case "blur":
o.blur(value);
break;
case "title":
var title = node.getElementsByTagName("title");
// Use the existing <title>.
if (title.length && (title = title[0])) {
title.firstChild.nodeValue = value;
} else {
title = $("title");
var val = R._g.doc.createTextNode(value);
title.appendChild(val);
node.appendChild(title);
}
break;
case "href":
case "target":
var pn = node.parentNode;
if (pn.tagName.toLowerCase() != "a") {
var hl = $("a");
pn.insertBefore(hl, node);
hl.appendChild(node);
pn = hl;
}
if (att == "target") {
pn.setAttributeNS(xlink, "show", value == "blank" ? "new" : value);
} else {
pn.setAttributeNS(xlink, att, value);
}
break;
case "cursor":
node.style.cursor = value;
break;
case "transform":
o.transform(value);
break;
case "arrow-start":
addArrow(o, value);
break;
case "arrow-end":
addArrow(o, value, 1);
break;
case "clip-rect":
var rect = Str(value).split(separator);
if (rect.length == 4) {
o.clip && o.clip.parentNode.parentNode.removeChild(o.clip.parentNode);
var el = $("clipPath"),
rc = $("rect");
el.id = R.createUUID();
$(rc, {
x: rect[0],
y: rect[1],
width: rect[2],
height: rect[3]
});
el.appendChild(rc);
o.paper.defs.appendChild(el);
$(node, {"clip-path": "url(#" + el.id + ")"});
o.clip = rc;
}
if (!value) {
var path = node.getAttribute("clip-path");
if (path) {
var clip = R._g.doc.getElementById(path.replace(/(^url\(#|\)$)/g, E));
clip && clip.parentNode.removeChild(clip);
$(node, {"clip-path": E});
delete o.clip;
}
}
break;
case "path":
if (o.type == "path") {
$(node, {d: value ? attrs.path = R._pathToAbsolute(value) : "M0,0"});
o._.dirty = 1;
if (o._.arrows) {
"startString" in o._.arrows && addArrow(o, o._.arrows.startString);
"endString" in o._.arrows && addArrow(o, o._.arrows.endString, 1);
}
}
break;
case "width":
node.setAttribute(att, value);
o._.dirty = 1;
if (attrs.fx) {
att = "x";
value = attrs.x;
} else {
break;
}
case "x":
if (attrs.fx) {
value = -attrs.x - (attrs.width || 0);
}
case "rx":
if (att == "rx" && o.type == "rect") {
break;
}
case "cx":
node.setAttribute(att, value);
o.pattern && updatePosition(o);
o._.dirty = 1;
break;
case "height":
node.setAttribute(att, value);
o._.dirty = 1;
if (attrs.fy) {
att = "y";
value = attrs.y;
} else {
break;
}
case "y":
if (attrs.fy) {
value = -attrs.y - (attrs.height || 0);
}
case "ry":
if (att == "ry" && o.type == "rect") {
break;
}
case "cy":
node.setAttribute(att, value);
o.pattern && updatePosition(o);
o._.dirty = 1;
break;
case "r":
if (o.type == "rect") {
$(node, {rx: value, ry: value});
} else {
node.setAttribute(att, value);
}
o._.dirty = 1;
break;
case "src":
if (o.type == "image") {
node.setAttributeNS(xlink, "href", value);
}
break;
case "stroke-width":
if (o._.sx != 1 || o._.sy != 1) {
value /= mmax(abs(o._.sx), abs(o._.sy)) || 1;
}
if (o.paper._vbSize) {
value *= o.paper._vbSize;
}
node.setAttribute(att, value);
if (attrs["stroke-dasharray"]) {
addDashes(o, attrs["stroke-dasharray"], params);
}
if (o._.arrows) {
"startString" in o._.arrows && addArrow(o, o._.arrows.startString);
"endString" in o._.arrows && addArrow(o, o._.arrows.endString, 1);
}
break;
case "stroke-dasharray":
addDashes(o, value, params);
break;
case "fill":
var isURL = Str(value).match(R._ISURL);
if (isURL) {
el = $("pattern");
var ig = $("image");
el.id = R.createUUID();
$(el, {x: 0, y: 0, patternUnits: "userSpaceOnUse", height: 1, width: 1});
$(ig, {x: 0, y: 0, "xlink:href": isURL[1]});
el.appendChild(ig);
(function (el) {
R._preload(isURL[1], function () {
var w = this.offsetWidth,
h = this.offsetHeight;
$(el, {width: w, height: h});
$(ig, {width: w, height: h});
o.paper.safari();
});
})(el);
o.paper.defs.appendChild(el);
$(node, {fill: "url(#" + el.id + ")"});
o.pattern = el;
o.pattern && updatePosition(o);
break;
}
var clr = R.getRGB(value);
if (!clr.error) {
delete params.gradient;
delete attrs.gradient;
!R.is(attrs.opacity, "undefined") &&
R.is(params.opacity, "undefined") &&
$(node, {opacity: attrs.opacity});
!R.is(attrs["fill-opacity"], "undefined") &&
R.is(params["fill-opacity"], "undefined") &&
$(node, {"fill-opacity": attrs["fill-opacity"]});
} else if ((o.type == "circle" || o.type == "ellipse" || Str(value).charAt() != "r") && addGradientFill(o, value)) {
if ("opacity" in attrs || "fill-opacity" in attrs) {
var gradient = R._g.doc.getElementById(node.getAttribute("fill").replace(/^url\(#|\)$/g, E));
if (gradient) {
var stops = gradient.getElementsByTagName("stop");
$(stops[stops.length - 1], {"stop-opacity": ("opacity" in attrs ? attrs.opacity : 1) * ("fill-opacity" in attrs ? attrs["fill-opacity"] : 1)});
}
}
attrs.gradient = value;
attrs.fill = "none";
break;
}
clr[has]("opacity") && $(node, {"fill-opacity": clr.opacity > 1 ? clr.opacity / 100 : clr.opacity});
case "stroke":
clr = R.getRGB(value);
node.setAttribute(att, clr.hex);
att == "stroke" && clr[has]("opacity") && $(node, {"stroke-opacity": clr.opacity > 1 ? clr.opacity / 100 : clr.opacity});
if (att == "stroke" && o._.arrows) {
"startString" in o._.arrows && addArrow(o, o._.arrows.startString);
"endString" in o._.arrows && addArrow(o, o._.arrows.endString, 1);
}
break;
case "gradient":
(o.type == "circle" || o.type == "ellipse" || Str(value).charAt() != "r") && addGradientFill(o, value);
break;
case "opacity":
if (attrs.gradient && !attrs[has]("stroke-opacity")) {
$(node, {"stroke-opacity": value > 1 ? value / 100 : value});
}
// fall
case "fill-opacity":
if (attrs.gradient) {
gradient = R._g.doc.getElementById(node.getAttribute("fill").replace(/^url\(#|\)$/g, E));
if (gradient) {
stops = gradient.getElementsByTagName("stop");
$(stops[stops.length - 1], {"stop-opacity": value});
}
break;
}
default:
att == "font-size" && (value = toInt(value, 10) + "px");
var cssrule = att.replace(/(\-.)/g, function (w) {
return w.substring(1).toUpperCase();
});
node.style[cssrule] = value;
o._.dirty = 1;
node.setAttribute(att, value);
break;
}
}
}
tuneText(o, params);
node.style.visibility = vis;
},
leading = 1.2,
tuneText = function (el, params) {
if (el.type != "text" || !(params[has]("text") || params[has]("font") || params[has]("font-size") || params[has]("x") || params[has]("y"))) {
return;
}
var a = el.attrs,
node = el.node,
fontSize = node.firstChild ? toInt(R._g.doc.defaultView.getComputedStyle(node.firstChild, E).getPropertyValue("font-size"), 10) : 10;
if (params[has]("text")) {
a.text = params.text;
while (node.firstChild) {
node.removeChild(node.firstChild);
}
var texts = Str(params.text).split("\n"),
tspans = [],
tspan;
for (var i = 0, ii = texts.length; i < ii; i++) {
tspan = $("tspan");
i && $(tspan, {dy: fontSize * leading, x: a.x});
tspan.appendChild(R._g.doc.createTextNode(texts[i]));
node.appendChild(tspan);
tspans[i] = tspan;
}
} else {
tspans = node.getElementsByTagName("tspan");
for (i = 0, ii = tspans.length; i < ii; i++) if (i) {
$(tspans[i], {dy: fontSize * leading, x: a.x});
} else {
$(tspans[0], {dy: 0});
}
}
$(node, {x: a.x, y: a.y});
el._.dirty = 1;
var bb = el._getBBox(),
dif = a.y - (bb.y + bb.height / 2);
dif && R.is(dif, "finite") && $(tspans[0], {dy: dif});
},
Element = function (node, svg) {
var X = 0,
Y = 0;
/*\
* Element.node
[ property (object) ]
**
* Gives you a reference to the DOM object, so you can assign event handlers or just mess around.
**
* Note: Don’t mess with it.
> Usage
| // draw a circle at coordinate 10,10 with radius of 10
| var c = paper.circle(10, 10, 10);
| c.node.onclick = function () {
| c.attr("fill", "red");
| };
\*/
this[0] = this.node = node;
/*\
* Element.raphael
[ property (object) ]
**
* Internal reference to @Raphael object. In case it is not available.
> Usage
| Raphael.el.red = function () {
| var hsb = this.paper.raphael.rgb2hsb(this.attr("fill"));
| hsb.h = 1;
| this.attr({fill: this.paper.raphael.hsb2rgb(hsb).hex});
| }
\*/
node.raphael = true;
/*\
* Element.id
[ property (number) ]
**
* Unique id of the element. Especially usesful when you want to listen to events of the element,
* because all events are fired in format `<module>.<action>.<id>`. Also useful for @Paper.getById method.
\*/
this.id = R._oid++;
node.raphaelid = this.id;
this.matrix = R.matrix();
this.realPath = null;
/*\
* Element.paper
[ property (object) ]
**
* Internal reference to “paper” where object drawn. Mainly for use in plugins and element extensions.
> Usage
| Raphael.el.cross = function () {
| this.attr({fill: "red"});
| this.paper.path("M10,10L50,50M50,10L10,50")
| .attr({stroke: "red"});
| }
\*/
this.paper = svg;
this.attrs = this.attrs || {};
this._ = {
transform: [],
sx: 1,
sy: 1,
deg: 0,
dx: 0,
dy: 0,
dirty: 1
};
!svg.bottom && (svg.bottom = this);
/*\
* Element.prev
[ property (object) ]
**
* Reference to the previous element in the hierarchy.
\*/
this.prev = svg.top;
svg.top && (svg.top.next = this);
svg.top = this;
/*\
* Element.next
[ property (object) ]
**
* Reference to the next element in the hierarchy.
\*/
this.next = null;
},
elproto = R.el;
Element.prototype = elproto;
elproto.constructor = Element;
R._engine.path = function (pathString, SVG) {
var el = $("path");
SVG.canvas && SVG.canvas.appendChild(el);
var p = new Element(el, SVG);
p.type = "path";
setFillAndStroke(p, {
fill: "none",
stroke: "#000",
path: pathString
});
return p;
};
/*\
* Element.rotate
[ method ]
**
* Deprecated! Use @Element.transform instead.
* Adds rotation by given angle around given point to the list of
* transformations of the element.
> Parameters
- deg (number) angle in degrees
- cx (number) #optional x coordinate of the centre of rotation
- cy (number) #optional y coordinate of the centre of rotation
* If cx & cy aren’t specified centre of the shape is used as a point of rotation.
= (object) @Element
\*/
elproto.rotate = function (deg, cx, cy) {
if (this.removed) {
return this;
}
deg = Str(deg).split(separator);
if (deg.length - 1) {
cx = toFloat(deg[1]);
cy = toFloat(deg[2]);
}
deg = toFloat(deg[0]);
(cy == null) && (cx = cy);
if (cx == null || cy == null) {
var bbox = this.getBBox(1);
cx = bbox.x + bbox.width / 2;
cy = bbox.y + bbox.height / 2;
}
this.transform(this._.transform.concat([["r", deg, cx, cy]]));
return this;
};
/*\
* Element.scale
[ method ]
**
* Deprecated! Use @Element.transform instead.
* Adds scale by given amount relative to given point to the list of
* transformations of the element.
> Parameters
- sx (number) horisontal scale amount
- sy (number) vertical scale amount
- cx (number) #optional x coordinate of the centre of scale
- cy (number) #optional y coordinate of the centre of scale
* If cx & cy aren’t specified centre of the shape is used instead.
= (object) @Element
\*/
elproto.scale = function (sx, sy, cx, cy) {
if (this.removed) {
return this;
}
sx = Str(sx).split(separator);
if (sx.length - 1) {
sy = toFloat(sx[1]);
cx = toFloat(sx[2]);
cy = toFloat(sx[3]);
}
sx = toFloat(sx[0]);
(sy == null) && (sy = sx);
(cy == null) && (cx = cy);
if (cx == null || cy == null) {
var bbox = this.getBBox(1);
}
cx = cx == null ? bbox.x + bbox.width / 2 : cx;
cy = cy == null ? bbox.y + bbox.height / 2 : cy;
this.transform(this._.transform.concat([["s", sx, sy, cx, cy]]));
return this;
};
/*\
* Element.translate
[ method ]
**
* Deprecated! Use @Element.transform instead.
* Adds translation by given amount to the list of transformations of the element.
> Parameters
- dx (number) horisontal shift
- dy (number) vertical shift
= (object) @Element
\*/
elproto.translate = function (dx, dy) {
if (this.removed) {
return this;
}
dx = Str(dx).split(separator);
if (dx.length - 1) {
dy = toFloat(dx[1]);
}
dx = toFloat(dx[0]) || 0;
dy = +dy || 0;
this.transform(this._.transform.concat([["t", dx, dy]]));
return this;
};
/*\
* Element.transform
[ method ]
**
* Adds transformation to the element which is separate to other attributes,
* i.e. translation doesn’t change `x` or `y` of the rectange. The format
* of transformation string is similar to the path string syntax:
| "t100,100r30,100,100s2,2,100,100r45s1.5"
* Each letter is a command. There are four commands: `t` is for translate, `r` is for rotate, `s` is for
* scale and `m` is for matrix.
*
* There are also alternative “absolute” translation, rotation and scale: `T`, `R` and `S`. They will not take previous transformation into account. For example, `...T100,0` will always move element 100 px horisontally, while `...t100,0` could move it vertically if there is `r90` before. Just compare results of `r90t100,0` and `r90T100,0`.
*
* So, the example line above could be read like “translate by 100, 100; rotate 30° around 100, 100; scale twice around 100, 100;
* rotate 45° around centre; scale 1.5 times relative to centre”. As you can see rotate and scale commands have origin
* coordinates as optional parameters, the default is the centre point of the element.
* Matrix accepts six parameters.
> Usage
| var el = paper.rect(10, 20, 300, 200);
| // translate 100, 100, rotate 45°, translate -100, 0
| el.transform("t100,100r45t-100,0");
| // if you want you can append or prepend transformations
| el.transform("...t50,50");
| el.transform("s2...");
| // or even wrap
| el.transform("t50,50...t-50-50");
| // to reset transformation call method with empty string
| el.transform("");
| // to get current value call it without parameters
| console.log(el.transform());
> Parameters
- tstr (string) #optional transformation string
* If tstr isn’t specified
= (string) current transformation string
* else
= (object) @Element
\*/
elproto.transform = function (tstr) {
var _ = this._;
if (tstr == null) {
return _.transform;
}
R._extractTransform(this, tstr);
this.clip && $(this.clip, {transform: this.matrix.invert()});
this.pattern && updatePosition(this);
this.node && $(this.node, {transform: this.matrix});
if (_.sx != 1 || _.sy != 1) {
var sw = this.attrs[has]("stroke-width") ? this.attrs["stroke-width"] : 1;
this.attr({"stroke-width": sw});
}
return this;
};
/*\
* Element.hide
[ method ]
**
* Makes element invisible. See @Element.show.
= (object) @Element
\*/
elproto.hide = function () {
!this.removed && this.paper.safari(this.node.style.display = "none");
return this;
};
/*\
* Element.show
[ method ]
**
* Makes element visible. See @Element.hide.
= (object) @Element
\*/
elproto.show = function () {
!this.removed && this.paper.safari(this.node.style.display = "");
return this;
};
/*\
* Element.remove
[ method ]
**
* Removes element from the paper.
\*/
elproto.remove = function () {
if (this.removed || !this.node.parentNode) {
return;
}
var paper = this.paper;
paper.__set__ && paper.__set__.exclude(this);
eve.unbind("raphael.*.*." + this.id);
if (this.gradient) {
paper.defs.removeChild(this.gradient);
}
R._tear(this, paper);
if (this.node.parentNode.tagName.toLowerCase() == "a") {
this.node.parentNode.parentNode.removeChild(this.node.parentNode);
} else {
this.node.parentNode.removeChild(this.node);
}
for (var i in this) {
this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null;
}
this.removed = true;
};
elproto._getBBox = function () {
if (this.node.style.display == "none") {
this.show();
var hide = true;
}
var bbox = {};
try {
bbox = this.node.getBBox();
} catch(e) {
// Firefox 3.0.x plays badly here
} finally {
bbox = bbox || {};
}
hide && this.hide();
return bbox;
};
/*\
* Element.attr
[ method ]
**
* Sets the attributes of the element.
> Parameters
- attrName (string) attribute’s name
- value (string) value
* or
- params (object) object of name/value pairs
* or
- attrName (string) attribute’s name
* or
- attrNames (array) in this case method returns array of current values for given attribute names
= (object) @Element if attrsName & value or params are passed in.
= (...) value of the attribute if only attrsName is passed in.
= (array) array of values of the attribute if attrsNames is passed in.
= (object) object of attributes if nothing is passed in.
> Possible parameters
# <p>Please refer to the <a href="http://www.w3.org/TR/SVG/" title="The W3C Recommendation for the SVG language describes these properties in detail.">SVG specification</a> for an explanation of these parameters.</p>
o arrow-end (string) arrowhead on the end of the path. The format for string is `<type>[-<width>[-<length>]]`. Possible types: `classic`, `block`, `open`, `oval`, `diamond`, `none`, width: `wide`, `narrow`, `medium`, length: `long`, `short`, `midium`.
o clip-rect (string) comma or space separated values: x, y, width and height
o cursor (string) CSS type of the cursor
o cx (number) the x-axis coordinate of the center of the circle, or ellipse
o cy (number) the y-axis coordinate of the center of the circle, or ellipse
o fill (string) colour, gradient or image
o fill-opacity (number)
o font (string)
o font-family (string)
o font-size (number) font size in pixels
o font-weight (string)
o height (number)
o href (string) URL, if specified element behaves as hyperlink
o opacity (number)
o path (string) SVG path string format
o r (number) radius of the circle, ellipse or rounded corner on the rect
o rx (number) horisontal radius of the ellipse
o ry (number) vertical radius of the ellipse
o src (string) image URL, only works for @Element.image element
o stroke (string) stroke colour
o stroke-dasharray (string) [“”, “`-`”, “`.`”, “`-.`”, “`-..`”, “`. `”, “`- `”, “`--`”, “`- .`”, “`--.`”, “`--..`”]
o stroke-linecap (string) [“`butt`”, “`square`”, “`round`”]
o stroke-linejoin (string) [“`bevel`”, “`round`”, “`miter`”]
o stroke-miterlimit (number)
o stroke-opacity (number)
o stroke-width (number) stroke width in pixels, default is '1'
o target (string) used with href
o text (string) contents of the text element. Use `\n` for multiline text
o text-anchor (string) [“`start`”, “`middle`”, “`end`”], default is “`middle`”
o title (string) will create tooltip with a given text
o transform (string) see @Element.transform
o width (number)
o x (number)
o y (number)
> Gradients
* Linear gradient format: “`‹angle›-‹colour›[-‹colour›[:‹offset›]]*-‹colour›`”, example: “`90-#fff-#000`” – 90°
* gradient from white to black or “`0-#fff-#f00:20-#000`” – 0° gradient from white via red (at 20%) to black.
*
* radial gradient: “`r[(‹fx›, ‹fy›)]‹colour›[-‹colour›[:‹offset›]]*-‹colour›`”, example: “`r#fff-#000`” –
* gradient from white to black or “`r(0.25, 0.75)#fff-#000`” – gradient from white to black with focus point
* at 0.25, 0.75. Focus point coordinates are in 0..1 range. Radial gradients can only be applied to circles and ellipses.
> Path String
# <p>Please refer to <a href="http://www.w3.org/TR/SVG/paths.html#PathData" title="Details of a path’s data attribute’s format are described in the SVG specification.">SVG documentation regarding path string</a>. Raphaël fully supports it.</p>
> Colour Parsing
# <ul>
# <li>Colour name (“<code>red</code>”, “<code>green</code>”, “<code>cornflowerblue</code>”, etc)</li>
# <li>#••• — shortened HTML colour: (“<code>#000</code>”, “<code>#fc0</code>”, etc)</li>
# <li>#•••••• — full length HTML colour: (“<code>#000000</code>”, “<code>#bd2300</code>”)</li>
# <li>rgb(•••, •••, •••) — red, green and blue channels’ values: (“<code>rgb(200, 100, 0)</code>”)</li>
# <li>rgb(•••%, •••%, •••%) — same as above, but in %: (“<code>rgb(100%, 175%, 0%)</code>”)</li>
# <li>rgba(•••, •••, •••, •••) — red, green and blue channels’ values: (“<code>rgba(200, 100, 0, .5)</code>”)</li>
# <li>rgba(•••%, •••%, •••%, •••%) — same as above, but in %: (“<code>rgba(100%, 175%, 0%, 50%)</code>”)</li>
# <li>hsb(•••, •••, •••) — hue, saturation and brightness values: (“<code>hsb(0.5, 0.25, 1)</code>”)</li>
# <li>hsb(•••%, •••%, •••%) — same as above, but in %</li>
# <li>hsba(•••, •••, •••, •••) — same as above, but with opacity</li>
# <li>hsl(•••, •••, •••) — almost the same as hsb, see <a href="http://en.wikipedia.org/wiki/HSL_and_HSV" title="HSL and HSV - Wikipedia, the free encyclopedia">Wikipedia page</a></li>
# <li>hsl(•••%, •••%, •••%) — same as above, but in %</li>
# <li>hsla(•••, •••, •••, •••) — same as above, but with opacity</li>
# <li>Optionally for hsb and hsl you could specify hue as a degree: “<code>hsl(240deg, 1, .5)</code>” or, if you want to go fancy, “<code>hsl(240°, 1, .5)</code>”</li>
# </ul>
\*/
elproto.attr = function (name, value) {
if (this.removed) {
return this;
}
if (name == null) {
var res = {};
for (var a in this.attrs) if (this.attrs[has](a)) {
res[a] = this.attrs[a];
}
res.gradient && res.fill == "none" && (res.fill = res.gradient) && delete res.gradient;
res.transform = this._.transform;
return res;
}
if (value == null && R.is(name, "string")) {
if (name == "fill" && this.attrs.fill == "none" && this.attrs.gradient) {
return this.attrs.gradient;
}
if (name == "transform") {
return this._.transform;
}
var names = name.split(separator),
out = {};
for (var i = 0, ii = names.length; i < ii; i++) {
name = names[i];
if (name in this.attrs) {
out[name] = this.attrs[name];
} else if (R.is(this.paper.customAttributes[name], "function")) {
out[name] = this.paper.customAttributes[name].def;
} else {
out[name] = R._availableAttrs[name];
}
}
return ii - 1 ? out : out[names[0]];
}
if (value == null && R.is(name, "array")) {
out = {};
for (i = 0, ii = name.length; i < ii; i++) {
out[name[i]] = this.attr(name[i]);
}
return out;
}
if (value != null) {
var params = {};
params[name] = value;
} else if (name != null && R.is(name, "object")) {
params = name;
}
for (var key in params) {
eve("raphael.attr." + key + "." + this.id, this, params[key]);
}
for (key in this.paper.customAttributes) if (this.paper.customAttributes[has](key) && params[has](key) && R.is(this.paper.customAttributes[key], "function")) {
var par = this.paper.customAttributes[key].apply(this, [].concat(params[key]));
this.attrs[key] = params[key];
for (var subkey in par) if (par[has](subkey)) {
params[subkey] = par[subkey];
}
}
setFillAndStroke(this, params);
return this;
};
/*\
* Element.toFront
[ method ]
**
* Moves the element so it is the closest to the viewer’s eyes, on top of other elements.
= (object) @Element
\*/
elproto.toFront = function () {
if (this.removed) {
return this;
}
if (this.node.parentNode.tagName.toLowerCase() == "a") {
this.node.parentNode.parentNode.appendChild(this.node.parentNode);
} else {
this.node.parentNode.appendChild(this.node);
}
var svg = this.paper;
svg.top != this && R._tofront(this, svg);
return this;
};
/*\
* Element.toBack
[ method ]
**
* Moves the element so it is the furthest from the viewer’s eyes, behind other elements.
= (object) @Element
\*/
elproto.toBack = function () {
if (this.removed) {
return this;
}
var parent = this.node.parentNode;
if (parent.tagName.toLowerCase() == "a") {
parent.parentNode.insertBefore(this.node.parentNode, this.node.parentNode.parentNode.firstChild);
} else if (parent.firstChild != this.node) {
parent.insertBefore(this.node, this.node.parentNode.firstChild);
}
R._toback(this, this.paper);
var svg = this.paper;
return this;
};
/*\
* Element.insertAfter
[ method ]
**
* Inserts current object after the given one.
= (object) @Element
\*/
elproto.insertAfter = function (element) {
if (this.removed) {
return this;
}
var node = element.node || element[element.length - 1].node;
if (node.nextSibling) {
node.parentNode.insertBefore(this.node, node.nextSibling);
} else {
node.parentNode.appendChild(this.node);
}
R._insertafter(this, element, this.paper);
return this;
};
/*\
* Element.insertBefore
[ method ]
**
* Inserts current object before the given one.
= (object) @Element
\*/
elproto.insertBefore = function (element) {
if (this.removed) {
return this;
}
var node = element.node || element[0].node;
node.parentNode.insertBefore(this.node, node);
R._insertbefore(this, element, this.paper);
return this;
};
elproto.blur = function (size) {
// Experimental. No Safari support. Use it on your own risk.
var t = this;
if (+size !== 0) {
var fltr = $("filter"),
blur = $("feGaussianBlur");
t.attrs.blur = size;
fltr.id = R.createUUID();
$(blur, {stdDeviation: +size || 1.5});
fltr.appendChild(blur);
t.paper.defs.appendChild(fltr);
t._blur = fltr;
$(t.node, {filter: "url(#" + fltr.id + ")"});
} else {
if (t._blur) {
t._blur.parentNode.removeChild(t._blur);
delete t._blur;
delete t.attrs.blur;
}
t.node.removeAttribute("filter");
}
return t;
};
R._engine.circle = function (svg, x, y, r) {
var el = $("circle");
svg.canvas && svg.canvas.appendChild(el);
var res = new Element(el, svg);
res.attrs = {cx: x, cy: y, r: r, fill: "none", stroke: "#000"};
res.type = "circle";
$(el, res.attrs);
return res;
};
R._engine.rect = function (svg, x, y, w, h, r) {
var el = $("rect");
svg.canvas && svg.canvas.appendChild(el);
var res = new Element(el, svg);
res.attrs = {x: x, y: y, width: w, height: h, r: r || 0, rx: r || 0, ry: r || 0, fill: "none", stroke: "#000"};
res.type = "rect";
$(el, res.attrs);
return res;
};
R._engine.ellipse = function (svg, x, y, rx, ry) {
var el = $("ellipse");
svg.canvas && svg.canvas.appendChild(el);
var res = new Element(el, svg);
res.attrs = {cx: x, cy: y, rx: rx, ry: ry, fill: "none", stroke: "#000"};
res.type = "ellipse";
$(el, res.attrs);
return res;
};
R._engine.image = function (svg, src, x, y, w, h) {
var el = $("image");
$(el, {x: x, y: y, width: w, height: h, preserveAspectRatio: "xMinYMin"});
el.setAttributeNS(xlink, "href", src);
svg.canvas && svg.canvas.appendChild(el);
var res = new Element(el, svg);
res.attrs = {x: x, y: y, width: w, height: h, src: src};
res.type = "image";
return res;
};
R._engine.text = function (svg, x, y, text) {
var el = $("text");
svg.canvas && svg.canvas.appendChild(el);
var res = new Element(el, svg);
res.attrs = {
x: x,
y: y,
"text-anchor": "middle",
text: text,
font: R._availableAttrs.font,
stroke: "none",
fill: "#000"
};
res.type = "text";
setFillAndStroke(res, res.attrs);
return res;
};
R._engine.setSize = function (width, height) {
this.width = width || this.width;
this.height = height || this.height;
this.canvas.setAttribute("width", this.width);
this.canvas.setAttribute("height", this.height);
if (this._viewBox) {
this.setViewBox.apply(this, this._viewBox);
}
return this;
};
R._engine.create = function () {
var con = R._getContainer.apply(0, arguments),
container = con && con.container,
x = con.x,
y = con.y,
width = con.width,
height = con.height;
if (!container) {
throw new Error("SVG container not found.");
}
var cnvs = $("svg"),
css = "overflow:hidden;",
isFloating;
x = x || 0;
y = y || 0;
width = width || 512;
height = height || 342;
$(cnvs, {
height: height,
version: 1.1,
width: width,
xmlns: "http://www.w3.org/2000/svg"
});
if (container == 1) {
cnvs.style.cssText = css + "position:absolute;left:" + x + "px;top:" + y + "px";
R._g.doc.body.appendChild(cnvs);
isFloating = 1;
} else {
cnvs.style.cssText = css + "position:relative";
if (container.firstChild) {
container.insertBefore(cnvs, container.firstChild);
} else {
container.appendChild(cnvs);
}
}
container = new R._Paper;
container.width = width;
container.height = height;
container.canvas = cnvs;
container.clear();
container._left = container._top = 0;
isFloating && (container.renderfix = function () {});
container.renderfix();
return container;
};
R._engine.setViewBox = function (x, y, w, h, fit) {
eve("raphael.setViewBox", this, this._viewBox, [x, y, w, h, fit]);
var size = mmax(w / this.width, h / this.height),
top = this.top,
aspectRatio = fit ? "meet" : "xMinYMin",
vb,
sw;
if (x == null) {
if (this._vbSize) {
size = 1;
}
delete this._vbSize;
vb = "0 0 " + this.width + S + this.height;
} else {
this._vbSize = size;
vb = x + S + y + S + w + S + h;
}
$(this.canvas, {
viewBox: vb,
preserveAspectRatio: aspectRatio
});
while (size && top) {
sw = "stroke-width" in top.attrs ? top.attrs["stroke-width"] : 1;
top.attr({"stroke-width": sw});
top._.dirty = 1;
top._.dirtyT = 1;
top = top.prev;
}
this._viewBox = [x, y, w, h, !!fit];
return this;
};
/*\
* Paper.renderfix
[ method ]
**
* Fixes the issue of Firefox and IE9 regarding subpixel rendering. If paper is dependant
* on other elements after reflow it could shift half pixel which cause for lines to lost their crispness.
* This method fixes the issue.
**
Special thanks to Mariusz Nowak (http://www.medikoo.com/) for this method.
\*/
R.prototype.renderfix = function () {
var cnvs = this.canvas,
s = cnvs.style,
pos;
try {
pos = cnvs.getScreenCTM() || cnvs.createSVGMatrix();
} catch (e) {
pos = cnvs.createSVGMatrix();
}
var left = -pos.e % 1,
top = -pos.f % 1;
if (left || top) {
if (left) {
this._left = (this._left + left) % 1;
s.left = this._left + "px";
}
if (top) {
this._top = (this._top + top) % 1;
s.top = this._top + "px";
}
}
};
/*\
* Paper.clear
[ method ]
**
* Clears the paper, i.e. removes all the elements.
\*/
R.prototype.clear = function () {
R.eve("raphael.clear", this);
var c = this.canvas;
while (c.firstChild) {
c.removeChild(c.firstChild);
}
this.bottom = this.top = null;
(this.desc = $("desc")).appendChild(R._g.doc.createTextNode("Created with Rapha\xebl " + R.version));
c.appendChild(this.desc);
c.appendChild(this.defs = $("defs"));
};
/*\
* Paper.remove
[ method ]
**
* Removes the paper from the DOM.
\*/
R.prototype.remove = function () {
eve("raphael.remove", this);
this.canvas.parentNode && this.canvas.parentNode.removeChild(this.canvas);
for (var i in this) {
this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null;
}
};
var setproto = R.st;
for (var method in elproto) if (elproto[has](method) && !setproto[has](method)) {
setproto[method] = (function (methodname) {
return function () {
var arg = arguments;
return this.forEach(function (el) {
el[methodname].apply(el, arg);
});
};
})(method);
}
})();
// ┌─────────────────────────────────────────────────────────────────────┐ \\
// │ Raphaël - JavaScript Vector Library │ \\
// ├─────────────────────────────────────────────────────────────────────┤ \\
// │ VML Module │ \\
// ├─────────────────────────────────────────────────────────────────────┤ \\
// │ Copyright (c) 2008-2011 Dmitry Baranovskiy (http://raphaeljs.com) │ \\
// │ Copyright (c) 2008-2011 Sencha Labs (http://sencha.com) │ \\
// │ Licensed under the MIT (http://raphaeljs.com/license.html) license. │ \\
// └─────────────────────────────────────────────────────────────────────┘ \\
(function(){
if (!R.vml) {
return;
}
var has = "hasOwnProperty",
Str = String,
toFloat = parseFloat,
math = Math,
round = math.round,
mmax = math.max,
mmin = math.min,
abs = math.abs,
fillString = "fill",
separator = /[, ]+/,
eve = R.eve,
ms = " progid:DXImageTransform.Microsoft",
S = " ",
E = "",
map = {M: "m", L: "l", C: "c", Z: "x", m: "t", l: "r", c: "v", z: "x"},
bites = /([clmz]),?([^clmz]*)/gi,
blurregexp = / progid:\S+Blur\([^\)]+\)/g,
val = /-?[^,\s-]+/g,
cssDot = "position:absolute;left:0;top:0;width:1px;height:1px",
zoom = 21600,
pathTypes = {path: 1, rect: 1, image: 1},
ovalTypes = {circle: 1, ellipse: 1},
path2vml = function (path) {
var total = /[ahqstv]/ig,
command = R._pathToAbsolute;
Str(path).match(total) && (command = R._path2curve);
total = /[clmz]/g;
if (command == R._pathToAbsolute && !Str(path).match(total)) {
var res = Str(path).replace(bites, function (all, command, args) {
var vals = [],
isMove = command.toLowerCase() == "m",
res = map[command];
args.replace(val, function (value) {
if (isMove && vals.length == 2) {
res += vals + map[command == "m" ? "l" : "L"];
vals = [];
}
vals.push(round(value * zoom));
});
return res + vals;
});
return res;
}
var pa = command(path), p, r;
res = [];
for (var i = 0, ii = pa.length; i < ii; i++) {
p = pa[i];
r = pa[i][0].toLowerCase();
r == "z" && (r = "x");
for (var j = 1, jj = p.length; j < jj; j++) {
r += round(p[j] * zoom) + (j != jj - 1 ? "," : E);
}
res.push(r);
}
return res.join(S);
},
compensation = function (deg, dx, dy) {
var m = R.matrix();
m.rotate(-deg, .5, .5);
return {
dx: m.x(dx, dy),
dy: m.y(dx, dy)
};
},
setCoords = function (p, sx, sy, dx, dy, deg) {
var _ = p._,
m = p.matrix,
fillpos = _.fillpos,
o = p.node,
s = o.style,
y = 1,
flip = "",
dxdy,
kx = zoom / sx,
ky = zoom / sy;
s.visibility = "hidden";
if (!sx || !sy) {
return;
}
o.coordsize = abs(kx) + S + abs(ky);
s.rotation = deg * (sx * sy < 0 ? -1 : 1);
if (deg) {
var c = compensation(deg, dx, dy);
dx = c.dx;
dy = c.dy;
}
sx < 0 && (flip += "x");
sy < 0 && (flip += " y") && (y = -1);
s.flip = flip;
o.coordorigin = (dx * -kx) + S + (dy * -ky);
if (fillpos || _.fillsize) {
var fill = o.getElementsByTagName(fillString);
fill = fill && fill[0];
o.removeChild(fill);
if (fillpos) {
c = compensation(deg, m.x(fillpos[0], fillpos[1]), m.y(fillpos[0], fillpos[1]));
fill.position = c.dx * y + S + c.dy * y;
}
if (_.fillsize) {
fill.size = _.fillsize[0] * abs(sx) + S + _.fillsize[1] * abs(sy);
}
o.appendChild(fill);
}
s.visibility = "visible";
};
R.toString = function () {
return "Your browser doesn\u2019t support SVG. Falling down to VML.\nYou are running Rapha\xebl " + this.version;
};
var addArrow = function (o, value, isEnd) {
var values = Str(value).toLowerCase().split("-"),
se = isEnd ? "end" : "start",
i = values.length,
type = "classic",
w = "medium",
h = "medium";
while (i--) {
switch (values[i]) {
case "block":
case "classic":
case "oval":
case "diamond":
case "open":
case "none":
type = values[i];
break;
case "wide":
case "narrow": h = values[i]; break;
case "long":
case "short": w = values[i]; break;
}
}
var stroke = o.node.getElementsByTagName("stroke")[0];
stroke[se + "arrow"] = type;
stroke[se + "arrowlength"] = w;
stroke[se + "arrowwidth"] = h;
},
setFillAndStroke = function (o, params) {
// o.paper.canvas.style.display = "none";
o.attrs = o.attrs || {};
var node = o.node,
a = o.attrs,
s = node.style,
xy,
newpath = pathTypes[o.type] && (params.x != a.x || params.y != a.y || params.width != a.width || params.height != a.height || params.cx != a.cx || params.cy != a.cy || params.rx != a.rx || params.ry != a.ry || params.r != a.r),
isOval = ovalTypes[o.type] && (a.cx != params.cx || a.cy != params.cy || a.r != params.r || a.rx != params.rx || a.ry != params.ry),
res = o;
for (var par in params) if (params[has](par)) {
a[par] = params[par];
}
if (newpath) {
a.path = R._getPath[o.type](o);
o._.dirty = 1;
}
params.href && (node.href = params.href);
params.title && (node.title = params.title);
params.target && (node.target = params.target);
params.cursor && (s.cursor = params.cursor);
"blur" in params && o.blur(params.blur);
if (params.path && o.type == "path" || newpath) {
node.path = path2vml(~Str(a.path).toLowerCase().indexOf("r") ? R._pathToAbsolute(a.path) : a.path);
if (o.type == "image") {
o._.fillpos = [a.x, a.y];
o._.fillsize = [a.width, a.height];
setCoords(o, 1, 1, 0, 0, 0);
}
}
"transform" in params && o.transform(params.transform);
if (isOval) {
var cx = +a.cx,
cy = +a.cy,
rx = +a.rx || +a.r || 0,
ry = +a.ry || +a.r || 0;
node.path = R.format("ar{0},{1},{2},{3},{4},{1},{4},{1}x", round((cx - rx) * zoom), round((cy - ry) * zoom), round((cx + rx) * zoom), round((cy + ry) * zoom), round(cx * zoom));
o._.dirty = 1;
}
if ("clip-rect" in params) {
var rect = Str(params["clip-rect"]).split(separator);
if (rect.length == 4) {
rect[2] = +rect[2] + (+rect[0]);
rect[3] = +rect[3] + (+rect[1]);
var div = node.clipRect || R._g.doc.createElement("div"),
dstyle = div.style;
dstyle.clip = R.format("rect({1}px {2}px {3}px {0}px)", rect);
if (!node.clipRect) {
dstyle.position = "absolute";
dstyle.top = 0;
dstyle.left = 0;
dstyle.width = o.paper.width + "px";
dstyle.height = o.paper.height + "px";
node.parentNode.insertBefore(div, node);
div.appendChild(node);
node.clipRect = div;
}
}
if (!params["clip-rect"]) {
node.clipRect && (node.clipRect.style.clip = "auto");
}
}
if (o.textpath) {
var textpathStyle = o.textpath.style;
params.font && (textpathStyle.font = params.font);
params["font-family"] && (textpathStyle.fontFamily = '"' + params["font-family"].split(",")[0].replace(/^['"]+|['"]+$/g, E) + '"');
params["font-size"] && (textpathStyle.fontSize = params["font-size"]);
params["font-weight"] && (textpathStyle.fontWeight = params["font-weight"]);
params["font-style"] && (textpathStyle.fontStyle = params["font-style"]);
}
if ("arrow-start" in params) {
addArrow(res, params["arrow-start"]);
}
if ("arrow-end" in params) {
addArrow(res, params["arrow-end"], 1);
}
if (params.opacity != null ||
params["stroke-width"] != null ||
params.fill != null ||
params.src != null ||
params.stroke != null ||
params["stroke-width"] != null ||
params["stroke-opacity"] != null ||
params["fill-opacity"] != null ||
params["stroke-dasharray"] != null ||
params["stroke-miterlimit"] != null ||
params["stroke-linejoin"] != null ||
params["stroke-linecap"] != null) {
var fill = node.getElementsByTagName(fillString),
newfill = false;
fill = fill && fill[0];
!fill && (newfill = fill = createNode(fillString));
if (o.type == "image" && params.src) {
fill.src = params.src;
}
params.fill && (fill.on = true);
if (fill.on == null || params.fill == "none" || params.fill === null) {
fill.on = false;
}
if (fill.on && params.fill) {
var isURL = Str(params.fill).match(R._ISURL);
if (isURL) {
fill.parentNode == node && node.removeChild(fill);
fill.rotate = true;
fill.src = isURL[1];
fill.type = "tile";
var bbox = o.getBBox(1);
fill.position = bbox.x + S + bbox.y;
o._.fillpos = [bbox.x, bbox.y];
R._preload(isURL[1], function () {
o._.fillsize = [this.offsetWidth, this.offsetHeight];
});
} else {
fill.color = R.getRGB(params.fill).hex;
fill.src = E;
fill.type = "solid";
if (R.getRGB(params.fill).error && (res.type in {circle: 1, ellipse: 1} || Str(params.fill).charAt() != "r") && addGradientFill(res, params.fill, fill)) {
a.fill = "none";
a.gradient = params.fill;
fill.rotate = false;
}
}
}
if ("fill-opacity" in params || "opacity" in params) {
var opacity = ((+a["fill-opacity"] + 1 || 2) - 1) * ((+a.opacity + 1 || 2) - 1) * ((+R.getRGB(params.fill).o + 1 || 2) - 1);
opacity = mmin(mmax(opacity, 0), 1);
fill.opacity = opacity;
if (fill.src) {
fill.color = "none";
}
}
node.appendChild(fill);
var stroke = (node.getElementsByTagName("stroke") && node.getElementsByTagName("stroke")[0]),
newstroke = false;
!stroke && (newstroke = stroke = createNode("stroke"));
if ((params.stroke && params.stroke != "none") ||
params["stroke-width"] ||
params["stroke-opacity"] != null ||
params["stroke-dasharray"] ||
params["stroke-miterlimit"] ||
params["stroke-linejoin"] ||
params["stroke-linecap"]) {
stroke.on = true;
}
(params.stroke == "none" || params.stroke === null || stroke.on == null || params.stroke == 0 || params["stroke-width"] == 0) && (stroke.on = false);
var strokeColor = R.getRGB(params.stroke);
stroke.on && params.stroke && (stroke.color = strokeColor.hex);
opacity = ((+a["stroke-opacity"] + 1 || 2) - 1) * ((+a.opacity + 1 || 2) - 1) * ((+strokeColor.o + 1 || 2) - 1);
var width = (toFloat(params["stroke-width"]) || 1) * .75;
opacity = mmin(mmax(opacity, 0), 1);
params["stroke-width"] == null && (width = a["stroke-width"]);
params["stroke-width"] && (stroke.weight = width);
width && width < 1 && (opacity *= width) && (stroke.weight = 1);
stroke.opacity = opacity;
params["stroke-linejoin"] && (stroke.joinstyle = params["stroke-linejoin"] || "miter");
stroke.miterlimit = params["stroke-miterlimit"] || 8;
params["stroke-linecap"] && (stroke.endcap = params["stroke-linecap"] == "butt" ? "flat" : params["stroke-linecap"] == "square" ? "square" : "round");
if ("stroke-dasharray" in params) {
var dasharray = {
"-": "shortdash",
".": "shortdot",
"-.": "shortdashdot",
"-..": "shortdashdotdot",
". ": "dot",
"- ": "dash",
"--": "longdash",
"- .": "dashdot",
"--.": "longdashdot",
"--..": "longdashdotdot"
};
stroke.dashstyle = dasharray[has](params["stroke-dasharray"]) ? dasharray[params["stroke-dasharray"]] : E;
}
newstroke && node.appendChild(stroke);
}
if (res.type == "text") {
res.paper.canvas.style.display = E;
var span = res.paper.span,
m = 100,
fontSize = a.font && a.font.match(/\d+(?:\.\d*)?(?=px)/);
s = span.style;
a.font && (s.font = a.font);
a["font-family"] && (s.fontFamily = a["font-family"]);
a["font-weight"] && (s.fontWeight = a["font-weight"]);
a["font-style"] && (s.fontStyle = a["font-style"]);
fontSize = toFloat(a["font-size"] || fontSize && fontSize[0]) || 10;
s.fontSize = fontSize * m + "px";
res.textpath.string && (span.innerHTML = Str(res.textpath.string).replace(/</g, "<").replace(/&/g, "&").replace(/\n/g, "<br>"));
var brect = span.getBoundingClientRect();
res.W = a.w = (brect.right - brect.left) / m;
res.H = a.h = (brect.bottom - brect.top) / m;
// res.paper.canvas.style.display = "none";
res.X = a.x;
res.Y = a.y + res.H / 2;
("x" in params || "y" in params) && (res.path.v = R.format("m{0},{1}l{2},{1}", round(a.x * zoom), round(a.y * zoom), round(a.x * zoom) + 1));
var dirtyattrs = ["x", "y", "text", "font", "font-family", "font-weight", "font-style", "font-size"];
for (var d = 0, dd = dirtyattrs.length; d < dd; d++) if (dirtyattrs[d] in params) {
res._.dirty = 1;
break;
}
// text-anchor emulation
switch (a["text-anchor"]) {
case "start":
res.textpath.style["v-text-align"] = "left";
res.bbx = res.W / 2;
break;
case "end":
res.textpath.style["v-text-align"] = "right";
res.bbx = -res.W / 2;
break;
default:
res.textpath.style["v-text-align"] = "center";
res.bbx = 0;
break;
}
res.textpath.style["v-text-kern"] = true;
}
// res.paper.canvas.style.display = E;
},
addGradientFill = function (o, gradient, fill) {
o.attrs = o.attrs || {};
var attrs = o.attrs,
pow = Math.pow,
opacity,
oindex,
type = "linear",
fxfy = ".5 .5";
o.attrs.gradient = gradient;
gradient = Str(gradient).replace(R._radial_gradient, function (all, fx, fy) {
type = "radial";
if (fx && fy) {
fx = toFloat(fx);
fy = toFloat(fy);
pow(fx - .5, 2) + pow(fy - .5, 2) > .25 && (fy = math.sqrt(.25 - pow(fx - .5, 2)) * ((fy > .5) * 2 - 1) + .5);
fxfy = fx + S + fy;
}
return E;
});
gradient = gradient.split(/\s*\-\s*/);
if (type == "linear") {
var angle = gradient.shift();
angle = -toFloat(angle);
if (isNaN(angle)) {
return null;
}
}
var dots = R._parseDots(gradient);
if (!dots) {
return null;
}
o = o.shape || o.node;
if (dots.length) {
o.removeChild(fill);
fill.on = true;
fill.method = "none";
fill.color = dots[0].color;
fill.color2 = dots[dots.length - 1].color;
var clrs = [];
for (var i = 0, ii = dots.length; i < ii; i++) {
dots[i].offset && clrs.push(dots[i].offset + S + dots[i].color);
}
fill.colors = clrs.length ? clrs.join() : "0% " + fill.color;
if (type == "radial") {
fill.type = "gradientTitle";
fill.focus = "100%";
fill.focussize = "0 0";
fill.focusposition = fxfy;
fill.angle = 0;
} else {
// fill.rotate= true;
fill.type = "gradient";
fill.angle = (270 - angle) % 360;
}
o.appendChild(fill);
}
return 1;
},
Element = function (node, vml) {
this[0] = this.node = node;
node.raphael = true;
this.id = R._oid++;
node.raphaelid = this.id;
this.X = 0;
this.Y = 0;
this.attrs = {};
this.paper = vml;
this.matrix = R.matrix();
this._ = {
transform: [],
sx: 1,
sy: 1,
dx: 0,
dy: 0,
deg: 0,
dirty: 1,
dirtyT: 1
};
!vml.bottom && (vml.bottom = this);
this.prev = vml.top;
vml.top && (vml.top.next = this);
vml.top = this;
this.next = null;
};
var elproto = R.el;
Element.prototype = elproto;
elproto.constructor = Element;
elproto.transform = function (tstr) {
if (tstr == null) {
return this._.transform;
}
var vbs = this.paper._viewBoxShift,
vbt = vbs ? "s" + [vbs.scale, vbs.scale] + "-1-1t" + [vbs.dx, vbs.dy] : E,
oldt;
if (vbs) {
oldt = tstr = Str(tstr).replace(/\.{3}|\u2026/g, this._.transform || E);
}
R._extractTransform(this, vbt + tstr);
var matrix = this.matrix.clone(),
skew = this.skew,
o = this.node,
split,
isGrad = ~Str(this.attrs.fill).indexOf("-"),
isPatt = !Str(this.attrs.fill).indexOf("url(");
matrix.translate(1, 1);
if (isPatt || isGrad || this.type == "image") {
skew.matrix = "1 0 0 1";
skew.offset = "0 0";
split = matrix.split();
if ((isGrad && split.noRotation) || !split.isSimple) {
o.style.filter = matrix.toFilter();
var bb = this.getBBox(),
bbt = this.getBBox(1),
dx = bb.x - bbt.x,
dy = bb.y - bbt.y;
o.coordorigin = (dx * -zoom) + S + (dy * -zoom);
setCoords(this, 1, 1, dx, dy, 0);
} else {
o.style.filter = E;
setCoords(this, split.scalex, split.scaley, split.dx, split.dy, split.rotate);
}
} else {
o.style.filter = E;
skew.matrix = Str(matrix);
skew.offset = matrix.offset();
}
oldt && (this._.transform = oldt);
return this;
};
elproto.rotate = function (deg, cx, cy) {
if (this.removed) {
return this;
}
if (deg == null) {
return;
}
deg = Str(deg).split(separator);
if (deg.length - 1) {
cx = toFloat(deg[1]);
cy = toFloat(deg[2]);
}
deg = toFloat(deg[0]);
(cy == null) && (cx = cy);
if (cx == null || cy == null) {
var bbox = this.getBBox(1);
cx = bbox.x + bbox.width / 2;
cy = bbox.y + bbox.height / 2;
}
this._.dirtyT = 1;
this.transform(this._.transform.concat([["r", deg, cx, cy]]));
return this;
};
elproto.translate = function (dx, dy) {
if (this.removed) {
return this;
}
dx = Str(dx).split(separator);
if (dx.length - 1) {
dy = toFloat(dx[1]);
}
dx = toFloat(dx[0]) || 0;
dy = +dy || 0;
if (this._.bbox) {
this._.bbox.x += dx;
this._.bbox.y += dy;
}
this.transform(this._.transform.concat([["t", dx, dy]]));
return this;
};
elproto.scale = function (sx, sy, cx, cy) {
if (this.removed) {
return this;
}
sx = Str(sx).split(separator);
if (sx.length - 1) {
sy = toFloat(sx[1]);
cx = toFloat(sx[2]);
cy = toFloat(sx[3]);
isNaN(cx) && (cx = null);
isNaN(cy) && (cy = null);
}
sx = toFloat(sx[0]);
(sy == null) && (sy = sx);
(cy == null) && (cx = cy);
if (cx == null || cy == null) {
var bbox = this.getBBox(1);
}
cx = cx == null ? bbox.x + bbox.width / 2 : cx;
cy = cy == null ? bbox.y + bbox.height / 2 : cy;
this.transform(this._.transform.concat([["s", sx, sy, cx, cy]]));
this._.dirtyT = 1;
return this;
};
elproto.hide = function () {
!this.removed && (this.node.style.display = "none");
return this;
};
elproto.show = function () {
!this.removed && (this.node.style.display = E);
return this;
};
elproto._getBBox = function () {
if (this.removed) {
return {};
}
return {
x: this.X + (this.bbx || 0) - this.W / 2,
y: this.Y - this.H,
width: this.W,
height: this.H
};
};
elproto.remove = function () {
if (this.removed || !this.node.parentNode) {
return;
}
this.paper.__set__ && this.paper.__set__.exclude(this);
R.eve.unbind("raphael.*.*." + this.id);
R._tear(this, this.paper);
this.node.parentNode.removeChild(this.node);
this.shape && this.shape.parentNode.removeChild(this.shape);
for (var i in this) {
this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null;
}
this.removed = true;
};
elproto.attr = function (name, value) {
if (this.removed) {
return this;
}
if (name == null) {
var res = {};
for (var a in this.attrs) if (this.attrs[has](a)) {
res[a] = this.attrs[a];
}
res.gradient && res.fill == "none" && (res.fill = res.gradient) && delete res.gradient;
res.transform = this._.transform;
return res;
}
if (value == null && R.is(name, "string")) {
if (name == fillString && this.attrs.fill == "none" && this.attrs.gradient) {
return this.attrs.gradient;
}
var names = name.split(separator),
out = {};
for (var i = 0, ii = names.length; i < ii; i++) {
name = names[i];
if (name in this.attrs) {
out[name] = this.attrs[name];
} else if (R.is(this.paper.customAttributes[name], "function")) {
out[name] = this.paper.customAttributes[name].def;
} else {
out[name] = R._availableAttrs[name];
}
}
return ii - 1 ? out : out[names[0]];
}
if (this.attrs && value == null && R.is(name, "array")) {
out = {};
for (i = 0, ii = name.length; i < ii; i++) {
out[name[i]] = this.attr(name[i]);
}
return out;
}
var params;
if (value != null) {
params = {};
params[name] = value;
}
value == null && R.is(name, "object") && (params = name);
for (var key in params) {
eve("raphael.attr." + key + "." + this.id, this, params[key]);
}
if (params) {
for (key in this.paper.customAttributes) if (this.paper.customAttributes[has](key) && params[has](key) && R.is(this.paper.customAttributes[key], "function")) {
var par = this.paper.customAttributes[key].apply(this, [].concat(params[key]));
this.attrs[key] = params[key];
for (var subkey in par) if (par[has](subkey)) {
params[subkey] = par[subkey];
}
}
// this.paper.canvas.style.display = "none";
if (params.text && this.type == "text") {
this.textpath.string = params.text;
}
setFillAndStroke(this, params);
// this.paper.canvas.style.display = E;
}
return this;
};
elproto.toFront = function () {
!this.removed && this.node.parentNode.appendChild(this.node);
this.paper && this.paper.top != this && R._tofront(this, this.paper);
return this;
};
elproto.toBack = function () {
if (this.removed) {
return this;
}
if (this.node.parentNode.firstChild != this.node) {
this.node.parentNode.insertBefore(this.node, this.node.parentNode.firstChild);
R._toback(this, this.paper);
}
return this;
};
elproto.insertAfter = function (element) {
if (this.removed) {
return this;
}
if (element.constructor == R.st.constructor) {
element = element[element.length - 1];
}
if (element.node.nextSibling) {
element.node.parentNode.insertBefore(this.node, element.node.nextSibling);
} else {
element.node.parentNode.appendChild(this.node);
}
R._insertafter(this, element, this.paper);
return this;
};
elproto.insertBefore = function (element) {
if (this.removed) {
return this;
}
if (element.constructor == R.st.constructor) {
element = element[0];
}
element.node.parentNode.insertBefore(this.node, element.node);
R._insertbefore(this, element, this.paper);
return this;
};
elproto.blur = function (size) {
var s = this.node.runtimeStyle,
f = s.filter;
f = f.replace(blurregexp, E);
if (+size !== 0) {
this.attrs.blur = size;
s.filter = f + S + ms + ".Blur(pixelradius=" + (+size || 1.5) + ")";
s.margin = R.format("-{0}px 0 0 -{0}px", round(+size || 1.5));
} else {
s.filter = f;
s.margin = 0;
delete this.attrs.blur;
}
return this;
};
R._engine.path = function (pathString, vml) {
var el = createNode("shape");
el.style.cssText = cssDot;
el.coordsize = zoom + S + zoom;
el.coordorigin = vml.coordorigin;
var p = new Element(el, vml),
attr = {fill: "none", stroke: "#000"};
pathString && (attr.path = pathString);
p.type = "path";
p.path = [];
p.Path = E;
setFillAndStroke(p, attr);
vml.canvas.appendChild(el);
var skew = createNode("skew");
skew.on = true;
el.appendChild(skew);
p.skew = skew;
p.transform(E);
return p;
};
R._engine.rect = function (vml, x, y, w, h, r) {
var path = R._rectPath(x, y, w, h, r),
res = vml.path(path),
a = res.attrs;
res.X = a.x = x;
res.Y = a.y = y;
res.W = a.width = w;
res.H = a.height = h;
a.r = r;
a.path = path;
res.type = "rect";
return res;
};
R._engine.ellipse = function (vml, x, y, rx, ry) {
var res = vml.path(),
a = res.attrs;
res.X = x - rx;
res.Y = y - ry;
res.W = rx * 2;
res.H = ry * 2;
res.type = "ellipse";
setFillAndStroke(res, {
cx: x,
cy: y,
rx: rx,
ry: ry
});
return res;
};
R._engine.circle = function (vml, x, y, r) {
var res = vml.path(),
a = res.attrs;
res.X = x - r;
res.Y = y - r;
res.W = res.H = r * 2;
res.type = "circle";
setFillAndStroke(res, {
cx: x,
cy: y,
r: r
});
return res;
};
R._engine.image = function (vml, src, x, y, w, h) {
var path = R._rectPath(x, y, w, h),
res = vml.path(path).attr({stroke: "none"}),
a = res.attrs,
node = res.node,
fill = node.getElementsByTagName(fillString)[0];
a.src = src;
res.X = a.x = x;
res.Y = a.y = y;
res.W = a.width = w;
res.H = a.height = h;
a.path = path;
res.type = "image";
fill.parentNode == node && node.removeChild(fill);
fill.rotate = true;
fill.src = src;
fill.type = "tile";
res._.fillpos = [x, y];
res._.fillsize = [w, h];
node.appendChild(fill);
setCoords(res, 1, 1, 0, 0, 0);
return res;
};
R._engine.text = function (vml, x, y, text) {
var el = createNode("shape"),
path = createNode("path"),
o = createNode("textpath");
x = x || 0;
y = y || 0;
text = text || "";
path.v = R.format("m{0},{1}l{2},{1}", round(x * zoom), round(y * zoom), round(x * zoom) + 1);
path.textpathok = true;
o.string = Str(text);
o.on = true;
el.style.cssText = cssDot;
el.coordsize = zoom + S + zoom;
el.coordorigin = "0 0";
var p = new Element(el, vml),
attr = {
fill: "#000",
stroke: "none",
font: R._availableAttrs.font,
text: text
};
p.shape = el;
p.path = path;
p.textpath = o;
p.type = "text";
p.attrs.text = Str(text);
p.attrs.x = x;
p.attrs.y = y;
p.attrs.w = 1;
p.attrs.h = 1;
setFillAndStroke(p, attr);
el.appendChild(o);
el.appendChild(path);
vml.canvas.appendChild(el);
var skew = createNode("skew");
skew.on = true;
el.appendChild(skew);
p.skew = skew;
p.transform(E);
return p;
};
R._engine.setSize = function (width, height) {
var cs = this.canvas.style;
this.width = width;
this.height = height;
width == +width && (width += "px");
height == +height && (height += "px");
cs.width = width;
cs.height = height;
cs.clip = "rect(0 " + width + " " + height + " 0)";
if (this._viewBox) {
R._engine.setViewBox.apply(this, this._viewBox);
}
return this;
};
R._engine.setViewBox = function (x, y, w, h, fit) {
R.eve("raphael.setViewBox", this, this._viewBox, [x, y, w, h, fit]);
var width = this.width,
height = this.height,
size = 1 / mmax(w / width, h / height),
H, W;
if (fit) {
H = height / h;
W = width / w;
if (w * H < width) {
x -= (width - w * H) / 2 / H;
}
if (h * W < height) {
y -= (height - h * W) / 2 / W;
}
}
this._viewBox = [x, y, w, h, !!fit];
this._viewBoxShift = {
dx: -x,
dy: -y,
scale: size
};
this.forEach(function (el) {
el.transform("...");
});
return this;
};
var createNode;
R._engine.initWin = function (win) {
var doc = win.document;
doc.createStyleSheet().addRule(".rvml", "behavior:url(#default#VML)");
try {
!doc.namespaces.rvml && doc.namespaces.add("rvml", "urn:schemas-microsoft-com:vml");
createNode = function (tagName) {
return doc.createElement('<rvml:' + tagName + ' class="rvml">');
};
} catch (e) {
createNode = function (tagName) {
return doc.createElement('<' + tagName + ' xmlns="urn:schemas-microsoft.com:vml" class="rvml">');
};
}
};
R._engine.initWin(R._g.win);
R._engine.create = function () {
var con = R._getContainer.apply(0, arguments),
container = con.container,
height = con.height,
s,
width = con.width,
x = con.x,
y = con.y;
if (!container) {
throw new Error("VML container not found.");
}
var res = new R._Paper,
c = res.canvas = R._g.doc.createElement("div"),
cs = c.style;
x = x || 0;
y = y || 0;
width = width || 512;
height = height || 342;
res.width = width;
res.height = height;
width == +width && (width += "px");
height == +height && (height += "px");
res.coordsize = zoom * 1e3 + S + zoom * 1e3;
res.coordorigin = "0 0";
res.span = R._g.doc.createElement("span");
res.span.style.cssText = "position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;";
c.appendChild(res.span);
cs.cssText = R.format("top:0;left:0;width:{0};height:{1};display:inline-block;position:relative;clip:rect(0 {0} {1} 0);overflow:hidden", width, height);
if (container == 1) {
R._g.doc.body.appendChild(c);
cs.left = x + "px";
cs.top = y + "px";
cs.position = "absolute";
} else {
if (container.firstChild) {
container.insertBefore(c, container.firstChild);
} else {
container.appendChild(c);
}
}
res.renderfix = function () {};
return res;
};
R.prototype.clear = function () {
R.eve("raphael.clear", this);
this.canvas.innerHTML = E;
this.span = R._g.doc.createElement("span");
this.span.style.cssText = "position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;display:inline;";
this.canvas.appendChild(this.span);
this.bottom = this.top = null;
};
R.prototype.remove = function () {
R.eve("raphael.remove", this);
this.canvas.parentNode.removeChild(this.canvas);
for (var i in this) {
this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null;
}
return true;
};
var setproto = R.st;
for (var method in elproto) if (elproto[has](method) && !setproto[has](method)) {
setproto[method] = (function (methodname) {
return function () {
var arg = arguments;
return this.forEach(function (el) {
el[methodname].apply(el, arg);
});
};
})(method);
}
})();
// EXPOSE
// SVG and VML are appended just before the EXPOSE line
// Even with AMD, Raphael should be defined globally
oldRaphael.was ? (g.win.Raphael = R) : (Raphael = R);
return R;
}));
| CelineBoudier/rapid-router | game/static/game/js/raphael.js | JavaScript | agpl-3.0 | 299,673 |
/**
MIT License http://www.opensource.org/licenses/mit-license.php
Author Igor Vladyka <[email protected]> (https://github.com/Igor-Vladyka/leaflet.browser.print)
**/
L.Control.BrowserPrint.Utils = {
_ignoreArray: [],
_cloneFactoryArray: [],
_cloneRendererArray: [],
_knownRenderers: {},
cloneOptions: function(options) {
var utils = this;
var retOptions = {};
for (var name in options) {
var item = options[name];
if (item && item.clone) {
retOptions[name] = item.clone();
} else if (item && item.onAdd) {
retOptions[name] = utils.cloneLayer(item);
} else {
retOptions[name] = item;
}
}
return retOptions;
},
cloneBasicOptionsWithoutLayers: function(options) {
var retOptions = {};
var optionNames = Object.getOwnPropertyNames(options);
if (optionNames.length) {
for (var i = 0; i < optionNames.length; i++) {
var optName = optionNames[i];
if (optName && optName != "layers") {
retOptions[optName] = options[optName];
}
}
return this.cloneOptions(retOptions);
}
return retOptions;
},
cloneInnerLayers: function (layer) {
var utils = this;
var layers = [];
layer.eachLayer(function (inner) {
var l = utils.cloneLayer(inner);
if (l) {
layers.push(l);
}
});
return layers;
},
initialize: function () {
this._knownRenderers = {};
// Renderers
this.registerRenderer(L.SVG, 'L.SVG');
this.registerRenderer(L.Canvas, 'L.Canvas');
this.registerLayer(L.TileLayer.WMS, 'L.TileLayer.WMS', function(layer, utils) { return L.tileLayer.wms(layer._url, utils.cloneOptions(layer.options)); });
this.registerLayer(L.TileLayer, 'L.TileLayer', function(layer, utils) { return L.tileLayer(layer._url, utils.cloneOptions(layer.options)); });
this.registerLayer(L.GridLayer, 'L.GridLayer', function(layer, utils) { return L.gridLayer(utils.cloneOptions(layer.options)); });
this.registerLayer(L.ImageOverlay, 'L.ImageOverlay', function(layer, utils) { return L.imageOverlay(layer._url, layer._bounds, utils.cloneOptions(layer.options)); });
this.registerLayer(L.Marker, 'L.Marker', function(layer, utils) { return L.marker(layer.getLatLng(), utils.cloneOptions(layer.options)); });
this.registerLayer(L.Popup, 'L.Popup', function(layer, utils) { return L.popup(utils.cloneOptions(layer.options)).setLatLng(layer.getLatLng()).setContent(layer.getContent()); });
this.registerLayer(L.Circle, 'L.Circle', function(layer, utils) { return L.circle(layer.getLatLng(), layer.getRadius(), utils.cloneOptions(layer.options)); });
this.registerLayer(L.CircleMarker, 'L.CircleMarker', function(layer, utils) { return L.circleMarker(layer.getLatLng(), utils.cloneOptions(layer.options)); });
this.registerLayer(L.Rectangle, 'L.Rectangle', function(layer, utils) { return L.rectangle(layer.getBounds(), utils.cloneOptions(layer.options)); });
this.registerLayer(L.Polygon, 'L.Polygon', function(layer, utils) { return L.polygon(layer.getLatLngs(), utils.cloneOptions(layer.options)); });
// MultiPolyline is removed in leaflet 1.0.0
this.registerLayer(L.MultiPolyline, 'L.MultiPolyline', function(layer, utils) { return L.polyline(layer.getLatLngs(), utils.cloneOptions(layer.options)); });
// MultiPolygon is removed in leaflet 1.0.0
this.registerLayer(L.MultiPolygon, 'L.MultiPolygon', function(layer, utils) { return L.multiPolygon(layer.getLatLngs(), utils.cloneOptions(layer.options)); });
this.registerLayer(L.Polyline, 'L.Polyline', function(layer, utils) { return L.polyline(layer.getLatLngs(), utils.cloneOptions(layer.options)); });
this.registerLayer(L.GeoJSON, 'L.GeoJSON', function(layer, utils) { return L.geoJson(layer.toGeoJSON(), utils.cloneOptions(layer.options)); });
this.registerIgnoreLayer(L.FeatureGroup, 'L.FeatureGroup');
this.registerIgnoreLayer(L.LayerGroup, 'L.LayerGroup');
// There is no point to clone tooltips here; L.tooltip(options);
this.registerLayer(L.Tooltip, 'L.Tooltip', function(){ return null; });
},
_register: function(array, type, identifier, builderFunction) {
if (type &&
!array.filter(function(l){ return l.identifier === identifier; }).length) {
array.push({
type: type,
identifier: identifier,
builder: builderFunction || function (layer) { return new type(layer.options); }
});
}
},
registerLayer: function(type, identifier, builderFunction) {
this._register(this._cloneFactoryArray, type, identifier, builderFunction);
},
registerRenderer: function(type, identifier, builderFunction) {
this._register(this._cloneRendererArray, type, identifier, builderFunction);
},
registerIgnoreLayer: function(type, identifier) {
this._register(this._ignoreArray, type, identifier);
},
cloneLayer: function(layer) {
if (!layer) return null;
// First we check if this layer is actual renderer
var renderer = this.__getRenderer(layer);
if (renderer) {
return renderer;
}
var factoryObject;
if (layer._group) { // Exceptional check for L.MarkerClusterGroup
factoryObject = this.__getFactoryObject(layer._group, true);
} else {
factoryObject = this.__getFactoryObject(layer);
}
// We clone and recreate layer if it's simple overlay
if (factoryObject) {
factoryObject = factoryObject.builder(layer, this);
}
return factoryObject;
},
getType: function(layer) {
if (!layer) return null;
var factoryObject = this.__getFactoryObject(layer);
if (factoryObject) {
factoryObject = factoryObject.identifier;
}
return factoryObject;
},
__getRenderer: function(oldRenderer) {
var renderer = this._knownRenderers[oldRenderer._leaflet_id];
if (!renderer) {
for (var i = 0; i < this._cloneRendererArray.length; i++) {
var factoryObject = this._cloneRendererArray[i];
if (oldRenderer instanceof factoryObject.type) {
this._knownRenderers[oldRenderer._leaflet_id] = factoryObject.builder(oldRenderer.options);
break;
}
}
renderer = this._knownRenderers[oldRenderer._leaflet_id];
}
return renderer;
},
__getFactoryObject: function (layer, skipIgnore) {
if (!skipIgnore) {
for (var i = 0; i < this._ignoreArray.length; i++) {
var ignoreObject = this._ignoreArray[i];
if (ignoreObject.type && layer instanceof ignoreObject.type) {
return null;
}
}
}
for (var i = 0; i < this._cloneFactoryArray.length; i++) {
var factoryObject = this._cloneFactoryArray[i];
if (factoryObject.type && layer instanceof factoryObject.type) {
return factoryObject;
}
}
for (var i = 0; i < this._cloneRendererArray.length; i++) {
var factoryObject = this._cloneRendererArray[i];
if (factoryObject.type && layer instanceof factoryObject.type) {
return null;
}
}
this.__unknownLayer__();
return null;
},
__unknownLayer__: function(){
console.warn('Unknown layer, cannot clone this layer. Leaflet version: ' + L.version);
console.info('For additional information please refer to documentation on: https://github.com/Igor-Vladyka/leaflet.browser.print.');
console.info('-------------------------------------------------------------------------------------------------------------------');
}
};
| Irstea/collec | display/node_modules/leaflet.browser.print/src/leaflet.browser.print.utils.js | JavaScript | agpl-3.0 | 7,246 |
// Copyright (C) 2015 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 25.3.1.3
description: >
When a generator is paused before a `try..catch` statement, `return` should
interrupt control flow as if a `return` statement had appeared at that
location in the function body.
---*/
function* g() {
yield;
try {
$ERROR('This code is unreachable (within `try` block)');
} catch (e) {
throw e;
}
$ERROR('This code is unreachable (following `try` statement)');
}
var iter = g();
var result;
iter.next();
result = iter.return(45);
assert.sameValue(result.value, 45, 'Result `value` following `return`');
assert.sameValue(result.done, true, 'Result `done` flag following `return`');
result = iter.next();
assert.sameValue(result.value,
undefined, 'Result `value` is undefined when complete'
);
assert.sameValue(
result.done, true, 'Result `done` flag is `true` when complete'
);
| m0ppers/arangodb | 3rdParty/V8/V8-5.0.71.39/test/test262/data/test/built-ins/GeneratorPrototype/return/try-catch-before-try.js | JavaScript | apache-2.0 | 988 |
// Copyright 2017, Google, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
const config = require('./config');
// TODO: Load the trace-agent and start it
// Trace must be started before any other code in the
// application.
require('@google-cloud/trace-agent').start({
projectId: config.get('GCLOUD_PROJECT')
});
// END TODO
require('@google-cloud/debug-agent').start({
allowExpressions: true,
projectId: config.get('GCLOUD_PROJECT')
});
const path = require('path');
const express = require('express');
const scores = require('./gcp/spanner');
const {ErrorReporting} = require('@google-cloud/error-reporting');
const errorReporting = new ErrorReporting({
projectId: config.get('GCLOUD_PROJECT')
});
const app = express();
// Static files
app.use(express.static('frontend/public/'));
app.disable('etag');
app.set('views', path.join(__dirname, 'web-app/views'));
app.set('view engine', 'pug');
app.set('trust proxy', true);
app.set('json spaces', 2);
// Questions
app.use('/questions', require('./web-app/questions'));
// Quizzes API
app.use('/api/quizzes', require('./api'));
// Display the home page
app.get('/', (req, res) => {
res.render('home.pug');
});
// Display the Leaderboard
app.get('/leaderboard', (req, res) => {
scores.getLeaderboard().then(scores => {
res.render('leaderboard.pug', {
scores
});
});
});
// Use Stackdriver Error Reporting with Express
app.use(errorReporting.express);
// Basic 404 handler
app.use((req, res) => {
res.status(404).send('Not Found');
});
// Basic error handler
app.use((err, req, res, next) => {
/* jshint unused:false */
console.error(err);
// If our routes specified a specific response, then send that. Otherwise,
// send a generic message so as not to leak anything.
res.status(500).send(err.response || 'Something broke!');
});
if (module === require.main) {
// Start the server
const server = app.listen(config.get('PORT'), () => {
const port = server.address().port;
console.log(`App listening on port ${port}`);
});
}
module.exports = app;
| GoogleCloudPlatform/training-data-analyst | courses/developingapps/v1.3/nodejs/stackdriver-trace-monitoring/end/frontend/app.js | JavaScript | apache-2.0 | 2,594 |
// Copyright (C) 2015 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 21.2.5.11
description: RegExp.prototype[Symbol.split] `length` property
info: >
The length property of the @@split method is 2.
ES6 Section 17:
[...]
Unless otherwise specified, the length property of a built-in Function
object has the attributes { [[Writable]]: false, [[Enumerable]]: false,
[[Configurable]]: true }.
includes: [propertyHelper.js]
---*/
assert.sameValue(RegExp.prototype[Symbol.split].length, 2);
verifyNotEnumerable(RegExp.prototype[Symbol.split], 'length');
verifyNotWritable(RegExp.prototype[Symbol.split], 'length');
verifyConfigurable(RegExp.prototype[Symbol.split], 'length');
| m0ppers/arangodb | 3rdParty/V8/V8-5.0.71.39/test/test262/data/test/built-ins/RegExp/prototype/Symbol.split/length.js | JavaScript | apache-2.0 | 781 |
angular.module('breadcrumbs', []); | caguillen214/directive-director | demoApp/components/breadcrumbs/breadcrumbs.js | JavaScript | apache-2.0 | 34 |
/*
* 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.
*/
'use strict';
angular.module('zeppelinWebApp').controller('MainCtrl', function($scope, $rootScope, $window) {
$scope.looknfeel = 'default';
var init = function() {
$scope.asIframe = (($window.location.href.indexOf('asIframe') > -1) ? true : false);
};
init();
$rootScope.$on('setIframe', function(event, data) {
if (!event.defaultPrevented) {
$scope.asIframe = data;
event.preventDefault();
}
});
$rootScope.$on('setLookAndFeel', function(event, data) {
if (!event.defaultPrevented && data && data !== '' && data !== $scope.looknfeel) {
$scope.looknfeel = data;
event.preventDefault();
}
});
// Set The lookAndFeel to default on every page
$rootScope.$on('$routeChangeStart', function(event, next, current) {
$rootScope.$broadcast('setLookAndFeel', 'default');
});
BootstrapDialog.defaultOptions.onshown = function() {
angular.element('#' + this.id).find('.btn:last').focus();
};
// Remove BootstrapDialog animation
BootstrapDialog.configDefaultOptions({animate: false});
});
| optimizely/incubator-zeppelin | zeppelin-web/src/app/app.controller.js | JavaScript | apache-2.0 | 1,628 |
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Returns the y-scale function.
*
* @private
* @returns {Function} scale function
*/
function get() {
/* eslint-disable no-invalid-this */
return this._yScale;
}
// EXPORTS //
module.exports = get;
| stdlib-js/stdlib | lib/node_modules/@stdlib/plot/components/svg/symbols/lib/props/y-scale/get.js | JavaScript | apache-2.0 | 840 |
// Copyright (c) 2012 Ecma International. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es5id: 15.2.3.7-6-a-297
description: >
Object.defineProperties - 'O' is an Arguments object, 'P' is an
array index named data property of 'O' but not defined in
[[ParameterMap]] of 'O', test TypeError is thrown when updating
the [[Configurable]] attribute value of 'P' which is not
configurable (10.6 [[DefineOwnProperty]] step 4)
includes: [propertyHelper.js]
---*/
var arg;
(function fun() {
arg = arguments;
}());
Object.defineProperty(arg, "0", {
value: 0,
writable: false,
enumerable: false,
configurable: false
});
try {
Object.defineProperties(arg, {
"0": {
configurable: true
}
});
$ERROR("Expected an exception.");
} catch (e) {
verifyEqualTo(arg, "0", 0);
verifyNotWritable(arg, "0");
verifyNotEnumerable(arg, "0");
verifyNotConfigurable(arg, "0");
if (!(e instanceof TypeError)) {
$ERROR("Expected TypeError, got " + e);
}
}
| m0ppers/arangodb | 3rdParty/V8/V8-5.0.71.39/test/test262/data/test/built-ins/Object/defineProperties/15.2.3.7-6-a-297.js | JavaScript | apache-2.0 | 1,101 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function drawApplicationTimeline(groupArray, eventObjArray, startTime, offset) {
var groups = new vis.DataSet(groupArray);
var items = new vis.DataSet(eventObjArray);
var container = $("#application-timeline")[0];
var options = {
groupOrder: function(a, b) {
return a.value - b.value
},
editable: false,
align: 'left',
showCurrentTime: false,
start: startTime,
zoomable: false,
locale: "en",
moment: function (date) {
return vis.moment(date).utcOffset(offset);
}
};
var applicationTimeline = new vis.Timeline(container);
applicationTimeline.setOptions(options);
applicationTimeline.setGroups(groups);
applicationTimeline.setItems(items);
setupZoomable("#application-timeline-zoom-lock", applicationTimeline);
setupExecutorEventAction();
function getIdForJobEntry(baseElem) {
var jobIdText = $($(baseElem).find(".application-timeline-content")[0]).text();
var jobId = jobIdText.match("\\(Job (\\d+)\\)$")[1];
return jobId;
}
function getSelectorForJobEntry(jobId) {
return "#job-" + jobId;
}
function setupJobEventAction() {
$(".vis-item.vis-range.job.application-timeline-object").each(function() {
$(this).click(function() {
var jobId = getIdForJobEntry(this);
var jobPagePath = uiRoot + appBasePath + "/jobs/job/?id=" + jobId;
window.location.href = jobPagePath;
});
$(this).hover(
function() {
$(getSelectorForJobEntry(getIdForJobEntry(this))).addClass("corresponding-item-hover");
$($(this).find("div.application-timeline-content")[0]).tooltip("show");
},
function() {
$(getSelectorForJobEntry(getIdForJobEntry(this))).removeClass("corresponding-item-hover");
$($(this).find("div.application-timeline-content")[0]).tooltip("hide");
}
);
});
}
setupJobEventAction();
$("span.expand-application-timeline").click(function() {
var status = window.localStorage.getItem("expand-application-timeline") == "true";
status = !status;
$("#application-timeline").toggleClass('collapsed');
var visibilityState = status ? "" : "none";
$("#application-timeline").css("display", visibilityState);
// Switch the class of the arrow from open to closed.
$(this).find('.expand-application-timeline-arrow').toggleClass('arrow-open');
$(this).find('.expand-application-timeline-arrow').toggleClass('arrow-closed');
window.localStorage.setItem("expand-application-timeline", "" + status);
});
}
$(function () {
if ($("span.expand-application-timeline").length &&
window.localStorage.getItem("expand-application-timeline") == "true") {
// Set it to false so that the click function can revert it
window.localStorage.setItem("expand-application-timeline", "false");
$("span.expand-application-timeline").trigger('click');
} else {
$("#application-timeline").css("display", "none");
}
});
function drawJobTimeline(groupArray, eventObjArray, startTime, offset) {
var groups = new vis.DataSet(groupArray);
var items = new vis.DataSet(eventObjArray);
var container = $('#job-timeline')[0];
var options = {
groupOrder: function(a, b) {
return a.value - b.value;
},
editable: false,
align: 'left',
showCurrentTime: false,
start: startTime,
zoomable: false,
locale: "en",
moment: function (date) {
return vis.moment(date).utcOffset(offset);
}
};
var jobTimeline = new vis.Timeline(container);
jobTimeline.setOptions(options);
jobTimeline.setGroups(groups);
jobTimeline.setItems(items);
setupZoomable("#job-timeline-zoom-lock", jobTimeline);
setupExecutorEventAction();
function getStageIdAndAttemptForStageEntry(baseElem) {
var stageIdText = $($(baseElem).find(".job-timeline-content")[0]).text();
var stageIdAndAttempt = stageIdText.match("\\(Stage (\\d+\\.\\d+)\\)$")[1].split(".");
return stageIdAndAttempt;
}
function getSelectorForStageEntry(stageIdAndAttempt) {
return "#stage-" + stageIdAndAttempt[0] + "-" + stageIdAndAttempt[1];
}
function setupStageEventAction() {
$(".vis-item.vis-range.stage.job-timeline-object").each(function() {
$(this).click(function() {
var stageIdAndAttempt = getStageIdAndAttemptForStageEntry(this);
var stagePagePath = uiRoot + appBasePath +
"/stages/stage/?id=" + stageIdAndAttempt[0] + "&attempt=" + stageIdAndAttempt[1];
window.location.href = stagePagePath;
});
$(this).hover(
function() {
$(getSelectorForStageEntry(getStageIdAndAttemptForStageEntry(this)))
.addClass("corresponding-item-hover");
$($(this).find("div.job-timeline-content")[0]).tooltip("show");
},
function() {
$(getSelectorForStageEntry(getStageIdAndAttemptForStageEntry(this)))
.removeClass("corresponding-item-hover");
$($(this).find("div.job-timeline-content")[0]).tooltip("hide");
}
);
});
}
setupStageEventAction();
$("span.expand-job-timeline").click(function() {
var status = window.localStorage.getItem("expand-job-timeline") == "true";
status = !status;
$("#job-timeline").toggleClass('collapsed');
var visibilityState = status ? "" : "none";
$("#job-timeline").css("display", visibilityState);
// Switch the class of the arrow from open to closed.
$(this).find('.expand-job-timeline-arrow').toggleClass('arrow-open');
$(this).find('.expand-job-timeline-arrow').toggleClass('arrow-closed');
window.localStorage.setItem("expand-job-timeline", "" + status);
});
}
$(function () {
if ($("span.expand-job-timeline").length &&
window.localStorage.getItem("expand-job-timeline") == "true") {
// Set it to false so that the click function can revert it
window.localStorage.setItem("expand-job-timeline", "false");
$("span.expand-job-timeline").trigger('click');
} else {
$("#job-timeline").css("display", "none");
}
});
function drawTaskAssignmentTimeline(groupArray, eventObjArray, minLaunchTime, maxFinishTime, offset) {
var groups = new vis.DataSet(groupArray);
var items = new vis.DataSet(eventObjArray);
var container = $("#task-assignment-timeline")[0];
var options = {
groupOrder: function(a, b) {
return a.value - b.value
},
editable: false,
align: 'left',
selectable: false,
showCurrentTime: false,
start: minLaunchTime,
end: maxFinishTime,
zoomable: false,
locale: "en",
moment: function (date) {
return vis.moment(date).utcOffset(offset);
}
};
var taskTimeline = new vis.Timeline(container);
taskTimeline.setOptions(options);
taskTimeline.setGroups(groups);
taskTimeline.setItems(items);
// If a user zooms while a tooltip is displayed, the user may zoom such that the cursor is no
// longer over the task that the tooltip corresponds to. So, when a user zooms, we should hide
// any currently displayed tooltips.
var currentDisplayedTooltip = null;
$("#task-assignment-timeline").on({
"mouseenter": function() {
currentDisplayedTooltip = this;
},
"mouseleave": function() {
currentDisplayedTooltip = null;
}
}, ".task-assignment-timeline-content");
taskTimeline.on("rangechange", function(prop) {
if (currentDisplayedTooltip !== null) {
$(currentDisplayedTooltip).tooltip("hide");
}
});
setupZoomable("#task-assignment-timeline-zoom-lock", taskTimeline);
$("span.expand-task-assignment-timeline").click(function() {
var status = window.localStorage.getItem("expand-task-assignment-timeline") == "true";
status = !status;
$("#task-assignment-timeline").toggleClass("collapsed");
var visibilityState = status ? "" : "none";
$("#task-assignment-timeline").css("display", visibilityState);
// Switch the class of the arrow from open to closed.
$(this).find(".expand-task-assignment-timeline-arrow").toggleClass("arrow-open");
$(this).find(".expand-task-assignment-timeline-arrow").toggleClass("arrow-closed");
window.localStorage.setItem("expand-task-assignment-timeline", "" + status);
});
}
$(function () {
if ($("span.expand-task-assignment-timeline").length &&
window.localStorage.getItem("expand-task-assignment-timeline") == "true") {
// Set it to false so that the click function can revert it
window.localStorage.setItem("expand-task-assignment-timeline", "false");
$("span.expand-task-assignment-timeline").trigger('click');
} else {
$("#task-assignment-timeline").css("display", "none");
}
});
function setupExecutorEventAction() {
$(".vis-item.vis-box.executor").each(function () {
$(this).hover(
function() {
$($(this).find(".executor-event-content")[0]).tooltip("show");
},
function() {
$($(this).find(".executor-event-content")[0]).tooltip("hide");
}
);
});
}
function setupZoomable(id, timeline) {
$(id + ' > input[type="checkbox"]').click(function() {
if (this.checked) {
timeline.setOptions({zoomable: true});
} else {
timeline.setOptions({zoomable: false});
}
});
$(id + " > span").click(function() {
$(this).parent().find('input:checkbox').trigger('click');
});
}
| witgo/spark | core/src/main/resources/org/apache/spark/ui/static/timeline-view.js | JavaScript | apache-2.0 | 10,145 |
var _Array$isArray = require("../core-js/array/is-array");
var arrayLikeToArray = require("./arrayLikeToArray");
function _maybeArrayLike(next, arr, i) {
if (arr && !_Array$isArray(arr) && typeof arr.length === "number") {
var len = arr.length;
return arrayLikeToArray(arr, i !== void 0 && i < len ? i : len);
}
return next(arr, i);
}
module.exports = _maybeArrayLike; | BigBoss424/portfolio | v8/development/node_modules/@babel/runtime-corejs3/helpers/maybeArrayLike.js | JavaScript | apache-2.0 | 386 |
// Copyright (C) 2015 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
description: Return value after successful match
es6id: 21.2.5.6
info: >
[...]
5. Let global be ToBoolean(Get(rx, "global")).
6. ReturnIfAbrupt(global).
7. If global is false, then
a. Return RegExpExec(rx, S).
21.2.5.2.1 Runtime Semantics: RegExpExec ( R, S )
[...]
7. Return RegExpBuiltinExec(R, S).
21.2.5.2.2 Runtime Semantics: RegExpBuiltinExec ( R, S )
[...]
20. Let A be ArrayCreate(n + 1).
[...]
24. Perform CreateDataProperty(A, "index", matchIndex).
25. Perform CreateDataProperty(A, "input", S).
26. Let matchedSubstr be the matched substring (i.e. the portion of S
between offset lastIndex inclusive and offset e exclusive).
27. Perform CreateDataProperty(A, "0", matchedSubstr).
[...]
29. Return A.
features: [Symbol.match]
---*/
var result = /b./[Symbol.match]('abcd');
assert(Array.isArray(result));
assert.sameValue(result.index, 1);
assert.sameValue(result.input, 'abcd');
assert.sameValue(result.length, 1);
assert.sameValue(result[0], 'bc');
| baslr/ArangoDB | 3rdParty/V8/V8-5.0.71.39/test/test262/data/test/built-ins/RegExp/prototype/Symbol.match/builtin-success-return-val.js | JavaScript | apache-2.0 | 1,194 |
/// Copyright (c) 2009 Microsoft Corporation
///
/// Redistribution and use in source and binary forms, with or without modification, are permitted provided
/// that the following conditions are met:
/// * Redistributions of source code must retain the above copyright notice, this list of conditions and
/// the following disclaimer.
/// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
/// the following disclaimer in the documentation and/or other materials provided with the distribution.
/// * Neither the name of Microsoft nor the names of its contributors may be used to
/// endorse or promote products derived from this software without specific prior written permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
/// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
/// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
/// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
/// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
/// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
/// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
ES5Harness.registerTest( {
id: "15.5.4.20-1-2",
path: "TestCases/chapter15/15.5/15.5.4/15.5.4.20/15.5.4.20-1-2.js",
description: "String.prototype.trim throws TypeError when string is null",
test: function testcase() {
try
{
String.prototype.trim.call(null);
return false;
}
catch(e)
{
return e instanceof TypeError;
}
},
precondition: function prereq() {
return fnExists(String.prototype.trim);
}
});
| hnafar/IronJS | Src/Tests/ietestcenter/chapter15/15.5/15.5.4/15.5.4.20/15.5.4.20-1-2.js | JavaScript | apache-2.0 | 1,997 |
"use strict";
var core_1 = require("@angular/core");
var http_1 = require("@angular/http");
var Rx_1 = require("rxjs/Rx");
require("rxjs/add/operator/map");
var config_1 = require("../config");
var grocery_1 = require("./grocery");
/* This is a simple service that reads grocery lists from the backend.
The Http service’s get() method is used to load JSON data,
and RxJS’s map() function is used to format the data into an array of Grocery objects. */
var GroceryListService = (function () {
function GroceryListService(http) {
this.http = http;
}
GroceryListService.prototype.load = function () {
var headers = new http_1.Headers();
headers.append("Authorization", "Bearer " + config_1.Config.token);
return this.http.get(config_1.Config.apiUrl + "Groceries", {
headers: headers
})
.map(function (res) { return res.json(); })
.map(function (data) {
var groceryList = [];
data.Result.forEach(function (grocery) {
groceryList.push(new grocery_1.Grocery(grocery.Id, grocery.Name));
});
return groceryList;
})
.catch(this.handleErrors);
};
/* The Http service’s post() method is being used to make an HTTP call to the backend,
and then using RxJS’s map() function to convert the returned data into a Grocery object.
This object is consumed in the ListComponent’s add() method,
which adds the grocery to the page’s list by calling this.groceryList.unshift(),
and then empties that page’s text field by setting this.grocery equal to "". */
GroceryListService.prototype.add = function (name) {
var headers = new http_1.Headers();
headers.append("Authorization", "Bearer " + config_1.Config.token);
headers.append("Content-Type", "application/json");
return this.http.post(config_1.Config.apiUrl + "Groceries", JSON.stringify({ Name: name }), { headers: headers })
.map(function (res) { return res.json(); })
.map(function (data) {
return new grocery_1.Grocery(data.Result.Id, name);
})
.catch(this.handleErrors);
};
GroceryListService.prototype.delete = function (id) {
var headers = new http_1.Headers();
headers.append("Authorization", "Bearer " + config_1.Config.token);
headers.append("Content-Type", "application/json");
return this.http.delete(config_1.Config.apiUrl + "Groceries/" + id, { headers: headers })
.map(function (res) { return res.json(); })
.catch(this.handleErrors);
};
GroceryListService.prototype.handleErrors = function (error) {
console.log(JSON.stringify(error.json()));
return Rx_1.Observable.throw(error);
};
return GroceryListService;
}());
GroceryListService = __decorate([
core_1.Injectable(),
__metadata("design:paramtypes", [http_1.Http])
], GroceryListService);
exports.GroceryListService = GroceryListService;
//# sourceMappingURL=grocery-list.service.js.map | Torgo13/CarWashApp | platforms/ios/build/emulator/CarWashApp.app/app/shared/grocery/grocery-list.service.js | JavaScript | apache-2.0 | 3,092 |
//// [internalAliasClassInsideLocalModuleWithExport.js]
(function (x) {
var c = (function () {
function c() {
}
c.prototype.foo = function (a) {
return a;
};
return c;
})();
x.c = c;
})(exports.x || (exports.x = {}));
var x = exports.x;
(function (m2) {
(function (m3) {
var c = x.c;
m3.c = c;
m3.cProp = new c();
var cReturnVal = m3.cProp.foo(10);
})(m2.m3 || (m2.m3 = {}));
var m3 = m2.m3;
})(exports.m2 || (exports.m2 = {}));
var m2 = exports.m2;
exports.d = new m2.m3.c();
////[internalAliasClassInsideLocalModuleWithExport.d.ts]
export declare module x {
class c {
public foo(a: number): number;
}
}
export declare module m2 {
module m3 {
export import c = x.c;
var cProp: c;
}
}
export declare var d: x.c;
| hippich/typescript | tests/baselines/reference/internalAliasClassInsideLocalModuleWithExport.js | JavaScript | apache-2.0 | 905 |
CKEDITOR.plugins.setLang('oembed', 'nl', {
title : "Integratie van media-inhoud (foto's, video, content)",
button : "Media-inhoud van externe websites",
pasteUrl : "Geef een URL van een pagina in dat ondersteund wordt (Bijv.: YouTube, Flickr, Qik, Vimeo, Hulu, Viddler, MyOpera, etc.) ...",
invalidUrl : "Please provide an valid URL!",
noEmbedCode : "No embed code found, or site is not supported!",
url : "URL:",
width: "Breedte:",
height: "Hoogte:",
widthTitle: "Width for the embeded Content",
heightTitle: "Height for the embeded Content",
maxWidth: "Maximale breedte:",
maxHeight: "Maximale hoogte:",
maxWidthTitle: "Maximum Width for the embeded Content",
maxHeightTitle: "Maximum Height for the embeded Content",
resizeType: "Resize Type (Only Video's):",
noresize: "No Resize (use default)",
responsive: "Responsive Resize",
custom: "Specific Resize",
autoClose: "Automatically Close Dialog after Code is Embeded",
noVimeo: "The owner of this video has set domain restrictions and you will not be able to embed it on your website.",
Error: "Media Content could not been retrieved, please try a different URL."
}); | ONLYOFFICE/CommunityServer | web/studio/ASC.Web.Studio/UserControls/Common/ckeditor/plugins/oembed/lang/nl.js | JavaScript | apache-2.0 | 1,170 |
$(function() {
//搜索框交互
var
placeholder = window.INPUT_PLACEHOLDER || '请输入要搜索的关键词',
baiduUrl = 'http://www.baidu.com/s?wd=',
googleUrl = 'http://www.google.com.hk/search?q=',
searchEl = $('#search');
$('.button', searchEl).on('click', function(e) {
var
keyword = $('.keyword', searchEl).val(),
url = e.target.name == 'baidu' ? baiduUrl : googleUrl;
window.open(url + encodeURIComponent(keyword));
e.preventDefault();
});
$('.keyword', searchEl)
.val(placeholder)
.on('focus', function(e) {
var keyword = $(e.target);
if(keyword.val() == placeholder) {
keyword.removeClass('default-word').val('');
}
})
.on('blur', function(e) {
var keyword = $(e.target);
if(keyword.val() == '') {
keyword.addClass('default-word').val(placeholder);
}
});
//收藏
$('#header .icon-favor').on('click', function(e) {
var
title = document.title || '设计师网址导航',
url = window.location.href;
try {
if(window.sidebar && window.sidebar.addPanel) {
window.sidebar.addPanel(title, url, '');
}else if(window.external) {
window.external.AddFavorite(url, title);
}else {
throw 'NOT_SUPPORTED';
}
}catch(err) {
alert('您的浏览器不支持自动收藏,请使用Ctrl+D进行收藏');
}
e.preventDefault();
});
//加入首页
$('#header .icon-homepage').on('click', function(e) {
try {
if(window.netscape) {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
Components.classes['@mozilla.org/preferences-service;1']
.getService(Components. interfaces.nsIPrefBranch)
.setCharPref('browser.startup.homepage',window.location.href);
alert('成功设为首页');
}else if(window.external) {
document.body.style.behavior='url(#default#homepage)';
document.body.setHomePage(location.href);
}else {
throw 'NOT_SUPPORTED';
}
}catch(err) {
alert('您的浏览器不支持或不允许自动设置首页, 请通过浏览器菜单设置');
}
e.preventDefault();
});
//导航区域
$('#catalog,#website-map').on('click', '.website-list>li, .more-item', function(e) {
var tarEl = e.target;
if(tarEl.tagName == 'A' && $(tarEl).parents('section.active')[0]) {
e.stopPropagation();
}else {
if(tarEl.tagName != 'LI') {
tarEl = $(tarEl).parents('li')[0];
}
if(tarEl) {
var aEl = $('a', tarEl);
if(aEl.length) {
var src = aEl.attr('href');
if(aEl.attr('target') == '_blank') {
window.open(src);
}else {
location.href = src;
}
}
}
e.preventDefault();
}
});
//快捷导航
catalogAnimationRunning = false;
function highlightCatalog(target) {
// *效果1*
// var listItem = $('li', target);
// for(var i=0; i<6; i++) {
// $([listItem[i], listItem[i+6]]).delay(50*i).animate({opacity:0.1},200, function(){
// $(this).animate({opacity:1}, 200);
// });
// }
/*效果2*/
target.addClass('highlight');
setTimeout(function() {
target.removeClass('highlight');
}, 800);
/*效果3*/
// target.addClass('shake');
//setTimeout(function() {
// target.removeClass('shake');
// }, 2000);
}
$('#shortcut nav').on('click', function(e) {
if(e.target.tagName != 'A') {
return;
}
var keyword = $(e.target).attr('href').slice(1);
var target = $('section[data-catalog="'+keyword+'"]');
if(target[0] && !catalogAnimationRunning) {
catalogAnimationRunning = true;
var top = target.offset().top;
$('html, body').animate({
scrollTop: top-20
}, 200, function() {
highlightCatalog(target);
catalogAnimationRunning = false;
});
}
e.preventDefault();
});
//热门关键字
(function() {
var hotWordCtn = $('#content .tips .hot-words');
var titleStr = '<b>'+KeywordConfig.title+'</b>';
var curIndex = 0;
function showHotWord() {
var html = titleStr;
for(var i=curIndex; i<KeywordConfig.num+curIndex; i++) {
if(KeywordConfig.data[i]) {
html += '<a href="'+KeywordConfig.data[i].url+'" class="website" target="_blank"><strong>'+KeywordConfig.data[i].kw+'</strong></a>';
}
}
hotWordCtn.empty().append(html);
curIndex += KeywordConfig.num;
if(curIndex >= KeywordConfig.data.length) {
curIndex = 0;
}
var children = hotWordCtn.children();
for(var i=0; i<children.length; i++) {
$(children[i]).delay(100*i).animate({opacity:0.1},200, function(){
$(this).animate({opacity:1}, 200);
});
}
showHotWord.timeout = setTimeout(showHotWord, KeywordConfig.delay*1000);
}
hotWordCtn.on('mouseenter', function() {
if(showHotWord.timeout) {
clearTimeout(showHotWord.timeout);
}
}).on('mouseleave', function() {
showHotWord.timeout = setTimeout(showHotWord, KeywordConfig.delay*1000);
});
if(hotWordCtn[0] && KeywordConfig) {
showHotWord();
}
})();
//文章序号
$('#aside .classics-article-list li').each(function(i, item) {
$(item).css('backgroundPosition', '0 '+(6+i*-50)+'px');
});
//回顶部
var goToTopEl = $('#go-to-top');
$(window).scroll(function() {
if($(window).scrollTop() >0) {
goToTopEl.removeClass('hide');
}else {
goToTopEl.addClass('hide');
}
});
}); | 27979831/27979831.github.io | navigation/js/main.js | JavaScript | apache-2.0 | 7,078 |
// Copyright 2007 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 DOM pattern base class.
*
* @author [email protected] (Robby Walker)
*/
goog.provide('goog.dom.pattern.AbstractPattern');
goog.require('goog.dom.TagWalkType');
goog.require('goog.dom.pattern.MatchType');
/**
* Base pattern class for DOM matching.
*
* @constructor
*/
goog.dom.pattern.AbstractPattern = function() {
/**
* The first node matched by this pattern.
* @type {Node}
*/
this.matchedNode = null;
};
/**
* Reset any internal state this pattern keeps.
*/
goog.dom.pattern.AbstractPattern.prototype.reset = function() {
// The base implementation does nothing.
};
/**
* Test whether this pattern matches the given token.
*
* @param {Node} token Token to match against.
* @param {goog.dom.TagWalkType} type The type of token.
* @return {goog.dom.pattern.MatchType} `MATCH` if the pattern matches.
*/
goog.dom.pattern.AbstractPattern.prototype.matchToken = function(token, type) {
return goog.dom.pattern.MatchType.NO_MATCH;
};
| teppeis/closure-library | closure/goog/dom/pattern/abstractpattern.js | JavaScript | apache-2.0 | 1,621 |
/**
* Copyright 2015 The AMP HTML 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.
*/
import {Platform} from '../../src/service/platform-impl';
describe('Platform', () => {
let isIos;
let isAndroid;
let isChrome;
let isFirefox;
let isSafari;
let isIe;
let isEdge;
let isWebKit;
let isStandalone;
let majorVersion;
let iosVersion;
let iosMajorVersion;
let userAgent;
beforeEach(() => {
isIos = false;
isAndroid = false;
isChrome = false;
isSafari = false;
isFirefox = false;
isIe = false;
isEdge = false;
isWebKit = false;
isStandalone = false;
majorVersion = 0;
iosVersion = '';
iosMajorVersion = null;
userAgent = '';
});
function testUserAgent(userAgentString) {
const platform = new Platform({navigator: {userAgent: userAgentString}});
expect(platform.isIos()).to.equal(isIos);
expect(platform.isAndroid()).to.equal(isAndroid);
expect(platform.isChrome()).to.equal(isChrome);
expect(platform.isSafari()).to.equal(isSafari);
expect(platform.isFirefox()).to.equal(isFirefox);
expect(platform.isIe()).to.equal(isIe);
expect(platform.isEdge()).to.equal(isEdge);
expect(platform.isWebKit()).to.equal(isWebKit);
expect(platform.getMajorVersion()).to.equal(majorVersion);
expect(platform.getIosVersionString()).to.equal(iosVersion);
expect(platform.getIosMajorVersion()).to.equal(iosMajorVersion);
}
function testStandalone(userAgentString, standAloneBoolean) {
const platform = new Platform({
navigator: {
standalone: standAloneBoolean,
userAgent: userAgentString,
},
});
expect(platform.isStandalone()).to.equal(isStandalone);
}
it('should tolerate empty or null', () => {
testUserAgent(null);
testUserAgent('');
testUserAgent(' ');
testStandalone(null, null);
testStandalone('', null);
testStandalone(' ', null);
});
it('iPhone 6 Plus v8', () => {
isIos = true;
isSafari = true;
isWebKit = true;
majorVersion = 8;
iosVersion = '8.0';
iosMajorVersion = 8;
isStandalone = true;
userAgent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X)' +
' AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0' +
' Mobile/12A4345d Safari/600.1.4';
testUserAgent(userAgent);
testStandalone(userAgent, isStandalone);
});
it('iPhone 6 Plus v9', () => {
isIos = true;
isSafari = true;
isWebKit = true;
majorVersion = 9;
iosVersion = '9.3';
iosMajorVersion = 9;
isStandalone = true;
userAgent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_3 like Mac OS X)' +
' AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0' +
' Mobile/13E230 Safari/601.1';
testUserAgent(userAgent);
testStandalone(userAgent, isStandalone);
});
it('iPhone 6 Plus no version', () => {
isIos = true;
isSafari = true;
isWebKit = true;
majorVersion = 9;
iosVersion = '9.3';
iosMajorVersion = 9;
isStandalone = true;
userAgent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_3 like Mac OS X)' +
' AppleWebKit/601.1.46 (KHTML, like Gecko)' +
' Mobile/13E230 Safari/601.1';
testUserAgent(userAgent);
testStandalone(userAgent, isStandalone);
});
it('iPhone ios 10.2.1', () => {
isIos = true;
isSafari = true;
isWebKit = true;
majorVersion = 10;
iosVersion = '10.2.1';
iosMajorVersion = 10;
isStandalone = true;
userAgent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_2_1 like Mac OS X)' +
' AppleWebKit/602.4.6 (KHTML, like Gecko) Version/10.0' +
' Mobile/14D27 Safari/602.1';
testUserAgent(userAgent);
testStandalone(userAgent, isStandalone);
});
it('iPad 2', () => {
isIos = true;
isSafari = true;
isWebKit = true;
majorVersion = 7;
iosVersion = '7.0';
iosMajorVersion = 7;
isStandalone = true;
userAgent = 'Mozilla/5.0 (iPad; CPU OS 7_0 like Mac OS X)' +
' AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0' +
' Mobile/11A465 Safari/9537.53';
testUserAgent(userAgent);
testStandalone(userAgent, isStandalone);
});
it('iPhone ios 10.2, Chrome ios', () => {
isIos = true;
isChrome = true;
isWebKit = true;
majorVersion = 56;
iosVersion = '10.2';
iosMajorVersion = 10;
isStandalone = true;
userAgent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_2 like Mac OS X)' +
' AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.73' +
' Mobile/16D32 Safari/602.1';
testUserAgent(userAgent);
testStandalone(userAgent, isStandalone);
});
it('Desktop Safari', () => {
isSafari = true;
isWebKit = true;
majorVersion = 7;
userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) ' +
'AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 ' +
'Safari/7046A194A';
testUserAgent(userAgent);
testStandalone(userAgent, isStandalone);
});
it('Nexus 6 Chrome', () => {
isAndroid = true;
isChrome = true;
isWebKit = true;
majorVersion = 44;
userAgent = 'Mozilla/5.0 (Linux; Android 5.1.1; Nexus 6 Build/LYZ28E)' +
' AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.20' +
' Mobile Safari/537.36';
testUserAgent(userAgent);
testStandalone(userAgent, isStandalone);
});
it('Firefox', () => {
isFirefox = true;
majorVersion = 40;
userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) ' +
'Gecko/20100101 Firefox/40.1';
testUserAgent(userAgent);
testStandalone(userAgent, isStandalone);
});
it('Firefox ios', () => {
isIos = true;
isFirefox = true;
isWebKit = true;
majorVersion = 7;
iosVersion = '10.3.1';
iosMajorVersion = 10;
isStandalone = true;
userAgent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X)' +
' AppleWebKit/603.1.30 (KHTML, like Gecko) FxiOS/7.5b3349' +
' Mobile/14E304 Safari/603.1.30';
testUserAgent(userAgent);
testStandalone(userAgent, isStandalone);
});
it('IE', () => {
isIe = true;
majorVersion = 10;
userAgent = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 7.0;' +
' InfoPath.3; .NET CLR 3.1.40767; Trident/6.0; en-IN)';
testUserAgent(userAgent);
testStandalone(userAgent, isStandalone);
});
it('IEMobile', () => {
isIe = true;
majorVersion = 10;
userAgent = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0;' +
' Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)';
testUserAgent(userAgent);
testStandalone(userAgent, isStandalone);
});
it('Edge', () => {
isEdge = true;
majorVersion = 12;
userAgent = 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36' +
' (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36' +
' Edge/12.10136';
testUserAgent(userAgent);
testStandalone(userAgent, isStandalone);
});
});
| avimehta/amphtml | test/functional/test-platform.js | JavaScript | apache-2.0 | 7,502 |
/*
* L.Handler.TouchZoom is used internally by L.Map to add touch-zooming on Webkit-powered mobile browsers.
*/
L.Handler.TouchZoom = L.Handler.extend({
enable: function() {
if (!L.Browser.touch || this._enabled) { return; }
L.DomEvent.addListener(this._map._container, 'touchstart', this._onTouchStart, this);
this._enabled = true;
},
disable: function() {
if (!this._enabled) { return; }
L.DomEvent.removeListener(this._map._container, 'touchstart', this._onTouchStart, this);
this._enabled = false;
},
_onTouchStart: function(e) {
if (!e.touches || e.touches.length != 2 || this._map._animatingZoom) { return; }
var p1 = this._map.mouseEventToLayerPoint(e.touches[0]),
p2 = this._map.mouseEventToLayerPoint(e.touches[1]),
viewCenter = this._map.containerPointToLayerPoint(this._map.getSize().divideBy(2));
this._startCenter = p1.add(p2).divideBy(2, true);
this._startDist = p1.distanceTo(p2);
//this._startTransform = this._map._mapPane.style.webkitTransform;
this._moved = false;
this._zooming = true;
this._centerOffset = viewCenter.subtract(this._startCenter);
L.DomEvent.addListener(document, 'touchmove', this._onTouchMove, this);
L.DomEvent.addListener(document, 'touchend', this._onTouchEnd, this);
L.DomEvent.preventDefault(e);
},
_onTouchMove: function(e) {
if (!e.touches || e.touches.length != 2) { return; }
if (!this._moved) {
this._map._mapPane.className += ' leaflet-zoom-anim';
this._map._prepareTileBg();
this._moved = true;
}
var p1 = this._map.mouseEventToLayerPoint(e.touches[0]),
p2 = this._map.mouseEventToLayerPoint(e.touches[1]);
this._scale = p1.distanceTo(p2) / this._startDist;
this._delta = p1.add(p2).divideBy(2, true).subtract(this._startCenter);
/*
* Used 2 translates instead of transform-origin because of a very strange bug -
* it didn't count the origin on the first touch-zoom but worked correctly afterwards
*/
this._map._tileBg.style.webkitTransform = [
L.DomUtil.getTranslateString(this._delta),
L.DomUtil.getScaleString(this._scale, this._startCenter)
].join(" ");
L.DomEvent.preventDefault(e);
},
_onTouchEnd: function(e) {
if (!this._moved || !this._zooming) { return; }
this._zooming = false;
var oldZoom = this._map.getZoom(),
floatZoomDelta = Math.log(this._scale)/Math.LN2,
roundZoomDelta = (floatZoomDelta > 0 ? Math.ceil(floatZoomDelta) : Math.floor(floatZoomDelta)),
zoom = this._map._limitZoom(oldZoom + roundZoomDelta),
zoomDelta = zoom - oldZoom,
centerOffset = this._centerOffset.subtract(this._delta).divideBy(this._scale),
centerPoint = this._map.getPixelOrigin().add(this._startCenter).add(centerOffset),
center = this._map.unproject(centerPoint);
L.DomEvent.removeListener(document, 'touchmove', this._onTouchMove);
L.DomEvent.removeListener(document, 'touchend', this._onTouchEnd);
var finalScale = Math.pow(2, zoomDelta);
this._map._runAnimation(center, zoom, finalScale / this._scale, this._startCenter.add(centerOffset));
}
}); | coomsie/Leaflet | src/handler/TouchZoom.js | JavaScript | bsd-2-clause | 3,183 |
/*
* World Calendars
* https://github.com/alexcjohnson/world-calendars
*
* Batch-converted from kbwood/calendars
* Many thanks to Keith Wood and all of the contributors to the original project!
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* http://keith-wood.name/calendars.html
Hindi INDIA localisation for Gregorian/Julian calendars for jQuery.
Written by Pawan Kumar Singh. */
var main = require('../main');
var _gregorian = main.calendars.gregorian;
var _julian = main.calendars.julian;
_gregorian.prototype.regionalOptions['hi-IN'] = {
name: 'Gregorian',
epochs: ['BCE', 'CE'],
monthNames: ['जनवरी',' फरवरी', 'मार्च', 'अप्रैल', 'मई', 'जून','जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर'],
monthNamesShort: ['जन', 'फर', 'मार्च','अप्रै', 'मई', 'जून','जुलाई', 'अग', 'सित', 'अक्टू', 'नव', 'दिस'],
dayNames: ['रविवार', 'सोमवार', 'मंगलवार', 'बुधवार', 'गुरुवार', 'शुक्रवार', 'शनिवार'],
dayNamesShort: ['रवि', 'सोम', 'मंगल', 'बुध', 'गुरु', 'शुक्र', 'शनि'],
dayNamesMin: ['र','सो','मं','बु','गु','शु','श'],
digits: null,
dateFormat: 'dd/mm/yyyy',
firstDay: 1,
isRTL: false
};
if (_julian) {
_julian.prototype.regionalOptions['hi-IN'] =
_gregorian.prototype.regionalOptions['hi-IN'];
}
| useabode/redash | node_modules/world-calendars/dist/regional/hi-IN.js | JavaScript | bsd-2-clause | 1,725 |
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
import React, {Component} from 'react';
import Link from 'gatsby-link';
import {Icon} from 'antd';
import './Footer.css';
import FacebookOSSLogo from './FacebookOSSLogo';
export default class Footer extends Component<{}> {
render() {
return (
<div className="Footer">
<a href="https://code.facebook.com/projects/" className="logoOSS">
<FacebookOSSLogo />
Facebook Open Source
</a>
<div className="SocialNetwork">
<a href="https://github.com/facebook/yoga">GitHub</a>
<a href="https://twitter.com/yogalayout">Twitter</a>
</div>
</div>
);
}
}
| facebook/css-layout | website/src/components/Footer.js | JavaScript | bsd-3-clause | 851 |
"aaaaaaaaaa,aaaaaaaaaaaaaaa".replace(/^(a+)\1*,\1+$/,"$1")
| daejunpark/jsaf | tests/interpreter_tests/regexp-17.js | JavaScript | bsd-3-clause | 59 |
// ==========================================================================
// Project: SproutCore - JavaScript Application Framework
// Copyright: ©2006-2011 Strobe Inc. and contributors.
// Portions ©2008-2011 Apple Inc. All rights reserved.
// License: Licensed under MIT license (see license.js)
// ==========================================================================
| darkrsw/safe | tests/clone_detector_tests/sproutcore/frameworks/bootstrap/core.js | JavaScript | bsd-3-clause | 398 |
/* ###########################################################################
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() {}
| fbiville/annotation-processing-ftw | doc/javac/8/windows/javac_files/developer.js | JavaScript | mit | 4,902 |
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();
});
});
| davidgf/moonmail-models | tests/click_report.test.js | JavaScript | mit | 1,612 |
/*!
* 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 );
| michael829/jquery-builder | dist/1.10.2/jquery-css-dimensions-effects-offset-wrap.js | JavaScript | mit | 226,026 |
'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();
};
| data-forge/data-forge-js | src/iterators/take.js | JavaScript | mit | 524 |
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;
});
| tomek-f/shittets | require-js-amd/require-zepto-lodash/static/js/lib/lodash-amd/internal/arrayMap.js | JavaScript | mit | 609 |
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* 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 | vinaymayar/maygh | src/client/util-sha1.js | JavaScript | mit | 5,625 |
/**
@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);
}
| dgeb/ember.js | packages/ember-routing-htmlbars/lib/helpers/action.js | JavaScript | mit | 8,975 |
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';
| RemusMar/three.js | src/Three.js | JavaScript | mit | 8,725 |
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',
);
},
);
});
| mmkassem/gitlabhq | spec/frontend/code_navigation/utils/index_spec.js | JavaScript | mit | 1,439 |
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(`_`)
}
| mingaldrichgan/gatsby | packages/gatsby/src/utils/webpack-helpers.js | JavaScript | mit | 220 |
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);
});
| danlevan/express-dot-engine | examples/index.js | JavaScript | mit | 1,097 |
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);
};
| zdqk/pomelo | lib/connectors/hybrid/switcher.js | JavaScript | mit | 2,721 |
'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',
};
}]);
| ZakMooney/cucumber-frontend | client/components/payloads/payloads.directives.js | JavaScript | mit | 1,390 |
/* 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;
}));
| joeyparrish/cdnjs | ajax/libs/flatpickr/4.6.0/flatpickr.js | JavaScript | mit | 117,429 |
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;
}); | beni55/sculptgl | src/gui/GuiConfig.js | JavaScript | mit | 677 |
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);
| VoiSmart/Rocket.Chat | client/sidebar/search/Row.js | JavaScript | mit | 782 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.