code
stringlengths 2
1.05M
|
---|
/**
* interact.js v1.1.2
*
* Copyright (c) 2012, 2013, 2014 Taye Adeyemi <[email protected]>
* Open source under the MIT License.
* https://raw.github.com/taye/interact.js/master/LICENSE
*/
(function () {
'use strict';
var document = window.document,
SVGElement = window.SVGElement || blank,
SVGSVGElement = window.SVGSVGElement || blank,
SVGElementInstance = window.SVGElementInstance || blank,
HTMLElement = window.HTMLElement || window.Element,
PointerEvent = (window.PointerEvent || window.MSPointerEvent),
pEventTypes,
hypot = Math.hypot || function (x, y) { return Math.sqrt(x * x + y * y); },
tmpXY = {}, // reduce object creation in getXY()
documents = [], // all documents being listened to
interactables = [], // all set interactables
interactions = [], // all interactions
dynamicDrop = false,
// {
// type: {
// selectors: ['selector', ...],
// contexts : [document, ...],
// listeners: [[listener, useCapture], ...]
// }
// }
delegatedEvents = {},
defaultOptions = {
draggable : false,
dragAxis : 'xy',
dropzone : false,
accept : null,
dropOverlap : 'pointer',
resizable : false,
squareResize: false,
resizeAxis : 'xy',
gesturable : false,
// no more than this number of actions can target the Interactable
dragMax : 1,
resizeMax : 1,
gestureMax: 1,
// no more than this number of actions can target the same
// element of this Interactable simultaneously
dragMaxPerElement : 1,
resizeMaxPerElement : 1,
gestureMaxPerElement: 1,
pointerMoveTolerance: 1,
actionChecker: null,
styleCursor: true,
preventDefault: 'auto',
// aww snap
snap: {
mode : 'grid',
endOnly : false,
actions : ['drag'],
range : Infinity,
grid : { x: 100, y: 100 },
gridOffset : { x: 0, y: 0 },
anchors : [],
paths : [],
elementOrigin: null,
arrayTypes : /^anchors$|^paths$|^actions$/,
objectTypes : /^grid$|^gridOffset$|^elementOrigin$/,
stringTypes : /^mode$/,
numberTypes : /^range$/,
boolTypes : /^endOnly$/
},
snapEnabled: false,
restrict: {
drag: null,
resize: null,
gesture: null,
endOnly: false
},
restrictEnabled: false,
autoScroll: {
container : null, // the item that is scrolled (Window or HTMLElement)
margin : 60,
speed : 300, // the scroll speed in pixels per second
numberTypes : /^margin$|^speed$/
},
autoScrollEnabled: false,
inertia: {
resistance : 10, // the lambda in exponential decay
minSpeed : 100, // target speed must be above this for inertia to start
endSpeed : 10, // the speed at which inertia is slow enough to stop
allowResume : true, // allow resuming an action in inertia phase
zeroResumeDelta : false, // if an action is resumed after launch, set dx/dy to 0
smoothEndDuration: 300, // animate to snap/restrict endOnly if there's no inertia
actions : ['drag', 'resize'], // allow inertia on these actions. gesture might not work
numberTypes: /^resistance$|^minSpeed$|^endSpeed$|^smoothEndDuration$/,
arrayTypes : /^actions$/,
boolTypes : /^(allowResume|zeroResumeDelta)$/
},
inertiaEnabled: false,
origin : { x: 0, y: 0 },
deltaSource : 'page',
},
// Things related to autoScroll
autoScroll = {
interaction: null,
i: null, // the handle returned by window.setInterval
x: 0, y: 0, // Direction each pulse is to scroll in
// scroll the window by the values in scroll.x/y
scroll: function () {
var options = autoScroll.interaction.target.options.autoScroll,
container = options.container || getWindow(autoScroll.interaction.element),
now = new Date().getTime(),
// change in time in seconds
dt = (now - autoScroll.prevTime) / 1000,
// displacement
s = options.speed * dt;
if (s >= 1) {
if (isWindow(container)) {
container.scrollBy(autoScroll.x * s, autoScroll.y * s);
}
else if (container) {
container.scrollLeft += autoScroll.x * s;
container.scrollTop += autoScroll.y * s;
}
autoScroll.prevTime = now;
}
if (autoScroll.isScrolling) {
cancelFrame(autoScroll.i);
autoScroll.i = reqFrame(autoScroll.scroll);
}
},
edgeMove: function (event) {
var interaction,
target,
doAutoscroll = false;
for (var i = 0; i < interactions.length; i++) {
interaction = interactions[i];
target = interaction.target;
if (target && target.options.autoScrollEnabled
&& (interaction.dragging || interaction.resizing)) {
doAutoscroll = true;
break;
}
}
if (!doAutoscroll) { return; }
var top,
right,
bottom,
left,
options = target.options.autoScroll,
container = options.container || getWindow(interaction.element);
if (isWindow(container)) {
left = event.clientX < autoScroll.margin;
top = event.clientY < autoScroll.margin;
right = event.clientX > container.innerWidth - autoScroll.margin;
bottom = event.clientY > container.innerHeight - autoScroll.margin;
}
else {
var rect = getElementRect(container);
left = event.clientX < rect.left + autoScroll.margin;
top = event.clientY < rect.top + autoScroll.margin;
right = event.clientX > rect.right - autoScroll.margin;
bottom = event.clientY > rect.bottom - autoScroll.margin;
}
autoScroll.x = (right ? 1: left? -1: 0);
autoScroll.y = (bottom? 1: top? -1: 0);
if (!autoScroll.isScrolling) {
// set the autoScroll properties to those of the target
autoScroll.margin = options.margin;
autoScroll.speed = options.speed;
autoScroll.start(interaction);
}
},
isScrolling: false,
prevTime: 0,
start: function (interaction) {
autoScroll.isScrolling = true;
cancelFrame(autoScroll.i);
autoScroll.interaction = interaction;
autoScroll.prevTime = new Date().getTime();
autoScroll.i = reqFrame(autoScroll.scroll);
},
stop: function () {
autoScroll.isScrolling = false;
cancelFrame(autoScroll.i);
}
},
// Does the browser support touch input?
supportsTouch = (('ontouchstart' in window) || window.DocumentTouch && document instanceof window.DocumentTouch),
// Does the browser support PointerEvents
supportsPointerEvent = !!PointerEvent,
// Less Precision with touch input
margin = supportsTouch || supportsPointerEvent? 20: 10,
// for ignoring browser's simulated mouse events
prevTouchTime = 0,
// Allow this many interactions to happen simultaneously
maxInteractions = 1,
actionCursors = {
drag : 'move',
resizex : 'e-resize',
resizey : 's-resize',
resizexy: 'se-resize',
gesture : ''
},
actionIsEnabled = {
drag : true,
resize : true,
gesture: true
},
// because Webkit and Opera still use 'mousewheel' event type
wheelEvent = 'onmousewheel' in document? 'mousewheel': 'wheel',
eventTypes = [
'dragstart',
'dragmove',
'draginertiastart',
'dragend',
'dragenter',
'dragleave',
'dropactivate',
'dropdeactivate',
'dropmove',
'drop',
'resizestart',
'resizemove',
'resizeinertiastart',
'resizeend',
'gesturestart',
'gesturemove',
'gestureinertiastart',
'gestureend',
'down',
'move',
'up',
'cancel',
'tap',
'doubletap',
'hold'
],
globalEvents = {},
// Opera Mobile must be handled differently
isOperaMobile = navigator.appName == 'Opera' &&
supportsTouch &&
navigator.userAgent.match('Presto'),
// scrolling doesn't change the result of
// getBoundingClientRect/getClientRects on iOS <=7 but it does on iOS 8
isIOS7orLower = (/iP(hone|od|ad)/.test(navigator.platform)
&& /OS [1-7][^\d]/.test(navigator.appVersion)),
// prefix matchesSelector
prefixedMatchesSelector = 'matchesSelector' in Element.prototype?
'matchesSelector': 'webkitMatchesSelector' in Element.prototype?
'webkitMatchesSelector': 'mozMatchesSelector' in Element.prototype?
'mozMatchesSelector': 'oMatchesSelector' in Element.prototype?
'oMatchesSelector': 'msMatchesSelector',
// will be polyfill function if browser is IE8
ie8MatchesSelector,
// native requestAnimationFrame or polyfill
reqFrame = window.requestAnimationFrame,
cancelFrame = window.cancelAnimationFrame,
// Events wrapper
events = (function () {
var useAttachEvent = ('attachEvent' in window) && !('addEventListener' in window),
addEvent = useAttachEvent? 'attachEvent': 'addEventListener',
removeEvent = useAttachEvent? 'detachEvent': 'removeEventListener',
on = useAttachEvent? 'on': '',
elements = [],
targets = [],
attachedListeners = [];
function add (element, type, listener, useCapture) {
var elementIndex = indexOf(elements, element),
target = targets[elementIndex];
if (!target) {
target = {
events: {},
typeCount: 0
};
elementIndex = elements.push(element) - 1;
targets.push(target);
attachedListeners.push((useAttachEvent ? {
supplied: [],
wrapped : [],
useCount: []
} : null));
}
if (!target.events[type]) {
target.events[type] = [];
target.typeCount++;
}
if (!contains(target.events[type], listener)) {
var ret;
if (useAttachEvent) {
var listeners = attachedListeners[elementIndex],
listenerIndex = indexOf(listeners.supplied, listener);
var wrapped = listeners.wrapped[listenerIndex] || function (event) {
if (!event.immediatePropagationStopped) {
event.target = event.srcElement;
event.currentTarget = element;
event.preventDefault = event.preventDefault || preventDef;
event.stopPropagation = event.stopPropagation || stopProp;
event.stopImmediatePropagation = event.stopImmediatePropagation || stopImmProp;
if (/mouse|click/.test(event.type)) {
event.pageX = event.clientX + element.ownerDdocument.documentElement.scrollLeft;
event.pageY = event.clientY + element.ownerDdocument.documentElement.scrollTop;
}
listener(event);
}
};
ret = element[addEvent](on + type, wrapped, Boolean(useCapture));
if (listenerIndex === -1) {
listeners.supplied.push(listener);
listeners.wrapped.push(wrapped);
listeners.useCount.push(1);
}
else {
listeners.useCount[listenerIndex]++;
}
}
else {
ret = element[addEvent](type, listener, useCapture || false);
}
target.events[type].push(listener);
return ret;
}
}
function remove (element, type, listener, useCapture) {
var i,
elementIndex = indexOf(elements, element),
target = targets[elementIndex],
listeners,
listenerIndex,
wrapped = listener;
if (!target || !target.events) {
return;
}
if (useAttachEvent) {
listeners = attachedListeners[elementIndex];
listenerIndex = indexOf(listeners.supplied, listener);
wrapped = listeners.wrapped[listenerIndex];
}
if (type === 'all') {
for (type in target.events) {
if (target.events.hasOwnProperty(type)) {
remove(element, type, 'all');
}
}
return;
}
if (target.events[type]) {
var len = target.events[type].length;
if (listener === 'all') {
for (i = 0; i < len; i++) {
remove(element, type, target.events[type][i], Boolean(useCapture));
}
} else {
for (i = 0; i < len; i++) {
if (target.events[type][i] === listener) {
element[removeEvent](on + type, wrapped, useCapture || false);
target.events[type].splice(i, 1);
if (useAttachEvent && listeners) {
listeners.useCount[listenerIndex]--;
if (listeners.useCount[listenerIndex] === 0) {
listeners.supplied.splice(listenerIndex, 1);
listeners.wrapped.splice(listenerIndex, 1);
listeners.useCount.splice(listenerIndex, 1);
}
}
break;
}
}
}
if (target.events[type] && target.events[type].length === 0) {
target.events[type] = null;
target.typeCount--;
}
}
if (!target.typeCount) {
targets.splice(elementIndex);
elements.splice(elementIndex);
attachedListeners.splice(elementIndex);
}
}
function preventDef () {
this.returnValue = false;
}
function stopProp () {
this.cancelBubble = true;
}
function stopImmProp () {
this.cancelBubble = true;
this.immediatePropagationStopped = true;
}
return {
add: add,
remove: remove,
useAttachEvent: useAttachEvent,
_elements: elements,
_targets: targets,
_attachedListeners: attachedListeners
};
}());
function blank () {}
function isElement (o) {
if (!o || (typeof o !== 'object')) { return false; }
var _window = getWindow(o) || window;
return (/object|function/.test(typeof _window.Element)
? o instanceof _window.Element //DOM2
: o.nodeType === 1 && typeof o.nodeName === "string");
}
function isWindow (thing) { return !!(thing && thing.Window) && (thing instanceof thing.Window); }
function isArray (thing) {
return isObject(thing)
&& (typeof thing.length !== undefined)
&& isFunction(thing.splice);
}
function isObject (thing) { return !!thing && (typeof thing === 'object'); }
function isFunction (thing) { return typeof thing === 'function'; }
function isNumber (thing) { return typeof thing === 'number' ; }
function isBool (thing) { return typeof thing === 'boolean' ; }
function isString (thing) { return typeof thing === 'string' ; }
function trySelector (value) {
if (!isString(value)) { return false; }
// an exception will be raised if it is invalid
document.querySelector(value);
return true;
}
function extend (dest, source) {
for (var prop in source) {
dest[prop] = source[prop];
}
return dest;
}
function copyCoords (dest, src) {
dest.page = dest.page || {};
dest.page.x = src.page.x;
dest.page.y = src.page.y;
dest.client = dest.client || {};
dest.client.x = src.client.x;
dest.client.y = src.client.y;
dest.timeStamp = src.timeStamp;
}
function setEventXY (targetObj, pointer, interaction) {
if (!pointer) {
if (interaction.pointerIds.length > 1) {
pointer = touchAverage(interaction.pointers);
}
else {
pointer = interaction.pointers[0];
}
}
getPageXY(pointer, tmpXY, interaction);
targetObj.page.x = tmpXY.x;
targetObj.page.y = tmpXY.y;
getClientXY(pointer, tmpXY, interaction);
targetObj.client.x = tmpXY.x;
targetObj.client.y = tmpXY.y;
targetObj.timeStamp = new Date().getTime();
}
function setEventDeltas (targetObj, prev, cur) {
targetObj.page.x = cur.page.x - prev.page.x;
targetObj.page.y = cur.page.y - prev.page.y;
targetObj.client.x = cur.client.x - prev.client.x;
targetObj.client.y = cur.client.y - prev.client.y;
targetObj.timeStamp = new Date().getTime() - prev.timeStamp;
// set pointer velocity
var dt = Math.max(targetObj.timeStamp / 1000, 0.001);
targetObj.page.speed = hypot(targetObj.page.x, targetObj.page.y) / dt;
targetObj.page.vx = targetObj.page.x / dt;
targetObj.page.vy = targetObj.page.y / dt;
targetObj.client.speed = hypot(targetObj.client.x, targetObj.page.y) / dt;
targetObj.client.vx = targetObj.client.x / dt;
targetObj.client.vy = targetObj.client.y / dt;
}
// Get specified X/Y coords for mouse or event.touches[0]
function getXY (type, pointer, xy) {
xy = xy || {};
type = type || 'page';
xy.x = pointer[type + 'X'];
xy.y = pointer[type + 'Y'];
return xy;
}
function getPageXY (pointer, page, interaction) {
page = page || {};
if (pointer instanceof InteractEvent) {
if (/inertiastart/.test(pointer.type)) {
interaction = interaction || pointer.interaction;
extend(page, interaction.inertiaStatus.upCoords.page);
page.x += interaction.inertiaStatus.sx;
page.y += interaction.inertiaStatus.sy;
}
else {
page.x = pointer.pageX;
page.y = pointer.pageY;
}
}
// Opera Mobile handles the viewport and scrolling oddly
else if (isOperaMobile) {
getXY('screen', pointer, page);
page.x += window.scrollX;
page.y += window.scrollY;
}
else {
getXY('page', pointer, page);
}
return page;
}
function getClientXY (pointer, client, interaction) {
client = client || {};
if (pointer instanceof InteractEvent) {
if (/inertiastart/.test(pointer.type)) {
extend(client, interaction.inertiaStatus.upCoords.client);
client.x += interaction.inertiaStatus.sx;
client.y += interaction.inertiaStatus.sy;
}
else {
client.x = pointer.clientX;
client.y = pointer.clientY;
}
}
else {
// Opera Mobile handles the viewport and scrolling oddly
getXY(isOperaMobile? 'screen': 'client', pointer, client);
}
return client;
}
function getScrollXY (win) {
win = win || window;
return {
x: win.scrollX || win.document.documentElement.scrollLeft,
y: win.scrollY || win.document.documentElement.scrollTop
};
}
function getPointerId (pointer) {
return isNumber(pointer.pointerId)? pointer.pointerId : pointer.identifier;
}
function getActualElement (element) {
return (element instanceof SVGElementInstance
? element.correspondingUseElement
: element);
}
function getWindow (node) {
if (isWindow(node)) {
return node;
}
var rootNode = (node.ownerDocument || node);
return rootNode.defaultView || rootNode.parentWindow;
}
function getElementRect (element) {
var scroll = isIOS7orLower
? { x: 0, y: 0 }
: getScrollXY(getWindow(element)),
clientRect = (element instanceof SVGElement)?
element.getBoundingClientRect():
element.getClientRects()[0];
return clientRect && {
left : clientRect.left + scroll.x,
right : clientRect.right + scroll.x,
top : clientRect.top + scroll.y,
bottom: clientRect.bottom + scroll.y,
width : clientRect.width || clientRect.right - clientRect.left,
height: clientRect.heigh || clientRect.bottom - clientRect.top
};
}
function getTouchPair (event) {
var touches = [];
// array of touches is supplied
if (isArray(event)) {
touches[0] = event[0];
touches[1] = event[1];
}
// an event
else {
if (event.type === 'touchend') {
if (event.touches.length === 1) {
touches[0] = event.touches[0];
touches[1] = event.changedTouches[0];
}
else if (event.touches.length === 0) {
touches[0] = event.changedTouches[0];
touches[1] = event.changedTouches[1];
}
}
else {
touches[0] = event.touches[0];
touches[1] = event.touches[1];
}
}
return touches;
}
function touchAverage (event) {
var touches = getTouchPair(event);
return {
pageX: (touches[0].pageX + touches[1].pageX) / 2,
pageY: (touches[0].pageY + touches[1].pageY) / 2,
clientX: (touches[0].clientX + touches[1].clientX) / 2,
clientY: (touches[0].clientY + touches[1].clientY) / 2
};
}
function touchBBox (event) {
if (!event.length && !(event.touches && event.touches.length > 1)) {
return;
}
var touches = getTouchPair(event),
minX = Math.min(touches[0].pageX, touches[1].pageX),
minY = Math.min(touches[0].pageY, touches[1].pageY),
maxX = Math.max(touches[0].pageX, touches[1].pageX),
maxY = Math.max(touches[0].pageY, touches[1].pageY);
return {
x: minX,
y: minY,
left: minX,
top: minY,
width: maxX - minX,
height: maxY - minY
};
}
function touchDistance (event, deltaSource) {
deltaSource = deltaSource || defaultOptions.deltaSource;
var sourceX = deltaSource + 'X',
sourceY = deltaSource + 'Y',
touches = getTouchPair(event);
var dx = touches[0][sourceX] - touches[1][sourceX],
dy = touches[0][sourceY] - touches[1][sourceY];
return hypot(dx, dy);
}
function touchAngle (event, prevAngle, deltaSource) {
deltaSource = deltaSource || defaultOptions.deltaSource;
var sourceX = deltaSource + 'X',
sourceY = deltaSource + 'Y',
touches = getTouchPair(event),
dx = touches[0][sourceX] - touches[1][sourceX],
dy = touches[0][sourceY] - touches[1][sourceY],
angle = 180 * Math.atan(dy / dx) / Math.PI;
if (isNumber(prevAngle)) {
var dr = angle - prevAngle,
drClamped = dr % 360;
if (drClamped > 315) {
angle -= 360 + (angle / 360)|0 * 360;
}
else if (drClamped > 135) {
angle -= 180 + (angle / 360)|0 * 360;
}
else if (drClamped < -315) {
angle += 360 + (angle / 360)|0 * 360;
}
else if (drClamped < -135) {
angle += 180 + (angle / 360)|0 * 360;
}
}
return angle;
}
function getOriginXY (interactable, element) {
var origin = interactable
? interactable.options.origin
: defaultOptions.origin;
if (origin === 'parent') {
origin = element.parentNode;
}
else if (origin === 'self') {
origin = interactable.getRect(element);
}
else if (trySelector(origin)) {
origin = closest(element, origin) || { x: 0, y: 0 };
}
if (isFunction(origin)) {
origin = origin(interactable && element);
}
if (isElement(origin)) {
origin = getElementRect(origin);
}
origin.x = ('x' in origin)? origin.x : origin.left;
origin.y = ('y' in origin)? origin.y : origin.top;
return origin;
}
// http://stackoverflow.com/a/5634528/2280888
function _getQBezierValue(t, p1, p2, p3) {
var iT = 1 - t;
return iT * iT * p1 + 2 * iT * t * p2 + t * t * p3;
}
function getQuadraticCurvePoint(startX, startY, cpX, cpY, endX, endY, position) {
return {
x: _getQBezierValue(position, startX, cpX, endX),
y: _getQBezierValue(position, startY, cpY, endY)
};
}
// http://gizma.com/easing/
function easeOutQuad (t, b, c, d) {
t /= d;
return -c * t*(t-2) + b;
}
function nodeContains (parent, child) {
while ((child = child.parentNode)) {
if (child === parent) {
return true;
}
}
return false;
}
function closest (child, selector) {
var parent = child.parentNode;
while (isElement(parent)) {
if (matchesSelector(parent, selector)) { return parent; }
parent = parent.parentNode;
}
return null;
}
function inContext (interactable, element) {
return interactable._context === element.ownerDocument
|| nodeContains(interactable._context, element);
}
function testIgnore (interactable, interactableElement, element) {
var ignoreFrom = interactable.options.ignoreFrom;
if (!ignoreFrom
// limit test to the interactable's element and its children
|| !isElement(element) || element === interactableElement.parentNode) {
return false;
}
if (isString(ignoreFrom)) {
return matchesSelector(element, ignoreFrom) || testIgnore(interactable, element.parentNode);
}
else if (isElement(ignoreFrom)) {
return element === ignoreFrom || nodeContains(ignoreFrom, element);
}
return false;
}
function testAllow (interactable, interactableElement, element) {
var allowFrom = interactable.options.allowFrom;
if (!allowFrom) { return true; }
// limit test to the interactable's element and its children
if (!isElement(element) || element === interactableElement.parentNode) {
return false;
}
if (isString(allowFrom)) {
return matchesSelector(element, allowFrom) || testAllow(interactable, element.parentNode);
}
else if (isElement(allowFrom)) {
return element === allowFrom || nodeContains(allowFrom, element);
}
return false;
}
function checkAxis (axis, interactable) {
if (!interactable) { return false; }
var thisAxis = interactable.options.dragAxis;
return (axis === 'xy' || thisAxis === 'xy' || thisAxis === axis);
}
function checkSnap (interactable, action) {
var options = interactable.options;
if (/^resize/.test(action)) {
action = 'resize';
}
return action !== 'gesture' && options.snapEnabled && contains(options.snap.actions, action);
}
function checkRestrict (interactable, action) {
var options = interactable.options;
if (/^resize/.test(action)) {
action = 'resize';
}
return options.restrictEnabled && options.restrict[action];
}
function withinInteractionLimit (interactable, element, action) {
action = /resize/.test(action)? 'resize': action;
var options = interactable.options,
maxActions = options[action + 'Max'],
maxPerElement = options[action + 'MaxPerElement'],
activeInteractions = 0,
targetCount = 0,
targetElementCount = 0;
for (var i = 0, len = interactions.length; i < len; i++) {
var interaction = interactions[i],
otherAction = /resize/.test(interaction.prepared)? 'resize': interaction.prepared,
active = interaction.interacting();
if (!active) { continue; }
activeInteractions++;
if (activeInteractions >= maxInteractions) {
return false;
}
if (interaction.target !== interactable) { continue; }
targetCount += (otherAction === action)|0;
if (targetCount >= maxActions) {
return false;
}
if (interaction.element === element) {
targetElementCount++;
if (otherAction !== action || targetElementCount >= maxPerElement) {
return false;
}
}
}
return maxInteractions > 0;
}
// Test for the element that's "above" all other qualifiers
function indexOfDeepestElement (elements) {
var dropzone,
deepestZone = elements[0],
index = deepestZone? 0: -1,
parent,
deepestZoneParents = [],
dropzoneParents = [],
child,
i,
n;
for (i = 1; i < elements.length; i++) {
dropzone = elements[i];
// an element might belong to multiple selector dropzones
if (!dropzone || dropzone === deepestZone) {
continue;
}
if (!deepestZone) {
deepestZone = dropzone;
index = i;
continue;
}
// check if the deepest or current are document.documentElement or document.rootElement
// - if the current dropzone is, do nothing and continue
if (dropzone.parentNode === dropzone.ownerDocument) {
continue;
}
// - if deepest is, update with the current dropzone and continue to next
else if (deepestZone.parentNode === dropzone.ownerDocument) {
deepestZone = dropzone;
index = i;
continue;
}
if (!deepestZoneParents.length) {
parent = deepestZone;
while (parent.parentNode && parent.parentNode !== parent.ownerDocument) {
deepestZoneParents.unshift(parent);
parent = parent.parentNode;
}
}
// if this element is an svg element and the current deepest is
// an HTMLElement
if (deepestZone instanceof HTMLElement
&& dropzone instanceof SVGElement
&& !(dropzone instanceof SVGSVGElement)) {
if (dropzone === deepestZone.parentNode) {
continue;
}
parent = dropzone.ownerSVGElement;
}
else {
parent = dropzone;
}
dropzoneParents = [];
while (parent.parentNode !== parent.ownerDocument) {
dropzoneParents.unshift(parent);
parent = parent.parentNode;
}
n = 0;
// get (position of last common ancestor) + 1
while (dropzoneParents[n] && dropzoneParents[n] === deepestZoneParents[n]) {
n++;
}
var parents = [
dropzoneParents[n - 1],
dropzoneParents[n],
deepestZoneParents[n]
];
child = parents[0].lastChild;
while (child) {
if (child === parents[1]) {
deepestZone = dropzone;
index = i;
deepestZoneParents = [];
break;
}
else if (child === parents[2]) {
break;
}
child = child.previousSibling;
}
}
return index;
}
function Interaction () {
this.target = null; // current interactable being interacted with
this.element = null; // the target element of the interactable
this.dropTarget = null; // the dropzone a drag target might be dropped into
this.dropElement = null; // the element at the time of checking
this.prevDropTarget = null; // the dropzone that was recently dragged away from
this.prevDropElement = null; // the element at the time of checking
this.prepared = null; // Action that's ready to be fired on next move event
this.matches = []; // all selectors that are matched by target element
this.matchElements = []; // corresponding elements
this.inertiaStatus = {
active : false,
smoothEnd : false,
startEvent: null,
upCoords: {},
xe: 0, ye: 0,
sx: 0, sy: 0,
t0: 0,
vx0: 0, vys: 0,
duration: 0,
resumeDx: 0,
resumeDy: 0,
lambda_v0: 0,
one_ve_v0: 0,
i : null
};
if (isFunction(Function.prototype.bind)) {
this.boundInertiaFrame = this.inertiaFrame.bind(this);
this.boundSmoothEndFrame = this.smoothEndFrame.bind(this);
}
else {
var that = this;
this.boundInertiaFrame = function () { return that.inertiaFrame(); };
this.boundSmoothEndFrame = function () { return that.smoothEndFrame(); };
}
this.activeDrops = {
dropzones: [], // the dropzones that are mentioned below
elements : [], // elements of dropzones that accept the target draggable
rects : [] // the rects of the elements mentioned above
};
// keep track of added pointers
this.pointers = [];
this.pointerIds = [];
this.downTargets = [];
this.downTimes = [];
this.holdTimers = [];
// Previous native pointer move event coordinates
this.prevCoords = {
page : { x: 0, y: 0 },
client : { x: 0, y: 0 },
timeStamp: 0
};
// current native pointer move event coordinates
this.curCoords = {
page : { x: 0, y: 0 },
client : { x: 0, y: 0 },
timeStamp: 0
};
// Starting InteractEvent pointer coordinates
this.startCoords = {
page : { x: 0, y: 0 },
client : { x: 0, y: 0 },
timeStamp: 0
};
// Change in coordinates and time of the pointer
this.pointerDelta = {
page : { x: 0, y: 0, vx: 0, vy: 0, speed: 0 },
client : { x: 0, y: 0, vx: 0, vy: 0, speed: 0 },
timeStamp: 0
};
this.downEvent = null; // pointerdown/mousedown/touchstart event
this.downPointer = {};
this.prevEvent = null; // previous action event
this.tapTime = 0; // time of the most recent tap event
this.prevTap = null;
this.startOffset = { left: 0, right: 0, top: 0, bottom: 0 };
this.restrictOffset = { left: 0, right: 0, top: 0, bottom: 0 };
this.snapOffset = { x: 0, y: 0};
this.gesture = {
start: { x: 0, y: 0 },
startDistance: 0, // distance between two touches of touchStart
prevDistance : 0,
distance : 0,
scale: 1, // gesture.distance / gesture.startDistance
startAngle: 0, // angle of line joining two touches
prevAngle : 0 // angle of the previous gesture event
};
this.snapStatus = {
x : 0, y : 0,
dx : 0, dy : 0,
realX : 0, realY : 0,
snappedX: 0, snappedY: 0,
anchors : [],
paths : [],
locked : false,
changed : false
};
this.restrictStatus = {
dx : 0, dy : 0,
restrictedX: 0, restrictedY: 0,
snap : null,
restricted : false,
changed : false
};
this.restrictStatus.snap = this.snapStatus;
this.pointerIsDown = false;
this.pointerWasMoved = false;
this.gesturing = false;
this.dragging = false;
this.resizing = false;
this.resizeAxes = 'xy';
this.mouse = false;
interactions.push(this);
}
Interaction.prototype = {
getPageXY : function (pointer, xy) { return getPageXY(pointer, xy, this); },
getClientXY: function (pointer, xy) { return getClientXY(pointer, xy, this); },
setEventXY : function (target, ptr) { return setEventXY(target, ptr, this); },
pointerOver: function (pointer, event, eventTarget) {
if (this.prepared || !this.mouse) { return; }
var curMatches = [],
curMatchElements = [],
prevTargetElement = this.element;
this.addPointer(pointer);
if (this.target
&& (testIgnore(this.target, this.element, eventTarget)
|| !testAllow(this.target, this.element, eventTarget)
|| !withinInteractionLimit(this.target, this.element, this.prepared))) {
// if the eventTarget should be ignored or shouldn't be allowed
// clear the previous target
this.target = null;
this.element = null;
this.matches = [];
this.matchElements = [];
}
var elementInteractable = interactables.get(eventTarget),
elementAction = (elementInteractable
&& !testIgnore(elementInteractable, eventTarget, eventTarget)
&& testAllow(elementInteractable, eventTarget, eventTarget)
&& validateAction(
elementInteractable.getAction(pointer, this, eventTarget),
elementInteractable));
elementAction = elementInteractable && withinInteractionLimit(elementInteractable, eventTarget, elementAction)
? elementAction
: null;
function pushCurMatches (interactable, selector) {
if (interactable
&& inContext(interactable, eventTarget)
&& !testIgnore(interactable, eventTarget, eventTarget)
&& testAllow(interactable, eventTarget, eventTarget)
&& matchesSelector(eventTarget, selector)) {
curMatches.push(interactable);
curMatchElements.push(eventTarget);
}
}
if (elementAction) {
this.target = elementInteractable;
this.element = eventTarget;
this.matches = [];
this.matchElements = [];
}
else {
interactables.forEachSelector(pushCurMatches);
if (this.validateSelector(pointer, curMatches, curMatchElements)) {
this.matches = curMatches;
this.matchElements = curMatchElements;
this.pointerHover(pointer, event, this.matches, this.matchElements);
events.add(eventTarget,
PointerEvent? pEventTypes.move : 'mousemove',
listeners.pointerHover);
}
else if (this.target) {
if (nodeContains(prevTargetElement, eventTarget)) {
this.pointerHover(pointer, event, this.matches, this.matchElements);
events.add(this.element,
PointerEvent? pEventTypes.move : 'mousemove',
listeners.pointerHover);
}
else {
this.target = null;
this.element = null;
this.matches = [];
this.matchElements = [];
}
}
}
},
// Check what action would be performed on pointerMove target if a mouse
// button were pressed and change the cursor accordingly
pointerHover: function (pointer, event, eventTarget, curEventTarget, matches, matchElements) {
var target = this.target;
if (!this.prepared && this.mouse) {
var action;
// update pointer coords for defaultActionChecker to use
this.setEventXY(this.curCoords, pointer);
if (matches) {
action = this.validateSelector(pointer, matches, matchElements);
}
else if (target) {
action = validateAction(target.getAction(this.pointers[0], this, this.element), this.target);
}
if (target && target.options.styleCursor) {
if (action) {
target._doc.documentElement.style.cursor = actionCursors[action];
}
else {
target._doc.documentElement.style.cursor = '';
}
}
}
else if (this.prepared) {
this.checkAndPreventDefault(event, target, this.element);
}
},
pointerOut: function (pointer, event, eventTarget) {
if (this.prepared) { return; }
// Remove temporary event listeners for selector Interactables
if (!interactables.get(eventTarget)) {
events.remove(eventTarget,
PointerEvent? pEventTypes.move : 'mousemove',
listeners.pointerHover);
}
if (this.target && this.target.options.styleCursor && !this.interacting()) {
this.target._doc.documentElement.style.cursor = '';
}
},
selectorDown: function (pointer, event, eventTarget, curEventTarget) {
var that = this,
element = eventTarget,
pointerIndex = this.addPointer(pointer),
action;
this.collectEventTargets(pointer, event, eventTarget, 'down');
this.holdTimers[pointerIndex] = window.setTimeout(function () {
that.pointerHold(pointer, event, eventTarget, curEventTarget);
}, 600);
this.pointerIsDown = true;
// Check if the down event hits the current inertia target
if (this.inertiaStatus.active && this.target.selector) {
// climb up the DOM tree from the event target
while (element && element !== element.ownerDocument) {
// if this element is the current inertia target element
if (element === this.element
// and the prospective action is the same as the ongoing one
&& validateAction(this.target.getAction(pointer, this, this.element), this.target) === this.prepared) {
// stop inertia so that the next move will be a normal one
cancelFrame(this.inertiaStatus.i);
this.inertiaStatus.active = false;
return;
}
element = element.parentNode;
}
}
// do nothing if interacting
if (this.interacting()) {
return;
}
function pushMatches (interactable, selector, context) {
var elements = ie8MatchesSelector
? context.querySelectorAll(selector)
: undefined;
if (inContext(interactable, element)
&& !testIgnore(interactable, element, eventTarget)
&& testAllow(interactable, element, eventTarget)
&& matchesSelector(element, selector, elements)) {
that.matches.push(interactable);
that.matchElements.push(element);
}
}
// update pointer coords for defaultActionChecker to use
this.setEventXY(this.curCoords, pointer);
if (this.matches.length && this.mouse) {
action = this.validateSelector(pointer, this.matches, this.matchElements);
}
else {
while (element && element !== element.ownerDocument && !action) {
this.matches = [];
this.matchElements = [];
interactables.forEachSelector(pushMatches);
action = this.validateSelector(pointer, this.matches, this.matchElements);
element = element.parentNode;
}
}
if (action) {
this.prepared = action;
return this.pointerDown(pointer, event, eventTarget, curEventTarget, action);
}
else {
// do these now since pointerDown isn't being called from here
this.downTimes[pointerIndex] = new Date().getTime();
this.downTargets[pointerIndex] = eventTarget;
this.downEvent = event;
extend(this.downPointer, pointer);
copyCoords(this.prevCoords, this.curCoords);
this.pointerWasMoved = false;
}
},
// Determine action to be performed on next pointerMove and add appropriate
// style and event Listeners
pointerDown: function (pointer, event, eventTarget, curEventTarget, forceAction) {
if (!forceAction && !this.inertiaStatus.active && this.pointerWasMoved && this.prepared) {
this.checkAndPreventDefault(event, this.target, this.element);
return;
}
this.pointerIsDown = true;
var pointerIndex = this.addPointer(pointer),
action;
// If it is the second touch of a multi-touch gesture, keep the target
// the same if a target was set by the first touch
// Otherwise, set the target if there is no action prepared
if ((this.pointerIds.length < 2 && !this.target) || !this.prepared) {
var interactable = interactables.get(curEventTarget);
if (interactable
&& !testIgnore(interactable, curEventTarget, eventTarget)
&& testAllow(interactable, curEventTarget, eventTarget)
&& (action = validateAction(forceAction || interactable.getAction(pointer, this), interactable, eventTarget))
&& withinInteractionLimit(interactable, curEventTarget, action)) {
this.target = interactable;
this.element = curEventTarget;
}
}
var target = this.target,
options = target && target.options;
if (target && !this.interacting()) {
action = action || validateAction(forceAction || target.getAction(pointer, this), target, this.element);
this.setEventXY(this.startCoords);
if (!action) { return; }
if (options.styleCursor) {
target._doc.documentElement.style.cursor = actionCursors[action];
}
this.resizeAxes = action === 'resizexy'?
'xy':
action === 'resizex'?
'x':
action === 'resizey'?
'y':
'';
if (action === 'gesture' && this.pointerIds.length < 2) {
action = null;
}
this.prepared = action;
this.snapStatus.snappedX = this.snapStatus.snappedY =
this.restrictStatus.restrictedX = this.restrictStatus.restrictedY = NaN;
this.downTimes[pointerIndex] = new Date().getTime();
this.downTargets[pointerIndex] = eventTarget;
this.downEvent = event;
extend(this.downPointer, pointer);
this.setEventXY(this.prevCoords);
this.pointerWasMoved = false;
this.checkAndPreventDefault(event, target, this.element);
}
// if inertia is active try to resume action
else if (this.inertiaStatus.active
&& curEventTarget === this.element
&& validateAction(target.getAction(pointer, this, this.element), target) === this.prepared) {
cancelFrame(this.inertiaStatus.i);
this.inertiaStatus.active = false;
this.checkAndPreventDefault(event, target, this.element);
}
},
pointerMove: function (pointer, event, eventTarget, curEventTarget, preEnd) {
this.recordPointer(pointer);
this.setEventXY(this.curCoords, (pointer instanceof InteractEvent)
? this.inertiaStatus.startEvent
: undefined);
var duplicateMove = (this.curCoords.page.x === this.prevCoords.page.x
&& this.curCoords.page.y === this.prevCoords.page.y
&& this.curCoords.client.x === this.prevCoords.client.x
&& this.curCoords.client.y === this.prevCoords.client.y);
var dx, dy,
pointerIndex = this.mouse? 0 : indexOf(this.pointerIds, getPointerId(pointer));
// register movement greater than pointerMoveTolerance
if (this.pointerIsDown && !this.pointerWasMoved) {
dx = this.curCoords.client.x - this.startCoords.client.x;
dy = this.curCoords.client.y - this.startCoords.client.y;
this.pointerWasMoved = hypot(dx, dy) > defaultOptions.pointerMoveTolerance;
}
if (!duplicateMove && (!this.pointerIsDown || this.pointerWasMoved)) {
if (this.pointerIsDown) {
window.clearTimeout(this.holdTimers[pointerIndex]);
}
this.collectEventTargets(pointer, event, eventTarget, 'move');
}
if (!this.pointerIsDown) { return; }
if (duplicateMove && this.pointerWasMoved && !preEnd) {
this.checkAndPreventDefault(event, this.target, this.element);
return;
}
// set pointer coordinate, time changes and speeds
setEventDeltas(this.pointerDelta, this.prevCoords, this.curCoords);
if (!this.prepared) { return; }
if (this.pointerWasMoved
// ignore movement while inertia is active
&& (!this.inertiaStatus.active || (pointer instanceof InteractEvent && /inertiastart/.test(pointer.type)))) {
// if just starting an action, calculate the pointer speed now
if (!this.interacting()) {
setEventDeltas(this.pointerDelta, this.prevCoords, this.curCoords);
// check if a drag is in the correct axis
if (this.prepared === 'drag') {
var absX = Math.abs(dx),
absY = Math.abs(dy),
targetAxis = this.target.options.dragAxis,
axis = (absX > absY ? 'x' : absX < absY ? 'y' : 'xy');
// if the movement isn't in the axis of the interactable
if (axis !== 'xy' && targetAxis !== 'xy' && targetAxis !== axis) {
// cancel the prepared action
this.prepared = null;
// then try to get a drag from another ineractable
var element = eventTarget;
// check element interactables
while (element && element !== element.ownerDocument) {
var elementInteractable = interactables.get(element);
if (elementInteractable
&& elementInteractable !== this.target
&& elementInteractable.getAction(this.downPointer, this, element) === 'drag'
&& checkAxis(axis, elementInteractable)) {
this.prepared = 'drag';
this.target = elementInteractable;
this.element = element;
break;
}
element = element.parentNode;
}
// if there's no drag from element interactables,
// check the selector interactables
if (!this.prepared) {
var getDraggable = function (interactable, selector, context) {
var elements = ie8MatchesSelector
? context.querySelectorAll(selector)
: undefined;
if (interactable === this.target) { return; }
if (inContext(interactable, eventTarget)
&& !testIgnore(interactable, element, eventTarget)
&& testAllow(interactable, element, eventTarget)
&& matchesSelector(element, selector, elements)
&& interactable.getAction(this.downPointer, this, element) === 'drag'
&& checkAxis(axis, interactable)
&& withinInteractionLimit(interactable, element, 'drag')) {
return interactable;
}
};
element = eventTarget;
while (element && element !== element.ownerDocument) {
var selectorInteractable = interactables.forEachSelector(getDraggable);
if (selectorInteractable) {
this.prepared = 'drag';
this.target = selectorInteractable;
this.element = element;
break;
}
element = element.parentNode;
}
}
}
}
}
var starting = !!this.prepared && !this.interacting();
if (starting && !withinInteractionLimit(this.target, this.element, this.prepared)) {
this.stop();
return;
}
if (this.prepared && this.target) {
var target = this.target,
shouldMove = true,
shouldSnap = checkSnap(target, this.prepared) && (!target.options.snap.endOnly || preEnd),
shouldRestrict = checkRestrict(target, this.prepared) && (!target.options.restrict.endOnly || preEnd);
if (starting) {
var rect = target.getRect(this.element),
snap = target.options.snap,
restrict = target.options.restrict,
width, height;
if (rect) {
this.startOffset.left = this.startCoords.page.x - rect.left;
this.startOffset.top = this.startCoords.page.y - rect.top;
this.startOffset.right = rect.right - this.startCoords.page.x;
this.startOffset.bottom = rect.bottom - this.startCoords.page.y;
if ('width' in rect) { width = rect.width; }
else { width = rect.right - rect.left; }
if ('height' in rect) { height = rect.height; }
else { height = rect.bottom - rect.top; }
}
else {
this.startOffset.left = this.startOffset.top = this.startOffset.right = this.startOffset.bottom = 0;
}
if (rect && snap.elementOrigin) {
this.snapOffset.x = this.startOffset.left - (width * snap.elementOrigin.x);
this.snapOffset.y = this.startOffset.top - (height * snap.elementOrigin.y);
}
else {
this.snapOffset.x = this.snapOffset.y = 0;
}
if (rect && restrict.elementRect) {
this.restrictOffset.left = this.startOffset.left - (width * restrict.elementRect.left);
this.restrictOffset.top = this.startOffset.top - (height * restrict.elementRect.top);
this.restrictOffset.right = this.startOffset.right - (width * (1 - restrict.elementRect.right));
this.restrictOffset.bottom = this.startOffset.bottom - (height * (1 - restrict.elementRect.bottom));
}
else {
this.restrictOffset.left = this.restrictOffset.top = this.restrictOffset.right = this.restrictOffset.bottom = 0;
}
}
var snapCoords = starting? this.startCoords.page : this.curCoords.page;
if (shouldSnap ) { this.setSnapping (snapCoords); } else { this.snapStatus .locked = false; }
if (shouldRestrict) { this.setRestriction(snapCoords); } else { this.restrictStatus.restricted = false; }
if (shouldSnap && this.snapStatus.locked && !this.snapStatus.changed) {
shouldMove = shouldRestrict && this.restrictStatus.restricted && this.restrictStatus.changed;
}
else if (shouldRestrict && this.restrictStatus.restricted && !this.restrictStatus.changed) {
shouldMove = false;
}
// move if snapping or restriction doesn't prevent it
if (shouldMove) {
var action = /resize/.test(this.prepared)? 'resize': this.prepared;
if (starting) {
var dragStartEvent = this[action + 'Start'](this.downEvent);
this.prevEvent = dragStartEvent;
// reset active dropzones
this.activeDrops.dropzones = [];
this.activeDrops.elements = [];
this.activeDrops.rects = [];
if (!this.dynamicDrop) {
this.setActiveDrops(this.element);
}
var dropEvents = this.getDropEvents(event, dragStartEvent);
if (dropEvents.activate) {
this.fireActiveDrops(dropEvents.activate);
}
snapCoords = this.curCoords.page;
// set snapping and restriction for the move event
if (shouldSnap ) { this.setSnapping (snapCoords); }
if (shouldRestrict) { this.setRestriction(snapCoords); }
}
this.prevEvent = this[action + 'Move'](event);
}
this.checkAndPreventDefault(event, this.target, this.element);
}
}
copyCoords(this.prevCoords, this.curCoords);
if (this.dragging || this.resizing) {
autoScroll.edgeMove(event);
}
},
dragStart: function (event) {
var dragEvent = new InteractEvent(this, event, 'drag', 'start', this.element);
this.dragging = true;
this.target.fire(dragEvent);
return dragEvent;
},
dragMove: function (event) {
var target = this.target,
dragEvent = new InteractEvent(this, event, 'drag', 'move', this.element),
draggableElement = this.element,
drop = this.getDrop(dragEvent, draggableElement);
this.dropTarget = drop.dropzone;
this.dropElement = drop.element;
var dropEvents = this.getDropEvents(event, dragEvent);
target.fire(dragEvent);
if (dropEvents.leave) { this.prevDropTarget.fire(dropEvents.leave); }
if (dropEvents.enter) { this.dropTarget.fire(dropEvents.enter); }
if (dropEvents.move ) { this.dropTarget.fire(dropEvents.move ); }
this.prevDropTarget = this.dropTarget;
this.prevDropElement = this.dropElement;
return dragEvent;
},
resizeStart: function (event) {
var resizeEvent = new InteractEvent(this, event, 'resize', 'start', this.element);
this.target.fire(resizeEvent);
this.resizing = true;
return resizeEvent;
},
resizeMove: function (event) {
var resizeEvent = new InteractEvent(this, event, 'resize', 'move', this.element);
this.target.fire(resizeEvent);
return resizeEvent;
},
gestureStart: function (event) {
var gestureEvent = new InteractEvent(this, event, 'gesture', 'start', this.element);
gestureEvent.ds = 0;
this.gesture.startDistance = this.gesture.prevDistance = gestureEvent.distance;
this.gesture.startAngle = this.gesture.prevAngle = gestureEvent.angle;
this.gesture.scale = 1;
this.gesturing = true;
this.target.fire(gestureEvent);
return gestureEvent;
},
gestureMove: function (event) {
if (!this.pointerIds.length) {
return this.prevEvent;
}
var gestureEvent;
gestureEvent = new InteractEvent(this, event, 'gesture', 'move', this.element);
gestureEvent.ds = gestureEvent.scale - this.gesture.scale;
this.target.fire(gestureEvent);
this.gesture.prevAngle = gestureEvent.angle;
this.gesture.prevDistance = gestureEvent.distance;
if (gestureEvent.scale !== Infinity &&
gestureEvent.scale !== null &&
gestureEvent.scale !== undefined &&
!isNaN(gestureEvent.scale)) {
this.gesture.scale = gestureEvent.scale;
}
return gestureEvent;
},
pointerHold: function (pointer, event, eventTarget) {
this.collectEventTargets(pointer, event, eventTarget, 'hold');
},
pointerUp: function (pointer, event, eventTarget, curEventTarget) {
var pointerIndex = this.mouse? 0 : indexOf(this.pointerIds, getPointerId(pointer));
window.clearTimeout(this.holdTimers[pointerIndex]);
this.collectEventTargets(pointer, event, eventTarget, 'up' );
this.collectEventTargets(pointer, event, eventTarget, 'tap');
this.pointerEnd(pointer, event, eventTarget, curEventTarget);
this.removePointer(pointer);
},
pointerCancel: function (pointer, event, eventTarget, curEventTarget) {
var pointerIndex = this.mouse? 0 : indexOf(this.pointerIds, getPointerId(pointer));
window.clearTimeout(this.holdTimers[pointerIndex]);
this.collectEventTargets(pointer, event, eventTarget, 'cancel');
this.pointerEnd(pointer, event, eventTarget, curEventTarget);
},
// End interact move events and stop auto-scroll unless inertia is enabled
pointerEnd: function (pointer, event, eventTarget, curEventTarget) {
var endEvent,
target = this.target,
options = target && target.options,
inertiaOptions = options && options.inertia,
inertiaStatus = this.inertiaStatus;
if (this.interacting()) {
if (inertiaStatus.active) { return; }
var pointerSpeed,
now = new Date().getTime(),
inertiaPossible = false,
inertia = false,
smoothEnd = false,
endSnap = checkSnap(target, this.prepared) && options.snap.endOnly,
endRestrict = checkRestrict(target, this.prepared) && options.restrict.endOnly,
dx = 0,
dy = 0,
startEvent;
if (this.dragging) {
if (options.dragAxis === 'x' ) { pointerSpeed = Math.abs(this.pointerDelta.client.vx); }
else if (options.dragAxis === 'y' ) { pointerSpeed = Math.abs(this.pointerDelta.client.vy); }
else /*options.dragAxis === 'xy'*/{ pointerSpeed = this.pointerDelta.client.speed; }
}
// check if inertia should be started
inertiaPossible = (options.inertiaEnabled
&& this.prepared !== 'gesture'
&& contains(inertiaOptions.actions, this.prepared)
&& event !== inertiaStatus.startEvent);
inertia = (inertiaPossible
&& (now - this.curCoords.timeStamp) < 50
&& pointerSpeed > inertiaOptions.minSpeed
&& pointerSpeed > inertiaOptions.endSpeed);
if (inertiaPossible && !inertia && (endSnap || endRestrict)) {
var snapRestrict = {};
snapRestrict.snap = snapRestrict.restrict = snapRestrict;
if (endSnap) {
this.setSnapping(this.curCoords.page, snapRestrict);
if (snapRestrict.locked) {
dx += snapRestrict.dx;
dy += snapRestrict.dy;
}
}
if (endRestrict) {
this.setRestriction(this.curCoords.page, snapRestrict);
if (snapRestrict.restricted) {
dx += snapRestrict.dx;
dy += snapRestrict.dy;
}
}
if (dx || dy) {
smoothEnd = true;
}
}
if (inertia || smoothEnd) {
copyCoords(inertiaStatus.upCoords, this.curCoords);
this.pointers[0] = inertiaStatus.startEvent = startEvent =
new InteractEvent(this, event, this.prepared, 'inertiastart', this.element);
inertiaStatus.t0 = now;
target.fire(inertiaStatus.startEvent);
if (inertia) {
inertiaStatus.vx0 = this.pointerDelta.client.vx;
inertiaStatus.vy0 = this.pointerDelta.client.vy;
inertiaStatus.v0 = pointerSpeed;
this.calcInertia(inertiaStatus);
var page = extend({}, this.curCoords.page),
origin = getOriginXY(target, this.element),
statusObject;
page.x = page.x + inertiaStatus.xe - origin.x;
page.y = page.y + inertiaStatus.ye - origin.y;
statusObject = {
useStatusXY: true,
x: page.x,
y: page.y,
dx: 0,
dy: 0,
snap: null
};
statusObject.snap = statusObject;
dx = dy = 0;
if (endSnap) {
var snap = this.setSnapping(this.curCoords.page, statusObject);
if (snap.locked) {
dx += snap.dx;
dy += snap.dy;
}
}
if (endRestrict) {
var restrict = this.setRestriction(this.curCoords.page, statusObject);
if (restrict.restricted) {
dx += restrict.dx;
dy += restrict.dy;
}
}
inertiaStatus.modifiedXe += dx;
inertiaStatus.modifiedYe += dy;
inertiaStatus.i = reqFrame(this.boundInertiaFrame);
}
else {
inertiaStatus.smoothEnd = true;
inertiaStatus.xe = dx;
inertiaStatus.ye = dy;
inertiaStatus.sx = inertiaStatus.sy = 0;
inertiaStatus.i = reqFrame(this.boundSmoothEndFrame);
}
inertiaStatus.active = true;
return;
}
if (endSnap || endRestrict) {
// fire a move event at the snapped coordinates
this.pointerMove(pointer, event, eventTarget, curEventTarget, true);
}
}
if (this.dragging) {
endEvent = new InteractEvent(this, event, 'drag', 'end', this.element);
var draggableElement = this.element,
drop = this.getDrop(endEvent, draggableElement);
this.dropTarget = drop.dropzone;
this.dropElement = drop.element;
var dropEvents = this.getDropEvents(event, endEvent);
if (dropEvents.leave) { this.prevDropTarget.fire(dropEvents.leave); }
if (dropEvents.enter) { this.dropTarget.fire(dropEvents.enter); }
if (dropEvents.drop ) { this.dropTarget.fire(dropEvents.drop ); }
if (dropEvents.deactivate) {
this.fireActiveDrops(dropEvents.deactivate);
}
target.fire(endEvent);
}
else if (this.resizing) {
endEvent = new InteractEvent(this, event, 'resize', 'end', this.element);
target.fire(endEvent);
}
else if (this.gesturing) {
endEvent = new InteractEvent(this, event, 'gesture', 'end', this.element);
target.fire(endEvent);
}
this.stop(event);
},
collectDrops: function (element) {
var drops = [],
elements = [],
i;
element = element || this.element;
// collect all dropzones and their elements which qualify for a drop
for (i = 0; i < interactables.length; i++) {
if (!interactables[i].options.dropzone) { continue; }
var current = interactables[i];
// test the draggable element against the dropzone's accept setting
if ((isElement(current.options.accept) && current.options.accept !== element)
|| (isString(current.options.accept)
&& !matchesSelector(element, current.options.accept))) {
continue;
}
// query for new elements if necessary
var dropElements = current.selector? current._context.querySelectorAll(current.selector) : [current._element];
for (var j = 0, len = dropElements.length; j < len; j++) {
var currentElement = dropElements[j];
if (currentElement === element) {
continue;
}
drops.push(current);
elements.push(currentElement);
}
}
return {
dropzones: drops,
elements: elements
};
},
fireActiveDrops: function (event) {
var i,
current,
currentElement,
prevElement;
// loop through all active dropzones and trigger event
for (i = 0; i < this.activeDrops.dropzones.length; i++) {
current = this.activeDrops.dropzones[i];
currentElement = this.activeDrops.elements [i];
// prevent trigger of duplicate events on same element
if (currentElement !== prevElement) {
// set current element as event target
event.target = currentElement;
current.fire(event);
}
prevElement = currentElement;
}
},
// Collect a new set of possible drops and save them in activeDrops.
// setActiveDrops should always be called when a drag has just started or a
// drag event happens while dynamicDrop is true
setActiveDrops: function (dragElement) {
// get dropzones and their elements that could receive the draggable
var possibleDrops = this.collectDrops(dragElement, true);
this.activeDrops.dropzones = possibleDrops.dropzones;
this.activeDrops.elements = possibleDrops.elements;
this.activeDrops.rects = [];
for (var i = 0; i < this.activeDrops.dropzones.length; i++) {
this.activeDrops.rects[i] = this.activeDrops.dropzones[i].getRect(this.activeDrops.elements[i]);
}
},
getDrop: function (event, dragElement) {
var validDrops = [];
if (dynamicDrop) {
this.setActiveDrops(dragElement);
}
// collect all dropzones and their elements which qualify for a drop
for (var j = 0; j < this.activeDrops.dropzones.length; j++) {
var current = this.activeDrops.dropzones[j],
currentElement = this.activeDrops.elements [j],
rect = this.activeDrops.rects [j];
validDrops.push(current.dropCheck(this.pointers[0], this.target, dragElement, currentElement, rect)
? currentElement
: null);
}
// get the most appropriate dropzone based on DOM depth and order
var dropIndex = indexOfDeepestElement(validDrops),
dropzone = this.activeDrops.dropzones[dropIndex] || null,
element = this.activeDrops.elements [dropIndex] || null;
return {
dropzone: dropzone,
element: element
};
},
getDropEvents: function (pointerEvent, dragEvent) {
var dragLeaveEvent = null,
dragEnterEvent = null,
dropActivateEvent = null,
dropDeactivateEvent = null,
dropMoveEvent = null,
dropEvent = null;
if (this.dropElement !== this.prevDropElement) {
// if there was a prevDropTarget, create a dragleave event
if (this.prevDropTarget) {
dragLeaveEvent = new InteractEvent(this, pointerEvent, 'drag', 'leave', this.prevDropElement, dragEvent.target);
dragLeaveEvent.draggable = dragEvent.interactable;
dragEvent.dragLeave = this.prevDropElement;
dragEvent.prevDropzone = this.prevDropTarget;
}
// if the dropTarget is not null, create a dragenter event
if (this.dropTarget) {
dragEnterEvent = new InteractEvent(this, pointerEvent, 'drag', 'enter', this.dropElement, dragEvent.target);
dragEnterEvent.draggable = dragEvent.interactable;
dragEvent.dragEnter = this.dropElement;
dragEvent.dropzone = this.dropTarget;
}
}
if (dragEvent.type === 'dragend' && this.dropTarget) {
dropEvent = new InteractEvent(this, pointerEvent, 'drop', null, this.dropElement, dragEvent.target);
dropEvent.draggable = dragEvent.interactable;
dragEvent.dropzone = this.dropTarget;
}
if (dragEvent.type === 'dragstart') {
dropActivateEvent = new InteractEvent(this, pointerEvent, 'drop', 'activate', this.element, dragEvent.target);
dropActivateEvent.draggable = dragEvent.interactable;
}
if (dragEvent.type === 'dragend') {
dropDeactivateEvent = new InteractEvent(this, pointerEvent, 'drop', 'deactivate', this.element, dragEvent.target);
dropDeactivateEvent.draggable = dragEvent.interactable;
}
if (dragEvent.type === 'dragmove' && this.dropTarget) {
dropMoveEvent = {
target : this.dropElement,
relatedTarget: dragEvent.target,
draggable : dragEvent.interactable,
dragmove : dragEvent,
type : 'dropmove',
timeStamp : dragEvent.timeStamp
};
dragEvent.dropzone = this.dropTarget;
}
return {
enter : dragEnterEvent,
leave : dragLeaveEvent,
activate : dropActivateEvent,
deactivate : dropDeactivateEvent,
move : dropMoveEvent,
drop : dropEvent
};
},
currentAction: function () {
return (this.dragging && 'drag') || (this.resizing && 'resize') || (this.gesturing && 'gesture') || null;
},
interacting: function () {
return this.dragging || this.resizing || this.gesturing;
},
clearTargets: function () {
if (this.target && !this.target.selector) {
this.target = this.element = null;
}
this.dropTarget = this.dropElement = this.prevDropTarget = this.prevDropElement = null;
},
stop: function (event) {
if (this.interacting()) {
autoScroll.stop();
this.matches = [];
this.matchElements = [];
var target = this.target;
if (target.options.styleCursor) {
target._doc.documentElement.style.cursor = '';
}
// prevent Default only if were previously interacting
if (event && isFunction(event.preventDefault)) {
this.checkAndPreventDefault(event, target, this.element);
}
if (this.dragging) {
this.activeDrops.dropzones = this.activeDrops.elements = this.activeDrops.rects = null;
}
this.clearTargets();
}
this.pointerIsDown = this.snapStatus.locked = this.dragging = this.resizing = this.gesturing = false;
this.prepared = this.prevEvent = null;
this.inertiaStatus.resumeDx = this.inertiaStatus.resumeDy = 0;
this.pointerIds .splice(0);
this.pointers .splice(0);
this.downTargets.splice(0);
this.downTimes .splice(0);
this.holdTimers .splice(0);
// delete interaction if it's not the only one
if (interactions.length > 1) {
interactions.splice(indexOf(interactions, this), 1);
}
},
inertiaFrame: function () {
var inertiaStatus = this.inertiaStatus,
options = this.target.options.inertia,
lambda = options.resistance,
t = new Date().getTime() / 1000 - inertiaStatus.t0;
if (t < inertiaStatus.te) {
var progress = 1 - (Math.exp(-lambda * t) - inertiaStatus.lambda_v0) / inertiaStatus.one_ve_v0;
if (inertiaStatus.modifiedXe === inertiaStatus.xe && inertiaStatus.modifiedYe === inertiaStatus.ye) {
inertiaStatus.sx = inertiaStatus.xe * progress;
inertiaStatus.sy = inertiaStatus.ye * progress;
}
else {
var quadPoint = getQuadraticCurvePoint(
0, 0,
inertiaStatus.xe, inertiaStatus.ye,
inertiaStatus.modifiedXe, inertiaStatus.modifiedYe,
progress);
inertiaStatus.sx = quadPoint.x;
inertiaStatus.sy = quadPoint.y;
}
this.pointerMove(inertiaStatus.startEvent, inertiaStatus.startEvent);
inertiaStatus.i = reqFrame(this.boundInertiaFrame);
}
else {
inertiaStatus.sx = inertiaStatus.modifiedXe;
inertiaStatus.sy = inertiaStatus.modifiedYe;
this.pointerMove(inertiaStatus.startEvent, inertiaStatus.startEvent);
inertiaStatus.active = false;
this.pointerEnd(inertiaStatus.startEvent, inertiaStatus.startEvent);
}
},
smoothEndFrame: function () {
var inertiaStatus = this.inertiaStatus,
t = new Date().getTime() - inertiaStatus.t0,
duration = this.target.options.inertia.smoothEndDuration;
if (t < duration) {
inertiaStatus.sx = easeOutQuad(t, 0, inertiaStatus.xe, duration);
inertiaStatus.sy = easeOutQuad(t, 0, inertiaStatus.ye, duration);
this.pointerMove(inertiaStatus.startEvent, inertiaStatus.startEvent);
inertiaStatus.i = reqFrame(this.boundSmoothEndFrame);
}
else {
inertiaStatus.sx = inertiaStatus.xe;
inertiaStatus.sy = inertiaStatus.ye;
this.pointerMove(inertiaStatus.startEvent, inertiaStatus.startEvent);
inertiaStatus.active = false;
inertiaStatus.smoothEnd = false;
this.pointerEnd(inertiaStatus.startEvent, inertiaStatus.startEvent);
}
},
addPointer: function (pointer) {
var id = getPointerId(pointer),
index = this.mouse? 0 : indexOf(this.pointerIds, id);
if (index === -1) {
index = this.pointerIds.length;
this.pointerIds.push(id);
}
this.pointers[index] = pointer;
return index;
},
removePointer: function (pointer) {
var id = getPointerId(pointer),
index = this.mouse? 0 : indexOf(this.pointerIds, id);
if (index === -1) { return; }
this.pointerIds .splice(index, 1);
this.pointers .splice(index, 1);
this.downTargets.splice(index, 1);
this.downTimes .splice(index, 1);
this.holdTimers .splice(index, 1);
},
recordPointer: function (pointer) {
// Do not update pointers while inertia is active.
// The inertia start event should be this.pointers[0]
if (this.inertiaStatus.active) { return; }
var index = this.mouse? 0: indexOf(this.pointerIds, getPointerId(pointer));
if (index === -1) { return; }
this.pointers[index] = pointer;
},
collectEventTargets: function (pointer, event, eventTarget, eventType) {
var pointerIndex = this.mouse? 0 : indexOf(this.pointerIds, getPointerId(pointer));
// do not fire a tap event if the pointer was moved before being lifted
if (eventType === 'tap' && (this.pointerWasMoved
// or if the pointerup target is different to the pointerdown target
|| !(this.downTargets[pointerIndex] && this.downTargets[pointerIndex] === eventTarget))) {
return;
}
var targets = [],
elements = [],
element = eventTarget;
function collectSelectors (interactable, selector, context) {
var els = ie8MatchesSelector
? context.querySelectorAll(selector)
: undefined;
if (interactable._iEvents[eventType]
&& isElement(element)
&& inContext(interactable, element)
&& !testIgnore(interactable, element, eventTarget)
&& testAllow(interactable, element, eventTarget)
&& matchesSelector(element, selector, els)) {
targets.push(interactable);
elements.push(element);
}
}
while (element) {
if (interact.isSet(element) && interact(element)._iEvents[eventType]) {
targets.push(interact(element));
elements.push(element);
}
interactables.forEachSelector(collectSelectors);
element = element.parentNode;
}
if (targets.length) {
this.firePointers(pointer, event, targets, elements, eventType);
}
},
firePointers: function (pointer, event, targets, elements, eventType) {
var pointerIndex = this.mouse? 0 : indexOf(getPointerId(pointer)),
pointerEvent = {},
i,
// for tap events
interval, dbl;
extend(pointerEvent, event);
if (event !== pointer) {
extend(pointerEvent, pointer);
}
pointerEvent.preventDefault = preventOriginalDefault;
pointerEvent.stopPropagation = InteractEvent.prototype.stopPropagation;
pointerEvent.stopImmediatePropagation = InteractEvent.prototype.stopImmediatePropagation;
pointerEvent.interaction = this;
pointerEvent.timeStamp = new Date().getTime();
pointerEvent.originalEvent = event;
pointerEvent.type = eventType;
pointerEvent.pointerId = getPointerId(pointer);
pointerEvent.pointerType = this.mouse? 'mouse' : !supportsPointerEvent? 'touch'
: isString(pointer.pointerType)
? pointer.pointerType
: [,,'touch', 'pen', 'mouse'][pointer.pointerType];
if (eventType === 'tap') {
pointerEvent.dt = pointerEvent.timeStamp - this.downTimes[pointerIndex];
interval = pointerEvent.timeStamp - this.tapTime;
dbl = (this.prevTap && this.prevTap.type !== 'doubletap'
&& this.prevTap.target === pointerEvent.target
&& interval < 500);
this.tapTime = pointerEvent.timeStamp;
}
for (i = 0; i < targets.length; i++) {
pointerEvent.currentTarget = elements[i];
pointerEvent.interactable = targets[i];
targets[i].fire(pointerEvent);
if (pointerEvent.immediatePropagationStopped
||(pointerEvent.propagationStopped && elements[i + 1] !== pointerEvent.currentTarget)) {
break;
}
}
if (dbl) {
var doubleTap = {};
extend(doubleTap, pointerEvent);
doubleTap.dt = interval;
doubleTap.type = 'doubletap';
for (i = 0; i < targets.length; i++) {
doubleTap.currentTarget = elements[i];
doubleTap.interactable = targets[i];
targets[i].fire(doubleTap);
if (doubleTap.immediatePropagationStopped
||(doubleTap.propagationStopped && elements[i + 1] !== doubleTap.currentTarget)) {
break;
}
}
this.prevTap = doubleTap;
}
else if (eventType === 'tap') {
this.prevTap = pointerEvent;
}
},
validateSelector: function (pointer, matches, matchElements) {
for (var i = 0, len = matches.length; i < len; i++) {
var match = matches[i],
matchElement = matchElements[i],
action = validateAction(match.getAction(pointer, this, matchElement), match);
if (action && withinInteractionLimit(match, matchElement, action)) {
this.target = match;
this.element = matchElement;
return action;
}
}
},
setSnapping: function (pageCoords, status) {
var snap = this.target.options.snap,
anchors = snap.anchors,
page,
closest,
range,
inRange,
snapChanged,
dx,
dy,
distance,
i, len;
status = status || this.snapStatus;
if (status.useStatusXY) {
page = { x: status.x, y: status.y };
}
else {
var origin = getOriginXY(this.target, this.element);
page = extend({}, pageCoords);
page.x -= origin.x;
page.y -= origin.y;
}
page.x -= this.inertiaStatus.resumeDx;
page.y -= this.inertiaStatus.resumeDy;
status.realX = page.x;
status.realY = page.y;
// change to infinite range when range is negative
if (snap.range < 0) { snap.range = Infinity; }
// create an anchor representative for each path's returned point
if (snap.mode === 'path') {
anchors = [];
for (i = 0, len = snap.paths.length; i < len; i++) {
var path = snap.paths[i];
if (isFunction(path)) {
path = path(page.x, page.y);
}
anchors.push({
x: isNumber(path.x) ? path.x : page.x,
y: isNumber(path.y) ? path.y : page.y,
range: isNumber(path.range)? path.range: snap.range
});
}
}
if ((snap.mode === 'anchor' || snap.mode === 'path') && anchors.length) {
closest = {
anchor: null,
distance: 0,
range: 0,
dx: 0,
dy: 0
};
for (i = 0, len = anchors.length; i < len; i++) {
var anchor = anchors[i];
range = isNumber(anchor.range)? anchor.range: snap.range;
dx = anchor.x - page.x + this.snapOffset.x;
dy = anchor.y - page.y + this.snapOffset.y;
distance = hypot(dx, dy);
inRange = distance < range;
// Infinite anchors count as being out of range
// compared to non infinite ones that are in range
if (range === Infinity && closest.inRange && closest.range !== Infinity) {
inRange = false;
}
if (!closest.anchor || (inRange?
// is the closest anchor in range?
(closest.inRange && range !== Infinity)?
// the pointer is relatively deeper in this anchor
distance / range < closest.distance / closest.range:
//the pointer is closer to this anchor
distance < closest.distance:
// The other is not in range and the pointer is closer to this anchor
(!closest.inRange && distance < closest.distance))) {
if (range === Infinity) {
inRange = true;
}
closest.anchor = anchor;
closest.distance = distance;
closest.range = range;
closest.inRange = inRange;
closest.dx = dx;
closest.dy = dy;
status.range = range;
}
}
inRange = closest.inRange;
snapChanged = (closest.anchor.x !== status.x || closest.anchor.y !== status.y);
status.snappedX = closest.anchor.x;
status.snappedY = closest.anchor.y;
status.dx = closest.dx;
status.dy = closest.dy;
}
else if (snap.mode === 'grid') {
var gridx = Math.round((page.x - snap.gridOffset.x - this.snapOffset.x) / snap.grid.x),
gridy = Math.round((page.y - snap.gridOffset.y - this.snapOffset.y) / snap.grid.y),
newX = gridx * snap.grid.x + snap.gridOffset.x + this.snapOffset.x,
newY = gridy * snap.grid.y + snap.gridOffset.y + this.snapOffset.y;
dx = newX - page.x;
dy = newY - page.y;
distance = hypot(dx, dy);
inRange = distance < snap.range;
snapChanged = (newX !== status.snappedX || newY !== status.snappedY);
status.snappedX = newX;
status.snappedY = newY;
status.dx = dx;
status.dy = dy;
status.range = snap.range;
}
status.changed = (snapChanged || (inRange && !status.locked));
status.locked = inRange;
return status;
},
setRestriction: function (pageCoords, status) {
var target = this.target,
action = /resize/.test(this.prepared)? 'resize' : this.prepared,
restrict = target && target.options.restrict,
restriction = restrict && restrict[action],
page;
if (!restriction) {
return status;
}
status = status || this.restrictStatus;
page = status.useStatusXY
? page = { x: status.x, y: status.y }
: page = extend({}, pageCoords);
if (status.snap && status.snap.locked) {
page.x += status.snap.dx || 0;
page.y += status.snap.dy || 0;
}
page.x -= this.inertiaStatus.resumeDx;
page.y -= this.inertiaStatus.resumeDy;
status.dx = 0;
status.dy = 0;
status.restricted = false;
var rect, restrictedX, restrictedY;
if (isString(restriction)) {
if (restriction === 'parent') {
restriction = this.element.parentNode;
}
else if (restriction === 'self') {
restriction = target.getRect(this.element);
}
else {
restriction = closest(this.element, restriction);
}
if (!restriction) { return status; }
}
if (isFunction(restriction)) {
restriction = restriction(page.x, page.y, this.element);
}
if (isElement(restriction)) {
restriction = getElementRect(restriction);
}
rect = restriction;
// object is assumed to have
// x, y, width, height or
// left, top, right, bottom
if ('x' in restriction && 'y' in restriction) {
restrictedX = Math.max(Math.min(rect.x + rect.width - this.restrictOffset.right , page.x), rect.x + this.restrictOffset.left);
restrictedY = Math.max(Math.min(rect.y + rect.height - this.restrictOffset.bottom, page.y), rect.y + this.restrictOffset.top );
}
else {
restrictedX = Math.max(Math.min(rect.right - this.restrictOffset.right , page.x), rect.left + this.restrictOffset.left);
restrictedY = Math.max(Math.min(rect.bottom - this.restrictOffset.bottom, page.y), rect.top + this.restrictOffset.top );
}
status.dx = restrictedX - page.x;
status.dy = restrictedY - page.y;
status.changed = status.restrictedX !== restrictedX || status.restrictedY !== restrictedY;
status.restricted = !!(status.dx || status.dy);
status.restrictedX = restrictedX;
status.restrictedY = restrictedY;
return status;
},
checkAndPreventDefault: function (event, interactable, element) {
if (!(interactable = interactable || this.target)) { return; }
var options = interactable.options,
prevent = options.preventDefault;
if (prevent === 'auto' && element && !/^input$|^textarea$/i.test(element.nodeName)) {
// do not preventDefault on pointerdown if the prepared action is a drag
// and dragging can only start from a certain direction - this allows
// a touch to pan the viewport if a drag isn't in the right direction
if (/down|start/i.test(event.type)
&& this.prepared === 'drag' && options.dragAxis !== 'xy') {
return;
}
event.preventDefault();
return;
}
if (prevent === true) {
event.preventDefault();
return;
}
},
calcInertia: function (status) {
var inertiaOptions = this.target.options.inertia,
lambda = inertiaOptions.resistance,
inertiaDur = -Math.log(inertiaOptions.endSpeed / status.v0) / lambda;
status.x0 = this.prevEvent.pageX;
status.y0 = this.prevEvent.pageY;
status.t0 = status.startEvent.timeStamp / 1000;
status.sx = status.sy = 0;
status.modifiedXe = status.xe = (status.vx0 - inertiaDur) / lambda;
status.modifiedYe = status.ye = (status.vy0 - inertiaDur) / lambda;
status.te = inertiaDur;
status.lambda_v0 = lambda / status.v0;
status.one_ve_v0 = 1 - inertiaOptions.endSpeed / status.v0;
}
};
function getInteractionFromPointer (pointer, eventType, eventTarget) {
var i = 0, len = interactions.length,
mouseEvent = (/mouse/i.test(pointer.pointerType || eventType)
// MSPointerEvent.MSPOINTER_TYPE_MOUSE
|| pointer.pointerType === 4),
interaction;
var id = getPointerId(pointer);
// try to resume inertia with a new pointer
if (/down|start/i.test(eventType)) {
for (i = 0; i < len; i++) {
interaction = interactions[i];
var element = eventTarget;
if (interaction.inertiaStatus.active && interaction.target.options.inertia.allowResume
&& (interaction.mouse === mouseEvent)) {
while (element) {
// if the element is the interaction element
if (element === interaction.element) {
// update the interaction's pointer
interaction.removePointer(interaction.pointers[0]);
interaction.addPointer(pointer);
return interaction;
}
element = element.parentNode;
}
}
}
}
// if it's a mouse interaction
if (mouseEvent || !(supportsTouch || supportsPointerEvent)) {
// find a mouse interaction that's not in inertia phase
for (i = 0; i < len; i++) {
if (interactions[i].mouse && !interactions[i].inertiaStatus.active) {
return interactions[i];
}
}
// find any interaction specifically for mouse.
// if the eventType is a mousedown, and inertia is active
// ignore the interaction
for (i = 0; i < len; i++) {
if (interactions[i].mouse && !(/down/.test(eventType) && interactions[i].inertiaStatus.active)) {
return interaction;
}
}
// create a new interaction for mouse
interaction = new Interaction();
interaction.mouse = true;
return interaction;
}
// get interaction that has this pointer
for (i = 0; i < len; i++) {
if (contains(interactions[i].pointerIds, id)) {
return interactions[i];
}
}
// at this stage, a pointerUp should not return an interaction
if (/up|end|out/i.test(eventType)) {
return null;
}
// get first idle interaction
for (i = 0; i < len; i++) {
interaction = interactions[i];
if ((!interaction.prepared || (interaction.target.gesturable()))
&& !interaction.interacting()
&& !(!mouseEvent && interaction.mouse)) {
interaction.addPointer(pointer);
return interaction;
}
}
return new Interaction();
}
function doOnInteractions (method) {
return (function (event) {
var interaction,
eventTarget = getActualElement(event.target),
curEventTarget = getActualElement(event.currentTarget),
i;
if (supportsTouch && /touch/.test(event.type)) {
prevTouchTime = new Date().getTime();
for (i = 0; i < event.changedTouches.length; i++) {
var pointer = event.changedTouches[i];
interaction = getInteractionFromPointer(pointer, event.type, eventTarget);
if (!interaction) { continue; }
interaction[method](pointer, event, eventTarget, curEventTarget);
}
}
else {
if (!supportsPointerEvent && /mouse/.test(event.type)) {
// ignore mouse events while touch interactions are active
for (i = 0; i < interactions.length; i++) {
if (!interactions[i].mouse && interactions[i].pointerIsDown) {
return;
}
}
// try to ignore mouse events that are simulated by the browser
// after a touch event
if (new Date().getTime() - prevTouchTime < 500) {
return;
}
}
interaction = getInteractionFromPointer(event, event.type, eventTarget);
if (!interaction) { return; }
interaction[method](event, event, eventTarget, curEventTarget);
}
});
}
function InteractEvent (interaction, event, action, phase, element, related) {
var client,
page,
target = interaction.target,
snapStatus = interaction.snapStatus,
restrictStatus = interaction.restrictStatus,
pointers = interaction.pointers,
deltaSource = (target && target.options || defaultOptions).deltaSource,
sourceX = deltaSource + 'X',
sourceY = deltaSource + 'Y',
options = target? target.options: defaultOptions,
origin = getOriginXY(target, element),
starting = phase === 'start',
ending = phase === 'end',
coords = starting? interaction.startCoords : interaction.curCoords;
element = element || interaction.element;
page = extend({}, coords.page);
client = extend({}, coords.client);
page.x -= origin.x;
page.y -= origin.y;
client.x -= origin.x;
client.y -= origin.y;
if (checkSnap(target, action) && !(starting && options.snap.elementOrigin)) {
this.snap = {
range : snapStatus.range,
locked : snapStatus.locked,
x : snapStatus.snappedX,
y : snapStatus.snappedY,
realX : snapStatus.realX,
realY : snapStatus.realY,
dx : snapStatus.dx,
dy : snapStatus.dy
};
if (snapStatus.locked) {
page.x += snapStatus.dx;
page.y += snapStatus.dy;
client.x += snapStatus.dx;
client.y += snapStatus.dy;
}
}
if (checkRestrict(target, action) && !(starting && options.restrict.elementRect) && restrictStatus.restricted) {
page.x += restrictStatus.dx;
page.y += restrictStatus.dy;
client.x += restrictStatus.dx;
client.y += restrictStatus.dy;
this.restrict = {
dx: restrictStatus.dx,
dy: restrictStatus.dy
};
}
this.pageX = page.x;
this.pageY = page.y;
this.clientX = client.x;
this.clientY = client.y;
this.x0 = interaction.startCoords.page.x;
this.y0 = interaction.startCoords.page.y;
this.clientX0 = interaction.startCoords.client.x;
this.clientY0 = interaction.startCoords.client.y;
this.ctrlKey = event.ctrlKey;
this.altKey = event.altKey;
this.shiftKey = event.shiftKey;
this.metaKey = event.metaKey;
this.button = event.button;
this.target = element;
this.t0 = interaction.downTimes[0];
this.type = action + (phase || '');
this.interaction = interaction;
this.interactable = target;
var inertiaStatus = interaction.inertiaStatus;
if (inertiaStatus.active) {
this.detail = 'inertia';
}
if (related) {
this.relatedTarget = related;
}
// end event dx, dy is difference between start and end points
if (ending || action === 'drop') {
if (deltaSource === 'client') {
this.dx = client.x - interaction.startCoords.client.x;
this.dy = client.y - interaction.startCoords.client.y;
}
else {
this.dx = page.x - interaction.startCoords.page.x;
this.dy = page.y - interaction.startCoords.page.y;
}
}
else if (starting) {
this.dx = 0;
this.dy = 0;
}
// copy properties from previousmove if starting inertia
else if (phase === 'inertiastart') {
this.dx = interaction.prevEvent.dx;
this.dy = interaction.prevEvent.dy;
}
else {
if (deltaSource === 'client') {
this.dx = client.x - interaction.prevEvent.clientX;
this.dy = client.y - interaction.prevEvent.clientY;
}
else {
this.dx = page.x - interaction.prevEvent.pageX;
this.dy = page.y - interaction.prevEvent.pageY;
}
}
if (interaction.prevEvent && interaction.prevEvent.detail === 'inertia'
&& !inertiaStatus.active && options.inertia.zeroResumeDelta) {
inertiaStatus.resumeDx += this.dx;
inertiaStatus.resumeDy += this.dy;
this.dx = this.dy = 0;
}
if (action === 'resize') {
if (options.squareResize || event.shiftKey) {
if (interaction.resizeAxes === 'y') {
this.dx = this.dy;
}
else {
this.dy = this.dx;
}
this.axes = 'xy';
}
else {
this.axes = interaction.resizeAxes;
if (interaction.resizeAxes === 'x') {
this.dy = 0;
}
else if (interaction.resizeAxes === 'y') {
this.dx = 0;
}
}
}
else if (action === 'gesture') {
this.touches = [pointers[0], pointers[1]];
if (starting) {
this.distance = touchDistance(pointers, deltaSource);
this.box = touchBBox(pointers);
this.scale = 1;
this.ds = 0;
this.angle = touchAngle(pointers, undefined, deltaSource);
this.da = 0;
}
else if (ending || event instanceof InteractEvent) {
this.distance = interaction.prevEvent.distance;
this.box = interaction.prevEvent.box;
this.scale = interaction.prevEvent.scale;
this.ds = this.scale - 1;
this.angle = interaction.prevEvent.angle;
this.da = this.angle - interaction.gesture.startAngle;
}
else {
this.distance = touchDistance(pointers, deltaSource);
this.box = touchBBox(pointers);
this.scale = this.distance / interaction.gesture.startDistance;
this.angle = touchAngle(pointers, interaction.gesture.prevAngle, deltaSource);
this.ds = this.scale - interaction.gesture.prevScale;
this.da = this.angle - interaction.gesture.prevAngle;
}
}
if (starting) {
this.timeStamp = interaction.downTimes[0];
this.dt = 0;
this.duration = 0;
this.speed = 0;
this.velocityX = 0;
this.velocityY = 0;
}
else if (phase === 'inertiastart') {
this.timeStamp = interaction.prevEvent.timeStamp;
this.dt = interaction.prevEvent.dt;
this.duration = interaction.prevEvent.duration;
this.speed = interaction.prevEvent.speed;
this.velocityX = interaction.prevEvent.velocityX;
this.velocityY = interaction.prevEvent.velocityY;
}
else {
this.timeStamp = new Date().getTime();
this.dt = this.timeStamp - interaction.prevEvent.timeStamp;
this.duration = this.timeStamp - interaction.downTimes[0];
if (event instanceof InteractEvent) {
var dx = this[sourceX] - interaction.prevEvent[sourceX],
dy = this[sourceY] - interaction.prevEvent[sourceY],
dt = this.dt / 1000;
this.speed = hypot(dx, dy) / dt;
this.velocityX = dx / dt;
this.velocityY = dy / dt;
}
// if normal move or end event, use previous user event coords
else {
// speed and velocity in pixels per second
this.speed = interaction.pointerDelta[deltaSource].speed;
this.velocityX = interaction.pointerDelta[deltaSource].vx;
this.velocityY = interaction.pointerDelta[deltaSource].vy;
}
}
if ((ending || phase === 'inertiastart')
&& interaction.prevEvent.speed > 600 && this.timeStamp - interaction.prevEvent.timeStamp < 150) {
var angle = 180 * Math.atan2(interaction.prevEvent.velocityY, interaction.prevEvent.velocityX) / Math.PI,
overlap = 22.5;
if (angle < 0) {
angle += 360;
}
var left = 135 - overlap <= angle && angle < 225 + overlap,
up = 225 - overlap <= angle && angle < 315 + overlap,
right = !left && (315 - overlap <= angle || angle < 45 + overlap),
down = !up && 45 - overlap <= angle && angle < 135 + overlap;
this.swipe = {
up : up,
down : down,
left : left,
right: right,
angle: angle,
speed: interaction.prevEvent.speed,
velocity: {
x: interaction.prevEvent.velocityX,
y: interaction.prevEvent.velocityY
}
};
}
}
InteractEvent.prototype = {
preventDefault: blank,
stopImmediatePropagation: function () {
this.immediatePropagationStopped = this.propagationStopped = true;
},
stopPropagation: function () {
this.propagationStopped = true;
}
};
function preventOriginalDefault () {
this.originalEvent.preventDefault();
}
function defaultActionChecker (pointer, interaction, element) {
var rect = this.getRect(element),
right,
bottom,
action = null,
page = extend({}, interaction.curCoords.page),
options = this.options;
if (!rect) { return null; }
if (actionIsEnabled.resize && options.resizable) {
right = options.resizeAxis !== 'y' && page.x > (rect.right - margin);
bottom = options.resizeAxis !== 'x' && page.y > (rect.bottom - margin);
}
interaction.resizeAxes = (right?'x': '') + (bottom?'y': '');
action = (interaction.resizeAxes)?
'resize' + interaction.resizeAxes:
actionIsEnabled.drag && options.draggable?
'drag':
null;
if (actionIsEnabled.gesture
&& interaction.pointerIds.length >=2
&& !(interaction.dragging || interaction.resizing)) {
action = 'gesture';
}
return action;
}
// Check if action is enabled globally and the current target supports it
// If so, return the validated action. Otherwise, return null
function validateAction (action, interactable) {
if (!isString(action)) { return null; }
var actionType = action.search('resize') !== -1? 'resize': action,
options = interactable;
if (( (actionType === 'resize' && options.resizable )
|| (action === 'drag' && options.draggable )
|| (action === 'gesture' && options.gesturable))
&& actionIsEnabled[actionType]) {
if (action === 'resize' || action === 'resizeyx') {
action = 'resizexy';
}
return action;
}
return null;
}
var listeners = {},
interactionListeners = [
'dragStart', 'dragMove', 'resizeStart', 'resizeMove', 'gestureStart', 'gestureMove',
'pointerOver', 'pointerOut', 'pointerHover', 'selectorDown',
'pointerDown', 'pointerMove', 'pointerUp', 'pointerCancel', 'pointerEnd',
'addPointer', 'removePointer', 'recordPointer',
];
for (var i = 0, len = interactionListeners.length; i < len; i++) {
var name = interactionListeners[i];
listeners[name] = doOnInteractions(name);
}
// bound to the interactable context when a DOM event
// listener is added to a selector interactable
function delegateListener (event, useCapture) {
var fakeEvent = {},
delegated = delegatedEvents[event.type],
element = event.target;
useCapture = useCapture? true: false;
// duplicate the event so that currentTarget can be changed
for (var prop in event) {
fakeEvent[prop] = event[prop];
}
fakeEvent.originalEvent = event;
fakeEvent.preventDefault = preventOriginalDefault;
// climb up document tree looking for selector matches
while (element && (element.ownerDocument && element !== element.ownerDocument)) {
for (var i = 0; i < delegated.selectors.length; i++) {
var selector = delegated.selectors[i],
context = delegated.contexts[i];
if (matchesSelector(element, selector)
&& nodeContains(context, event.target)
&& nodeContains(context, element)) {
var listeners = delegated.listeners[i];
fakeEvent.currentTarget = element;
for (var j = 0; j < listeners.length; j++) {
if (listeners[j][1] === useCapture) {
listeners[j][0](fakeEvent);
}
}
}
}
element = element.parentNode;
}
}
function delegateUseCapture (event) {
return delegateListener.call(this, event, true);
}
interactables.indexOfElement = function indexOfElement (element, context) {
context = context || document;
for (var i = 0; i < this.length; i++) {
var interactable = this[i];
if ((interactable.selector === element
&& (interactable._context === context))
|| (!interactable.selector && interactable._element === element)) {
return i;
}
}
return -1;
};
interactables.get = function interactableGet (element, options) {
return this[this.indexOfElement(element, options && options.context)];
};
interactables.forEachSelector = function (callback) {
for (var i = 0; i < this.length; i++) {
var interactable = this[i];
if (!interactable.selector) {
continue;
}
var ret = callback(interactable, interactable.selector, interactable._context, i, this);
if (ret !== undefined) {
return ret;
}
}
};
/*\
* interact
[ method ]
*
* The methods of this variable can be used to set elements as
* interactables and also to change various default settings.
*
* Calling it as a function and passing an element or a valid CSS selector
* string returns an Interactable object which has various methods to
* configure it.
*
- element (Element | string) The HTML or SVG Element to interact with or CSS selector
= (object) An @Interactable
*
> Usage
| interact(document.getElementById('draggable')).draggable(true);
|
| var rectables = interact('rect');
| rectables
| .gesturable(true)
| .on('gesturemove', function (event) {
| // something cool...
| })
| .autoScroll(true);
\*/
function interact (element, options) {
return interactables.get(element, options) || new Interactable(element, options);
}
// A class for easy inheritance and setting of an Interactable's options
function IOptions (options) {
for (var option in defaultOptions) {
if (options.hasOwnProperty(option)
&& typeof options[option] === typeof defaultOptions[option]) {
this[option] = options[option];
}
}
}
IOptions.prototype = defaultOptions;
/*\
* Interactable
[ property ]
**
* Object type returned by @interact
\*/
function Interactable (element, options) {
this._element = element;
this._iEvents = this._iEvents || {};
var _window;
if (trySelector(element)) {
this.selector = element;
var context = options && options.context;
_window = context? getWindow(context) : window;
if (context && (_window.Node
? context instanceof _window.Node
: (isElement(context) || context === _window.document))) {
this._context = context;
}
}
else {
_window = getWindow(element);
if (isElement(element, _window)) {
if (PointerEvent) {
events.add(this._element, pEventTypes.down, listeners.pointerDown );
events.add(this._element, pEventTypes.move, listeners.pointerHover);
}
else {
events.add(this._element, 'mousedown' , listeners.pointerDown );
events.add(this._element, 'mousemove' , listeners.pointerHover);
events.add(this._element, 'touchstart', listeners.pointerDown );
events.add(this._element, 'touchmove' , listeners.pointerHover);
}
}
}
this._doc = _window.document;
if (!contains(documents, this._doc)) {
listenToDocument(this._doc);
}
interactables.push(this);
this.set(options);
}
Interactable.prototype = {
setOnEvents: function (action, phases) {
if (action === 'drop') {
var drop = phases.ondrop || phases.onDrop || phases.drop,
dropactivate = phases.ondropactivate || phases.onDropActivate || phases.dropactivate
|| phases.onactivate || phases.onActivate || phases.activate,
dropdeactivate = phases.ondropdeactivate || phases.onDropDeactivate || phases.dropdeactivate
|| phases.ondeactivate || phases.onDeactivate || phases.deactivate,
dragenter = phases.ondragenter || phases.onDropEnter || phases.dragenter
|| phases.onenter || phases.onEnter || phases.enter,
dragleave = phases.ondragleave || phases.onDropLeave || phases.dragleave
|| phases.onleave || phases.onLeave || phases.leave,
dropmove = phases.ondropmove || phases.onDropMove || phases.dropmove
|| phases.onmove || phases.onMove || phases.move;
if (isFunction(drop) ) { this.ondrop = drop ; }
if (isFunction(dropactivate) ) { this.ondropactivate = dropactivate ; }
if (isFunction(dropdeactivate)) { this.ondropdeactivate = dropdeactivate; }
if (isFunction(dragenter) ) { this.ondragenter = dragenter ; }
if (isFunction(dragleave) ) { this.ondragleave = dragleave ; }
if (isFunction(dropmove) ) { this.ondropmove = dropmove ; }
}
else {
var start = phases.onstart || phases.onStart || phases.start,
move = phases.onmove || phases.onMove || phases.move,
end = phases.onend || phases.onEnd || phases.end,
inertiastart = phases.oninertiastart || phases.onInertiaStart || phases.inertiastart;
action = 'on' + action;
if (isFunction(start) ) { this[action + 'start' ] = start ; }
if (isFunction(move) ) { this[action + 'move' ] = move ; }
if (isFunction(end) ) { this[action + 'end' ] = end ; }
if (isFunction(inertiastart)) { this[action + 'inertiastart' ] = inertiastart ; }
}
return this;
},
/*\
* Interactable.draggable
[ method ]
*
* Gets or sets whether drag actions can be performed on the
* Interactable
*
= (boolean) Indicates if this can be the target of drag events
| var isDraggable = interact('ul li').draggable();
* or
- options (boolean | object) #optional true/false or An object with event listeners to be fired on drag events (object makes the Interactable draggable)
= (object) This Interactable
| interact(element).draggable({
| onstart: function (event) {},
| onmove : function (event) {},
| onend : function (event) {},
|
| // the axis in which the first movement must be
| // for the drag sequence to start
| // 'xy' by default - any direction
| axis: 'x' || 'y' || 'xy',
|
| // max number of drags that can happen concurrently
| // with elements of this Interactable. 1 by default
| max: Infinity,
|
| // max number of drags that can target the same element
| // 1 by default
| maxPerElement: 2
| });
\*/
draggable: function (options) {
if (isObject(options)) {
this.options.draggable = true;
this.setOnEvents('drag', options);
if (isNumber(options.max)) {
this.options.dragMax = options.max;
}
if (isNumber(options.maxPerElement)) {
this.options.dragMaxPerElement = options.maxPerElement;
}
if (/^x$|^y$|^xy$/.test(options.axis)) {
this.options.dragAxis = options.axis;
}
else if (options.axis === null) {
delete this.options.dragAxis;
}
return this;
}
if (isBool(options)) {
this.options.draggable = options;
return this;
}
if (options === null) {
delete this.options.draggable;
return this;
}
return this.options.draggable;
},
/*\
* Interactable.dropzone
[ method ]
*
* Returns or sets whether elements can be dropped onto this
* Interactable to trigger drop events
*
* Dropzones can receive the following events:
* - `dragactivate` and `dragdeactivate` when an acceptable drag starts and ends
* - `dragenter` and `dragleave` when a draggable enters and leaves the dropzone
* - `drop` when a draggable is dropped into this dropzone
*
* Use the `accept` option to allow only elements that match the given CSS selector or element.
*
* Use the `overlap` option to set how drops are checked for. The allowed values are:
* - `'pointer'`, the pointer must be over the dropzone (default)
* - `'center'`, the draggable element's center must be over the dropzone
* - a number from 0-1 which is the `(intersection area) / (draggable area)`.
* e.g. `0.5` for drop to happen when half of the area of the
* draggable is over the dropzone
*
- options (boolean | object | null) #optional The new value to be set.
| interact('.drop').dropzone({
| accept: '.can-drop' || document.getElementById('single-drop'),
| overlap: 'pointer' || 'center' || zeroToOne
| }
= (boolean | object) The current setting or this Interactable
\*/
dropzone: function (options) {
if (isObject(options)) {
this.options.dropzone = true;
this.setOnEvents('drop', options);
this.accept(options.accept);
if (/^(pointer|center)$/.test(options.overlap)) {
this.options.dropOverlap = options.overlap;
}
else if (isNumber(options.overlap)) {
this.options.dropOverlap = Math.max(Math.min(1, options.overlap), 0);
}
return this;
}
if (isBool(options)) {
this.options.dropzone = options;
return this;
}
if (options === null) {
delete this.options.dropzone;
return this;
}
return this.options.dropzone;
},
/*\
* Interactable.dropCheck
[ method ]
*
* The default function to determine if a dragend event occured over
* this Interactable's element. Can be overridden using
* @Interactable.dropChecker.
*
- pointer (MouseEvent | PointerEvent | Touch) The event that ends a drag
- draggable (Interactable) The Interactable being dragged
- draggableElement (Element) The actual element that's being dragged
- dropElement (Element) The dropzone element
- rect (object) #optional The rect of dropElement
= (boolean) whether the pointer was over this Interactable
\*/
dropCheck: function (pointer, draggable, draggableElement, dropElement, rect) {
if (!(rect = rect || this.getRect(dropElement))) {
return false;
}
var dropOverlap = this.options.dropOverlap;
if (dropOverlap === 'pointer') {
var page = getPageXY(pointer),
origin = getOriginXY(draggable, draggableElement),
horizontal,
vertical;
page.x += origin.x;
page.y += origin.y;
horizontal = (page.x > rect.left) && (page.x < rect.right);
vertical = (page.y > rect.top ) && (page.y < rect.bottom);
return horizontal && vertical;
}
var dragRect = draggable.getRect(draggableElement);
if (dropOverlap === 'center') {
var cx = dragRect.left + dragRect.width / 2,
cy = dragRect.top + dragRect.height / 2;
return cx >= rect.left && cx <= rect.right && cy >= rect.top && cy <= rect.bottom;
}
if (isNumber(dropOverlap)) {
var overlapArea = (Math.max(0, Math.min(rect.right , dragRect.right ) - Math.max(rect.left, dragRect.left))
* Math.max(0, Math.min(rect.bottom, dragRect.bottom) - Math.max(rect.top , dragRect.top ))),
overlapRatio = overlapArea / (dragRect.width * dragRect.height);
return overlapRatio >= dropOverlap;
}
},
/*\
* Interactable.dropChecker
[ method ]
*
* Gets or sets the function used to check if a dragged element is
* over this Interactable. See @Interactable.dropCheck.
*
- checker (function) #optional
* The checker is a function which takes a mouseUp/touchEnd event as a
* parameter and returns true or false to indicate if the the current
* draggable can be dropped into this Interactable
*
= (Function | Interactable) The checker function or this Interactable
\*/
dropChecker: function (checker) {
if (isFunction(checker)) {
this.dropCheck = checker;
return this;
}
return this.dropCheck;
},
/*\
* Interactable.accept
[ method ]
*
* Gets or sets the Element or CSS selector match that this
* Interactable accepts if it is a dropzone.
*
- newValue (Element | string | null) #optional
* If it is an Element, then only that element can be dropped into this dropzone.
* If it is a string, the element being dragged must match it as a selector.
* If it is null, the accept options is cleared - it accepts any element.
*
= (string | Element | null | Interactable) The current accept option if given `undefined` or this Interactable
\*/
accept: function (newValue) {
if (isElement(newValue)) {
this.options.accept = newValue;
return this;
}
// test if it is a valid CSS selector
if (trySelector(newValue)) {
this.options.accept = newValue;
return this;
}
if (newValue === null) {
delete this.options.accept;
return this;
}
return this.options.accept;
},
/*\
* Interactable.resizable
[ method ]
*
* Gets or sets whether resize actions can be performed on the
* Interactable
*
= (boolean) Indicates if this can be the target of resize elements
| var isResizeable = interact('input[type=text]').resizable();
* or
- options (boolean | object) #optional true/false or An object with event listeners to be fired on resize events (object makes the Interactable resizable)
= (object) This Interactable
| interact(element).resizable({
| onstart: function (event) {},
| onmove : function (event) {},
| onend : function (event) {},
|
| axis : 'x' || 'y' || 'xy' // default is 'xy',
|
| // limit multiple resizes.
| // See the explanation in @Interactable.draggable example
| max: 1,
| maxPerElement: 1,
| });
\*/
resizable: function (options) {
if (isObject(options)) {
this.options.resizable = true;
this.setOnEvents('resize', options);
if (isNumber(options.max)) {
this.options.resizeMax = options.max;
}
if (isNumber(options.maxPerElement)) {
this.options.resizeMaxPerElement = options.maxPerElement;
}
if (/^x$|^y$|^xy$/.test(options.axis)) {
this.options.resizeAxis = options.axis;
}
else if (options.axis === null) {
this.options.resizeAxis = defaultOptions.resizeAxis;
}
return this;
}
if (isBool(options)) {
this.options.resizable = options;
return this;
}
return this.options.resizable;
},
// misspelled alias
resizeable: blank,
/*\
* Interactable.squareResize
[ method ]
*
* Gets or sets whether resizing is forced 1:1 aspect
*
= (boolean) Current setting
*
* or
*
- newValue (boolean) #optional
= (object) this Interactable
\*/
squareResize: function (newValue) {
if (isBool(newValue)) {
this.options.squareResize = newValue;
return this;
}
if (newValue === null) {
delete this.options.squareResize;
return this;
}
return this.options.squareResize;
},
/*\
* Interactable.gesturable
[ method ]
*
* Gets or sets whether multitouch gestures can be performed on the
* Interactable's element
*
= (boolean) Indicates if this can be the target of gesture events
| var isGestureable = interact(element).gesturable();
* or
- options (boolean | object) #optional true/false or An object with event listeners to be fired on gesture events (makes the Interactable gesturable)
= (object) this Interactable
| interact(element).gesturable({
| onstart: function (event) {},
| onmove : function (event) {},
| onend : function (event) {},
|
| // limit multiple gestures.
| // See the explanation in @Interactable.draggable example
| max: 1,
| maxPerElement: 1,
| });
\*/
gesturable: function (options) {
if (isObject(options)) {
this.options.gesturable = true;
this.setOnEvents('gesture', options);
if (isNumber(options.max)) {
this.options.gestureMax = options.max;
}
if (isNumber(options.maxPerElement)) {
this.options.gestureMaxPerElement = options.maxPerElement;
}
return this;
}
if (isBool(options)) {
this.options.gesturable = options;
return this;
}
if (options === null) {
delete this.options.gesturable;
return this;
}
return this.options.gesturable;
},
// misspelled alias
gestureable: blank,
/*\
* Interactable.autoScroll
[ method ]
*
* Returns or sets whether or not any actions near the edges of the
* window/container trigger autoScroll for this Interactable
*
= (boolean | object)
* `false` if autoScroll is disabled; object with autoScroll properties
* if autoScroll is enabled
*
* or
*
- options (object | boolean | null) #optional
* options can be:
* - an object with margin, distance and interval properties,
* - true or false to enable or disable autoScroll or
* - null to use default settings
= (Interactable) this Interactable
\*/
autoScroll: function (options) {
var defaults = defaultOptions.autoScroll;
if (isObject(options)) {
var autoScroll = this.options.autoScroll;
if (autoScroll === defaults) {
autoScroll = this.options.autoScroll = {
margin : defaults.margin,
distance : defaults.distance,
interval : defaults.interval,
container: defaults.container
};
}
autoScroll.margin = this.validateSetting('autoScroll', 'margin', options.margin);
autoScroll.speed = this.validateSetting('autoScroll', 'speed' , options.speed);
autoScroll.container =
(isElement(options.container) || isWindow(options.container)
? options.container
: defaults.container);
this.options.autoScrollEnabled = true;
this.options.autoScroll = autoScroll;
return this;
}
if (isBool(options)) {
this.options.autoScrollEnabled = options;
return this;
}
if (options === null) {
delete this.options.autoScrollEnabled;
delete this.options.autoScroll;
return this;
}
return (this.options.autoScrollEnabled
? this.options.autoScroll
: false);
},
/*\
* Interactable.snap
[ method ]
**
* Returns or sets if and how action coordinates are snapped. By
* default, snapping is relative to the pointer coordinates. You can
* change this by setting the
* [`elementOrigin`](https://github.com/taye/interact.js/pull/72).
**
= (boolean | object) `false` if snap is disabled; object with snap properties if snap is enabled
**
* or
**
- options (object | boolean | null) #optional
= (Interactable) this Interactable
> Usage
| interact('.handle').snap({
| mode : 'grid', // event coords should snap to the corners of a grid
| range : Infinity, // the effective distance of snap points
| grid : { x: 100, y: 100 }, // the x and y spacing of the grid points
| gridOffset : { x: 0, y: 0 }, // the offset of the grid points
| });
|
| interact('.handle').snap({
| mode : 'anchor', // snap to specified points
| anchors : [
| { x: 100, y: 100, range: 25 }, // a point with x, y and a specific range
| { x: 200, y: 200 } // a point with x and y. it uses the default range
| ]
| });
|
| interact(document.querySelector('#thing')).snap({
| mode : 'path',
| paths: [
| { // snap to points on these x and y axes
| x: 100,
| y: 100,
| range: 25
| },
| // give this function the x and y page coords and snap to the object returned
| function (x, y) {
| return {
| x: x,
| y: (75 + 50 * Math.sin(x * 0.04)),
| range: 40
| };
| }]
| })
|
| interact(element).snap({
| // do not snap during normal movement.
| // Instead, trigger only one snapped move event
| // immediately before the end event.
| endOnly: true,
|
| // https://github.com/taye/interact.js/pull/72#issue-41813493
| elementOrigin: { x: 0, y: 0 }
| });
\*/
snap: function (options) {
var defaults = defaultOptions.snap;
if (isObject(options)) {
var snap = this.options.snap;
if (snap === defaults) {
snap = {};
}
snap.mode = this.validateSetting('snap', 'mode' , options.mode);
snap.endOnly = this.validateSetting('snap', 'endOnly' , options.endOnly);
snap.actions = this.validateSetting('snap', 'actions' , options.actions);
snap.range = this.validateSetting('snap', 'range' , options.range);
snap.paths = this.validateSetting('snap', 'paths' , options.paths);
snap.grid = this.validateSetting('snap', 'grid' , options.grid);
snap.gridOffset = this.validateSetting('snap', 'gridOffset' , options.gridOffset);
snap.anchors = this.validateSetting('snap', 'anchors' , options.anchors);
snap.elementOrigin = this.validateSetting('snap', 'elementOrigin', options.elementOrigin);
this.options.snapEnabled = true;
this.options.snap = snap;
return this;
}
if (isBool(options)) {
this.options.snapEnabled = options;
return this;
}
if (options === null) {
delete this.options.snapEnabled;
delete this.options.snap;
return this;
}
return (this.options.snapEnabled
? this.options.snap
: false);
},
/*\
* Interactable.inertia
[ method ]
**
* Returns or sets if and how events continue to run after the pointer is released
**
= (boolean | object) `false` if inertia is disabled; `object` with inertia properties if inertia is enabled
**
* or
**
- options (object | boolean | null) #optional
= (Interactable) this Interactable
> Usage
| // enable and use default settings
| interact(element).inertia(true);
|
| // enable and use custom settings
| interact(element).inertia({
| // value greater than 0
| // high values slow the object down more quickly
| resistance : 16,
|
| // the minimum launch speed (pixels per second) that results in inertia start
| minSpeed : 200,
|
| // inertia will stop when the object slows down to this speed
| endSpeed : 20,
|
| // boolean; should actions be resumed when the pointer goes down during inertia
| allowResume : true,
|
| // boolean; should the jump when resuming from inertia be ignored in event.dx/dy
| zeroResumeDelta: false,
|
| // if snap/restrict are set to be endOnly and inertia is enabled, releasing
| // the pointer without triggering inertia will animate from the release
| // point to the snaped/restricted point in the given amount of time (ms)
| smoothEndDuration: 300,
|
| // an array of action types that can have inertia (no gesture)
| actions : ['drag', 'resize']
| });
|
| // reset custom settings and use all defaults
| interact(element).inertia(null);
\*/
inertia: function (options) {
var defaults = defaultOptions.inertia;
if (isObject(options)) {
var inertia = this.options.inertia;
if (inertia === defaults) {
inertia = this.options.inertia = {
resistance : defaults.resistance,
minSpeed : defaults.minSpeed,
endSpeed : defaults.endSpeed,
actions : defaults.actions,
allowResume : defaults.allowResume,
zeroResumeDelta : defaults.zeroResumeDelta,
smoothEndDuration: defaults.smoothEndDuration
};
}
inertia.resistance = this.validateSetting('inertia', 'resistance' , options.resistance);
inertia.minSpeed = this.validateSetting('inertia', 'minSpeed' , options.minSpeed);
inertia.endSpeed = this.validateSetting('inertia', 'endSpeed' , options.endSpeed);
inertia.actions = this.validateSetting('inertia', 'actions' , options.actions);
inertia.allowResume = this.validateSetting('inertia', 'allowResume' , options.allowResume);
inertia.zeroResumeDelta = this.validateSetting('inertia', 'zeroResumeDelta' , options.zeroResumeDelta);
inertia.smoothEndDuration = this.validateSetting('inertia', 'smoothEndDuration', options.smoothEndDuration);
this.options.inertiaEnabled = true;
this.options.inertia = inertia;
return this;
}
if (isBool(options)) {
this.options.inertiaEnabled = options;
return this;
}
if (options === null) {
delete this.options.inertiaEnabled;
delete this.options.inertia;
return this;
}
return (this.options.inertiaEnabled
? this.options.inertia
: false);
},
getAction: function (pointer, interaction, element) {
var action = this.defaultActionChecker(pointer, interaction, element);
if (this.options.actionChecker) {
action = this.options.actionChecker(pointer, action, this, element, interaction);
}
return action;
},
defaultActionChecker: defaultActionChecker,
/*\
* Interactable.actionChecker
[ method ]
*
* Gets or sets the function used to check action to be performed on
* pointerDown
*
- checker (function | null) #optional A function which takes a pointer event, defaultAction string and an interactable as parameters and returns 'drag' 'resize[axes]' or 'gesture' or null.
= (Function | Interactable) The checker function or this Interactable
\*/
actionChecker: function (newValue) {
if (isFunction(newValue)) {
this.options.actionChecker = newValue;
return this;
}
if (newValue === null) {
delete this.options.actionChecker;
return this;
}
return this.options.actionChecker;
},
/*\
* Interactable.getRect
[ method ]
*
* The default function to get an Interactables bounding rect. Can be
* overridden using @Interactable.rectChecker.
*
- element (Element) #optional The element to measure. Meant to be used for selector Interactables which don't have a specific element.
= (object) The object's bounding rectangle.
o {
o top : 0,
o left : 0,
o bottom: 0,
o right : 0,
o width : 0,
o height: 0
o }
\*/
getRect: function rectCheck (element) {
element = element || this._element;
if (this.selector && !(isElement(element))) {
element = this._context.querySelector(this.selector);
}
return getElementRect(element);
},
/*\
* Interactable.rectChecker
[ method ]
*
* Returns or sets the function used to calculate the interactable's
* element's rectangle
*
- checker (function) #optional A function which returns this Interactable's bounding rectangle. See @Interactable.getRect
= (function | object) The checker function or this Interactable
\*/
rectChecker: function (checker) {
if (isFunction(checker)) {
this.getRect = checker;
return this;
}
if (checker === null) {
delete this.options.getRect;
return this;
}
return this.getRect;
},
/*\
* Interactable.styleCursor
[ method ]
*
* Returns or sets whether the action that would be performed when the
* mouse on the element are checked on `mousemove` so that the cursor
* may be styled appropriately
*
- newValue (boolean) #optional
= (boolean | Interactable) The current setting or this Interactable
\*/
styleCursor: function (newValue) {
if (isBool(newValue)) {
this.options.styleCursor = newValue;
return this;
}
if (newValue === null) {
delete this.options.styleCursor;
return this;
}
return this.options.styleCursor;
},
/*\
* Interactable.preventDefault
[ method ]
*
* Returns or sets whether to prevent the browser's default behaviour
* in response to pointer events. Can be set to
* - `true` to always prevent
* - `false` to never prevent
* - `'auto'` to allow interact.js to try to guess what would be best
* - `null` to set to the default ('auto')
*
- newValue (boolean | string | null) #optional `true`, `false` or `'auto'`
= (boolean | string | Interactable) The current setting or this Interactable
\*/
preventDefault: function (newValue) {
if (isBool(newValue) || newValue === 'auto') {
this.options.preventDefault = newValue;
return this;
}
if (newValue === null) {
delete this.options.preventDefault;
return this;
}
return this.options.preventDefault;
},
/*\
* Interactable.origin
[ method ]
*
* Gets or sets the origin of the Interactable's element. The x and y
* of the origin will be subtracted from action event coordinates.
*
- origin (object | string) #optional An object eg. { x: 0, y: 0 } or string 'parent', 'self' or any CSS selector
* OR
- origin (Element) #optional An HTML or SVG Element whose rect will be used
**
= (object) The current origin or this Interactable
\*/
origin: function (newValue) {
if (trySelector(newValue)) {
this.options.origin = newValue;
return this;
}
else if (isObject(newValue)) {
this.options.origin = newValue;
return this;
}
if (newValue === null) {
delete this.options.origin;
return this;
}
return this.options.origin;
},
/*\
* Interactable.deltaSource
[ method ]
*
* Returns or sets the mouse coordinate types used to calculate the
* movement of the pointer.
*
- newValue (string) #optional Use 'client' if you will be scrolling while interacting; Use 'page' if you want autoScroll to work
= (string | object) The current deltaSource or this Interactable
\*/
deltaSource: function (newValue) {
if (newValue === 'page' || newValue === 'client') {
this.options.deltaSource = newValue;
return this;
}
if (newValue === null) {
delete this.options.deltaSource;
return this;
}
return this.options.deltaSource;
},
/*\
* Interactable.restrict
[ method ]
**
* Returns or sets the rectangles within which actions on this
* interactable (after snap calculations) are restricted. By default,
* restricting is relative to the pointer coordinates. You can change
* this by setting the
* [`elementRect`](https://github.com/taye/interact.js/pull/72).
**
- newValue (object) #optional an object with keys drag, resize, and/or gesture whose values are rects, Elements, CSS selectors, or 'parent' or 'self'
= (object) The current restrictions object or this Interactable
**
| interact(element).restrict({
| // the rect will be `interact.getElementRect(element.parentNode)`
| drag: element.parentNode,
|
| // x and y are relative to the the interactable's origin
| resize: { x: 100, y: 100, width: 200, height: 200 }
| })
|
| interact('.draggable').restrict({
| // the rect will be the selected element's parent
| drag: 'parent',
|
| // do not restrict during normal movement.
| // Instead, trigger only one restricted move event
| // immediately before the end event.
| endOnly: true,
|
| // https://github.com/taye/interact.js/pull/72#issue-41813493
| elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
| });
\*/
restrict: function (newValue) {
if (newValue === undefined) {
return this.options.restrict;
}
if (isBool(newValue)) {
defaultOptions.restrictEnabled = newValue;
}
else if (isObject(newValue)) {
var newRestrictions = {};
if (isObject(newValue.drag) || trySelector(newValue.drag)) {
newRestrictions.drag = newValue.drag;
}
if (isObject(newValue.resize) || trySelector(newValue.resize)) {
newRestrictions.resize = newValue.resize;
}
if (isObject(newValue.gesture) || trySelector(newValue.gesture)) {
newRestrictions.gesture = newValue.gesture;
}
if (isBool(newValue.endOnly)) {
newRestrictions.endOnly = newValue.endOnly;
}
if (isObject(newValue.elementRect)) {
newRestrictions.elementRect = newValue.elementRect;
}
this.options.restrictEnabled = true;
this.options.restrict = newRestrictions;
}
else if (newValue === null) {
delete this.options.restrict;
delete this.options.restrictEnabled;
}
return this;
},
/*\
* Interactable.context
[ method ]
*
* Get's the selector context Node of the Interactable. The default is `window.document`.
*
= (Node) The context Node of this Interactable
**
\*/
context: function () {
return this._context;
},
_context: document,
/*\
* Interactable.ignoreFrom
[ method ]
*
* If the target of the `mousedown`, `pointerdown` or `touchstart`
* event or any of it's parents match the given CSS selector or
* Element, no drag/resize/gesture is started.
*
- newValue (string | Element | null) #optional a CSS selector string, an Element or `null` to not ignore any elements
= (string | Element | object) The current ignoreFrom value or this Interactable
**
| interact(element, { ignoreFrom: document.getElementById('no-action') });
| // or
| interact(element).ignoreFrom('input, textarea, a');
\*/
ignoreFrom: function (newValue) {
if (trySelector(newValue)) { // CSS selector to match event.target
this.options.ignoreFrom = newValue;
return this;
}
if (isElement(newValue)) { // specific element
this.options.ignoreFrom = newValue;
return this;
}
if (newValue === null) {
delete this.options.ignoreFrom;
return this;
}
return this.options.ignoreFrom;
},
/*\
* Interactable.allowFrom
[ method ]
*
* A drag/resize/gesture is started only If the target of the
* `mousedown`, `pointerdown` or `touchstart` event or any of it's
* parents match the given CSS selector or Element.
*
- newValue (string | Element | null) #optional a CSS selector string, an Element or `null` to allow from any element
= (string | Element | object) The current allowFrom value or this Interactable
**
| interact(element, { allowFrom: document.getElementById('drag-handle') });
| // or
| interact(element).allowFrom('.handle');
\*/
allowFrom: function (newValue) {
if (trySelector(newValue)) { // CSS selector to match event.target
this.options.allowFrom = newValue;
return this;
}
if (isElement(newValue)) { // specific element
this.options.allowFrom = newValue;
return this;
}
if (newValue === null) {
delete this.options.allowFrom;
return this;
}
return this.options.allowFrom;
},
/*\
* Interactable.validateSetting
[ method ]
*
- context (string) eg. 'snap', 'autoScroll'
- option (string) The name of the value being set
- value (any type) The value being validated
*
= (typeof value) A valid value for the give context-option pair
* - null if defaultOptions[context][value] is undefined
* - value if it is the same type as defaultOptions[context][value],
* - this.options[context][value] if it is the same type as defaultOptions[context][value],
* - or defaultOptions[context][value]
\*/
validateSetting: function (context, option, value) {
var defaults = defaultOptions[context],
current = this.options[context];
if (defaults !== undefined && defaults[option] !== undefined) {
if ('objectTypes' in defaults && defaults.objectTypes.test(option)) {
if (isObject(value)) { return value; }
else {
return (option in current && isObject(current[option])
? current [option]
: defaults[option]);
}
}
if ('arrayTypes' in defaults && defaults.arrayTypes.test(option)) {
if (isArray(value)) { return value; }
else {
return (option in current && isArray(current[option])
? current[option]
: defaults[option]);
}
}
if ('stringTypes' in defaults && defaults.stringTypes.test(option)) {
if (isString(value)) { return value; }
else {
return (option in current && isString(current[option])
? current[option]
: defaults[option]);
}
}
if ('numberTypes' in defaults && defaults.numberTypes.test(option)) {
if (isNumber(value)) { return value; }
else {
return (option in current && isNumber(current[option])
? current[option]
: defaults[option]);
}
}
if ('boolTypes' in defaults && defaults.boolTypes.test(option)) {
if (isBool(value)) { return value; }
else {
return (option in current && isBool(current[option])
? current[option]
: defaults[option]);
}
}
if ('elementTypes' in defaults && defaults.elementTypes.test(option)) {
if (isElement(value)) { return value; }
else {
return (option in current && isElement(current[option])
? current[option]
: defaults[option]);
}
}
}
return null;
},
/*\
* Interactable.element
[ method ]
*
* If this is not a selector Interactable, it returns the element this
* interactable represents
*
= (Element) HTML / SVG Element
\*/
element: function () {
return this._element;
},
/*\
* Interactable.fire
[ method ]
*
* Calls listeners for the given InteractEvent type bound globally
* and directly to this Interactable
*
- iEvent (InteractEvent) The InteractEvent object to be fired on this Interactable
= (Interactable) this Interactable
\*/
fire: function (iEvent) {
if (!(iEvent && iEvent.type) || !contains(eventTypes, iEvent.type)) {
return this;
}
var listeners,
i,
len,
onEvent = 'on' + iEvent.type,
funcName = '';
// Interactable#on() listeners
if (iEvent.type in this._iEvents) {
listeners = this._iEvents[iEvent.type];
for (i = 0, len = listeners.length; i < len && !iEvent.immediatePropagationStopped; i++) {
funcName = listeners[i].name;
listeners[i](iEvent);
}
}
// interactable.onevent listener
if (isFunction(this[onEvent])) {
funcName = this[onEvent].name;
this[onEvent](iEvent);
}
// interact.on() listeners
if (iEvent.type in globalEvents && (listeners = globalEvents[iEvent.type])) {
for (i = 0, len = listeners.length; i < len && !iEvent.immediatePropagationStopped; i++) {
funcName = listeners[i].name;
listeners[i](iEvent);
}
}
return this;
},
/*\
* Interactable.on
[ method ]
*
* Binds a listener for an InteractEvent or DOM event.
*
- eventType (string | array) The type of event or array of types to listen for
- listener (function) The function to be called on the given event(s)
- useCapture (boolean) #optional useCapture flag for addEventListener
= (object) This Interactable
\*/
on: function (eventType, listener, useCapture) {
var i;
if (isArray(eventType)) {
for (i = 0; i < eventType.length; i++) {
this.on(eventType[i], listener, useCapture);
}
return this;
}
if (eventType === 'wheel') {
eventType = wheelEvent;
}
// convert to boolean
useCapture = useCapture? true: false;
if (contains(eventTypes, eventType)) {
// if this type of event was never bound to this Interactable
if (!(eventType in this._iEvents)) {
this._iEvents[eventType] = [listener];
}
else {
this._iEvents[eventType].push(listener);
}
}
// delegated event for selector
else if (this.selector) {
if (!delegatedEvents[eventType]) {
delegatedEvents[eventType] = {
selectors: [],
contexts : [],
listeners: []
};
// add delegate listener functions
for (i = 0; i < documents.length; i++) {
events.add(documents[i], eventType, delegateListener);
events.add(documents[i], eventType, delegateUseCapture, true);
}
}
var delegated = delegatedEvents[eventType],
index;
for (index = delegated.selectors.length - 1; index >= 0; index--) {
if (delegated.selectors[index] === this.selector
&& delegated.contexts[index] === this._context) {
break;
}
}
if (index === -1) {
index = delegated.selectors.length;
delegated.selectors.push(this.selector);
delegated.contexts .push(this._context);
delegated.listeners.push([]);
}
// keep listener and useCapture flag
delegated.listeners[index].push([listener, useCapture]);
}
else {
events.add(this._element, eventType, listener, useCapture);
}
return this;
},
/*\
* Interactable.off
[ method ]
*
* Removes an InteractEvent or DOM event listener
*
- eventType (string | array) The type of event or array of types that were listened for
- listener (function) The listener function to be removed
- useCapture (boolean) #optional useCapture flag for removeEventListener
= (object) This Interactable
\*/
off: function (eventType, listener, useCapture) {
var i;
if (isArray(eventType)) {
for (i = 0; i < eventType.length; i++) {
this.off(eventType[i], listener, useCapture);
}
return this;
}
var eventList,
index = -1;
// convert to boolean
useCapture = useCapture? true: false;
if (eventType === 'wheel') {
eventType = wheelEvent;
}
// if it is an action event type
if (contains(eventTypes, eventType)) {
eventList = this._iEvents[eventType];
if (eventList && (index = indexOf(eventList, listener)) !== -1) {
this._iEvents[eventType].splice(index, 1);
}
}
// delegated event
else if (this.selector) {
var delegated = delegatedEvents[eventType],
matchFound = false;
if (!delegated) { return this; }
// count from last index of delegated to 0
for (index = delegated.selectors.length - 1; index >= 0; index--) {
// look for matching selector and context Node
if (delegated.selectors[index] === this.selector
&& delegated.contexts[index] === this._context) {
var listeners = delegated.listeners[index];
// each item of the listeners array is an array: [function, useCaptureFlag]
for (i = listeners.length - 1; i >= 0; i--) {
var fn = listeners[i][0],
useCap = listeners[i][1];
// check if the listener functions and useCapture flags match
if (fn === listener && useCap === useCapture) {
// remove the listener from the array of listeners
listeners.splice(i, 1);
// if all listeners for this interactable have been removed
// remove the interactable from the delegated arrays
if (!listeners.length) {
delegated.selectors.splice(index, 1);
delegated.contexts .splice(index, 1);
delegated.listeners.splice(index, 1);
// remove delegate function from context
events.remove(this._context, eventType, delegateListener);
events.remove(this._context, eventType, delegateUseCapture, true);
// remove the arrays if they are empty
if (!delegated.selectors.length) {
delegatedEvents[eventType] = null;
}
}
// only remove one listener
matchFound = true;
break;
}
}
if (matchFound) { break; }
}
}
}
// remove listener from this Interatable's element
else {
events.remove(this, listener, useCapture);
}
return this;
},
/*\
* Interactable.set
[ method ]
*
* Reset the options of this Interactable
- options (object) The new settings to apply
= (object) This Interactablw
\*/
set: function (options) {
if (!options || !isObject(options)) {
options = {};
}
this.options = new IOptions(options);
this.draggable ('draggable' in options? options.draggable : this.options.draggable );
this.dropzone ('dropzone' in options? options.dropzone : this.options.dropzone );
this.resizable ('resizable' in options? options.resizable : this.options.resizable );
this.gesturable('gesturable' in options? options.gesturable: this.options.gesturable);
var settings = [
'accept', 'actionChecker', 'allowFrom', 'autoScroll', 'deltaSource',
'dropChecker', 'ignoreFrom', 'inertia', 'origin', 'preventDefault',
'rectChecker', 'restrict', 'snap', 'styleCursor'
];
for (var i = 0, len = settings.length; i < len; i++) {
var setting = settings[i];
if (setting in options) {
this[setting](options[setting]);
}
}
return this;
},
/*\
* Interactable.unset
[ method ]
*
* Remove this interactable from the list of interactables and remove
* it's drag, drop, resize and gesture capabilities
*
= (object) @interact
\*/
unset: function () {
events.remove(this, 'all');
if (!isString(this.selector)) {
events.remove(this, 'all');
if (this.options.styleCursor) {
this._element.style.cursor = '';
}
}
else {
// remove delegated events
for (var type in delegatedEvents) {
var delegated = delegatedEvents[type];
for (var i = 0; i < delegated.selectors.length; i++) {
if (delegated.selectors[i] === this.selector
&& delegated.contexts[i] === this._context) {
delegated.selectors.splice(i, 1);
delegated.contexts .splice(i, 1);
delegated.listeners.splice(i, 1);
// remove the arrays if they are empty
if (!delegated.selectors.length) {
delegatedEvents[type] = null;
}
}
events.remove(this._context, type, delegateListener);
events.remove(this._context, type, delegateUseCapture, true);
break;
}
}
}
this.dropzone(false);
interactables.splice(indexOf(interactables, this), 1);
return interact;
}
};
Interactable.prototype.gestureable = Interactable.prototype.gesturable;
Interactable.prototype.resizeable = Interactable.prototype.resizable;
/*\
* interact.isSet
[ method ]
*
* Check if an element has been set
- element (Element) The Element being searched for
= (boolean) Indicates if the element or CSS selector was previously passed to interact
\*/
interact.isSet = function(element, options) {
return interactables.indexOfElement(element, options && options.context) !== -1;
};
/*\
* interact.on
[ method ]
*
* Adds a global listener for an InteractEvent or adds a DOM event to
* `document`
*
- type (string | array) The type of event or array of types to listen for
- listener (function) The function to be called on the given event(s)
- useCapture (boolean) #optional useCapture flag for addEventListener
= (object) interact
\*/
interact.on = function (type, listener, useCapture) {
if (isArray(type)) {
for (var i = 0; i < type.length; i++) {
interact.on(type[i], listener, useCapture);
}
return interact;
}
// if it is an InteractEvent type, add listener to globalEvents
if (contains(eventTypes, type)) {
// if this type of event was never bound
if (!globalEvents[type]) {
globalEvents[type] = [listener];
}
else {
globalEvents[type].push(listener);
}
}
// If non InteractEvent type, addEventListener to document
else {
events.add(document, type, listener, useCapture);
}
return interact;
};
/*\
* interact.off
[ method ]
*
* Removes a global InteractEvent listener or DOM event from `document`
*
- type (string | array) The type of event or array of types that were listened for
- listener (function) The listener function to be removed
- useCapture (boolean) #optional useCapture flag for removeEventListener
= (object) interact
\*/
interact.off = function (type, listener, useCapture) {
if (isArray(type)) {
for (var i = 0; i < type.length; i++) {
interact.off(type[i], listener, useCapture);
}
return interact;
}
if (!contains(eventTypes, type)) {
events.remove(document, type, listener, useCapture);
}
else {
var index;
if (type in globalEvents
&& (index = indexOf(globalEvents[type], listener)) !== -1) {
globalEvents[type].splice(index, 1);
}
}
return interact;
};
/*\
* interact.simulate
[ method ]
*
* Simulate pointer down to begin to interact with an interactable element
- action (string) The action to be performed - drag, resize, etc.
- element (Element) The DOM Element to resize/drag
- pointerEvent (object) #optional Pointer event whose pageX/Y coordinates will be the starting point of the interact drag/resize
= (object) interact
\*/
interact.simulate = function (action, element, pointerEvent) {
var event = {},
clientRect;
if (action === 'resize') {
action = 'resizexy';
}
// return if the action is not recognised
if (!/^(drag|resizexy|resizex|resizey)$/.test(action)) {
return interact;
}
if (pointerEvent) {
extend(event, pointerEvent);
}
else {
clientRect = (element instanceof SVGElement)
? element.getBoundingClientRect()
: clientRect = element.getClientRects()[0];
if (action === 'drag') {
event.pageX = clientRect.left + clientRect.width / 2;
event.pageY = clientRect.top + clientRect.height / 2;
}
else {
event.pageX = clientRect.right;
event.pageY = clientRect.bottom;
}
}
event.target = event.currentTarget = element;
event.preventDefault = event.stopPropagation = blank;
listeners.pointerDown(event, action);
return interact;
};
/*\
* interact.enableDragging
[ method ]
*
* Returns or sets whether dragging is enabled for any Interactables
*
- newValue (boolean) #optional `true` to allow the action; `false` to disable action for all Interactables
= (boolean | object) The current setting or interact
\*/
interact.enableDragging = function (newValue) {
if (newValue !== null && newValue !== undefined) {
actionIsEnabled.drag = newValue;
return interact;
}
return actionIsEnabled.drag;
};
/*\
* interact.enableResizing
[ method ]
*
* Returns or sets whether resizing is enabled for any Interactables
*
- newValue (boolean) #optional `true` to allow the action; `false` to disable action for all Interactables
= (boolean | object) The current setting or interact
\*/
interact.enableResizing = function (newValue) {
if (newValue !== null && newValue !== undefined) {
actionIsEnabled.resize = newValue;
return interact;
}
return actionIsEnabled.resize;
};
/*\
* interact.enableGesturing
[ method ]
*
* Returns or sets whether gesturing is enabled for any Interactables
*
- newValue (boolean) #optional `true` to allow the action; `false` to disable action for all Interactables
= (boolean | object) The current setting or interact
\*/
interact.enableGesturing = function (newValue) {
if (newValue !== null && newValue !== undefined) {
actionIsEnabled.gesture = newValue;
return interact;
}
return actionIsEnabled.gesture;
};
interact.eventTypes = eventTypes;
/*\
* interact.debug
[ method ]
*
* Returns debugging data
= (object) An object with properties that outline the current state and expose internal functions and variables
\*/
interact.debug = function () {
var interaction = interactions[0] || new Interaction();
return {
interactions : interactions,
target : interaction.target,
dragging : interaction.dragging,
resizing : interaction.resizing,
gesturing : interaction.gesturing,
prepared : interaction.prepared,
matches : interaction.matches,
matchElements : interaction.matchElements,
prevCoords : interaction.prevCoords,
startCoords : interaction.startCoords,
pointerIds : interaction.pointerIds,
pointers : interaction.pointers,
addPointer : listeners.addPointer,
removePointer : listeners.removePointer,
recordPointer : listeners.recordPointer,
snap : interaction.snapStatus,
restrict : interaction.restrictStatus,
inertia : interaction.inertiaStatus,
downTime : interaction.downTimes[0],
downEvent : interaction.downEvent,
downPointer : interaction.downPointer,
prevEvent : interaction.prevEvent,
Interactable : Interactable,
IOptions : IOptions,
interactables : interactables,
pointerIsDown : interaction.pointerIsDown,
defaultOptions : defaultOptions,
defaultActionChecker : defaultActionChecker,
actionCursors : actionCursors,
dragMove : listeners.dragMove,
resizeMove : listeners.resizeMove,
gestureMove : listeners.gestureMove,
pointerUp : listeners.pointerUp,
pointerDown : listeners.pointerDown,
pointerMove : listeners.pointerMove,
pointerHover : listeners.pointerHover,
events : events,
globalEvents : globalEvents,
delegatedEvents : delegatedEvents
};
};
// expose the functions used to calculate multi-touch properties
interact.getTouchAverage = touchAverage;
interact.getTouchBBox = touchBBox;
interact.getTouchDistance = touchDistance;
interact.getTouchAngle = touchAngle;
interact.getElementRect = getElementRect;
interact.matchesSelector = matchesSelector;
interact.closest = closest;
/*\
* interact.margin
[ method ]
*
* Returns or sets the margin for autocheck resizing used in
* @Interactable.getAction. That is the distance from the bottom and right
* edges of an element clicking in which will start resizing
*
- newValue (number) #optional
= (number | interact) The current margin value or interact
\*/
interact.margin = function (newvalue) {
if (isNumber(newvalue)) {
margin = newvalue;
return interact;
}
return margin;
};
/*\
* interact.styleCursor
[ styleCursor ]
*
* Returns or sets whether the cursor style of the document is changed
* depending on what action is being performed
*
- newValue (boolean) #optional
= (boolean | interact) The current setting of interact
\*/
interact.styleCursor = function (newValue) {
if (isBool(newValue)) {
defaultOptions.styleCursor = newValue;
return interact;
}
return defaultOptions.styleCursor;
};
/*\
* interact.autoScroll
[ method ]
*
* Returns or sets whether or not actions near the edges of the window or
* specified container element trigger autoScroll by default
*
- options (boolean | object) true or false to simply enable or disable or an object with margin, distance, container and interval properties
= (object) interact
* or
= (boolean | object) `false` if autoscroll is disabled and the default autoScroll settings if it is enabled
\*/
interact.autoScroll = function (options) {
var defaults = defaultOptions.autoScroll;
if (isObject(options)) {
defaultOptions.autoScrollEnabled = true;
if (isNumber(options.margin)) { defaults.margin = options.margin;}
if (isNumber(options.speed) ) { defaults.speed = options.speed ;}
defaults.container =
(isElement(options.container) || isWindow(options.container)
? options.container
: defaults.container);
return interact;
}
if (isBool(options)) {
defaultOptions.autoScrollEnabled = options;
return interact;
}
// return the autoScroll settings if autoScroll is enabled
// otherwise, return false
return defaultOptions.autoScrollEnabled? defaults: false;
};
/*\
* interact.snap
[ method ]
*
* Returns or sets whether actions are constrained to a grid or a
* collection of coordinates
*
- options (boolean | object) #optional New settings
* `true` or `false` to simply enable or disable
* or an object with some of the following properties
o {
o mode : 'grid', 'anchor' or 'path',
o range : the distance within which snapping to a point occurs,
o actions: ['drag', 'resizex', 'resizey', 'resizexy'], an array of action types that can snapped (['drag'] by default) (no gesture)
o grid : {
o x, y: the distances between the grid lines,
o },
o gridOffset: {
o x, y: the x/y-axis values of the grid origin
o },
o anchors: [
o {
o x: x coordinate to snap to,
o y: y coordinate to snap to,
o range: optional range for this anchor
o }
o {
o another anchor
o }
o ]
o }
*
= (object | interact) The default snap settings object or interact
\*/
interact.snap = function (options) {
var snap = defaultOptions.snap;
if (isObject(options)) {
defaultOptions.snapEnabled = true;
if (isString(options.mode) ) { snap.mode = options.mode; }
if (isBool (options.endOnly) ) { snap.endOnly = options.endOnly; }
if (isNumber(options.range) ) { snap.range = options.range; }
if (isArray (options.actions) ) { snap.actions = options.actions; }
if (isArray (options.anchors) ) { snap.anchors = options.anchors; }
if (isObject(options.grid) ) { snap.grid = options.grid; }
if (isObject(options.gridOffset) ) { snap.gridOffset = options.gridOffset; }
if (isObject(options.elementOrigin)) { snap.elementOrigin = options.elementOrigin; }
return interact;
}
if (isBool(options)) {
defaultOptions.snapEnabled = options;
return interact;
}
return defaultOptions.snapEnabled;
};
/*\
* interact.inertia
[ method ]
*
* Returns or sets inertia settings.
*
* See @Interactable.inertia
*
- options (boolean | object) #optional New settings
* `true` or `false` to simply enable or disable
* or an object of inertia options
= (object | interact) The default inertia settings object or interact
\*/
interact.inertia = function (options) {
var inertia = defaultOptions.inertia;
if (isObject(options)) {
defaultOptions.inertiaEnabled = true;
if (isNumber(options.resistance) ) { inertia.resistance = options.resistance ; }
if (isNumber(options.minSpeed) ) { inertia.minSpeed = options.minSpeed ; }
if (isNumber(options.endSpeed) ) { inertia.endSpeed = options.endSpeed ; }
if (isNumber(options.smoothEndDuration)) { inertia.smoothEndDuration = options.smoothEndDuration; }
if (isBool (options.allowResume) ) { inertia.allowResume = options.allowResume ; }
if (isBool (options.zeroResumeDelta) ) { inertia.zeroResumeDelta = options.zeroResumeDelta ; }
if (isArray (options.actions) ) { inertia.actions = options.actions ; }
return interact;
}
if (isBool(options)) {
defaultOptions.inertiaEnabled = options;
return interact;
}
return {
enabled: defaultOptions.inertiaEnabled,
resistance: inertia.resistance,
minSpeed: inertia.minSpeed,
endSpeed: inertia.endSpeed,
actions: inertia.actions,
allowResume: inertia.allowResume,
zeroResumeDelta: inertia.zeroResumeDelta
};
};
/*\
* interact.supportsTouch
[ method ]
*
= (boolean) Whether or not the browser supports touch input
\*/
interact.supportsTouch = function () {
return supportsTouch;
};
/*\
* interact.supportsPointerEvent
[ method ]
*
= (boolean) Whether or not the browser supports PointerEvents
\*/
interact.supportsPointerEvent = function () {
return supportsPointerEvent;
};
/*\
* interact.currentAction
[ method ]
*
= (string) What action is currently being performed
\*/
interact.currentAction = function () {
for (var i = 0, len = interactions.length; i < len; i++) {
var action = interactions[i].currentAction();
if (action) { return action; }
}
return null;
};
/*\
* interact.stop
[ method ]
*
* Cancels the current interaction
*
- event (Event) An event on which to call preventDefault()
= (object) interact
\*/
interact.stop = function (event) {
for (var i = interactions.length - 1; i > 0; i--) {
interactions[i].stop(event);
}
return interact;
};
/*\
* interact.dynamicDrop
[ method ]
*
* Returns or sets whether the dimensions of dropzone elements are
* calculated on every dragmove or only on dragstart for the default
* dropChecker
*
- newValue (boolean) #optional True to check on each move. False to check only before start
= (boolean | interact) The current setting or interact
\*/
interact.dynamicDrop = function (newValue) {
if (isBool(newValue)) {
//if (dragging && dynamicDrop !== newValue && !newValue) {
//calcRects(dropzones);
//}
dynamicDrop = newValue;
return interact;
}
return dynamicDrop;
};
/*\
* interact.deltaSource
[ method ]
* Returns or sets weather pageX/Y or clientX/Y is used to calculate dx/dy.
*
* See @Interactable.deltaSource
*
- newValue (string) #optional 'page' or 'client'
= (string | Interactable) The current setting or interact
\*/
interact.deltaSource = function (newValue) {
if (newValue === 'page' || newValue === 'client') {
defaultOptions.deltaSource = newValue;
return this;
}
return defaultOptions.deltaSource;
};
/*\
* interact.restrict
[ method ]
*
* Returns or sets the default rectangles within which actions (after snap
* calculations) are restricted.
*
* See @Interactable.restrict
*
- newValue (object) #optional an object with keys drag, resize, and/or gesture and rects or Elements as values
= (object) The current restrictions object or interact
\*/
interact.restrict = function (newValue) {
var defaults = defaultOptions.restrict;
if (newValue === undefined) {
return defaultOptions.restrict;
}
if (isBool(newValue)) {
defaultOptions.restrictEnabled = newValue;
}
else if (isObject(newValue)) {
if (isObject(newValue.drag) || /^parent$|^self$/.test(newValue.drag)) {
defaults.drag = newValue.drag;
}
if (isObject(newValue.resize) || /^parent$|^self$/.test(newValue.resize)) {
defaults.resize = newValue.resize;
}
if (isObject(newValue.gesture) || /^parent$|^self$/.test(newValue.gesture)) {
defaults.gesture = newValue.gesture;
}
if (isBool(newValue.endOnly)) {
defaults.endOnly = newValue.endOnly;
}
if (isObject(newValue.elementRect)) {
defaults.elementRect = newValue.elementRect;
}
defaultOptions.restrictEnabled = true;
}
else if (newValue === null) {
defaults.drag = defaults.resize = defaults.gesture = null;
defaults.endOnly = false;
}
return this;
};
/*\
* interact.pointerMoveTolerance
[ method ]
* Returns or sets the distance the pointer must be moved before an action
* sequence occurs. This also affects tolerance for tap events.
*
- newValue (number) #optional The movement from the start position must be greater than this value
= (number | Interactable) The current setting or interact
\*/
interact.pointerMoveTolerance = function (newValue) {
if (isNumber(newValue)) {
defaultOptions.pointerMoveTolerance = newValue;
return this;
}
return defaultOptions.pointerMoveTolerance;
};
/*\
* interact.maxInteractions
[ method ]
**
* Returns or sets the maximum number of concurrent interactions allowed.
* By default only 1 interaction is allowed at a time (for backwards
* compatibility). To allow multiple interactions on the same Interactables
* and elements, you need to enable it in the draggable, resizable and
* gesturable `'max'` and `'maxPerElement'` options.
**
- newValue (number) #optional Any number. newValue <= 0 means no interactions.
\*/
interact.maxInteractions = function (newValue) {
if (isNumber(newValue)) {
maxInteractions = newValue;
return this;
}
return maxInteractions;
};
function endAllInteractions (event) {
for (var i = 0; i < interactions.length; i++) {
interactions[i].pointerEnd(event, event);
}
}
function listenToDocument (doc) {
if (contains(documents, doc)) { return; }
var win = doc.defaultView || doc.parentWindow;
// add delegate event listener
for (var eventType in delegatedEvents) {
events.add(doc, eventType, delegateListener);
events.add(doc, eventType, delegateUseCapture, true);
}
if (PointerEvent) {
if (PointerEvent === win.MSPointerEvent) {
pEventTypes = {
up: 'MSPointerUp', down: 'MSPointerDown', over: 'mouseover',
out: 'mouseout', move: 'MSPointerMove', cancel: 'MSPointerCancel' };
}
else {
pEventTypes = {
up: 'pointerup', down: 'pointerdown', over: 'pointerover',
out: 'pointerout', move: 'pointermove', cancel: 'pointercancel' };
}
events.add(doc, pEventTypes.down , listeners.selectorDown );
events.add(doc, pEventTypes.move , listeners.pointerMove );
events.add(doc, pEventTypes.over , listeners.pointerOver );
events.add(doc, pEventTypes.out , listeners.pointerOut );
events.add(doc, pEventTypes.up , listeners.pointerUp );
events.add(doc, pEventTypes.cancel, listeners.pointerCancel);
// autoscroll
events.add(doc, pEventTypes.move, autoScroll.edgeMove);
}
else {
events.add(doc, 'mousedown', listeners.selectorDown);
events.add(doc, 'mousemove', listeners.pointerMove );
events.add(doc, 'mouseup' , listeners.pointerUp );
events.add(doc, 'mouseover', listeners.pointerOver );
events.add(doc, 'mouseout' , listeners.pointerOut );
events.add(doc, 'touchstart' , listeners.selectorDown );
events.add(doc, 'touchmove' , listeners.pointerMove );
events.add(doc, 'touchend' , listeners.pointerUp );
events.add(doc, 'touchcancel', listeners.pointerCancel);
// autoscroll
events.add(doc, 'mousemove', autoScroll.edgeMove);
events.add(doc, 'touchmove', autoScroll.edgeMove);
}
events.add(win, 'blur', endAllInteractions);
try {
if (win.frameElement) {
var parentDoc = win.frameElement.ownerDocument,
parentWindow = parentDoc.defaultView;
events.add(parentDoc , 'mouseup' , listeners.pointerEnd);
events.add(parentDoc , 'touchend' , listeners.pointerEnd);
events.add(parentDoc , 'touchcancel' , listeners.pointerEnd);
events.add(parentDoc , 'pointerup' , listeners.pointerEnd);
events.add(parentDoc , 'MSPointerUp' , listeners.pointerEnd);
events.add(parentWindow, 'blur' , endAllInteractions );
}
}
catch (error) {
interact.windowParentError = error;
}
// For IE's lack of Event#preventDefault
if (events.useAttachEvent) {
events.add(doc, 'selectstart', function (event) {
var interaction = interactions[0];
if (interaction.currentAction()) {
interaction.checkAndPreventDefault(event);
}
});
}
documents.push(doc);
}
listenToDocument(document);
function indexOf (array, target) {
for (var i = 0, len = array.length; i < len; i++) {
if (array[i] === target) {
return i;
}
}
return -1;
}
function contains (array, target) {
return indexOf(array, target) !== -1;
}
function matchesSelector (element, selector, nodeList) {
if (ie8MatchesSelector) {
return ie8MatchesSelector(element, selector, nodeList);
}
return element[prefixedMatchesSelector](selector);
}
// For IE8's lack of an Element#matchesSelector
// taken from http://tanalin.com/en/blog/2012/12/matches-selector-ie8/ and modified
if (!(prefixedMatchesSelector in Element.prototype) || !isFunction(Element.prototype[prefixedMatchesSelector])) {
ie8MatchesSelector = function (element, selector, elems) {
elems = elems || element.parentNode.querySelectorAll(selector);
for (var i = 0, len = elems.length; i < len; i++) {
if (elems[i] === element) {
return true;
}
}
return false;
};
}
// requestAnimationFrame polyfill
(function() {
var lastTime = 0,
vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
reqFrame = window[vendors[x]+'RequestAnimationFrame'];
cancelFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!reqFrame) {
reqFrame = function(callback) {
var currTime = new Date().getTime(),
timeToCall = Math.max(0, 16 - (currTime - lastTime)),
id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!cancelFrame) {
cancelFrame = function(id) {
clearTimeout(id);
};
}
}());
/* global exports: true, module, define */
// http://documentcloud.github.io/underscore/docs/underscore.html#section-11
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = interact;
}
exports.interact = interact;
}
// AMD
else if (typeof define === 'function' && define.amd) {
define('interact', function() {
return interact;
});
}
else {
window.interact = interact;
}
} ());
|
var base64url = require('urlsafe-base64')
, After = require('json-list-response').After
, inherits = require('util').inherits
module.exports = DateAfter
function DateAfter(value, options) {
After.call(this, value, options)
this.skip = 0
this.value = 0
if (value) {
value = base64url.decode(value)
if (value.length === 9) {
this.value = value.readDoubleBE(0)
this.skip = value.readUInt8(8)
}
}
}
inherits(DateAfter, After)
DateAfter.prototype.add = function (row) {
var value = row[this.key]
if (!value) return
if (+this.value === +value) {
this.skip++
} else {
this.skip = 0
this.value = value
}
}
DateAfter.prototype.toString = function () {
if (!this.value) return ''
var buf = new Buffer(9)
buf.writeDoubleBE(+this.value || 0, 0)
buf.writeUInt8(this.skip, 8)
return base64url.encode(buf)
}
DateAfter.prototype.mongoSorting = function (list, sorting) {
var obj = {}
obj[sorting.key] = {}
obj[sorting.key][sorting.descending ? '$lte' : '$gte'] = new Date(this.value)
list.selector.$and.push(obj)
list.cursor.skip(this.skip + 1)
}
|
export goCommand from './goCommand'
export goReducer from './goReducer'
export parseBestmove from './parseBestmove'
export parseId from './parseId'
export parseInfo from './parseInfo'
export parseOption from './parseOption'
export initReducer from './initReducer'
|
exports.translate = function(tag) {
return this.import("riot").compile(tag);
};
|
en.resources.define("audio",{
name: "Engine",
src: "./audio/ship_engine.ogg",
}, function(content, callback){
var sound = client.audio.createSound();
sound.load(content.src, function(sound){
content.sound = sound;
callback(content.type, content);
});
}, function(content){
return content.sound;
}); |
var express = require("express");
var Pusher = require("pusher");
var bodyParser = require("body-parser");
var env = require("node-env-file");
var app = express();
app.use(bodyParser.urlencoded());
try {
env(__dirname + "/.env");
} catch (_error) {
error = _error;
console.log(error);
}
var pusher = new Pusher({
appId: process.env.PUSHER_APP_ID,
key: process.env.PUSHER_APP_KEY,
secret: process.env.PUSHER_APP_SECRET
});
app.use('/', express["static"]('dist'));
app.post("/pusher/auth", function(req, res) {
var socketId = req.body.socket_id;
var channel = req.body.channel_name;
var auth = pusher.authenticate(socketId, channel);
res.send(auth);
});
var port = process.env.PORT || 5000;
app.listen(port);
|
var app = angular.module("ethics-app");
// User create controller
app.controller("userCreateController", function($scope, $rootScope, $routeParams, $filter, $translate, $location, config, $window, $authenticationService, $userService, $universityService, $instituteService) {
/*************************************************
FUNCTIONS
*************************************************/
/**
* [redirect description]
* @param {[type]} path [description]
* @return {[type]} [description]
*/
$scope.redirect = function(path){
$location.url(path);
};
/**
* [description]
* @param {[type]} former_status [description]
* @return {[type]} [description]
*/
$scope.getGroupName = function(former_status){
if(former_status){
return $filter('translate')('FORMER_INSTITUTES');
} else {
return $filter('translate')('INSTITUTES');
}
};
/**
* [send description]
* @return {[type]} [description]
*/
$scope.send = function(){
// Validate input
if($scope.createUserForm.$invalid) {
// Update UI
$scope.createUserForm.email_address.$pristine = false;
$scope.createUserForm.title.$pristine = false;
$scope.createUserForm.first_name.$pristine = false;
$scope.createUserForm.last_name.$pristine = false;
$scope.createUserForm.institute_id.$pristine = false;
$scope.createUserForm.blocked.$pristine = false;
} else {
$scope.$parent.loading = { status: true, message: $filter('translate')('CREATING_NEW_USER') };
// Create new user
$userService.create($scope.new_user)
.then(function onSuccess(response) {
var user = response.data;
// Redirect
$scope.redirect("/users/" + user.user_id);
})
.catch(function onError(response) {
$window.alert(response.data);
});
}
};
/**
* [description]
* @param {[type]} related_data [description]
* @return {[type]} [description]
*/
$scope.load = function(related_data){
// Check which kind of related data needs to be requested
switch (related_data) {
case 'universities': {
$scope.$parent.loading = { status: true, message: $filter('translate')('LOADING_UNIVERSITIES') };
// Load universities
$universityService.list({
orderby: 'name.asc',
limit: null,
offset: null
})
.then(function onSuccess(response) {
$scope.universities = response.data;
$scope.$parent.loading = { status: false, message: "" };
})
.catch(function onError(response) {
$window.alert(response.data);
});
break;
}
case 'institutes': {
if($scope.university_id){
if($scope.university_id !== null){
$scope.$parent.loading = { status: true, message: $filter('translate')('LOADING_INSTITUTES') };
// Load related institutes
$instituteService.listByUniversity($scope.university_id, {
orderby: 'name.asc',
limit: null,
offset: null,
former: false
})
.then(function onSuccess(response) {
$scope.institutes = response.data;
$scope.$parent.loading = { status: false, message: "" };
})
.catch(function onError(response) {
$window.alert(response.data);
});
} else {
// Reset institutes
$scope.institutes = [];
$scope.new_user.institute_id = null;
}
} else {
// Reset institutes
$scope.institutes = [];
$scope.new_user.institute_id = null;
}
break;
}
}
};
/*************************************************
INIT
*************************************************/
$scope.new_user = $userService.init();
$scope.authenticated_member = $authenticationService.get();
// Load universities
$scope.load('universities');
// Set default value by member
$scope.university_id = $scope.authenticated_member.university_id;
// Load related institutes
$scope.load('institutes');
// Set default value by member
$scope.new_user.institute_id = $scope.authenticated_member.institute_id;
});
|
#!/usr/bin/env node
var child_process = require('child_process');
var argv = require('yargs')
.boolean(['readability', 'open'])
.argv;
var pdfdify = require('../lib');
var srcUrl = argv._[0];
console.log("Convertering: '"+srcUrl+"'");
pdfdify.convert({
title:argv.title|| srcUrl,
readability:argv.readability,
srcUrl:srcUrl
},function (err, pdfFile) {
if (err) {
throw err;
}
console.log("Created: '"+pdfFile+"'");
if(argv.open) {
child_process.exec('open "'+pdfFile+'"');
}
}); |
/**
* Sizzle Engine Support v2.2.0
* http://rightjs.org/plugins/sizzle
*
* Copyright (C) 2009-2011 Nikolay Nemshilov
*/
/**
* sizzle initialization script
*
* Copyright (C) 2010-2011 Nikolay Nemshilov
*/
RightJS.Sizzle = {
version: '2.2.0'
};
/*!
* Sizzle CSS Selector Engine - v1.0
* Copyright 2009, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
* More information: http://sizzlejs.com/
*/
(function(){
var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
done = 0,
toString = Object.prototype.toString,
hasDuplicate = false,
baseHasDuplicate = true;
// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
// Thus far that includes Google Chrome.
[0, 0].sort(function(){
baseHasDuplicate = false;
return 0;
});
var Sizzle = function(selector, context, results, seed) {
results = results || [];
context = context || document;
var origContext = context;
if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
return [];
}
if ( !selector || typeof selector !== "string" ) {
return results;
}
var parts = [], m, set, checkSet, extra, prune = true, contextXML = Sizzle.isXML(context),
soFar = selector, ret, cur, pop, i;
// Reset the position of the chunker regexp (start from head)
do {
chunker.exec("");
m = chunker.exec(soFar);
if ( m ) {
soFar = m[3];
parts.push( m[1] );
if ( m[2] ) {
extra = m[3];
break;
}
}
} while ( m );
if ( parts.length > 1 && origPOS.exec( selector ) ) {
if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
set = posProcess( parts[0] + parts[1], context );
} else {
set = Expr.relative[ parts[0] ] ?
[ context ] :
Sizzle( parts.shift(), context );
while ( parts.length ) {
selector = parts.shift();
if ( Expr.relative[ selector ] ) {
selector += parts.shift();
}
set = posProcess( selector, set );
}
}
} else {
// Take a shortcut and set the context if the root selector is an ID
// (but not if it'll be faster if the inner selector is an ID)
if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
ret = Sizzle.find( parts.shift(), context, contextXML );
context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0];
}
if ( context ) {
ret = seed ?
{ expr: parts.pop(), set: makeArray(seed) } :
Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set;
if ( parts.length > 0 ) {
checkSet = makeArray(set);
} else {
prune = false;
}
while ( parts.length ) {
cur = parts.pop();
pop = cur;
if ( !Expr.relative[ cur ] ) {
cur = "";
} else {
pop = parts.pop();
}
if ( pop == null ) {
pop = context;
}
Expr.relative[ cur ]( checkSet, pop, contextXML );
}
} else {
checkSet = parts = [];
}
}
if ( !checkSet ) {
checkSet = set;
}
if ( !checkSet ) {
Sizzle.error( cur || selector );
}
if ( toString.call(checkSet) === "[object Array]" ) {
if ( !prune ) {
results.push.apply( results, checkSet );
} else if ( context && context.nodeType === 1 ) {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
results.push( set[i] );
}
}
} else {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
results.push( set[i] );
}
}
}
} else {
makeArray( checkSet, results );
}
if ( extra ) {
Sizzle( extra, origContext, results, seed );
Sizzle.uniqueSort( results );
}
return results;
};
Sizzle.uniqueSort = function(results){
if ( sortOrder ) {
hasDuplicate = baseHasDuplicate;
results.sort(sortOrder);
if ( hasDuplicate ) {
for ( var i = 1; i < results.length; i++ ) {
if ( results[i] === results[i-1] ) {
results.splice(i--, 1);
}
}
}
}
return results;
};
Sizzle.matches = function(expr, set){
return Sizzle(expr, null, null, set);
};
Sizzle.find = function(expr, context, isXML){
var set;
if ( !expr ) {
return [];
}
for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
var type = Expr.order[i], match;
if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
var left = match[1];
match.splice(1,1);
if ( left.substr( left.length - 1 ) !== "\\" ) {
match[1] = (match[1] || "").replace(/\\/g, "");
set = Expr.find[ type ]( match, context, isXML );
if ( set != null ) {
expr = expr.replace( Expr.match[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = context.getElementsByTagName("*");
}
return {set: set, expr: expr};
};
Sizzle.filter = function(expr, set, inplace, not){
var old = expr, result = [], curLoop = set, match, anyFound,
isXMLFilter = set && set[0] && Sizzle.isXML(set[0]);
while ( expr && set.length ) {
for ( var type in Expr.filter ) {
if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
var filter = Expr.filter[ type ], found, item, left = match[1];
anyFound = false;
match.splice(1,1);
if ( left.substr( left.length - 1 ) === "\\" ) {
continue;
}
if ( curLoop === result ) {
result = [];
}
if ( Expr.preFilter[ type ] ) {
match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
if ( !match ) {
anyFound = found = true;
} else if ( match === true ) {
continue;
}
}
if ( match ) {
for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
var pass = not ^ !!found;
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
} else {
curLoop[i] = false;
}
} else if ( pass ) {
result.push( item );
anyFound = true;
}
}
}
}
if ( found !== undefined ) {
if ( !inplace ) {
curLoop = result;
}
expr = expr.replace( Expr.match[ type ], "" );
if ( !anyFound ) {
return [];
}
break;
}
}
}
// Improper expression
if ( expr === old ) {
if ( anyFound == null ) {
Sizzle.error( expr );
} else {
break;
}
}
old = expr;
}
return curLoop;
};
Sizzle.error = function( msg ) {
throw "Syntax error, unrecognized expression: " + msg;
};
var Expr = Sizzle.selectors = {
order: [ "ID", "NAME", "TAG" ],
match: {
ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
},
leftMatch: {},
attrMap: {
"class": "className",
"for": "htmlFor"
},
attrHandle: {
href: function(elem){
return elem.getAttribute("href");
}
},
relative: {
"+": function(checkSet, part){
var isPartStr = typeof part === "string",
isTag = isPartStr && !/\W/.test(part),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag ) {
part = part.toLowerCase();
}
for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
if ( (elem = checkSet[i]) ) {
while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
elem || false :
elem === part;
}
}
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
}
},
">": function(checkSet, part){
var isPartStr = typeof part === "string",
elem, i = 0, l = checkSet.length;
if ( isPartStr && !/\W/.test(part) ) {
part = part.toLowerCase();
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
}
}
} else {
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
checkSet[i] = isPartStr ?
elem.parentNode :
elem.parentNode === part;
}
}
if ( isPartStr ) {
Sizzle.filter( part, checkSet, true );
}
}
},
"": function(checkSet, part, isXML){
var doneName = done++, checkFn = dirCheck, nodeCheck;
if ( typeof part === "string" && !/\W/.test(part) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
},
"~": function(checkSet, part, isXML){
var doneName = done++, checkFn = dirCheck, nodeCheck;
if ( typeof part === "string" && !/\W/.test(part) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML);
}
},
find: {
ID: function(match, context, isXML){
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
},
NAME: function(match, context){
if ( typeof context.getElementsByName !== "undefined" ) {
var ret = [], results = context.getElementsByName(match[1]);
for ( var i = 0, l = results.length; i < l; i++ ) {
if ( results[i].getAttribute("name") === match[1] ) {
ret.push( results[i] );
}
}
return ret.length === 0 ? null : ret;
}
},
TAG: function(match, context){
return context.getElementsByTagName(match[1]);
}
},
preFilter: {
CLASS: function(match, curLoop, inplace, result, not, isXML){
match = " " + match[1].replace(/\\/g, "") + " ";
if ( isXML ) {
return match;
}
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) {
if ( !inplace ) {
result.push( elem );
}
} else if ( inplace ) {
curLoop[i] = false;
}
}
}
return false;
},
ID: function(match){
return match[1].replace(/\\/g, "");
},
TAG: function(match, curLoop){
return match[1].toLowerCase();
},
CHILD: function(match){
if ( match[1] === "nth" ) {
// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
// calculate the numbers (first)n+(last) including if they are negative
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
}
// TODO: Move to normal caching system
match[0] = done++;
return match;
},
ATTR: function(match, curLoop, inplace, result, not, isXML){
var name = match[1].replace(/\\/g, "");
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
return match;
},
PSEUDO: function(match, curLoop, inplace, result, not){
if ( match[1] === "not" ) {
// If we're dealing with a complex expression, or a simple one
if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
match[3] = Sizzle(match[3], null, null, curLoop);
} else {
var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
if ( !inplace ) {
result.push.apply( result, ret );
}
return false;
}
} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
return true;
}
return match;
},
POS: function(match){
match.unshift( true );
return match;
}
},
filters: {
enabled: function(elem){
return elem.disabled === false && elem.type !== "hidden";
},
disabled: function(elem){
return elem.disabled === true;
},
checked: function(elem){
return elem.checked === true;
},
selected: function(elem){
// Accessing this property makes selected-by-default
// options in Safari work properly
elem.parentNode.selectedIndex;
return elem.selected === true;
},
parent: function(elem){
return !!elem.firstChild;
},
empty: function(elem){
return !elem.firstChild;
},
has: function(elem, i, match){
return !!Sizzle( match[3], elem ).length;
},
header: function(elem){
return (/h\d/i).test( elem.nodeName );
},
text: function(elem){
return "text" === elem.type;
},
radio: function(elem){
return "radio" === elem.type;
},
checkbox: function(elem){
return "checkbox" === elem.type;
},
file: function(elem){
return "file" === elem.type;
},
password: function(elem){
return "password" === elem.type;
},
submit: function(elem){
return "submit" === elem.type;
},
image: function(elem){
return "image" === elem.type;
},
reset: function(elem){
return "reset" === elem.type;
},
button: function(elem){
return "button" === elem.type || elem.nodeName.toLowerCase() === "button";
},
input: function(elem){
return (/input|select|textarea|button/i).test(elem.nodeName);
}
},
setFilters: {
first: function(elem, i){
return i === 0;
},
last: function(elem, i, match, array){
return i === array.length - 1;
},
even: function(elem, i){
return i % 2 === 0;
},
odd: function(elem, i){
return i % 2 === 1;
},
lt: function(elem, i, match){
return i < match[3] - 0;
},
gt: function(elem, i, match){
return i > match[3] - 0;
},
nth: function(elem, i, match){
return match[3] - 0 === i;
},
eq: function(elem, i, match){
return match[3] - 0 === i;
}
},
filter: {
PSEUDO: function(elem, match, i, array){
var name = match[1], filter = Expr.filters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
} else if ( name === "contains" ) {
return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0;
} else if ( name === "not" ) {
var not = match[3];
for ( var j = 0, l = not.length; j < l; j++ ) {
if ( not[j] === elem ) {
return false;
}
}
return true;
} else {
Sizzle.error( "Syntax error, unrecognized expression: " + name );
}
},
CHILD: function(elem, match){
var type = match[1], node = elem;
switch (type) {
case 'only':
case 'first':
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
case 'last':
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
case 'nth':
var first = match[2], last = match[3];
if ( first === 1 && last === 0 ) {
return true;
}
var doneName = match[0],
parent = elem.parentNode;
if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
var count = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.nodeIndex = ++count;
}
}
parent.sizcache = doneName;
}
var diff = elem.nodeIndex - last;
if ( first === 0 ) {
return diff === 0;
} else {
return ( diff % first === 0 && diff / first >= 0 );
}
}
},
ID: function(elem, match){
return elem.nodeType === 1 && elem.getAttribute("id") === match;
},
TAG: function(elem, match){
return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match;
},
CLASS: function(elem, match){
return (" " + (elem.className || elem.getAttribute("class")) + " ")
.indexOf( match ) > -1;
},
ATTR: function(elem, match){
var name = match[1],
result = Expr.attrHandle[ name ] ?
Expr.attrHandle[ name ]( elem ) :
elem[ name ] != null ?
elem[ name ] :
elem.getAttribute( name ),
value = result + "",
type = match[2],
check = match[4];
return result == null ?
type === "!=" :
type === "=" ?
value === check :
type === "*=" ?
value.indexOf(check) >= 0 :
type === "~=" ?
(" " + value + " ").indexOf(check) >= 0 :
!check ?
value && result !== false :
type === "!=" ?
value !== check :
type === "^=" ?
value.indexOf(check) === 0 :
type === "$=" ?
value.substr(value.length - check.length) === check :
type === "|=" ?
value === check || value.substr(0, check.length + 1) === check + "-" :
false;
},
POS: function(elem, match, i, array){
var name = match[2], filter = Expr.setFilters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
}
}
}
};
var origPOS = Expr.match.POS,
fescape = function(all, num){
return "\\" + (num - 0 + 1);
};
for ( var type in Expr.match ) {
Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
}
var makeArray = function(array, results) {
array = Array.prototype.slice.call( array, 0 );
if ( results ) {
results.push.apply( results, array );
return results;
}
return array;
};
// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
// Provide a fallback method if it does not work
} catch(e){
makeArray = function(array, results) {
var ret = results || [], i = 0;
if ( toString.call(array) === "[object Array]" ) {
Array.prototype.push.apply( ret, array );
} else {
if ( typeof array.length === "number" ) {
for ( var l = array.length; i < l; i++ ) {
ret.push( array[i] );
}
} else {
for ( ; array[i]; i++ ) {
ret.push( array[i] );
}
}
}
return ret;
};
}
var sortOrder, siblingCheck;
if ( document.documentElement.compareDocumentPosition ) {
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
return a.compareDocumentPosition ? -1 : 1;
}
return a.compareDocumentPosition(b) & 4 ? -1 : 1;
};
} else {
sortOrder = function( a, b ) {
var ap = [], bp = [], aup = a.parentNode, bup = b.parentNode,
cur = aup, al, bl;
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// If the nodes are siblings (or identical) we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
siblingCheck = function( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
};
}
// Utility function for retreiving the text value of an array of DOM nodes
Sizzle.getText = function( elems ) {
var ret = "", elem;
for ( var i = 0; elems[i]; i++ ) {
elem = elems[i];
// Get the text from text nodes and CDATA nodes
if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
ret += elem.nodeValue;
// Traverse everything else, except comment nodes
} else if ( elem.nodeType !== 8 ) {
ret += Sizzle.getText( elem.childNodes );
}
}
return ret;
};
// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
// We're going to inject a fake input element with a specified name
var form = document.createElement("div"),
id = "script" + (new Date()).getTime();
form.innerHTML = "<a name='" + id + "'/>";
// Inject it into the root element, check its status, and remove it quickly
var root = document.documentElement;
root.insertBefore( form, root.firstChild );
// The workaround has to do additional checks after a getElementById
// Which slows things down for other browsers (hence the branching)
if ( document.getElementById( id ) ) {
Expr.find.ID = function(match, context, isXML){
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : [];
}
};
Expr.filter.ID = function(elem, match){
var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
return elem.nodeType === 1 && node && node.nodeValue === match;
};
}
root.removeChild( form );
root = form = null; // release memory in IE
})();
(function(){
// Check to see if the browser returns only elements
// when doing getElementsByTagName("*")
// Create a fake element
var div = document.createElement("div");
div.appendChild( document.createComment("") );
// Make sure no comments are found
if ( div.getElementsByTagName("*").length > 0 ) {
Expr.find.TAG = function(match, context){
var results = context.getElementsByTagName(match[1]);
// Filter out possible comments
if ( match[1] === "*" ) {
var tmp = [];
for ( var i = 0; results[i]; i++ ) {
if ( results[i].nodeType === 1 ) {
tmp.push( results[i] );
}
}
results = tmp;
}
return results;
};
}
// Check to see if an attribute returns normalized href attributes
div.innerHTML = "<a href='#'></a>";
if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
div.firstChild.getAttribute("href") !== "#" ) {
Expr.attrHandle.href = function(elem){
return elem.getAttribute("href", 2);
};
}
div = null; // release memory in IE
})();
if ( document.querySelectorAll ) {
(function(){
var oldSizzle = Sizzle, div = document.createElement("div");
div.innerHTML = "<p class='TEST'></p>";
// Safari can't handle uppercase or unicode characters when
// in quirks mode.
if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
return;
}
Sizzle = function(query, context, extra, seed){
context = context || document;
// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if ( !seed && context.nodeType === 9 && !Sizzle.isXML(context) ) {
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(e){}
}
return oldSizzle(query, context, extra, seed);
};
for ( var prop in oldSizzle ) {
Sizzle[ prop ] = oldSizzle[ prop ];
}
div = null; // release memory in IE
})();
}
(function(){
var div = document.createElement("div");
div.innerHTML = "<div class='test e'></div><div class='test'></div>";
// Opera can't find a second classname (in 9.6)
// Also, make sure that getElementsByClassName actually exists
if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
return;
}
// Safari caches class attributes, doesn't catch changes (in 3.2)
div.lastChild.className = "e";
if ( div.getElementsByClassName("e").length === 1 ) {
return;
}
Expr.order.splice(1, 0, "CLASS");
Expr.find.CLASS = function(match, context, isXML) {
if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
return context.getElementsByClassName(match[1]);
}
};
div = null; // release memory in IE
})();
function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
elem = elem[dir];
var match = false;
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 && !isXML ){
elem.sizcache = doneName;
elem.sizset = i;
}
if ( elem.nodeName.toLowerCase() === cur ) {
match = elem;
break;
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
elem = elem[dir];
var match = false;
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 ) {
if ( !isXML ) {
elem.sizcache = doneName;
elem.sizset = i;
}
if ( typeof cur !== "string" ) {
if ( elem === cur ) {
match = true;
break;
}
} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
match = elem;
break;
}
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
Sizzle.contains = document.compareDocumentPosition ? function(a, b){
return !!(a.compareDocumentPosition(b) & 16);
} : function(a, b){
return a !== b && (a.contains ? a.contains(b) : true);
};
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 : 0).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
var posProcess = function(selector, context){
var tmpSet = [], later = "", match,
root = context.nodeType ? [context] : context;
// Position selectors must be done after the filter
// And so must :not(positional) so we move all PSEUDOs to the end
while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
later += match[0];
selector = selector.replace( Expr.match.PSEUDO, "" );
}
selector = Expr.relative[selector] ? selector + "*" : selector;
for ( var i = 0, l = root.length; i < l; i++ ) {
Sizzle( selector, root[i], tmpSet );
}
return Sizzle.filter( later, tmpSet );
};
// EXPOSE
window.Sizzle = Sizzle;
})();
RightJS([RightJS.Document, RightJS.Element]).each('include', {
first: function(rule) {
return this.find(rule)[0];
},
find: function(rule) {
return RightJS(Sizzle(rule, this._)).map(RightJS.$);
}
});
|
import React from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import getIn from '@mzvonar/getin';
import isEvent from './../utils/isEvent';
import getPath from './../utils/getPath';
import deepEqual from 'react-fast-compare';
function deleteChildren(object, children) {
let deleted = {};
for(let i = 0, length = children.length; i < length; i += 1) {
const key = children[i];
if(Object.prototype.hasOwnProperty.call(object, key)) {
deleted[key] = object[key];
delete object[key];
}
}
return deleted;
}
function cleanComponentProps(value, props) {
const componentProps = Object.assign({}, props);
const input = componentProps.input;
// const value = componentProps.value;
deleteChildren(componentProps, [
'component',
'_mrf',
'input',
'value',
'validate',
'formSubmitted',
'readOnly',
'disabled'
]);
const inputProps = {};
if(componentProps.type === 'radio') {
inputProps.checked = value === componentProps.value;
}
else if(componentProps.type === 'checkbox') {
inputProps.checked = !!value;
}
else {
inputProps.value = typeof value !== 'undefined' ? value : /*(!props.input.dirty ? props.initialValue : '') ||*/ '';
}
inputProps.id = props.id;
inputProps.readOnly = props.readOnly;
inputProps.disabled = props.disabled;
inputProps.autoComplete = props.autoComplete;
inputProps.maxLength = props.maxLength;
componentProps.input = inputProps;
return componentProps;
}
function getValue(event) {
if(isEvent(event)) {
return event.target.value;
}
else {
return event;
}
}
function generateErrorMessages(errors, errorMessages) {
const messages = [];
if(errors && errors.length > 0 && errorMessages) {
for(let i = 0, length = errors.length; i < length; i += 1) {
if(errorMessages[errors[i]]) {
messages.push(errorMessages[errors[i]]);
}
}
}
return messages;
}
const ignoreForUpdate = [
'_mrf'
];
class ConnectedInput extends React.Component {
static get propTypes() {
return {
component: PropTypes.oneOfType([PropTypes.func, PropTypes.string]).isRequired,
name: PropTypes.string.isRequired
}
}
static get defaultProps() {
return {
component: 'input',
}
}
constructor(props, context) {
super(props, context);
this.state = {
value: props.value
};
this.onChange = this.onChange.bind(this);
this.onBlur = this.onBlur.bind(this);
}
componentDidMount() {
this.props._mrf.registerInput(this.props.name, {
required: this.props.required,
validate: this.props.validate,
value: (this.props.type === 'hidden' && this.props.inputValue) ? this.props.inputValue : undefined
}, this.props.initialValue, this.props.initialErrors);
}
UNSAFE_componentWillReceiveProps(nextProps) {
if(nextProps.value !== this.props.value) {
this.setState({
value: nextProps.value
});
}
if(this.props.type === 'hidden' && nextProps.inputValue !== this.props.inputValue) {
this.props._mrf.inputChange(this.props.name, nextProps.inputValue);
}
}
componentWillUnmount() {
this.props._mrf.removeInput(this.props.name);
}
shouldComponentUpdate(nextProps, nextState) {
const nextPropsKeys = Object.keys(nextProps);
const thisPropsKeys = Object.keys(this.props);
if(nextPropsKeys.length !== thisPropsKeys.length || nextState.value !== this.state.value) {
return true;
}
for(let i = 0, length = nextPropsKeys.length; i < length; i += 1) {
const key = nextPropsKeys[i];
if(!~ignoreForUpdate.indexOf(key) && !deepEqual(this.props[key], nextProps[key])) {
return true
}
}
return false;
}
// UNSAFE_componentWillReceiveProps(nextProps) {
// if(this.props.type === 'hidden' && nextProps.value !== this.props.value) {
// this.onChange(nextProps.value);
// }
// }
onChange(e) {
const value = getValue(e);
this.setState({
value: value
});
this.props._mrf.inputChange(this.props.name, value);
if(this.props.onChange) {
this.props.onChange(e);
}
}
onBlur(e) {
this.props._mrf.inputBlur(this.props.name);
if(this.props._mrf.asyncValidate) {
this.props._mrf.asyncValidate(this.props.name, getValue(e), true, false);
}
if(this.props.onBlur) {
this.props.onBlur(e);
}
}
render() {
const formSubmitted = this.props.formSubmitted;
let componentProps = cleanComponentProps(this.state.value, this.props);
componentProps.input.onChange = this.onChange;
componentProps.input.onBlur = this.onBlur;
if(typeof this.props.component === 'string') {
return React.createElement(this.props.component, Object.assign(componentProps.input, {
type: this.props.type,
className: this.props.className
}));
}
else {
return React.createElement(this.props.component, Object.assign(componentProps, {
meta: {
pristine: this.props.input.pristine,
dirty: this.props.input.dirty,
touched: formSubmitted === true ? true : this.props.input.touched,
valid: this.props.input.valid,
errors: this.props.input.errors,
errorMessages: generateErrorMessages(this.props.input.errors, this.props.errors),
initialErrors: this.props.input.initialErrors,
asyncValidation: this.props.input.asyncValidation,
asyncErrors: this.props.input.asyncErrors,
formSubmitted: formSubmitted
}
}));
}
}
}
function mapStateToProps(state, ownProps) {
const formState = ownProps._mrf.getFormState(state);
return {
input: getIn(formState, ['inputs', ownProps.name]) || {},
value: getIn(formState, ['values', ...getPath(ownProps.name)]),
initialValue: getIn(formState, ['initialValues', ...getPath(ownProps.name)]),
initialErrors: getIn(formState, ['initialInputErrors', ownProps.name]),
inputValue: ownProps.value,
formSubmitted: getIn(formState, 'submitted', false)
}
}
const mapDispatchToProps = {};
export default connect(mapStateToProps, mapDispatchToProps)(ConnectedInput); |
import { createTest } from 'tests/test-utils'
import moment from 'moment'
import { EventTypes, Disciplines } from 'client/calendar/events/types'
import _ from 'lodash'
import ncnca2017 from '../2017-ncnca-events'
import usac2017 from '../2017-usac-events'
const events = _.concat(
// does not inlcude older events that do not comply with this requirements
ncnca2017,
usac2017
)
//TODO: make this tests event centric or test-case centric?
const test = createTest('Common events tests')
const parseDate = date => moment(date, 'MMMM DD YYYY')
const getKeyByValue = (obj, value) => Object.keys(obj).filter(key => obj[key] === value)
const getFirstKeyByValue = (obj, value) => getKeyByValue(obj, value)[0]
test('Event must have short id as part of long id and separately as "_shortId" property', t => {
events.forEach((event, i) => {
const eventId = event.id
const shortIdFromId = eventId.match(/[a-zA-Z0-9_$]+$/gm)[0] //matches part after last '-'
t.equal(event._shortId, shortIdFromId,
`#${event.name} "${event._shortId}" => "${shortIdFromId}"`)
})
t.end()
})
test('Event must have unique id across all events', t => {
const eventsById = _.groupBy(events, 'id')
_.map(eventsById, (value, key) => {
if (value.length !== 1) {
t.fail(`There are "${value.length}" events with id: "${key}", id must be unique.`)
}
})
t.end()
})
test('Event must have _shortId that only contains predefined characters', t => {
events.forEach((event, i) => {
const matches = event._shortId.match(/[a-zA-Z0-9_$]+$/gm) //matches part after last '-'
if (matches && matches.length === 1) {
t.pass(`#${event._shortId} for event "${event.name}"`)
} else {
t.fail(`Problematic _shortId: "#${event._shortId}" for event "${event.name}"`)
}
})
t.end()
})
test('Event must have id starting from "evt-"', t => {
events.forEach((event, i) => {
t.ok(event.id.startsWith(('evt-')),
`${event.name}`)
})
t.end()
})
test('Event must have date in a format "MMMM DD YYYY"', t => {
events.forEach((event, i) => {
const date = moment(event.date, 'MMMM DD YYYY')
t.ok(date.isValid(),
`${event.name}`)
})
t.end()
})
test('Event with USAC permit should have permit starting from events year', t => {
events
.filter(x => x.usacPermit)
.forEach((event, i) => {
const date = parseDate(event.date)
t.ok(event.usacPermit.startsWith(date.year() + '-'), `${event.name}`)
})
t.end()
})
test('Event with promoters', t => {
events.forEach((event, i) => {
t.comment(`${event.name}`)
if (event.promoters) {
t.ok(Array.isArray(event.promoters), 'promoters should be an array')
if (event.promoters.length >= 1) {
t.ok(event.promoters.every(x => x.id),
'each promoter should have an id')
t.ok(event.promoters.every(x => x.id && x.id.startsWith('prm-')),
'each promoter\'s id should start from "prm-"')
}
}
})
t.end()
})
test('Each Event must have at least city and state set in Location', t => {
events.forEach((event, i) => {
t.comment(`${event.name}`)
t.ok(event.location, 'has location set')
t.ok(event.location.city, 'has city set')
t.ok(event.location.state, 'has state set')
})
t.end()
})
test('Each Event must have Type and Discipline set to one of the pre-defined ones', t => {
const allDisciplines = _.values(Disciplines)
const getEventTypesForDiscipline = discipline => {
const disciplineKey = getFirstKeyByValue(Disciplines, discipline)
return _.values(EventTypes[disciplineKey])
}
events.forEach((event, i) => {
t.comment(`${event.id}`)
t.ok(allDisciplines.includes(event.discipline),
'should have discipline equal to one of the pre-defined ones')
t.ok(getEventTypesForDiscipline(event.discipline).includes(event.type),
'should have type set to one that corresponds to event\'s discipline'
+ `, current one is set to: "${event.type}" which is not part of "${event.discipline}" discipline`)
})
t.end()
})
test('Event that is moved, when have "movedToEventId" should point to existing event', t => {
const eventsById = _.keyBy(events, 'id')
events
.filter(x => x.movedToEventId)
.forEach((event, i) => {
t.comment(`${event.name}`)
const movedToEvent = eventsById[event.movedToEventId]
t.ok(movedToEvent, 'moved to event id should point to existing event')
t.comment(`Provided evnet id: ${event.movedToEventId}`)
t.ok(event.movedToEventId !== event.id, 'moved to event id should point to a different event')
t.comment(`Provided evnet id: ${event.movedToEventId}`)
t.ok(parseDate(movedToEvent.date) > parseDate(event.date),
'moved to event should be later than the event it is moved from')
})
t.end()
})
|
/**
* Global Variable Configuration
* (sails.config.globals)
*
* Configure which global variables which will be exposed
* automatically by Sails.
*
* For more information on configuration, check out:
* http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.globals.html
*/
module.exports.globals = {
/****************************************************************************
* *
* Expose the lodash installed in Sails core as a global variable. If this *
* is disabled, like any other node module you can always run npm install *
* lodash --save, then var _ = require('lodash') at the top of any file. *
* *
****************************************************************************/
// _: true,
/****************************************************************************
* *
* Expose the async installed in Sails core as a global variable. If this is *
* disabled, like any other node module you can always run npm install async *
* --save, then var async = require('async') at the top of any file. *
* *
****************************************************************************/
// async: true,
/****************************************************************************
* *
* Expose the sails instance representing your app. If this is disabled, you *
* can still get access via req._sails. *
* *
****************************************************************************/
// sails: true,
/****************************************************************************
* *
* Expose each of your app's services as global variables (using their *
* "globalId"). E.g. a service defined in api/models/NaturalLanguage.js *
* would have a globalId of NaturalLanguage by default. If this is disabled, *
* you can still access your services via sails.services.* *
* *
****************************************************************************/
// services: true,
/****************************************************************************
* *
* Expose each of your app's models as global variables (using their *
* "globalId"). E.g. a model defined in api/models/User.js would have a *
* globalId of User by default. If this is disabled, you can still access *
* your models via sails.models.*. *
* *
****************************************************************************/
// models: true
};
|
this.NesDb = this.NesDb || {};
NesDb[ '9F3DE783494F7FF30679A17B0C5B912834121095' ] = {
"$": {
"name": "Nekketsu Kouha Kunio-kun",
"altname": "熱血硬派くにおくん",
"class": "Licensed",
"catalog": "TJC-KN",
"publisher": "Technos",
"developer": "Technos",
"region": "Japan",
"players": "2",
"date": "1987-04-17"
},
"cartridge": [
{
"$": {
"system": "Famicom",
"crc": "A7D3635E",
"sha1": "9F3DE783494F7FF30679A17B0C5B912834121095",
"dump": "ok",
"dumper": "bootgod",
"datedumped": "2007-06-24"
},
"board": [
{
"$": {
"type": "HVC-UNROM",
"pcb": "HVC-UNROM-02",
"mapper": "2"
},
"prg": [
{
"$": {
"name": "TJC-KN-0 PRG",
"size": "128k",
"crc": "A7D3635E",
"sha1": "9F3DE783494F7FF30679A17B0C5B912834121095"
}
}
],
"vram": [
{
"$": {
"size": "8k"
}
}
],
"chip": [
{
"$": {
"type": "74xx161"
}
},
{
"$": {
"type": "74xx32"
}
}
],
"pad": [
{
"$": {
"h": "1",
"v": "0"
}
}
]
}
]
}
]
};
|
/**
* Interaction for the tags module
*
* @author Tijs Verkoyen <[email protected]>
*/
jsBackend.tags =
{
// init, something like a constructor
init: function()
{
$dataGridTag = $('.jsDataGrid td.tag');
if($dataGridTag.length > 0) $dataGridTag.inlineTextEdit({ params: { fork: { action: 'edit' } }, tooltip: jsBackend.locale.msg('ClickToEdit') });
}
};
$(jsBackend.tags.init);
|
/* global WebFont */
(function () {
'use strict';
function FontLoaderFactory () {
return {
setFonts : function () {
WebFont.load({
custom: {
families: [ 'FontAwesome','Ubuntu','Oxygen','Open Sans' ],
urls: [ '/fonts/base.css']
}
});
}
};
}
angular.module('app.core.fontloader', [])
.factory('FontLoader',FontLoaderFactory);
})();
|
module.exports = handler
var debug = require('../debug').server
var fs = require('fs')
function handler (err, req, res, next) {
debug('Error page because of ' + err.message)
var ldp = req.app.locals.ldp
// If the user specifies this function
// then, they can customize the error programmatically
if (ldp.errorHandler) {
return ldp.errorHandler(err, req, res, next)
}
// If noErrorPages is set,
// then use built-in express default error handler
if (ldp.noErrorPages) {
return res
.status(err.status)
.send(err.message + '\n' || '')
}
// Check if error page exists
var errorPage = ldp.errorPages + err.status.toString() + '.html'
fs.readFile(errorPage, 'utf8', function (readErr, text) {
if (readErr) {
return res
.status(err.status)
.send(err.message || '')
}
res.status(err.status)
res.header('Content-Type', 'text/html')
res.send(text)
})
}
|
const DateTime = Jymfony.Component.DateTime.DateTime;
const DateTimeZone = Jymfony.Component.DateTime.DateTimeZone;
const TimeSpan = Jymfony.Component.DateTime.TimeSpanInterface;
const { expect } = require('chai');
describe('[DateTime] DateTime', function () {
it('should accept string on construction', () => {
const dt = new DateTime('2017-03-24T00:00:00', 'Etc/UTC');
expect(dt).to.be.instanceOf(DateTime);
});
it('should accept unix timestamp on construction', () => {
const dt = new DateTime(1490313600, 'Etc/UTC');
expect(dt).to.be.instanceOf(DateTime);
});
it('should accept a js Date object on construction', () => {
const date = new Date(1490313600000);
const dt = new DateTime(date, 'Etc/UTC');
expect(dt).to.be.instanceOf(DateTime);
expect(dt.year).to.be.equal(2017);
expect(dt.month).to.be.equal(3);
expect(dt.day).to.be.equal(24);
expect(dt.hour).to.be.equal(0);
expect(dt.minute).to.be.equal(0);
expect(dt.second).to.be.equal(0);
expect(dt.millisecond).to.be.equal(0);
});
it('today should set time to midnight', () => {
const dt = DateTime.today;
expect(dt.hour).to.be.equal(0);
expect(dt.minute).to.be.equal(0);
expect(dt.second).to.be.equal(0);
expect(dt.millisecond).to.be.equal(0);
});
it('yesterday should set time to midnight', () => {
const dt = DateTime.yesterday;
expect(dt.hour).to.be.equal(0);
expect(dt.minute).to.be.equal(0);
expect(dt.second).to.be.equal(0);
expect(dt.millisecond).to.be.equal(0);
});
let tests = [
[ '2017-01-01T00:00:00', 'P-1D', '2016-12-31T00:00:00+0000' ],
[ '2016-12-31T00:00:00', 'P+1D', '2017-01-01T00:00:00+0000' ],
[ '2016-11-30T00:00:00', 'P+1D', '2016-12-01T00:00:00+0000' ],
[ '2017-01-01T00:00:00', 'P-1Y', '2016-01-01T00:00:00+0000' ],
[ '2016-02-29T00:00:00', 'P-1Y', '2015-02-28T00:00:00+0000' ],
];
for (const t of tests) {
it('add timespan should work correctly', () => {
const [ date, span, expected ] = t;
let dt = new DateTime(date);
dt = dt.modify(new TimeSpan(span));
expect(dt.toString()).to.be.equal(expected);
});
}
it('createFromFormat should correctly parse a date', () => {
const dt = DateTime.createFromFormat(DateTime.RFC2822, 'Wed, 20 Jun 2018 10:19:32 GMT');
expect(dt.toString()).to.be.equal('2018-06-20T10:19:32+0000');
});
tests = [
[ '2020 mar 29 01:00 Europe/Rome', 3600, 1, 0 ],
[ '2020 mar 29 02:00 Europe/Rome', 7200, 3, 0 ],
[ '2020 mar 29 03:00 Europe/Rome', 7200, 3, 0 ],
[ '2020 mar 29 04:00 Europe/Rome', 7200, 4, 0 ],
[ '2020 may 04 02:00 Europe/Rome', 7200, 2, 0 ],
];
for (const index of tests.keys()) {
const t = tests[index];
it('should correctly handle timezone transitions #'+index, () => {
const dt = new DateTime(t[0]);
expect(dt.timezone).to.be.instanceOf(DateTimeZone);
expect(dt.timezone.getOffset(dt)).to.be.equal(t[1]);
expect(dt.hour).to.be.equal(t[2]);
expect(dt.minute).to.be.equal(t[3]);
});
}
it('should correctly handle timezone transitions on modify', () => {
let dt = new DateTime('2020 mar 29 01:59:59 Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(3600);
dt = dt.modify(new TimeSpan('PT1S'));
expect(dt.timezone.name).to.be.equal('Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.hour).to.be.equal(3);
expect(dt.minute).to.be.equal(0);
});
it('should correctly handle between rules', () => {
let dt = new DateTime('1866 dec 11 00:00 Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(2996);
dt = new DateTime('1866 dec 11 23:59:59 Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(2996);
expect(dt.toString()).to.be.equal('1866-12-11T23:59:59+0049');
dt = dt.modify(new TimeSpan('PT1S'));
expect(dt.timezone.name).to.be.equal('Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(2996);
expect(dt.hour).to.be.equal(0);
expect(dt.minute).to.be.equal(0);
dt = new DateTime('1893 Oct 31 23:49:55', 'Europe/Rome');
expect(dt.timezone.name).to.be.equal('Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(2996);
expect(dt.day).to.be.equal(31);
expect(dt.hour).to.be.equal(23);
expect(dt.minute).to.be.equal(49);
expect(dt.second).to.be.equal(55);
dt = dt.modify(new TimeSpan('PT1S'));
expect(dt.timezone.name).to.be.equal('Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(3600);
expect(dt.hour).to.be.equal(0);
expect(dt.minute).to.be.equal(0);
expect(dt.second).to.be.equal(0);
dt = new DateTime('1916 Jun 3 23:59:59', 'Europe/Rome');
expect(dt.timezone.name).to.be.equal('Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(3600);
expect(dt.hour).to.be.equal(23);
expect(dt.minute).to.be.equal(59);
expect(dt.second).to.be.equal(59);
dt = dt.modify(new TimeSpan('PT1S'));
expect(dt.timezone.name).to.be.equal('Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.month).to.be.equal(6);
expect(dt.day).to.be.equal(4);
expect(dt.hour).to.be.equal(1);
expect(dt.minute).to.be.equal(0);
expect(dt.second).to.be.equal(0);
dt = new DateTime('2020 Oct 25 01:59:59', 'Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.hour).to.be.equal(1);
expect(dt.minute).to.be.equal(59);
expect(dt.second).to.be.equal(59);
dt = dt.modify(new TimeSpan('PT1H'));
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.hour).to.be.equal(2);
expect(dt.minute).to.be.equal(59);
expect(dt.second).to.be.equal(59);
dt = dt.modify(new TimeSpan('PT1S'));
expect(dt.timezone.getOffset(dt)).to.be.equal(3600);
expect(dt.hour).to.be.equal(2);
expect(dt.minute).to.be.equal(0);
expect(dt.second).to.be.equal(0);
dt = new DateTime('2020 Oct 25 01:59:59', 'Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
dt = dt.modify(new TimeSpan('P1D'));
expect(dt.timezone.getOffset(dt)).to.be.equal(3600);
expect(dt.timestamp).to.be.equal(1603673999);
expect(dt.hour).to.be.equal(1);
expect(dt.minute).to.be.equal(59);
expect(dt.second).to.be.equal(59);
dt = dt.modify(new TimeSpan('P-1D'));
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.timestamp).to.be.equal(1603583999);
expect(dt.hour).to.be.equal(1);
expect(dt.minute).to.be.equal(59);
expect(dt.second).to.be.equal(59);
dt = dt.modify(new TimeSpan('P1M'));
expect(dt.timezone.getOffset(dt)).to.be.equal(3600);
expect(dt.timestamp).to.be.equal(1606265999);
expect(dt.hour).to.be.equal(1);
expect(dt.minute).to.be.equal(59);
expect(dt.second).to.be.equal(59);
expect(dt.day).to.be.equal(25);
expect(dt.month).to.be.equal(11);
expect(dt.year).to.be.equal(2020);
dt = dt.modify(new TimeSpan('P-1M'));
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.timestamp).to.be.equal(1603583999);
dt = dt.modify(new TimeSpan('P1Y'));
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.timestamp).to.be.equal(1635119999);
expect(dt.hour).to.be.equal(1);
expect(dt.minute).to.be.equal(59);
expect(dt.second).to.be.equal(59);
expect(dt.day).to.be.equal(25);
expect(dt.month).to.be.equal(10);
expect(dt.year).to.be.equal(2021);
dt = dt.modify(new TimeSpan('P7D'));
expect(dt.timezone.getOffset(dt)).to.be.equal(3600);
expect(dt.timestamp).to.be.equal(1635728399);
dt = dt.modify(new TimeSpan('P-1Y7D'));
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.timestamp).to.be.equal(1603583999);
});
it ('invalid times for timezone', () => {
let dt = new DateTime('1893 Oct 31 23:49:58', 'Europe/Rome');
expect(dt.timezone.name).to.be.equal('Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(3600);
expect(dt.year).to.be.equal(1893);
expect(dt.month).to.be.equal(11);
expect(dt.day).to.be.equal(1);
expect(dt.hour).to.be.equal(0);
expect(dt.minute).to.be.equal(0);
expect(dt.second).to.be.equal(2);
dt = new DateTime('2020 mar 29 02:01:00 Europe/Rome');
expect(dt.timezone.name).to.be.equal('Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.hour).to.be.equal(3);
expect(dt.minute).to.be.equal(1);
});
});
|
module.exports = function () {
var modules = [];
var creeps = Game.creeps;
var spawn = Game.spawns.Spawn1;
var score = spawn ? spawn.room.survivalInfo.score : 0;
var minions = {
total: 0,
build: 0,
carry: 0,
harvest: 0,
guard: 0,
medic: 0,
runner: 0
};
if (score == 0 || spawn.spawning != null) return; // no action when already spawning
for (var i in creeps) {
var creep = creeps[i];
minions.total++;
minions[creep.memory.module]++;
}
var getTough = function (amount) {
var modules = [];
amount += Math.round(score / 250);
for (var i = 0; i < amount; i++) {
modules.push(TOUGH);
}
return modules;
};
var spawnCreep = function (modules, memory) {
var creep = spawn.createCreep(modules, undefined, memory);
if (typeof creep != 'number') {
console.log('created ' + memory.module, modules);
}
return creep;
};
if (minions.harvest < 2) {
spawnCreep([WORK, WORK, WORK, CARRY, MOVE], {module: 'harvest'});
}
else if (minions.carry < 2) {
spawnCreep([CARRY, MOVE, MOVE], {module: 'carry'});
}
else if (score > 1000 && minions.runner < 1 || score > 2000 && minions.runner < 2) {
spawnCreep([CARRY, MOVE, MOVE, CARRY, MOVE], {module: 'runner'});
}
else if (minions.medic < minions.guard / 2) {
modules = [];
modules.push(HEAL, HEAL, HEAL, HEAL, MOVE);
spawnCreep(modules, {module: 'medic'});
}
else if (minions.harvest > 0 && ((score < 1100 && minions.guard < 6) || (score > 1100 && score < 2100 && minions.guard < 12) || score > 2100)) {
modules = getTough(0);
modules.push(RANGED_ATTACK, RANGED_ATTACK, RANGED_ATTACK, MOVE, MOVE);
spawnCreep(modules, {module: 'guard'});
}
};
|
/**
* @class A wrapper around WebGL.
* @name GL
* @param {HTMLCanvasElement} element A canvas element.
* @param {function} onload A callback function.
* @param {function} callbacks.onerror A callback function.
* @param {function} callbacks.onprogress A callback function.
* @param {function} callbacks.onloadstart A callback function.
* @param {function} callbacks.onremove A callback function.
* @property {WebGLRenderingContext} ctx
*/
function GL(element, callbacks) {
var ctx,
identifiers = ["webgl", "experimental-webgl"],
i,
l;
for (var i = 0, l = identifiers.length; i < l; ++i) {
try {
ctx = element.getContext(identifiers[i], {antialias: true, alpha: false/*, preserveDrawingBuffer: true*/});
} catch(e) {
}
if (ctx) {
break;
}
}
if (!ctx) {
console.error("[WebGLContext]: Failed to create a WebGLContext");
throw "[WebGLContext]: Failed to create a WebGLContext";
}
var hasVertexTexture = ctx.getParameter(ctx.MAX_VERTEX_TEXTURE_IMAGE_UNITS) > 0;
var hasFloatTexture = ctx.getExtension("OES_texture_float");
var compressedTextures = ctx.getExtension("WEBGL_compressed_texture_s3tc");
if (!hasVertexTexture) {
console.error("[WebGLContext]: No vertex shader texture support");
throw "[WebGLContext]: No vertex shader texture support";
}
if (!hasFloatTexture) {
console.error("[WebGLContext]: No float texture support");
throw "[WebGLContext]: No float texture support";
}
if (!compressedTextures) {
console.warn("[WebGLContext]: No compressed textures support");
}
var refreshViewProjectionMatrix = false;
var projectionMatrix = mat4.create();
var viewMatrix = mat4.create();
var viewProjectionMatrix = mat4.create();
var matrixStack = [];
var textureStore = {};
var textureStoreById = {};
var shaderUnitStore = {};
var shaderStore = {};
var boundShader;
var boundShaderName = "";
var boundTextures = [];
var floatPrecision = "precision mediump float;\n";
var textureHandlers = {};
ctx.viewport(0, 0, element.clientWidth, element.clientHeight);
ctx.depthFunc(ctx.LEQUAL);
ctx.enable(ctx.DEPTH_TEST);
ctx.enable(ctx.CULL_FACE);
function textureOptions(wrapS, wrapT, magFilter, minFilter) {
ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_WRAP_S, wrapS);
ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_WRAP_T, wrapT);
ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_MAG_FILTER, magFilter);
ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_MIN_FILTER, minFilter);
}
/**
* Sets a perspective projection matrix.
*
* @memberof GL
* @instance
* @param {number} fovy
* @param {number} aspect
* @param {number} near
* @param {number} far
*/
function setPerspective(fovy, aspect, near, far) {
mat4.perspective(projectionMatrix, fovy, aspect, near, far);
refreshViewProjectionMatrix = true;
}
/**
* Sets an orthogonal projection matrix.
*
* @memberof GL
* @instance
* @param {number} left
* @param {number} right
* @param {number} bottom
* @param {number} top
* @param {number} near
* @param {number} far
*/
function setOrtho(left, right, bottom, top, near, far) {
mat4.ortho(projectionMatrix, left, right, bottom, top, near, far);
refreshViewProjectionMatrix = true;
}
/**
* Resets the view matrix.
*
* @memberof GL
* @instance
*/
function loadIdentity() {
mat4.identity(viewMatrix);
refreshViewProjectionMatrix = true;
}
/**
* Translates the view matrix.
*
* @memberof GL
* @instance
* @param {vec3} v Translation.
*/
function translate(v) {
mat4.translate(viewMatrix, viewMatrix, v);
refreshViewProjectionMatrix = true;
}
/**
* Rotates the view matrix.
*
* @memberof GL
* @instance
* @param {number} radians Angle.
* @param {vec3} axis The rotation axis..
*/
function rotate(radians, axis) {
mat4.rotate(viewMatrix, viewMatrix, radians, axis);
refreshViewProjectionMatrix = true;
}
/**
* Scales the view matrix.
*
* @memberof GL
* @instance
* @param {vec3} v Scaling.
*/
function scale(v) {
mat4.scale(viewMatrix, viewMatrix, v);
refreshViewProjectionMatrix = true;
}
/**
* Sets the view matrix to a look-at matrix.
*
* @memberof GL
* @instance
* @param {vec3} eye
* @param {vec3} center
* @param {vec3} up
*/
function lookAt(eye, center, up) {
mat4.lookAt(viewMatrix, eye, center, up);
refreshViewProjectionMatrix = true;
}
/**
* Multiplies the view matrix by another matrix.
*
* @memberof GL
* @instance
* @param {mat4} mat.
*/
function multMat(mat) {
mat4.multiply(viewMatrix, viewMatrix, mat);
refreshViewProjectionMatrix = true;
}
/**
* Pushes the current view matrix in the matrix stack.
*
* @memberof GL
* @instance
*/
function pushMatrix() {
matrixStack.push(mat4.clone(viewMatrix));
refreshViewProjectionMatrix = true;
}
/**
* Pops the matrix stacks and sets the popped matrix to the view matrix.
*
* @memberof GL
* @instance
*/
function popMatrix() {
viewMatrix = matrixStack.pop();
refreshViewProjectionMatrix = true;
}
/**
* Gets the view-projection matrix.
*
* @memberof GL
* @instance
* @returns {mat4} MVP.
*/
function getViewProjectionMatrix() {
if (refreshViewProjectionMatrix) {
mat4.multiply(viewProjectionMatrix, projectionMatrix, viewMatrix);
refreshViewProjectionMatrix = false;
}
return viewProjectionMatrix;
}
/**
* Gets the projection matrix.
*
* @memberof GL
* @instance
* @returns {mat4} P.
*/
function getProjectionMatrix() {
return projectionMatrix;
}
/**
* Gets the view matrix.
*
* @memberof GL
* @instance
* @returns {mat4} MV.
*/
function getViewMatrix() {
return viewMatrix;
}
function setProjectionMatrix(matrix) {
mat4.copy(projectionMatrix, matrix);
refreshViewProjectionMatrix = true;
}
function setViewMatrix(matrix) {
mat4.copy(viewMatrix, matrix);
refreshViewProjectionMatrix = true;
}
/**
* Creates a new {@link GL.ShaderUnit}, or grabs it from the cache if it was previously created, and returns it.
*
* @memberof GL
* @instance
* @param {string} source GLSL source.
* @param {number} type Shader unit type.
* @param {string} name Owning shader's name.
* @returns {GL.ShaderUnit} The created shader unit.
*/
function createShaderUnit(source, type, name) {
var hash = String.hashCode(source);
if (!shaderUnitStore[hash]) {
shaderUnitStore[hash] = new ShaderUnit(ctx, source, type, name);
}
return shaderUnitStore[hash];
}
/**
* Creates a new {@link GL.Shader} program, or grabs it from the cache if it was previously created, and returns it.
*
* @memberof GL
* @instance
* @param {string} name The name of the shader.
* @param {string} vertexSource Vertex shader GLSL source.
* @param {string} fragmentSource Fragment shader GLSL source.
* @param {array} defines An array of strings that will be added as #define-s to the shader source.
* @returns {GL.Shader?} The created shader, or a previously cached version, or null if it failed to compile and link.
*/
function createShader(name, vertexSource, fragmentSource, defines) {
if (!shaderStore[name]) {
defines = defines || [];
for (var i = 0; i < defines.length; i++) {
defines[i] = "#define " + defines[i];
}
defines = defines.join("\n") + "\n";
var vertexUnit = createShaderUnit(defines + vertexSource, ctx.VERTEX_SHADER, name);
var fragmentUnit = createShaderUnit(floatPrecision + defines + fragmentSource, ctx.FRAGMENT_SHADER, name);
if (vertexUnit.ready && fragmentUnit.ready) {
shaderStore[name] = new Shader(ctx, name, vertexUnit, fragmentUnit);
}
}
if (shaderStore[name] && shaderStore[name].ready) {
return shaderStore[name];
}
}
/**
* Checks if a shader is ready for use.
*
* @memberof GL
* @instance
* @param {string} name The name of the shader.
* @returns {boolean} The shader's status.
*/
function shaderStatus(name) {
var shader = shaderStore[name];
return shader && shader.ready;
}
/**
* Enables the WebGL vertex attribute arrays in the range defined by start-end.
*
* @memberof GL
* @instance
* @param {number} start The first attribute.
* @param {number} end The last attribute.
*/
function enableVertexAttribs(start, end) {
for (var i = start; i < end; i++) {
ctx.enableVertexAttribArray(i);
}
}
/**
* Disables the WebGL vertex attribute arrays in the range defined by start-end.
*
* @memberof GL
* @instance
* @param {number} start The first attribute.
* @param {number} end The last attribute.
*/
function disableVertexAttribs(start, end) {
for (var i = start; i < end; i++) {
ctx.disableVertexAttribArray(i);
}
}
/**
* Binds a shader. This automatically handles the vertex attribute arrays. Returns the currently bound shader.
*
* @memberof GL
* @instance
* @param {string} name The name of the shader.
* @returns {GL.Shader} The bound shader.
*/
function bindShader(name) {
var shader = shaderStore[name];
if (shader && (!boundShader || boundShader.id !== shader.id)) {
var oldAttribs = 0;
if (boundShader) {
oldAttribs = boundShader.attribs;
}
var newAttribs = shader.attribs;
ctx.useProgram(shader.id);
if (newAttribs > oldAttribs) {
enableVertexAttribs(oldAttribs, newAttribs);
} else if (newAttribs < oldAttribs) {
disableVertexAttribs(newAttribs, oldAttribs);
}
boundShaderName = name;
boundShader = shader;
}
return boundShader;
}
/**
* Loads a texture, with optional options that will be sent to the texture's constructor,
* If the texture was already loaded previously, it returns it.
*
* @memberof GL
* @instance
* @param {string} source The texture's url.
* @param {object} options Options.
*/
function loadTexture(source, fileType, isFromMemory, options) {
if (!textureStore[source]) {
textureStore[source] = new AsyncTexture(source, fileType, options, textureHandlers, ctx, compressedTextures, callbacks, isFromMemory);
textureStoreById[textureStore[source].id] = textureStore[source];
}
return textureStore[source];
}
/**
* Unloads a texture.
*
* @memberof GL
* @instance
* @param {string} source The texture's url.
*/
function removeTexture(source) {
if (textureStore[source]) {
callbacks.onremove(textureStore[source]);
delete textureStore[source];
}
}
function textureLoaded(source) {
var texture = textureStore[source];
return (texture && texture.loaded());
}
/**
* Binds a texture to the specified texture unit.
*
* @memberof GL
* @instance
* @param {(string|null)} object A texture source.
* @param {number} [unit] The texture unit.
*/
function bindTexture(source, unit) {
//console.log(source);
var texture;
unit = unit || 0;
if (typeof source === "string") {
texture = textureStore[source];
} else if (typeof source === "number") {
texture = textureStoreById[source];
}
if (texture && texture.impl && texture.impl.ready) {
// Only bind if actually necessary
if (!boundTextures[unit] || boundTextures[unit].id !== texture.id) {
boundTextures[unit] = texture.impl;
ctx.activeTexture(ctx.TEXTURE0 + unit);
ctx.bindTexture(ctx.TEXTURE_2D, texture.impl.id);
}
} else {
boundTextures[unit] = null;
ctx.activeTexture(ctx.TEXTURE0 + unit);
ctx.bindTexture(ctx.TEXTURE_2D, null);
}
}
/**
* Creates a new {@link GL.Rect} and returns it.
*
* @memberof GL
* @instance
* @param {number} x X coordinate.
* @param {number} y Y coordinate.
* @param {number} z Z coordinate.
* @param {number} hw Half of the width.
* @param {number} hh Half of the height.
* @param {number} stscale A scale that is applied to the texture coordinates.
* @returns {GL.Rect} The rectangle.
*/
function createRect(x, y, z, hw, hh, stscale) {
return new Rect(ctx, x, y, z, hw, hh, stscale);
}
/**
* Creates a new {@link GL.Cube} and returns it.
*
* @memberof GL
* @instance
* @param {number} x1 Minimum X coordinate.
* @param {number} y1 Minimum Y coordinate.
* @param {number} z1 Minimum Z coordinate.
* @param {number} x2 Maximum X coordinate.
* @param {number} y2 Maximum Y coordinate.
* @param {number} z2 Maximum Z coordinate.
* @returns {GL.Cube} The cube.
*/
function createCube(x1, y1, z1, x2, y2, z2) {
return new Cube(ctx, x1, y1, z1, x2, y2, z2);
}
/**
* Creates a new {@link GL.Sphere} and returns it.
*
* @memberof GL
* @instance
* @param {number} x X coordinate.
* @param {number} y Y coordinate.
* @param {number} z Z coordinate.
* @param {number} latitudeBands Latitude bands.
* @param {number} longitudeBands Longitude bands.
* @param {number} radius The sphere radius.
* @returns {GL.Sphere} The sphere.
*/
function createSphere(x, y, z, latitudeBands, longitudeBands, radius) {
return new Sphere(ctx, x, y, z, latitudeBands, longitudeBands, radius);
}
/**
* Creates a new {@link GL.Cylinder} and returns it.
*
* @memberof GL
* @instance
* @param {number} x X coordinate.
* @param {number} y Y coordinate.
* @param {number} z Z coordinate.
* @param {number} r The cylinder radius.
* @param {number} h The cylinder height.
* @param {number} bands Number of bands..
* @returns {GL.Cylinder} The cylinder.
*/
function createCylinder(x, y, z, r, h, bands) {
return new Cylinder(ctx, x, y, z, r, h, bands);
}
/**
* Registers an external handler for an unsupported texture type.
*
* @memberof GL
* @instance
* @param {string} fileType The file format the handler handles.
* @param {function} textureHandler
*/
function registerTextureHandler(fileType, textureHandler) {
textureHandlers[fileType] = textureHandler;
}
textureHandlers[".png"] = NativeTexture;
textureHandlers[".gif"] = NativeTexture;
textureHandlers[".jpg"] = NativeTexture;
return {
setPerspective: setPerspective,
setOrtho: setOrtho,
loadIdentity: loadIdentity,
translate: translate,
rotate: rotate,
scale: scale,
lookAt: lookAt,
multMat: multMat,
pushMatrix: pushMatrix,
popMatrix: popMatrix,
createShader: createShader,
shaderStatus: shaderStatus,
bindShader: bindShader,
getViewProjectionMatrix: getViewProjectionMatrix,
getProjectionMatrix: getProjectionMatrix,
getViewMatrix: getViewMatrix,
setProjectionMatrix: setProjectionMatrix,
setViewMatrix: setViewMatrix,
loadTexture: loadTexture,
removeTexture: removeTexture,
textureLoaded: textureLoaded,
textureOptions: textureOptions,
bindTexture: bindTexture,
createRect: createRect,
createSphere: createSphere,
createCube: createCube,
createCylinder: createCylinder,
ctx: ctx,
registerTextureHandler: registerTextureHandler
};
}
|
import hotkeys from "hotkeys-js";
export default class HotkeyHandler {
constructor(hotkeyRegistry) {
this.hotkeyRegistry = hotkeyRegistry;
hotkeys("*", { keyup: true, keydown: false }, event => {
event.preventDefault();
this.hotkeyRegistry.resetLastPressedKeyCodes();
return false;
});
hotkeys("*", { keyup: false, keydown: true }, event => {
event.preventDefault();
const pressed = hotkeys.getPressedKeyCodes();
this.hotkeyRegistry.onKeyPressed(pressed);
return false;
});
}
dispose() {
hotkeys.deleteScope("all");
}
}
|
$(function(){
BrowserDetect.init();
$('.minifyme').on("navminified", function() {
// $('td.expand,th.expand').toggle();
});
// Activate all popovers (if NOT mobile)
if ( !BrowserDetect.isMobile() ) {
$('[data-toggle="popover"]').popover();
}
});
$.fn.pressEnter = function(fn) {
return this.each(function() {
$(this).bind('enterPress', fn);
$(this).keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterPress");
}
})
});
};
function ensureHeightOfSidebar() {
$('#left-panel').css('height',$('#main').height());
}
BrowserDetect =
// From http://stackoverflow.com/questions/13478303/correct-way-to-use-modernizr-to-detect-ie
{
init: function ()
{
this.browser = this.searchString(this.dataBrowser) || "Other";
this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "Unknown";
},
isMobile: function ()
{
if (navigator.userAgent.search(/(Android|Touch|iPhone|iPad)/) == -1) {
return false;
} else {
return true;
}
},
searchString: function (data)
{
for (var i=0 ; i < data.length ; i++)
{
var dataString = data[i].string;
this.versionSearchString = data[i].subString;
if (dataString.indexOf(data[i].subString) != -1)
{
return data[i].identity;
}
}
},
searchVersion: function (dataString)
{
var index = dataString.indexOf(this.versionSearchString);
if (index == -1) return;
return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
},
dataBrowser:
[
{ string: navigator.userAgent, subString: "Chrome", identity: "Chrome" },
{ string: navigator.userAgent, subString: "MSIE", identity: "Explorer" },
{ string: navigator.userAgent, subString: "Firefox", identity: "Firefox" },
{ string: navigator.userAgent, subString: "Safari", identity: "Safari" },
{ string: navigator.userAgent, subString: "Opera", identity: "Opera" }
]
}; |
/*
Author: Gerard Lamusse
Created: 08/2015
Version: 1.0
URL: https://github.com/u12206050/jsonZipper
*/
var jsonZipper = (function(){
var jz = function(_jsonObj, _options) {
var Z = this;
var MAP = [];
var opts = _options && typeof(_options) !== "boolean" ? _options : {};
/* Public Functions */
Z.zip = function() {
if (Z.status === "zipable") {
Z.uzOpts = {I:[],A:Z.isArray,eC:[],iC:[]};
if (Z.isArray) {
var x = 0;
var y = Z.JO.length;
while (x < y) {
compress(Z.JO[x++]);
}
} else {
compress(Z.JO);
}
Z.status = "zipped";
return {M:MAP,D:Z.JO,O:Z.uzOpts};
} return false;
};
Z.unzip = function() {
if (Z.status === "unzipable") {
if (Z.isArray) {
var x = 0;
var y = Z.JO.length;
while (x < y) {
extract(Z.JO[x++]);
}
} else {
extract(Z.JO);
}
Z.status = "unzipped";
return Z.JO;
} return false;
};
Z.compress = function(obj) {
if (Z.status === "compressing") {
Z.JO.push(obj);
compress(obj);
} else if (Z.status === "ready to load object") {
Z.isArray = true;
Z.uzOpts = {I:[],A:Z.isArray,eC:[],iC:[]};
Z.status = "compressing";
Z.JO = [];
Z.JO.push(obj);
compress(obj);
} else return false;
return {M:MAP,D:Z.JO,O:Z.uzOpts};
};
var prevExtractIndex = false;
var extracted = [];
Z.extract = function(i) {
if (Z.status === "unzipable" || Z.status === "zipped") {
if (extracted.indexOf(i) > -1) {
prev = Z.JO[i];
} else {
if (!prevExtractIndex || prevExtractIndex+1 !== i) {
setPrev(i);
}
extract(Z.JO[i]);
extracted.push(i);
}
prevExtractIndex = i;
}
return Z.JO[i];
};
Z.length = function() {
return JSON.stringify(Z.JO).length + (MAP ? JSON.stringify(MAP).length : 0);
};
Z.options = function(opts,isArray) {
/* []: An array of key names that will be used as identifiers.
WARGING: Should be within every object, but repeating, NO Booleans or Integers allowed.
Hint: Most common values that can be guessed/used from previous objects */
Z.identifiers = opts.identifiers || [];
/* boolean: If _jsonObj is an array or not */
Z.isArray = opts.isArray || isArray;
/* []: An array of key names not to map or zip */
Z.exclude = opts.exclude || [];
/* []: An array of key names which values to include in mapping will need identifiers */
Z.include = opts.include || [];
/* []: An array of key names to be removed from the object */
Z.remove = opts.remove || false;
/* {}: An object containing key(s) to add, with function(s) which return the value */
Z.add = opts.add || false;
}
Z.load = function(_jsonObj, isJZobj) {
Z.startLength = 0;
MAP = [];
try {
var stringIT = JSON.stringify(_jsonObj);
Z.startLength = stringIT.length;
Z.JO = JSON.parse(stringIT);
}
catch (err) {
throw "The json object has recursive references or is too big to load into memory";
}
Z.status = "zipable";
if (isJZobj) {
if (Z.JO.D && Z.JO.O && Z.JO.M) {
MAP = Z.JO.M;
Z.identifiers = Z.JO.O.I || [];
Z.isArray = Z.JO.O.A;
Z.exclude = Z.JO.O.eC || false;
Z.include = Z.JO.O.iC || false;
Z.JO = Z.JO.D;
Z.remove = false;
Z.add = false;
Z.status = "unzipable";
} else
Z.options(isJZobj,_jsonObj.constructor === Array);
}
prev = false;
prevID = false;
};
/* Private Functions */
var getID = function(key, value) {
var mI = MAP.indexOf(key);
if (mI < 0) {
if (value) {
return MAP.push(key) - 1;
}
if (Z.exclude.indexOf(key) > -1) {
Z.uzOpts.eC.push(key);
return key;
} else {
mI = MAP.push(key) - 1;
if (Z.identifiers.indexOf(key) > -1) {
Z.uzOpts.I.push(mI);
}
if (Z.include.indexOf(key) > -1) {
Z.uzOpts.iC.push(mI);
}
}
}
return mI;
};
/* Compress the given object, taking note of the previous object */
var prev = false;
var prevID = false;
var compress = function(J) {
add(J);
var keys = Object.keys(J);
var prevSame = prev ? true : false;
var id = '';
var i=0;
for (xend=Z.identifiers.length; i<xend; i++) {
var ikey = Z.identifiers[i];
J[ikey] = getID(J[ikey],1);
id += J[ikey];
}
if (!prevSame || !prevID || prevID !== id) {
prevSame = false;
prev = J;
prevID = id;
}
i=0;
for (iend=keys.length; i<iend; i++) {
var key = keys[i];
if (Z.remove && Z.remove.indexOf(key) > -1)
delete J[key];
else {
var mI = getID(key);
if (prevSame && (MAP[prev[mI]] === J[key] || prev[mI] === J[key]))
delete J[key];
else if (Z.include.indexOf(key) > -1) {
if (Z.identifiers.indexOf(key) > -1)
J[mI] = J[key];
else J[mI] = getID(J[key],1);
delete J[key];
} else if (mI !== key) {
J[mI] = J[key];
delete J[key];
}
}
}
};
/* Extract the given object, taking note of the previous object */
var extract = function(J) {
if (J === prev)
return;
add(J);
var prevSame = Z.isArray ? isSame(prev, J) : false;
var keys = Object.keys(J);
if (prevSame)
extend(prev,J);
else if (Z.identifiers) {
var x=0;
for (xend=Z.identifiers.length; x<xend; x++) {
var ikey = Z.identifiers[x];
J[ikey] = MAP[J[ikey]];
}
}
var i=0;
for (iend=keys.length; i<iend; i++) {
var key = keys[i]*1;
var value = J[key];
if (Z.remove && Z.remove.indexOf(key) > -1)
delete J[key];
else {
if (Z.exclude.indexOf(key) > -1) {
J[key] = J[key];
if (Z.include.indexOf(key) > -1)
J[key] = MAP[J[key]];
} else {
if (Z.include.indexOf(key) > -1)
J[MAP[key]] = MAP[J[key]];
else
J[MAP[key]] = J[key];
delete J[key];
}
}
}
prev = J;
};
/* Add the additional keys and values to the given object */
var add = function(J) {
if (Z.add) {
for (var key in Z.add) {
if('undefined' !== typeof Z.add[key]){
if (typeof(Z.add[key]) === "function")
J[key] = Z.add[key](J);
else
J[key] = Z.add[key];
}
}
}
};
/* Set the previous full object from the current index, incl. */
var setPrev = function(i) {
if (i > 0) {
var x=0;
for (xend=Z.identifiers.length; x<xend; x++) {
if ('undefined' === typeof Z.JO[i][Z.identifiers[x]]) {
setPrev(i-1);
return;
}
}
extract(Z.JO[i]);
} else
extract(Z.JO[0]);
};
/* Checks if identiifiers match */
var isSame = function(obj1, obj2) {
if (Z.identifiers && obj1 && obj2 && obj1 !== obj2) {
var x=0;
for (xend=Z.identifiers.length; x<xend; x++) {
var key = Z.identifiers[x];
var mKey = MAP[Z.identifiers[x]];
if ('undefined' === typeof obj1[mKey] || ('undefined' !== typeof obj2[key] && MAP[obj2[key]] !== obj1[mKey]))
return false;
}
} else return false;
return true;
};
/* Merges an object by reference into the first one, replacing values from the second object into the first if duplicate keys exist */
var merge = function(obj1,obj2) {
for (var key in obj2) {
if('undefined' !== typeof obj2[key]) {
obj1[key] = obj2[key];
}
}
};
/* Adds all keys and values from the base to obj2 for each key that does not exist in obj2 */
var extend = function(base,obj2) {
for (var key in base) {
if('undefined' === typeof obj2[key]) {
obj2[key] = base[key];
}
}
};
Z.setID = opts.setID || false;
Z.options(opts,_jsonObj.constructor === Array)
Z.status = "ready to load object";
/* Check if object is given and if options is object or 'compressed' flag */
if (_jsonObj && typeof(_jsonObj) === "object") {
/* When unzipping an object ensure _options is true and not an object, once loaded, you can set the options */
if (_options && typeof(_options) === "boolean") {
Z.load(_jsonObj,true);
} else {
Z.load(_jsonObj,false);
}
}
};
return jz;
})(); |
// (The MIT License)
//
// Copyright Michał Czapracki, [email protected]
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
/**
* @fileoverview
* @author Michał Czapracki
*
* An extended config example
*
* Try invoking this file like:
* node simple --config=./myvars
* or
* node examples/simple --config=./examples/myvars --no-all-fixes-global --all-fixes-heap --quiet=
*/
var path = require('path');
var flatconfig = require('flatconfig'),
args = flatconfig.parseArgs(process.argv.slice(2));
if (!args['config']) {
console.log('Usage: ' + process.argv.slice(0, 2).join(' ')
+ ' --config=path/to/config');
process.exit(1);
}
var cfgpath = args['config'][0];
delete args['config'];
var config = flatconfig.load(__dirname + '/cfg.js',
path.resolve(process.cwd(), cfgpath),
args),
flat = flatconfig.flatten(config);
if (!config.quiet) {
console.log('The configuration resolved to: ');
for (var k in flat) {
console.log(' ', k, '=', JSON.stringify(flat[k]));
}
console.log('');
console.log('The resulting JSON is: ');
}
console.log(JSON.stringify(config));
|
'use strict';
(function() {
// ProductAppliers Controller Spec
describe('ProductAppliersController', function() {
// Initialize global variables
var ProductAppliersController,
scope,
$httpBackend,
$stateParams,
$location;
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function() {
jasmine.addMatchers({
toEqualData: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Then we can start by loading the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
// Set a new global scope
scope = $rootScope.$new();
// Point global variables to injected services
$stateParams = _$stateParams_;
$httpBackend = _$httpBackend_;
$location = _$location_;
// Initialize the ProductAppliers controller.
ProductAppliersController = $controller('ProductAppliersController', {
$scope: scope
});
}));
it('$scope.find() should create an array with at least one productApplier object fetched from XHR', inject(function(ProductAppliers) {
// Create sample productApplier using the ProductAppliers service
var sampleProductApplier = new ProductAppliers({
title: 'An ProductApplier about MEAN',
content: 'MEAN rocks!'
});
// Create a sample productAppliers array that includes the new productApplier
var sampleProductAppliers = [sampleProductApplier];
// Set GET response
$httpBackend.expectGET('productAppliers').respond(sampleProductAppliers);
// Run controller functionality
scope.find();
$httpBackend.flush();
// Test scope value
expect(scope.productAppliers).toEqualData(sampleProductAppliers);
}));
it('$scope.findOne() should create an array with one productApplier object fetched from XHR using a productApplierId URL parameter', inject(function(ProductAppliers) {
// Define a sample productApplier object
var sampleProductApplier = new ProductAppliers({
title: 'An ProductApplier about MEAN',
content: 'MEAN rocks!'
});
// Set the URL parameter
$stateParams.productApplierId = '525a8422f6d0f87f0e407a33';
// Set GET response
$httpBackend.expectGET(/productAppliers\/([0-9a-fA-F]{24})$/).respond(sampleProductApplier);
// Run controller functionality
scope.findOne();
$httpBackend.flush();
// Test scope value
expect(scope.productApplier).toEqualData(sampleProductApplier);
}));
it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(ProductAppliers) {
// Create a sample productApplier object
var sampleProductApplierPostData = new ProductAppliers({
title: 'An ProductApplier about MEAN',
content: 'MEAN rocks!'
});
// Create a sample productApplier response
var sampleProductApplierResponse = new ProductAppliers({
_id: '525cf20451979dea2c000001',
title: 'An ProductApplier about MEAN',
content: 'MEAN rocks!'
});
// Fixture mock form input values
scope.title = 'An ProductApplier about MEAN';
scope.content = 'MEAN rocks!';
// Set POST response
$httpBackend.expectPOST('productAppliers', sampleProductApplierPostData).respond(sampleProductApplierResponse);
// Run controller functionality
scope.create();
$httpBackend.flush();
// Test form inputs are reset
expect(scope.title).toEqual('');
expect(scope.content).toEqual('');
// Test URL redirection after the productApplier was created
expect($location.path()).toBe('/productAppliers/' + sampleProductApplierResponse._id);
}));
it('$scope.update() should update a valid productApplier', inject(function(ProductAppliers) {
// Define a sample productApplier put data
var sampleProductApplierPutData = new ProductAppliers({
_id: '525cf20451979dea2c000001',
title: 'An ProductApplier about MEAN',
content: 'MEAN Rocks!'
});
// Mock productApplier in scope
scope.productApplier = sampleProductApplierPutData;
// Set PUT response
$httpBackend.expectPUT(/productAppliers\/([0-9a-fA-F]{24})$/).respond();
// Run controller functionality
scope.update();
$httpBackend.flush();
// Test URL location to new object
expect($location.path()).toBe('/productAppliers/' + sampleProductApplierPutData._id);
}));
it('$scope.remove() should send a DELETE request with a valid productApplierId and remove the productApplier from the scope', inject(function(ProductAppliers) {
// Create new productApplier object
var sampleProductApplier = new ProductAppliers({
_id: '525a8422f6d0f87f0e407a33'
});
// Create new productAppliers array and include the productApplier
scope.productAppliers = [sampleProductApplier];
// Set expected DELETE response
$httpBackend.expectDELETE(/productAppliers\/([0-9a-fA-F]{24})$/).respond(204);
// Run controller functionality
scope.remove(sampleProductApplier);
$httpBackend.flush();
// Test array after successful delete
expect(scope.productAppliers.length).toBe(0);
}));
});
}());
|
/* global expect */
describe('outputFormat', () => {
describe('when given a format', () => {
it('decides the output that will be used for serializing errors', () => {
expect(
function () {
const clonedExpect = expect.clone().outputFormat('html');
clonedExpect(42, 'to equal', 24);
},
'to throw',
{
htmlMessage:
'<div style="font-family: monospace; white-space: nowrap">' +
'<div><span style="color: red; font-weight: bold">expected</span> <span style="color: #0086b3">42</span> <span style="color: red; font-weight: bold">to equal</span> <span style="color: #0086b3">24</span></div>' +
'</div>',
}
);
expect(
function () {
const clonedExpect = expect.clone().outputFormat('ansi');
clonedExpect(42, 'to equal', 24);
},
'to throw',
{
message:
'\n\x1b[31m\x1b[1mexpected\x1b[22m\x1b[39m 42 \x1b[31m\x1b[1mto equal\x1b[22m\x1b[39m 24\n',
}
);
});
});
});
|
'use strict';
const fs = require('fs');
const remote = require('electron').remote;
const mainProcess = remote.require('./main');
module.exports = {
template: `
<v-list dense class="pt-0">
<v-list-tile to="recent-projects" :router="true">
<v-list-tile-action>
<v-icon>list</v-icon>
</v-list-tile-action>
<v-list-tile-content>
<v-list-tile-title id="recent-projects">Recent projects</v-list-tile-title>
</v-list-tile-content>
</v-list-tile>
<v-list-tile @click="existingProject">
<v-list-tile-action>
<v-icon>folder_open</v-icon>
</v-list-tile-action>
<v-list-tile-content>
<v-list-tile-title id="open-project">Add existing project</v-list-tile-title>
</v-list-tile-content>
</v-list-tile>
<v-list-tile to="create-project" :router="true">
<v-list-tile-action>
<v-icon>create_new_folder</v-icon>
</v-list-tile-action>
<v-list-tile-content>
<v-list-tile-title id="create-project">Create new project</v-list-tile-title>
</v-list-tile-content>
</v-list-tile>
<v-list-tile @click="globalProject" v-if="globalComposerFileExists">
<v-list-tile-action>
<v-icon>public</v-icon>
</v-list-tile-action>
<v-list-tile-content>
<v-list-tile-title id="global-composer">Global composer</v-list-tile-title>
</v-list-tile-content>
</v-list-tile>
<v-list-tile to="settings" :router="true">
<v-list-tile-action>
<v-icon>settings</v-icon>
</v-list-tile-action>
<v-list-tile-content>
<v-list-tile-title id="open-settings">Settings</v-list-tile-title>
</v-list-tile-content>
</v-list-tile>
</v-list>
`,
computed: {
globalComposerFileExists() {
return fs.existsSync(remote.app.getPath('home') + '/.composer');
}
},
methods: {
existingProject: () => {
mainProcess.openDirectory();
},
globalProject: () => {
mainProcess.openProject(remote.app.getPath('home') + '/.composer');
},
}
}
|
var sys = require("sys"),
my_http = require("http"),
path = require("path"),
url = require("url"),
filesys = require("fs");
my_http.createServer(function(request,response){
var my_path = url.parse(request.url).pathname;
var full_path = path.join(process.cwd(),my_path);
path.exists(full_path,function(exists){
if(!exists){
response.writeHeader(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
}
else{
filesys.readFile(full_path, "binary", function(err, file) {
if(err) {
response.writeHeader(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
}
else{
response.writeHeader(200);
response.write(file, "binary");
response.end();
}
});
}
});
}).listen(8080);
sys.puts("Server Running on 8080");
|
var path = require('path');
var fs = require('fs');
var Writer = require('broccoli-writer');
var Handlebars = require('handlebars');
var walkSync = require('walk-sync');
var RSVP = require('rsvp');
var helpers = require('broccoli-kitchen-sink-helpers');
var mkdirp = require('mkdirp');
var Promise = RSVP.Promise;
var EXTENSIONS_REGEX = new RegExp('.(hbs|handlebars)');
var HandlebarsWriter = function (inputTree, files, options) {
if (!(this instanceof HandlebarsWriter)) {
return new HandlebarsWriter(inputTree, files, options);
}
this.inputTree = inputTree;
this.files = files;
this.options = options || {};
this.context = this.options.context || {};
this.destFile = this.options.destFile || function (filename) {
return filename.replace(/(hbs|handlebars)$/, 'html');
};
this.handlebars = this.options.handlebars || Handlebars;
this.loadPartials();
this.loadHelpers();
};
HandlebarsWriter.prototype = Object.create(Writer.prototype);
HandlebarsWriter.prototype.constructor = HandlebarsWriter;
HandlebarsWriter.prototype.loadHelpers = function () {
var helpers = this.options.helpers;
if (!helpers) return;
if ('function' === typeof helpers) helpers = helpers();
if ('object' !== typeof helpers) {
throw Error('options.helpers must be an object or a function that returns an object');
}
this.handlebars.registerHelper(helpers);
};
HandlebarsWriter.prototype.loadPartials = function () {
var partials = this.options.partials;
var partialsPath;
var partialFiles;
if (!partials) return;
if ('string' !== typeof partials) {
throw Error('options.partials must be a string');
}
partialsPath = path.join(process.cwd(), partials);
partialFiles = walkSync(partialsPath).filter(EXTENSIONS_REGEX.test.bind(EXTENSIONS_REGEX));
partialFiles.forEach(function (file) {
var key = file.replace(partialsPath, '').replace(EXTENSIONS_REGEX, '');
var filePath = path.join(partialsPath, file);
this.handlebars.registerPartial(key, fs.readFileSync(filePath).toString());
}, this);
};
HandlebarsWriter.prototype.write = function (readTree, destDir) {
var self = this;
this.loadPartials();
this.loadHelpers();
return readTree(this.inputTree).then(function (sourceDir) {
var targetFiles = helpers.multiGlob(self.files, {cwd: sourceDir});
return RSVP.all(targetFiles.map(function (targetFile) {
function write (output) {
var destFilepath = path.join(destDir, self.destFile(targetFile));
mkdirp.sync(path.dirname(destFilepath));
var str = fs.readFileSync(path.join(sourceDir, targetFile)).toString();
var template = self.handlebars.compile(str);
fs.writeFileSync(destFilepath, template(output));
}
var output = ('function' !== typeof self.context) ? self.context : self.context(targetFile);
return Promise.resolve(output).then(write);
}));
});
};
module.exports = HandlebarsWriter; |
var _a;
import app from './app';
import toHTML from './vdom-to-html';
import { _createEventTests, _createStateTests } from './apprun-dev-tools-tests';
app['debug'] = true;
window['_apprun-help'] = ['', () => {
Object.keys(window).forEach(cmd => {
if (cmd.startsWith('_apprun-')) {
cmd === '_apprun-help' ?
console.log('AppRun Commands:') :
console.log(`* ${cmd.substring(8)}: ${window[cmd][0]}`);
}
});
}];
function newWin(html) {
const win = window.open('', '_apprun_debug', 'toolbar=0');
win.document.write(`<html>
<title>AppRun Analyzer | ${document.location.href}</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI" }
li { margin-left: 80px; }
</style>
<body>
<div id="main">${html}</div>
</script>
</body>
</html>`);
win.document.close();
}
const get_components = () => {
const o = { components: {} };
app.run('get-components', o);
const { components } = o;
return components;
};
const viewElement = element => app.h("div", null,
element.tagName.toLowerCase(),
element.id ? '#' + element.id : '',
' ',
element.className && element.className.split(' ').map(c => '.' + c).join());
const viewComponents = state => {
const Events = ({ events }) => app.h("ul", null, events && events.filter(event => event.name !== '.').map(event => app.h("li", null, event.name)));
const Components = ({ components }) => app.h("ul", null, components.map(component => app.h("li", null,
app.h("div", null, component.constructor.name),
app.h(Events, { events: component['_actions'] }))));
return app.h("ul", null, state.map(({ element, comps }) => app.h("li", null,
app.h("div", null, viewElement(element)),
app.h(Components, { components: comps }))));
};
const viewEvents = state => {
const Components = ({ components }) => app.h("ul", null, components.map(component => app.h("li", null,
app.h("div", null, component.constructor.name))));
const Events = ({ events, global }) => app.h("ul", null, events && events
.filter(event => event.global === global && event.event !== '.')
.map(({ event, components }) => app.h("li", null,
app.h("div", null, event),
app.h(Components, { components: components }))));
return app.h("div", null,
app.h("div", null, "GLOBAL EVENTS"),
app.h(Events, { events: state, global: true }),
app.h("div", null, "LOCAL EVENTS"),
app.h(Events, { events: state, global: false }));
};
const _events = (print) => {
const global_events = app['_events'];
const events = {};
const cache = get_components();
const add_component = component => component['_actions'].forEach(event => {
events[event.name] = events[event.name] || [];
events[event.name].push(component);
});
if (cache instanceof Map) {
for (let [key, comps] of cache) {
comps.forEach(add_component);
}
}
else {
Object.keys(cache).forEach(el => cache[el].forEach(add_component));
}
const data = [];
Object.keys(events).forEach(event => {
data.push({ event, components: events[event], global: global_events[event] ? true : false });
});
data.sort(((a, b) => a.event > b.event ? 1 : -1)).map(e => e.event);
if (print) {
const vdom = viewEvents(data);
newWin(toHTML(vdom));
}
else {
console.log('=== GLOBAL EVENTS ===');
data.filter(event => event.global && event.event !== '.')
.forEach(({ event, components }) => console.log({ event }, components));
console.log('=== LOCAL EVENTS ===');
data.filter(event => !event.global && event.event !== '.')
.forEach(({ event, components }) => console.log({ event }, components));
}
};
const _components = (print) => {
const components = get_components();
const data = [];
if (components instanceof Map) {
for (let [key, comps] of components) {
const element = typeof key === 'string' ? document.getElementById(key) : key;
data.push({ element, comps });
}
}
else {
Object.keys(components).forEach(el => {
const element = typeof el === 'string' ? document.getElementById(el) : el;
data.push({ element, comps: components[el] });
});
}
if (print) {
const vdom = viewComponents(data);
newWin(toHTML(vdom));
}
else {
data.forEach(({ element, comps }) => console.log(element, comps));
}
};
let debugging = Number((_a = window === null || window === void 0 ? void 0 : window.localStorage) === null || _a === void 0 ? void 0 : _a.getItem('__apprun_debugging__')) || 0;
app.on('debug', p => {
if (debugging & 1 && p.event)
console.log(p);
if (debugging & 2 && p.vdom)
console.log(p);
});
window['_apprun-components'] = ['components [print]', (p) => {
_components(p === 'print');
}];
window['_apprun-events'] = ['events [print]', (p) => {
_events(p === 'print');
}];
window['_apprun-log'] = ['log [event|view] on|off', (a1, a2) => {
var _a;
if (a1 === 'on') {
debugging = 3;
}
else if (a1 === 'off') {
debugging = 0;
}
else if (a1 === 'event') {
if (a2 === 'on') {
debugging |= 1;
}
else if (a2 === 'off') {
debugging &= ~1;
}
}
else if (a1 === 'view') {
if (a2 === 'on') {
debugging |= 2;
}
else if (a2 === 'off') {
debugging &= ~2;
}
}
console.log(`* log ${a1} ${a2 || ''}`);
(_a = window === null || window === void 0 ? void 0 : window.localStorage) === null || _a === void 0 ? void 0 : _a.setItem('__apprun_debugging__', `${debugging}`);
}];
window['_apprun-create-event-tests'] = ['create-event-tests',
() => _createEventTests()
];
window['_apprun-create-state-tests'] = ['create-state-tests <start|stop>',
(p) => _createStateTests(p)
];
window['_apprun'] = (strings) => {
const [cmd, ...p] = strings[0].split(' ').filter(c => !!c);
const command = window[`_apprun-${cmd}`];
if (command)
command[1](...p);
else
window['_apprun-help'][1]();
};
console.info('AppRun DevTools 2.27: type "_apprun `help`" to list all available commands.');
const reduxExt = window['__REDUX_DEVTOOLS_EXTENSION__'];
if (reduxExt) {
let devTools_running = false;
const devTools = window['__REDUX_DEVTOOLS_EXTENSION__'].connect();
if (devTools) {
const hash = location.hash || '#';
devTools.send(hash, '');
const buf = [{ component: null, state: '' }];
console.info('Connected to the Redux DevTools');
devTools.subscribe((message) => {
if (message.type === 'START')
devTools_running = true;
else if (message.type === 'STOP')
devTools_running = false;
else if (message.type === 'DISPATCH') {
// console.log('From Redux DevTools: ', message);
const idx = message.payload.index;
if (idx === 0) {
app.run(hash);
}
else {
const { component, state } = buf[idx];
component === null || component === void 0 ? void 0 : component.setState(state);
}
}
});
const send = (component, action, state) => {
if (state == null)
return;
buf.push({ component, state });
devTools.send(action, state);
};
app.on('debug', p => {
if (devTools_running && p.event) {
const state = p.newState;
const type = p.event;
const payload = p.p;
const action = { type, payload };
const component = p.component;
if (state instanceof Promise) {
state.then(s => send(component, action, s));
}
else {
send(component, action, state);
}
}
});
}
}
//# sourceMappingURL=apprun-dev-tools.js.map |
import './index.css';
import React, {Component} from 'react';
import { postToggleDevice } from '../ajax';
export default class SocketDevice extends Component {
constructor() {
super();
this.state = {clicked: false, device: {}};
this.clicked = this.clicked.bind(this);
}
componentWillMount() {
var device = this.props.device;
if (device.enabled) {
this.setState({clicked: true});
}
this.setState({device: device});
}
clicked() {
var nextState = !this.state.clicked;
var id = this.state.device.id;
if (this.props.valueControl) {
this.props.valueControl(id, 'enabled', nextState);
this.setState({clicked: nextState});
} else {
this.toggle(id);
}
}
toggle() {
var id = this.state.device.id;
postToggleDevice(id, function (device) {
this.setState({clicked: device.enabled, device: device});
}.bind(this));
}
render() {
var name = this.state.device.name;
var classes = 'icon-tinted' + (this.state.clicked ? ' active' : '');
return (<div className="m-t-1">
<h4>
<a className={classes} onClick={this.clicked}><i className="fa fa-plug fa-lg"/></a> {name}
</h4>
</div>);
}
}
SocketDevice.propTypes = {
device: React.PropTypes.object.isRequired,
valueControl: React.PropTypes.func.isRequired
};
|
var config = {
container: "#basic-example",
connectors: {
type: 'step'
},
node: {
HTMLclass: 'nodeExample1'
}
},
ceo = {
text: {
name: "Mark Hill",
title: "Chief executive officer",
contact: "Tel: 01 213 123 134",
},
image: "../headshots/2.jpg"
},
cto = {
parent: ceo,
text:{
name: "Joe Linux",
title: "Chief Technology Officer",
},
stackChildren: true,
image: "../headshots/1.jpg"
},
cbo = {
parent: ceo,
stackChildren: true,
text:{
name: "Linda May",
title: "Chief Business Officer",
},
image: "../headshots/5.jpg"
},
cdo = {
parent: ceo,
text:{
name: "John Green",
title: "Chief accounting officer",
contact: "Tel: 01 213 123 134",
},
image: "../headshots/6.jpg"
},
cio = {
parent: cto,
text:{
name: "Ron Blomquist",
title: "Chief Information Security Officer"
},
image: "../headshots/8.jpg"
},
ciso = {
parent: cto,
text:{
name: "Michael Rubin",
title: "Chief Innovation Officer",
contact: {val: "[email protected]", href: "mailto:[email protected]"}
},
image: "../headshots/9.jpg"
},
cio2 = {
parent: cdo,
text:{
name: "Erica Reel",
title: "Chief Customer Officer"
},
link: {
href: "http://www.google.com"
},
image: "../headshots/10.jpg"
},
ciso2 = {
parent: cbo,
text:{
name: "Alice Lopez",
title: "Chief Communications Officer"
},
image: "../headshots/7.jpg"
},
ciso3 = {
parent: cbo,
text:{
name: "Mary Johnson",
title: "Chief Brand Officer"
},
image: "../headshots/4.jpg"
},
ciso4 = {
parent: cbo,
text:{
name: "Kirk Douglas",
title: "Chief Business Development Officer"
},
image: "../headshots/11.jpg"
}
chart_config = [
config,
ceo,
cto,
cbo,
cdo,
cio,
ciso,
cio2,
ciso2,
ciso3,
ciso4
];
// Another approach, same result
// JSON approach
/*
var chart_config = {
chart: {
container: "#basic-example",
connectors: {
type: 'step'
},
node: {
HTMLclass: 'nodeExample1'
}
},
nodeStructure: {
text: {
name: "Mark Hill",
title: "Chief executive officer",
contact: "Tel: 01 213 123 134",
},
image: "../headshots/2.jpg",
children: [
{
text:{
name: "Joe Linux",
title: "Chief Technology Officer",
},
stackChildren: true,
image: "../headshots/1.jpg",
children: [
{
text:{
name: "Ron Blomquist",
title: "Chief Information Security Officer"
},
image: "../headshots/8.jpg"
},
{
text:{
name: "Michael Rubin",
title: "Chief Innovation Officer",
contact: "[email protected]"
},
image: "../headshots/9.jpg"
}
]
},
{
stackChildren: true,
text:{
name: "Linda May",
title: "Chief Business Officer",
},
image: "../headshots/5.jpg",
children: [
{
text:{
name: "Alice Lopez",
title: "Chief Communications Officer"
},
image: "../headshots/7.jpg"
},
{
text:{
name: "Mary Johnson",
title: "Chief Brand Officer"
},
image: "../headshots/4.jpg"
},
{
text:{
name: "Kirk Douglas",
title: "Chief Business Development Officer"
},
image: "../headshots/11.jpg"
}
]
},
{
text:{
name: "John Green",
title: "Chief accounting officer",
contact: "Tel: 01 213 123 134",
},
image: "../headshots/6.jpg",
children: [
{
text:{
name: "Erica Reel",
title: "Chief Customer Officer"
},
link: {
href: "http://www.google.com"
},
image: "../headshots/10.jpg"
}
]
}
]
}
};
*/ |
require( ['build/index'] );
|
/*
* Copyright (c) 2016 airbug Inc. http://airbug.com
*
* bugcore may be freely distributed under the MIT license.
*/
//-------------------------------------------------------------------------------
// Annotations
//-------------------------------------------------------------------------------
//@TestFile
//@Require('Class')
//@Require('Map')
//@Require('ObservableMap')
//@Require('PutChange')
//@Require('TypeUtil')
//@Require('bugdouble.BugDouble')
//@Require('bugmeta.BugMeta')
//@Require('bugunit.TestTag')
//-------------------------------------------------------------------------------
// Context
//-------------------------------------------------------------------------------
require('bugpack').context("*", function(bugpack) {
//-------------------------------------------------------------------------------
// BugPack
//-------------------------------------------------------------------------------
var Class = bugpack.require('Class');
var Map = bugpack.require('Map');
var ObservableMap = bugpack.require('ObservableMap');
var PutChange = bugpack.require('PutChange');
var TypeUtil = bugpack.require('TypeUtil');
var BugDouble = bugpack.require('bugdouble.BugDouble');
var BugMeta = bugpack.require('bugmeta.BugMeta');
var TestTag = bugpack.require('bugunit.TestTag');
//-------------------------------------------------------------------------------
// Simplify References
//-------------------------------------------------------------------------------
var bugmeta = BugMeta.context();
var spyOnObject = BugDouble.spyOnObject;
var test = TestTag.test;
//-------------------------------------------------------------------------------
// Declare Tests
//-------------------------------------------------------------------------------
/**
* This tests...
* 1) Instantiating a ObservableMap class with no parameters
*/
var observableMapInstantiationTest = {
// Setup Test
//-------------------------------------------------------------------------------
setup: function() {
this.testObservableMap = new ObservableMap();
},
// Run Test
//-------------------------------------------------------------------------------
test: function(test) {
test.assertTrue(Class.doesExtend(this.testObservableMap.getObserved(), Map),
"Assert ObservableMap.observed defaults to a Map")
}
};
bugmeta.tag(observableMapInstantiationTest).with(
test().name("ObservableMap - instantiation test")
);
/**
* This tests...
* 1) Instantiating a ObservableMap class with parameters
*/
var observableMapInstantiationWithParametersTest = {
// Setup Test
//-------------------------------------------------------------------------------
setup: function() {
this.testKey = "testKey";
this.testValue = "testValue";
this.testMap = new Map();
this.testMap.put(this.testKey, this.testValue);
this.testObservableMap = new ObservableMap(this.testMap);
},
// Run Test
//-------------------------------------------------------------------------------
test: function(test) {
test.assertTrue(Class.doesExtend(this.testObservableMap.getObserved(), Map),
"Assert ObservableMap.observed was set to a Map");
test.assertEqual(this.testObservableMap.getObserved().get(this.testKey), this.testValue,
"Assert ObservableMap.observed was set correctly");
}
};
bugmeta.tag(observableMapInstantiationWithParametersTest).with(
test().name("ObservableMap - instantiation with parameters test")
);
});
|
const app = require('../server');
const readline = require('readline');
const {
User,
Role,
RoleMapping,
} = app.models;
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
Role.findOne({ where: { name: 'admin' } })
.then((role) => {
if (!role) {
console.log('No admin role found. Create fixtures first.');
process.exit();
}
const admin = {};
const fields = ['username', 'password'];
let field = fields.shift();
console.log(`${field}: `);
rl.on('line', (line) => {
admin[field] = line;
field = fields.shift();
if (!field) {
process.stdout.write('Creating the user... ');
User.create(admin)
.then(user =>
RoleMapping.create({
UserId: user.id,
RoleId: role.id,
})
)
.then(() => {
console.log('Done!\n');
process.exit(0);
})
.catch((err) => {
console.error(err);
process.exit(1);
});
return;
}
process.stdout.write(`${field}: \n`);
});
});
|
var dbm = require('db-migrate');
var type = dbm.dataType;
exports.up = function(db, callback) {
db.addColumn("troop_type", "production_cost", "int", callback);
};
exports.down = function(db, callback) {
};
|
'use strict';
// you have to require the utils module and call adapter function
const utils = require('@iobroker/adapter-core'); // Get common adapter utils
const adapterName = require('./package.json').name.split('.').pop();
// include node-ssdp and node-upnp-subscription
const {Client, Server} = require('node-ssdp');
const Subscription = require('./lib/upnp-subscription');
const parseString = require('xml2js').parseString;
const DOMParser = require('xmldom').DOMParser;
const request = require('request');
const nodeSchedule = require('node-schedule');
let adapter;
let client = new Client();
const tasks = [];
let taskRunning = false;
const actions = {}; // scheduled actions
const crons = {};
const checked = {}; // store checked objects for polling
let discoveredDevices = [];
let sidPromise; // Read SIDs promise
let globalCb; // callback for last processTasks
function startCronJob(cron) {
console.log('Start cron JOB: ' + cron);
crons[cron] = nodeSchedule.scheduleJob(cron, () => pollActions(cron));
}
function stopCronJob(cron) {
if (crons[cron]) {
crons[cron].cancel();
delete crons[cron];
}
}
function pollActions(cron) {
Object.keys(actions).forEach(id =>
actions[id].cron === cron && addTask({name: 'sendCommand', id}));
processTasks();
}
function reschedule(changedId, deletedCron) {
const schedules = {};
if (changedId) {
if (!deletedCron) {
Object.keys(actions).forEach(_id => {
if (_id !== changedId) {
const cron = actions[_id].cron;
schedules[cron] = schedules[cron] || 0;
schedules[cron]++;
}
});
if (!schedules[actions[changedId].cron]) {
// start cron job
startCronJob(actions[changedId].cron);
}
} else {
Object.keys(actions).forEach(_id => {
const cron = actions[_id].cron;
schedules[cron] = schedules[cron] || 0;
schedules[cron]++;
});
if (schedules[deletedCron] === 1 && crons[deletedCron]) {
// stop cron job
stopCronJob(deletedCron);
}
}
} else {
// first
Object.keys(actions).forEach(_id => {
const cron = actions[_id].cron;
schedules[cron] = schedules[cron] || 0;
schedules[cron]++;
});
Object.keys(schedules).forEach(cron => startCronJob(cron));
}
}
function startAdapter(options) {
options = options || {};
Object.assign(options, {name: adapterName, strictObjectChecks: false});
adapter = new utils.Adapter(options);
// is called when adapter shuts down - callback has to be called under any circumstances!
adapter.on('unload', callback => {
try {
server.stop(); // advertise shutting down and stop listening
adapter.log.info('cleaned everything up...');
clearAliveAndSIDStates(callback);
} catch (e) {
callback();
}
});
adapter.on('objectChange', (id, obj) => {
if (obj && obj.common && obj.common.custom &&
obj.common.custom[adapter.namespace] &&
obj.common.custom[adapter.namespace].enabled &&
obj.native && obj.native.request
) {
if (!actions[id]) {
adapter.log.info(`enabled polling of ${id} with schedule ${obj.common.custom[adapter.namespace].schedule}`);
setImmediate(() => reschedule(id));
}
actions[id] = {cron: obj.common.custom[adapter.namespace].schedule};
} else if (actions[id]) {
adapter.log.debug('Removed polling for ' + id);
setImmediate((id, cron) => reschedule(id, cron), id, actions[id].cron);
delete actions[id];
}
});
// is called if a subscribed state changes
adapter.on('stateChange', (id, state) => {
if (!state || state.ack) {
return;
}
// Subscribe to an service when its state Alive is true
if (id.match(/\.request$/)) {
// Control a device when a related object changes its value
if (checked[id] !== undefined) {
checked[id] && sendCommand(id);
} else {
adapter.getObject(id, (err, obj) => {
if (obj && obj.native && obj.native.request) {
checked[id] = true;
sendCommand(id);
} else {
checked[id] = false;
}
});
}
}
});
// is called when databases are connected and adapter received configuration.
// start here!
adapter.on('ready', () => {
main();
});
// Some message was sent to adapter instance over message box. Used by email, pushover, text2speech, ...
adapter.on('message', obj => {
if (typeof obj === 'object' && obj.message) {
if (obj.command === 'send') {
// e.g. send email or pushover or whatever
adapter.log.info('send command');
// Send response in callback if required
obj.callback && adapter.sendTo(obj.from, obj.command, 'Message received', obj.callback);
}
}
});
return adapter;
}
function getValueFromArray(value) {
if (typeof value === 'object' && value instanceof Array && value[0] !== undefined) {
return value[0] !== null ? value[0].toString() : '';
} else {
return value !== null && value !== undefined ? value.toString() : '';
}
}
let foundIPs = []; // Array for the caught broadcast answers
function sendBroadcast() {
// adapter.log.debug('Send Broadcast');
// Sends a Broadcast and catch the URL with xml device description file
client.on('response', (headers, _statusCode, _rinfo) => {
let answer = (headers || {}).LOCATION;
if (answer && foundIPs.indexOf(answer) === -1) {
foundIPs.push(answer);
if (answer !== answer.match(/.*dummy.xml/g)) {
setTimeout(() => firstDevLookup(answer), 1000);
}
}
});
client.search('ssdp:all');
}
// Read the xml device description file of each upnp device the first time
function firstDevLookup(strLocation, cb) {
const originalStrLocation = strLocation;
adapter.log.debug('firstDevLookup for ' + strLocation);
request(strLocation, (error, response, body) => {
if (!error && response.statusCode === 200) {
adapter.log.debug('Positive answer for request of the XML file for ' + strLocation);
try {
const xmlStringSerialized = new DOMParser().parseFromString((body || '').toString(), 'text/xml');
parseString(xmlStringSerialized, {explicitArray: true, mergeAttrs: true}, (err, result) => {
let path;
let xmlDeviceType;
let xmlTypeOfDevice;
let xmlUDN;
let xmlManufacturer;
adapter.log.debug('Parsing the XML file for ' + strLocation);
if (err) {
adapter.log.warn('Error: ' + err);
} else {
adapter.log.debug('Creating objects for ' + strLocation);
let i;
if (!result || !result.root || !result.root.device) {
adapter.log.debug('Error by parsing of ' + strLocation + ': Cannot find deviceType');
return;
}
path = result.root.device[0];
//Looking for deviceType of device
try {
xmlDeviceType = getValueFromArray(path.deviceType);
xmlTypeOfDevice = xmlDeviceType.replace(/:\d/, '');
xmlTypeOfDevice = xmlTypeOfDevice.replace(/.*:/, '');
xmlTypeOfDevice = nameFilter(xmlTypeOfDevice);
adapter.log.debug('TypeOfDevice ' + xmlTypeOfDevice);
} catch (err) {
adapter.log.debug(`Can not read deviceType of ${strLocation}`);
xmlDeviceType = '';
}
//Looking for the port
let strPort = strLocation.replace(/\bhttp:\/\/.*\d:/ig, '');
strPort = strPort.replace(/\/.*/g, '');
if (strPort.match(/http:/ig)) {
strPort = '';
} else {
strPort = parseInt(strPort, 10);
}
// Looking for the IP of a device
strLocation = strLocation.replace(/http:\/\/|"/g, '').replace(/:\d*\/.*/ig, '');
//Looking for UDN of a device
try {
xmlUDN = getValueFromArray(path.UDN).replace(/"/g, '').replace(/uuid:/g, '');
} catch (err) {
adapter.log.debug(`Can not read UDN of ${strLocation}`);
xmlUDN = '';
}
//Looking for the manufacturer of a device
try {
xmlManufacturer = getValueFromArray(path.manufacturer).replace(/"/g, '');
} catch (err) {
adapter.log.debug('Can not read manufacturer of ' + strLocation);
xmlManufacturer = '';
}
// Extract the path to the device icon that is delivered by the device
// let i_icons = 0;
let xmlIconURL;
let xmlFN;
let xmlManufacturerURL;
let xmlModelNumber;
let xmlModelDescription;
let xmlModelName;
let xmlModelURL;
try {
// i_icons = path.iconList[0].icon.length;
xmlIconURL = getValueFromArray(path.iconList[0].icon[0].url).replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not find a icon for ${strLocation}`);
xmlIconURL = '';
}
//Looking for the friendlyName of a device
try {
xmlFN = nameFilter(getValueFromArray(path.friendlyName));
} catch (err) {
adapter.log.debug(`Can not read friendlyName of ${strLocation}`);
xmlFN = 'Unknown';
}
//Looking for the manufacturerURL
try {
xmlManufacturerURL = getValueFromArray(path.manufacturerURL).replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not read manufacturerURL of ${strLocation}`);
xmlManufacturerURL = '';
}
// Looking for the modelNumber
try {
xmlModelNumber = getValueFromArray(path.modelNumber).replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not read modelNumber of ${strLocation}`);
xmlModelNumber = '';
}
// Looking for the modelDescription
try {
xmlModelDescription = getValueFromArray(path.modelDescription).replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not read modelDescription of ${strLocation}`);
xmlModelDescription = '';
}
// Looking for the modelName
try {
xmlModelName = getValueFromArray(path.modelName).replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not read modelName of ${strLocation}`);
xmlModelName = '';
}
// Looking for the modelURL
try {
xmlModelURL = getValueFromArray(path.modelURL).replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not read modelURL of ${strLocation}`);
xmlModelURL = '';
}
// START - Creating the root object of a device
adapter.log.debug(`Creating root element for device: ${xmlFN}`);
addTask({
name: 'setObjectNotExists',
id: `${xmlFN}.${xmlTypeOfDevice}`,
obj: {
type: 'device',
common: {
name: xmlFN,
extIcon: `http://${strLocation}:${strPort}${xmlIconURL}`
},
native: {
ip: strLocation,
port: strPort,
uuid: xmlUDN,
deviceType: xmlDeviceType,
manufacturer: xmlManufacturer,
manufacturerURL: xmlManufacturerURL,
modelNumber: xmlModelNumber,
modelDescription: xmlModelDescription,
modelName: xmlModelName,
modelURL: xmlModelURL,
name: xmlFN,
}
}
});
let pathRoot = result.root.device[0];
let objectName = `${xmlFN}.${xmlTypeOfDevice}`;
createServiceList(result, xmlFN, xmlTypeOfDevice, objectName, strLocation, strPort, pathRoot);
const aliveID = `${adapter.namespace}.${xmlFN}.${xmlTypeOfDevice}.Alive`;
addTask({
name: 'setObjectNotExists',
id: aliveID,
obj: {
type: 'state',
common: {
name: 'Alive',
type: 'boolean',
role: 'indicator.reachable',
def: false,
read: true,
write: false
},
native: {}
}
});
// Add to Alives list
getIDs()
.then(result => result.alives.indexOf(aliveID) === -1 && result.alives.push(aliveID));
// START - Creating SubDevices list for a device
let lenSubDevices = 0;
let xmlfriendlyName;
if (path.deviceList && path.deviceList[0].device) {
// Counting SubDevices
lenSubDevices = path.deviceList[0].device.length;
if (lenSubDevices) {
// adapter.log.debug('Found more than one SubDevice');
for (i = lenSubDevices - 1; i >= 0; i--) {
// Looking for deviceType of device
try {
xmlDeviceType = getValueFromArray(path.deviceList[0].device[i].deviceType).replace(/"/g, '');
xmlTypeOfDevice = xmlDeviceType.replace(/:\d/, '');
xmlTypeOfDevice = xmlTypeOfDevice.replace(/.*:/, '');
xmlTypeOfDevice = nameFilter(xmlTypeOfDevice);
adapter.log.debug(`TypeOfDevice ${xmlTypeOfDevice}`);
} catch (err) {
adapter.log.debug(`Can not read deviceType of ${strLocation}`);
xmlDeviceType = '';
}
//Looking for the friendlyName of the SubDevice
try {
xmlfriendlyName = getValueFromArray(path.deviceList[0].device[i].friendlyName);
xmlFN = nameFilter(xmlfriendlyName);
} catch (err) {
adapter.log.debug(`Can not read friendlyName of SubDevice from ${xmlFN}`);
xmlfriendlyName = 'Unknown';
}
//Looking for the manufacturer of a device
try {
xmlManufacturer = getValueFromArray(path.deviceList[0].device[i].manufacturer).replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not read manufacturer of ${xmlfriendlyName}`);
xmlManufacturer = '';
}
//Looking for the manufacturerURL
try {
xmlManufacturerURL = getValueFromArray(path.deviceList[0].device[i].manufacturerURL);
} catch (err) {
adapter.log.debug(`Can not read manufacturerURL of ${xmlfriendlyName}`);
xmlManufacturerURL = '';
}
//Looking for the modelNumber
try {
xmlModelNumber = getValueFromArray(path.deviceList[0].device[i].modelNumber);
} catch (err) {
adapter.log.debug(`Can not read modelNumber of ${xmlfriendlyName}`);
xmlModelNumber = '';
}
//Looking for the modelDescription
try {
xmlModelDescription = getValueFromArray(path.deviceList[0].device[i].modelDescription);
} catch (err) {
adapter.log.debug(`Can not read modelDescription of ${xmlfriendlyName}`);
xmlModelDescription = '';
}
//Looking for deviceType of device
try {
xmlDeviceType = getValueFromArray(path.deviceList[0].device[i].deviceType);
} catch (err) {
adapter.log.debug(`Can not read DeviceType of ${xmlfriendlyName}`);
xmlDeviceType = '';
}
//Looking for the modelName
try {
xmlModelName = getValueFromArray(path.deviceList[0].device[i].modelName);
} catch (err) {
adapter.log.debug(`Can not read modelName of ${xmlfriendlyName}`);
xmlModelName = '';
}
//Looking for the modelURL
try {
xmlModelURL = path.deviceList[0].device[i].modelURL;
} catch (err) {
adapter.log.debug(`Can not read modelURL of ${xmlfriendlyName}`);
xmlModelURL = '';
}
//Looking for UDN of a device
try {
xmlUDN = getValueFromArray(path.deviceList[0].device[i].UDN)
.replace(/"/g, '')
.replace(/uuid:/g, '');
} catch (err) {
adapter.log.debug(`Can not read UDN of ${xmlfriendlyName}`);
xmlUDN = '';
}
//The SubDevice object
addTask({
name: 'setObjectNotExists',
id: `${xmlFN}.${xmlTypeOfDevice}`,
obj: {
type: 'device',
common: {
name: xmlfriendlyName
},
native: {
ip: strLocation,
port: strPort,
uuid: xmlUDN,
deviceType: xmlDeviceType.toString(),
manufacturer: xmlManufacturer.toString(),
manufacturerURL: xmlManufacturerURL.toString(),
modelNumber: xmlModelNumber.toString(),
modelDescription: xmlModelDescription.toString(),
modelName: xmlModelName.toString(),
modelURL: xmlModelURL.toString(),
name: xmlfriendlyName
}
}
}); //END SubDevice Object
let pathSub = result.root.device[0].deviceList[0].device[i];
let objectNameSub = `${xmlFN}.${xmlTypeOfDevice}`;
createServiceList(result, xmlFN, xmlTypeOfDevice, objectNameSub, strLocation, strPort, pathSub);
const aliveID = `${adapter.namespace}.${xmlFN}.${xmlTypeOfDevice}.Alive`;
addTask({
name: 'setObjectNotExists',
id: aliveID,
obj: {
type: 'state',
common: {
name: 'Alive',
type: 'boolean',
role: 'indicator.reachable',
def: false,
read: true,
write: false
},
native: {}
}
});
// Add to Alives list
getIDs()
.then(result => result.alives.indexOf(aliveID) === -1 && result.alives.push(aliveID));
let TypeOfSubDevice = xmlTypeOfDevice;
//START - Creating SubDevices list for a sub-device
if (path.deviceList[0].device[i].deviceList && path.deviceList[0].device[i].deviceList[0].device) {
//Counting SubDevices
let i_SubSubDevices = path.deviceList[0].device[i].deviceList[0].device.length;
let i2;
if (i_SubSubDevices) {
for (i2 = i_SubSubDevices - 1; i2 >= 0; i--) {
adapter.log.debug(`Device ${i2} ` + path.deviceList[0].device[i].deviceList[0].device[i2].friendlyName);
//Looking for deviceType of device
try {
xmlDeviceType = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].deviceType).replace(/"/g, '');
xmlTypeOfDevice = xmlDeviceType
.replace(/:\d/, '')
.replace(/.*:/, '');
xmlTypeOfDevice = nameFilter(xmlTypeOfDevice);
adapter.log.debug(`TypeOfDevice ${xmlTypeOfDevice}`);
} catch (err) {
adapter.log.debug(`Can not read deviceType of ${strLocation}`);
xmlDeviceType = '';
}
//Looking for the friendlyName of the SubDevice
try {
xmlfriendlyName = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].friendlyName);
xmlFN = nameFilter(xmlfriendlyName);
} catch (err) {
adapter.log.debug(`Can not read friendlyName of SubDevice from ${xmlFN}`);
xmlfriendlyName = 'Unknown';
}
//Looking for the manufacturer of a device
try {
xmlManufacturer = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].manufacturer).replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not read manufacturer of ${xmlfriendlyName}`);
xmlManufacturer = '';
}
//Looking for the manufacturerURL
try {
xmlManufacturerURL = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].manufacturerURL);
} catch (err) {
adapter.log.debug(`Can not read manufacturerURL of ${xmlfriendlyName}`);
xmlManufacturerURL = '';
}
//Looking for the modelNumber
try {
xmlModelNumber = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].modelNumber);
} catch (err) {
adapter.log.debug(`Can not read modelNumber of ${xmlfriendlyName}`);
xmlModelNumber = '';
}
//Looking for the modelDescription
try {
xmlModelDescription = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].modelDescription);
} catch (err) {
adapter.log.debug(`Can not read modelDescription of ${xmlfriendlyName}`);
xmlModelDescription = '';
}
//Looking for deviceType of device
try {
xmlDeviceType = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].deviceType);
} catch (err) {
adapter.log.debug('Can not read DeviceType of ' + xmlfriendlyName);
xmlDeviceType = '';
}
//Looking for the modelName
try {
xmlModelName = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].modelName);
} catch (err) {
adapter.log.debug(`Can not read DeviceType of ${xmlfriendlyName}`);
xmlModelName = '';
}
//Looking for the modelURL
try {
xmlModelURL = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].modelURL);
} catch (err) {
adapter.log.debug(`Can not read modelURL of ${xmlfriendlyName}`);
xmlModelURL = '';
}
//Looking for UDN of a device
try {
xmlUDN = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].UDN)
.replace(/"/g, '')
.replace(/uuid:/g, '');
} catch (err) {
adapter.log.debug(`Can not read UDN of ${xmlfriendlyName}`);
xmlUDN = '';
}
//The SubDevice object
addTask({
name: 'setObjectNotExists',
id: `${xmlFN}.${TypeOfSubDevice}.${xmlTypeOfDevice}`,
obj: {
type: 'device',
common: {
name: xmlfriendlyName
},
native: {
ip: strLocation,
port: strPort,
uuid: xmlUDN,
deviceType: xmlDeviceType.toString(),
manufacturer: xmlManufacturer.toString(),
manufacturerURL: xmlManufacturerURL.toString(),
modelNumber: xmlModelNumber.toString(),
modelDescription: xmlModelDescription.toString(),
modelName: xmlModelName.toString(),
modelURL: xmlModelURL.toString(),
name: xmlfriendlyName
}
}
}); //END SubDevice Object
pathSub = result.root.device[0].deviceList[0].device[i].deviceList[0].device[i2];
objectNameSub = `${xmlFN}.${TypeOfSubDevice}.${xmlTypeOfDevice}`;
createServiceList(result, xmlFN, `${TypeOfSubDevice}.${xmlTypeOfDevice}`, objectNameSub, strLocation, strPort, pathSub);
const aliveID = `${adapter.namespace}.${xmlFN}.${TypeOfSubDevice}.${xmlTypeOfDevice}.Alive`;
addTask({
name: 'setObjectNotExists',
id: aliveID,
obj: {
type: 'state',
common: {
name: 'Alive',
type: 'boolean',
role: 'indicator.reachable',
def: false,
read: true,
write: false
},
native: {}
}
});
// Add to Alives list
getIDs()
.then(result => result.alives.indexOf(aliveID) === -1 && result.alives.push(aliveID));
}
}
}
}
}
}
}
// remove device from processed list
const pos = discoveredDevices.indexOf(originalStrLocation);
pos !== -1 && discoveredDevices.splice(pos, 1);
processTasks();
cb && cb();
});
} catch (error) {
adapter.log.debug(`Cannot parse answer from ${strLocation}: ${error}`);
// remove device from processed list
const pos = discoveredDevices.indexOf(originalStrLocation);
pos !== -1 && discoveredDevices.splice(pos, 1);
processTasks();
cb && cb();
}
} else {
// remove device from processed list
const pos = discoveredDevices.indexOf(originalStrLocation);
pos !== -1 && discoveredDevices.splice(pos, 1);
cb && cb();
}
});
}
function createServiceList(result, xmlFN, xmlTypeOfDevice, object, strLocation, strPort, path) {
if (!path.serviceList) {
adapter.log.debug('No service list found at ' + JSON.stringify(path));
return;
}
if (!path.serviceList[0] || !path.serviceList[0].service || !path.serviceList[0].service.length) {
adapter.log.debug('No services found in the service list');
return;
}
let i;
let xmlService;
let xmlServiceType;
let xmlServiceID;
let xmlControlURL;
let xmlEventSubURL;
let xmlSCPDURL;
let i_services = path.serviceList[0].service.length;
//Counting services
//adapter.log.debug('Number of services: ' + i_services);
for (i = i_services - 1; i >= 0; i--) {
try {
xmlService = getValueFromArray(path.serviceList[0].service[i].serviceType)
.replace(/urn:.*:service:/g, '')
.replace(/:\d/g, '')
.replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not read service of ${xmlFN}`);
xmlService = 'Unknown';
}
try {
xmlServiceType = getValueFromArray(path.serviceList[0].service[i].serviceType);
} catch (err) {
adapter.log.debug(`Can not read serviceType of ${xmlService}`);
xmlServiceType = '';
}
try {
xmlServiceID = getValueFromArray(path.serviceList[0].service[i].serviceId);
} catch (err) {
adapter.log.debug(`Can not read serviceID of ${xmlService}`);
xmlServiceID = '';
}
try {
xmlControlURL = getValueFromArray(path.serviceList[0].service[i].controlURL);
} catch (err) {
adapter.log.debug(`Can not read controlURL of ${xmlService}`);
xmlControlURL = '';
}
try {
xmlEventSubURL = getValueFromArray(path.serviceList[0].service[i].eventSubURL);
} catch (err) {
adapter.log.debug(`Can not read eventSubURL of ${xmlService}`);
xmlEventSubURL = '';
}
try {
xmlSCPDURL = getValueFromArray(path.serviceList[0].service[i].SCPDURL);
if (!xmlSCPDURL.match(/^\//)) {
xmlSCPDURL = `/${xmlSCPDURL}`;
}
} catch (err) {
adapter.log.debug(`Can not read SCPDURL of ${xmlService}`);
xmlSCPDURL = '';
}
addTask({
name: 'setObjectNotExists',
id: `${object}.${xmlService}`,
obj: {
type: 'channel',
common: {
name: xmlService
},
native: {
serviceType: xmlServiceType,
serviceID: xmlServiceID,
controlURL: xmlControlURL,
eventSubURL: xmlEventSubURL,
SCPDURL: xmlSCPDURL,
name: xmlService
}
}
});
const sid = `${adapter.namespace}.${object}.${xmlService}.sid`;
addTask({
name: 'setObjectNotExists',
id: sid,
obj: {
type: 'state',
common: {
name: 'Subscription ID',
type: 'string',
role: 'state',
def: '',
read: true,
write: true
},
native: {}
}
});
// Add to SID list
getIDs()
.then(result => result.sids.indexOf(sid) === -1 && result.sids.push(sid));
let SCPDlocation = `http://${strLocation}:${strPort}${xmlSCPDURL}`;
let service = `${xmlFN}.${xmlTypeOfDevice}.${xmlService}`;
addTask({name: 'readSCPD', SCPDlocation, service});
}
}
// Read the SCPD File of a upnp device service
function readSCPD(SCPDlocation, service, cb) {
adapter.log.debug('readSCPD for ' + SCPDlocation);
request(SCPDlocation, (error, response, body) => {
if (!error && response.statusCode === 200) {
try {
parseString(body, {explicitArray: true}, (err, result) => {
adapter.log.debug('Parsing the SCPD XML file for ' + SCPDlocation);
if (err) {
adapter.log.warn('Error: ' + err);
cb();
} else if (!result || !result.scpd) {
adapter.log.debug('Error by parsing of ' + SCPDlocation);
cb();
} else {
createServiceStateTable(result, service);
createActionList(result, service);
processTasks();
cb();
}
}); //END function
} catch (error) {
adapter.log.debug(`Cannot parse answer from ${SCPDlocation}: ${error}`);
cb();
}
} else {
cb();
}
});
}
function createServiceStateTable(result, service) {
if (!result.scpd || !result.scpd.serviceStateTable) {
return;
}
let path = result.scpd.serviceStateTable[0] || result.scpd.serviceStateTable;
if (!path.stateVariable || !path.stateVariable.length) {
return;
}
let iStateVarLength = path.stateVariable.length;
let xmlName;
let xmlDataType;
// Counting stateVariable's
// adapter.log.debug('Number of stateVariables: ' + iStateVarLength);
try {
for (let i2 = iStateVarLength - 1; i2 >= 0; i2--) {
let stateVariableAttr;
let strAllowedValues = [];
let strMinimum;
let strMaximum;
let strDefaultValue;
let strStep;
stateVariableAttr = path.stateVariable[i2]['$'].sendEvents;
xmlName = getValueFromArray(path.stateVariable[i2].name);
xmlDataType = getValueFromArray(path.stateVariable[i2].dataType);
try {
let allowed = path.stateVariable[i2].allowedValueList[0].allowedValue;
strAllowedValues = Object.keys(allowed).map(xmlAllowedValue => allowed[xmlAllowedValue]).join(' ');
} catch (err) {
}
try {
strDefaultValue = getValueFromArray(path.stateVariable[i2].defaultValue);
} catch (err) {
}
if (path.stateVariable[i2].allowedValueRange) {
try {
strMinimum = getValueFromArray(path.stateVariable[i2].allowedValueRange[0].minimum);
} catch (err) {
}
try {
strMaximum = getValueFromArray(path.stateVariable[i2].allowedValueRange[0].maximum);
} catch (err) {
}
try {
strStep = getValueFromArray(path.stateVariable[i2].allowedValueRange[0].step);
} catch (err) {
}
}
// Handles DataType ui2 as Number
let dataType;
if (xmlDataType.toString() === 'ui2') {
dataType = 'number';
} else {
dataType = xmlDataType.toString();
}
addTask({
name: 'setObjectNotExists',
id: `${service}.${xmlName}`,
obj: {
type: 'state',
common: {
name: xmlName,
type: dataType,
role: 'state',
read: true,
write: true
},
native: {
name: xmlName,
sendEvents: stateVariableAttr,
allowedValues: strAllowedValues,
defaultValue: strDefaultValue,
minimum: strMinimum,
maximum: strMaximum,
step: strStep,
}
}
});
}//END for
} catch (err) {
}
//END Add serviceList for SubDevice
} //END function
function createActionList(result, service) {
if (!result || !result.scpd || !result.scpd.actionList || !result.scpd.actionList[0]) {
return;
}
let path = result.scpd.actionList[0];
if (!path.action || !path.action.length) {
return;
}
let actionLen = path.action.length;
//Counting action's
//adapter.log.debug('Number of actions: ' + actionLen);
for (let i2 = actionLen - 1; i2 >= 0; i2--) {
let xmlName = getValueFromArray(path.action[i2].name);
addTask({
name: 'setObjectNotExists',
id: `${service}.${xmlName}`,
obj: {
type: 'channel',
common: {
name: xmlName
},
native: {
name: xmlName
}
}
});
try {
createArgumentList(result, service, xmlName, i2, path);
} catch (err) {
adapter.log.debug(`There is no argument for ${xmlName}`);
}
}
}
function createArgumentList(result, service, actionName, action_number, path) {
let iLen = 0;
let action;
let _arguments;
// adapter.log.debug('Reading argumentList for ' + actionName);
action = path.action[action_number].argumentList;
if (action && action[0] && action[0].argument) {
_arguments = action[0].argument;
iLen = _arguments.length;
} else {
return;
}
addTask({
name: 'setObjectNotExists',
id: `${service}.${actionName}.request`,
obj: {
type: 'state',
common: {
name: 'Initiate poll',
role: 'button',
type: 'boolean',
def: false,
read: false,
write: true
},
native: {
actionName: actionName,
service: service,
request: true
}
}
}); //END adapter.setObject()
// Counting arguments's
for (let i2 = iLen - 1; i2 >= 0; i2--) {
let xmlName = 'Unknown';
let xmlDirection = '';
let xmlRelStateVar = '';
let argument = _arguments[i2];
try {
xmlName = getValueFromArray(argument.name);
} catch (err) {
adapter.log.debug(`Can not read argument "name" of ${actionName}`);
}
try {
xmlDirection = getValueFromArray(argument.direction);
} catch (err) {
adapter.log.debug(`Can not read direction of ${actionName}`);
}
try {
xmlRelStateVar = getValueFromArray(argument.relatedStateVariable);
} catch (err) {
adapter.log.debug(`Can not read relatedStateVariable of ${actionName}`);
}
addTask({
name: 'setObjectNotExists',
id: `${service}.${actionName}.${xmlName}`,
obj: {
type: 'state',
common: {
name: xmlName,
role: 'state.argument.' + xmlDirection,
type: 'string',
def: '',
read: true,
write: true
},
native: {
direction: xmlDirection,
relatedStateVariable: xmlRelStateVar,
argumentNumber: i2 + 1,
name: xmlName,
}
}
}); //END adapter.setObject()
}
} //END function
//END Creating argumentList
let showTimer = null;
function processTasks(cb) {
if (!taskRunning && tasks.length) {
if (cb) {
globalCb = cb; // used by unload
}
taskRunning = true;
setImmediate(_processTasks);
adapter.log.debug('Started processTasks with ' + tasks.length + ' tasks');
showTimer = setInterval(() => adapter.log.debug(`Tasks ${tasks.length}...`), 5000);
} else if (cb) {
cb();
}
}
function addTask(task) {
tasks.push(task);
}
function _processTasks() {
if (!tasks.length) {
taskRunning = false;
adapter.log.debug('All tasks processed');
clearInterval(showTimer);
if (globalCb) {
globalCb();
globalCb = null;
}
} else {
const task = tasks.shift();
if (task.name === 'sendCommand') {
sendCommand(task.id, () => setTimeout(_processTasks, 0));
} else
if (task.name === 'firstDevLookup') {
firstDevLookup(task.location, () => setTimeout(_processTasks, 0));
} else
if (task.name === 'subscribeEvent') {
subscribeEvent(task.deviceID, () => setTimeout(_processTasks, 0));
} else if (task.name === 'setState') {
adapter.setState(task.id, task.state, err => {
if (typeof task.cb === 'function') {
task.cb(() => setTimeout(_processTasks, 0));
} else {
setTimeout(_processTasks, 0);
}
});
} else
if (task.name === 'valChannel') {
valChannel(task.strState, task.serviceID, () => {
writeState(task.serviceID, task.stateName, task.val, () =>
setTimeout(_processTasks, 0));
});
} else
if (task.name === 'readSCPD') {
readSCPD(task.SCPDlocation, task.service, () => setTimeout(_processTasks, 0));
} else
if (task.name === 'setObjectNotExists') {
if(task.obj.common.type){
switch (task.obj.common.type){
case 'bool':
task.obj.common.type = 'boolean';
break;
case 'i1':
case 'i2':
case 'i4':
case 'ui1':
case 'ui2':
case 'ui4':
case 'int':
case 'r4':
case 'r8':
case 'fixed.14.4':
case 'fixed':
case 'float':
task.obj.common.type = 'number';
break;
case 'char string':
case 'date':
case 'dateTime':
case 'dateTime.tz':
case 'time':
case 'time.tz':
case 'bin.base64':
case 'bin.hex':
case 'uri':
case 'uuid':
task.obj.common.type = 'string';
break;
}
if(task.obj.common.name === 'bool'){
task.obj.common.name = 'boolean';
}
}
adapter.setObjectNotExists(task.id, task.obj, () => {
if (task.obj.type === 'state' && task.id.match(/\.sid$/)) {
adapter.getState(task.id, (err, state) => {
if (!state) {
adapter.setState(task.id, false, true, (err, state) =>
setTimeout(_processTasks, 0));
} else {
setTimeout(_processTasks, 0);
}
});
} else {
setTimeout(_processTasks, 0);
}
});
} else {
adapter.log.warn('Unknown task: ' + task.name);
setTimeout(_processTasks, 0);
}
}
}
function startServer() {
//START Server for Alive and ByeBye messages
// let own_uuid = 'uuid:f40c2981-7329-40b7-8b04-27f187aecfb5'; //this string is for filter message's from upnp Adapter
let server = new Server({ssdpIp: '239.255.255.250'});
// helper variables for start adding new devices
// let devices;
// Identification of upnp Adapter/ioBroker as upnp Service and it's capabilities
// at this time there is no implementation of upnp service capabilities, it is only necessary for the server to run
server.addUSN('upnp:rootdevice');
server.addUSN('urn:schemas-upnp-org:device:IoTManagementandControlDevice:1');
server.on('advertise-alive', headers => {
let usn = getValueFromArray(headers['USN'])
.replace(/uuid:/ig, '')
.replace(/::.*/ig, '');
let nt = getValueFromArray(headers['NT']);
let location = getValueFromArray(headers['LOCATION']);
if (!usn.match(/f40c2981-7329-40b7-8b04-27f187aecfb5/)) {
if (discoveredDevices.indexOf(location) === -1) {
discoveredDevices.push(location);
adapter.getDevices((err, devices) => {
let foundUUID = false;
for (let i = 0; i < devices.length; i++) {
if (!devices[i] || !devices[i].native || !devices[i].native.uuid) continue;
const deviceUUID = devices[i].native.uuid;
const deviceUSN = devices[i].native.deviceType;
// Set object Alive for the Service true
if (deviceUUID === usn && deviceUSN === nt) {
let maxAge = getValueFromArray(headers['CACHE-CONTROL'])
.replace(/max-age.=./ig, '')
.replace(/max-age=/ig, '')
.replace(/"/g, '');
addTask({
name: 'setState',
id: `${devices[i]._id}.Alive`,
state: {val: true, ack: true, expire: parseInt(maxAge)}
});
addTask({name: 'subscribeEvent', deviceID: devices[i]._id});
}
if (deviceUUID === usn) {
foundUUID = true;
break;
}
}
if (!foundUUID && adapter.config.enableAutoDiscover) {
adapter.log.debug(`Found new device: ${location}`);
addTask({name: 'firstDevLookup', location});
} else {
const pos = discoveredDevices.indexOf(location);
pos !== -1 && discoveredDevices.splice(pos, 1);
}
processTasks();
});
}
}
});
server.on('advertise-bye', headers => {
let usn = JSON.stringify(headers['USN']);
usn = usn.toString();
usn = usn.replace(/uuid:/g, '');
try {
usn.replace(/::.*/ig, '')
} catch (err) {
}
// let nt = JSON.stringify(headers['NT']);
// let location = JSON.stringify(headers['LOCATION']);
if (!usn.match(/.*f40c2981-7329-40b7-8b04-27f187aecfb5.*/)) {
adapter.getDevices((err, devices) => {
let device;
let deviceID;
let deviceUUID;
let deviceUSN;
for (device in devices) {
if (!devices.hasOwnProperty(device)) continue;
deviceUUID = JSON.stringify(devices[device]['native']['uuid']);
deviceUSN = JSON.stringify(devices[device]['native']['deviceType']);
//Set object Alive for the Service false
if (deviceUUID === usn) {
deviceID = JSON.stringify(devices[device]._id);
deviceID = deviceID.replace(/"/ig, '');
addTask({
name: 'setState',
id: `${deviceID}.Alive`,
state: {val: false, ack: true}
});
}
}
processTasks();
}); //END adapter.getDevices()
}
});
setTimeout(() => server.start(), 15000);
}
// Subscribe to every service that is alive. Triggered by change alive from false/null to true.
async function subscribeEvent(id, cb) {
const service = id.replace(/\.Alive/ig, '');
if (adapter.config.enableAutoSubscription === true) {
adapter.getObject(service, (err, obj) => {
let deviceIP = obj.native.ip;
let devicePort = obj.native.port;
const parts = obj._id.split('.');
parts.pop();
const channelID = parts.join('.');
adapter.getChannelsOf(channelID, async (err, channels) => {
for (let x = channels.length - 1; x >= 0; x--) {
const eventUrl = getValueFromArray(channels[x].native.eventSubURL).replace(/"/g, '');
if(channels[x].native.serviceType) {
try {
const infoSub = new Subscription(deviceIP, devicePort, eventUrl, 1000);
listener(eventUrl, channels[x]._id, infoSub);
} catch (err) {
}
}
}
cb();
}); //END adapter.getChannelsOf()
}); //END adapter.getObjects()
} else {
cb();
}
}
// message handler for subscriptions
function listener(eventUrl, channelID, infoSub) {
let variableTimeout;
let resetTimeoutTimer;
infoSub.on('subscribed', data => {
variableTimeout += 5;
setTimeout(() => adapter.setState(channelID + '.sid', {val: ((data && data.sid) || '').toString(), ack: true}), variableTimeout);
resetTimeoutTimer && clearTimeout(resetTimeoutTimer);
resetTimeoutTimer = setTimeout(() => {
variableTimeout = 0;
resetTimeoutTimer = null;
}, 100);
});
infoSub.on('message', data => {
adapter.log.debug('Listener message: ' + JSON.stringify(data));
variableTimeout += 5;
setTimeout(() =>
getIDs()
.then(result => lookupService(data, JSON.parse(JSON.stringify(result.sids))))
,variableTimeout);
resetTimeoutTimer && clearTimeout(resetTimeoutTimer);
resetTimeoutTimer = setTimeout(() => {
variableTimeout = 0;
resetTimeoutTimer = null;
}, 100);
});
infoSub.on('error', err => {
adapter.log.debug(`Subscription error: ` + JSON.stringify(err));
// subscription.unsubscribe();
});
infoSub.on('resubscribed', data => {
// adapter.log.info('SID: ' + JSON.stringify(sid) + ' ' + eventUrl + ' ' + _channel._id);
variableTimeout += 5;
setTimeout(() => adapter.setState(channelID + '.sid', {val: ((data && data.sid) || '').toString(), ack: true}), variableTimeout);
resetTimeoutTimer && clearTimeout(resetTimeoutTimer);
resetTimeoutTimer = setTimeout(() => {
variableTimeout = 0;
resetTimeoutTimer = null;
}, 100);
});
}
function lookupService(data, SIDs, cb) {
if (!SIDs || !SIDs.length || !data || !data.sid) {
cb && cb();
} else {
const id = SIDs.shift();
adapter.getState(id, (err, state) => {
if (err || !state || typeof state !== 'object') {
adapter.log.error(`Error in lookupService: ${err || 'No object ' + id}`);
setImmediate(lookupService, data, cb);
} else {
setNewState(state, id.replace(/\.sid$/, ''), data, () =>
setImmediate(lookupService, data, cb));
}
});
}
}
function setNewState(state, serviceID, data, cb) {
adapter.log.debug('setNewState: ' + state + ' ' + JSON.stringify(data));
// Extract the value of the state
let valueSID = state.val;
if (valueSID !== null && valueSID !== undefined) {
valueSID = valueSID.toString().toLowerCase();
if (valueSID.indexOf(data.sid.toString().toLowerCase()) !== -1) {
serviceID = serviceID.replace(/\.sid$/, '');
// Select sub element with States
let newStates = data.body['e:propertyset']['e:property'];
if (newStates && newStates.LastChange && newStates.LastChange._) {
newStates = newStates.LastChange._;
adapter.log.info('Number 1: ' + newStates);
} else if (newStates) {
newStates = newStates.LastChange;
adapter.log.info('Number 2: ' + newStates);
} else {
adapter.log.info('Number 3: ' + newStates);
}
let newStates2 = JSON.stringify(newStates) || '';
// TODO: Must be refactored
if (newStates2 === undefined){
adapter.log.info('State: ' + state + ' Service ID: ' + serviceID + ' Data: ' + JSON.stringify(data));
}else if (newStates2.match(/<Event.*/ig)) {
parseString(newStates, (err, result) => {
let states = convertEventObject(result['Event']);
// split every array member into state name and value, then push it to ioBroker state
let stateName;
let val;
if (states) {
for (let x = states.length - 1; x >= 0; x--) {
let strState = states[x].toString();
stateName = strState.match(/"\w*/i);
stateName = stateName ? stateName[0] : strState;
stateName = stateName.replace(/"/i, '');
// looking for the value
val = strState.match(/val":"(\w*(:\w*|,\s\w*)*)/ig);
if (val) {
val = val[0];
val = val.replace(/val":"/ig, '');
}
addTask({name: 'valChannel', strState, serviceID, stateName, val});
}
processTasks();
}
cb();
}); //END parseString()
} else if (newStates2.match(/"\$":/ig)) {
let states = convertWM(newStates);
// split every array member into state name and value, then push it to ioBroker state
if (states) {
let stateName;
for (let z = states.length - 1; z >= 0; z--) {
let strState = states[z].toString();
stateName = strState.match(/"\w*/i);
stateName = stateName ? stateName[0] : strState;
stateName = stateName.replace(/^"|"$/g, '');
addTask({name: 'valChannel', strState, serviceID, stateName, val: valLookup(strState)});
}
processTasks();
}
cb();
} else {
// Read all other messages and write the states to the related objects
let states = convertInitialObject(newStates);
if (states) {
// split every array member into state name and value, then push it to ioBroker state
let stateName;
for (let z = states.length - 1; z >= 0; z--) {
let strState = states[z].toString();
stateName = strState.match(/"\w*/i);
stateName = stateName ? stateName[0] : strState;
stateName = stateName.replace(/^"|"$/g, '');
addTask({name: 'valChannel', strState, serviceID, stateName, val: valLookup(strState)});
}
processTasks();
}
cb();
}
} else {
cb();
}
} else {
cb();
}
}
// write state
function writeState(sID, sname, val, cb) {
adapter.getObject(`${sID}.A_ARG_TYPE_${sname}`, (err, obj) => {
if (obj) {
if(obj.common.type === 'number'){
val = parseInt(val);
}
adapter.setState(`${sID}.A_ARG_TYPE_${sname}`, {val: val, ack: true}, err => {
adapter.getObject(`${sID}.${sname}`, (err, obj) => {
if (obj) {
adapter.setState(`${sID}.${sname}`, {val: val, ack: true}, cb);
} else {
cb();
}
});
});
} else {
adapter.getObject(`${sID}.${sname}`, (err, obj) => {
if (obj) {
if(obj.common.type === 'number'){
val = parseInt(val);
}
adapter.setState(`${sID}.${sname}`, {val: val, ack: true}, cb);
} else {
cb();
}
});
}
});
}
// looking for the value of channel
function valChannel(strState, serviceID, cb) {
//looking for the value of channel
let channel = strState.match(/channel":"(\w*(:\w*|,\s\w*)*)/ig);
if (channel) {
channel = channel.toString();
channel = channel.replace(/channel":"/ig, '');
adapter.setState(`${serviceID}.A_ARG_TYPE_Channel`, {val: channel, ack: true}, cb);
} else {
cb()
}
}
// looking for the value
function valLookup(strState) {
let val = strState.match(/\w*":"(\w*\D\w|\w*|,\s\w*|(\w*:)*(\*)*(\/)*(,)*(-)*(\.)*)*/ig);
if (val) {
val = val.toString();
val = val.replace(/"\w*":"/i, '');
val = val.replace(/"/ig, '');
val = val.replace(/\w*:/, '')
}
return val;
}
// Not used now
// function convertEvent(data){
// let change = data.replace(/<\\.*>/ig, '{"');
// change = data.replace(/</ig, '{"');
// change = change.replace(/\s/ig, '""');
// change = change.replace(/=/ig, ':');
// change = change.replace(/\\/ig, '');
// change = change.replace(/>/ig, '}');
// }
//convert the event JSON into an array
function convertEventObject(result) {
const regex = new RegExp(/"\w*":\[{"\$":{("\w*":"(\w*:\w*:\w*|(\w*,\s\w*)*|\w*)"(,"\w*":"\w*")*)}/ig);
return (JSON.stringify(result) || '').match(regex);
}
//convert the initial message JSON into an array
function convertInitialObject(result) {
const regex = new RegExp(/"\w*":"(\w*|\w*\D\w*|(\w*-)*\w*:\w*|(\w*,\w*)*|\w*:\S*\*)"/g);
return (JSON.stringify(result) || '').match(regex);
}
//convert the initial message JSON into an array for windows media player/server
function convertWM(result) {
const regex = new RegExp(/"\w*":{".":"(\w*"|((http-get:\*:\w*\/((\w*\.)*|(\w*-)*|(\w*\.)*(\w*-)*)\w*:\w*\.\w*=\w*(,)*)*((http-get|rtsp-rtp-udp):\*:\w*\/(\w*(\.|-))*\w*:\*(,)*)*))/g);
return (JSON.stringify(result) || '').match(regex);
}
//END Event listener
// clear Alive and sid's states when Adapter stops
function clearAliveAndSIDStates(cb) {
// Clear sid
getIDs()
.then(result => {
result.sids.forEach(id => {
addTask({name: 'setState', id, state: {val: '', ack: true}});
});
result.alives.forEach(id => {
addTask({name: 'setState', id, state: {val: false, ack: true}});
});
processTasks(cb);
});
}
function getIDs() {
if (sidPromise) {
return sidPromise;
} else {
// Fill array arrSID if it is empty
sidPromise = new Promise(resolve => {
adapter.getStatesOf(`upnp.${adapter.instance}`, (err, _states) => {
const sids = [];
const alives = [];
err && adapter.log.error('Cannot get SIDs: ' + err);
if (_states) {
_states.forEach(obj => {
if (obj._id.match(/\.sid$/)) {
// if the match deliver an id of an object add them to the array
sids.push(obj._id);
} else
if (obj._id.match(/\.Alive/g)) {
alives.push(obj._id);
}
});
}
// adapter.log.debug('Array arrSID is now filled');
// When the array is filled start the search
resolve({sids, alives});
});
});
return sidPromise;
}
}
// control the devices
function sendCommand(id, cb) {
adapter.log.debug('Send Command for ' + id);
let parts = id.split('.');
parts.pop();
let actionName = parts.pop();
let service = parts.join('.');
id = id.replace('.request', '');
adapter.getObject(service, (err, obj) => {
let vServiceType = obj.native.serviceType;
let serviceName = obj.native.name;
let device = service.replace(`.${serviceName}`, '');
let vControlURL = obj.native.controlURL;
adapter.getObject(device, (err, obj) => {
let ip = obj.native.ip;
let port = obj.native.port;
let cName = JSON.stringify(obj._id);
cName = cName.replace(/\.\w*"$/g, '');
cName = cName.replace(/^"/g, '');
adapter.getStatesOf(cName, (err, _states) => {
let args = [];
for (let x = _states.length - 1; x >= 0; x--) {
let argumentsOfAction = _states[x]._id;
let obj = _states[x];
let test2 = id + '\\.';
try {
test2 = test2.replace(/\(/gi, '.');
} catch (err) {
adapter.log.debug(err)
}
try {
test2 = test2.replace(/\)/gi, '.');
} catch (err) {
adapter.log.debug(err)
}
try {
test2 = test2.replace(/\[/gi, '.');
} catch (err) {
adapter.log.debug(err)
}
try {
test2 = test2.replace(/ ]/gi, '.');
} catch (err) {
adapter.log.debug(err)
}
let re = new RegExp(test2, 'g');
let testResult = re.test(argumentsOfAction);
if (testResult && argumentsOfAction !== id) {
args.push(obj);
}
}
let body = '';
// get all states of the arguments as string
adapter.getStates(`${id}.*`, (err, idStates) => {
adapter.log.debug('get all states of the arguments as string ');
let helperBody = [];
let states = JSON.stringify(idStates);
states = states.replace(/,"ack":\w*,"ts":\d*,"q":\d*,"from":"(\w*\.)*(\d*)","lc":\d*/g, '');
for (let z = args.length - 1; z >= 0; z--) {
// check if the argument has to be send with the action
if (args[z].native.direction === 'in') {
let argNo = args[z].native.argumentNumber;
// check if the argument is already written to the helperBody array, if not found value and add to array
if (helperBody[argNo] == null) {
let test2 = getValueFromArray(args[z]._id);
// replace signs that could cause problems with regex
test2 = test2
.replace(/\(/gi, '.')
.replace(/\)/gi, '.')
.replace(/\[/gi, '.')
.replace(/]/gi, '.');
let test3 = test2 + '":{"val":("[^"]*|\\d*)}?';
let patt = new RegExp(test3, 'g');
let testResult2;
let testResult = states.match(patt);
testResult2 = JSON.stringify(testResult);
testResult2 = testResult2.match(/val\\":(\\"[^"]*|\d*)}?/g);
testResult2 = JSON.stringify(testResult2);
testResult2 = testResult2.replace(/\["val(\\)*":(\\)*/, '');
testResult2 = testResult2.replace(/]/, '');
testResult2 = testResult2.replace(/}"/, '');
testResult2 = testResult2.replace(/"/g, '');
//extract argument name from id string
let test1 = args[z]._id;
let argName = test1.replace(`${id}\.`, '');
helperBody[argNo] = '<' + argName + '>' + testResult2 + '</' + argName + '>';
}
}
}
//convert helperBody array to string and add it to main body string
helperBody = helperBody.toString().replace(/,/g, '');
body += helperBody;
body = `<u:${actionName} xmlns:u="${vServiceType}">${body}</u:${actionName}>`;
createMessage(vServiceType, actionName, ip, port, vControlURL, body, id, cb);
});
})
});
});
}
function readSchedules() {
return new Promise(resolve => {
adapter.getObjectView('system', 'custom', {startkey: adapter.namespace + '.', endkey: adapter.namespace + '.\uFFFF'}, (err, doc) => {
if (doc && doc.rows) {
for (let i = 0, l = doc.rows.length; i < l; i++) {
if (doc.rows[i].value) {
let id = doc.rows[i].id;
let obj = doc.rows[i].value;
if (id.startsWith(adapter.namespace) && obj[adapter.namespace] && obj[adapter.namespace].enabled && id.match(/\.request$/)) {
actions[id] = {cron: obj[adapter.namespace].schedule};
}
}
}
}
resolve();
});
});
}
// create Action message
function createMessage(sType, aName, _ip, _port, cURL, body, actionID, cb) {
const UA = 'UPnP/1.0, ioBroker.upnp';
let url = `http://${_ip}:${_port}${cURL}`;
const contentType = 'text/xml; charset="utf-8"';
let soapAction = `${sType}#${aName}`;
let postData = `
<s:Envelope s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">
<s:Body>${body}</s:Body>
</s:Envelope>`;
//Options for the SOAP message
let options = {
uri: url,
headers: {
'Content-Type': contentType,
'SOAPAction': `"${soapAction}"`,
'USER-AGENT': UA
},
method: 'POST',
body: postData
};
// Send Action message to Device/Service
request(options, (err, res, body) => {
adapter.log.debug('Options for request: ' + JSON.stringify(options));
if (err) {
adapter.log.warn(`Error sending SOAP request: ${err}`);
} else {
if (res.statusCode !== 200) {
adapter.log.warn(`Unexpected answer from upnp service: ` + JSON.stringify(res) + `\n Sent message: ` + JSON.stringify(options));
} else {
//look for data in the response
// die Zusätlichen infos beim Argument namen müssen entfernt werden damit er genutzt werden kann
let foundData = body.match(/<[^\/]\w*\s*[^<]*/g);
if (foundData) {
actionID = actionID.replace(/\.request$/, '');
for (let i = foundData.length - 1; i >= 0; i--) {
let foundArgName = foundData[i].match(/<\w*>/);
let strFoundArgName;
let argValue;
if (foundArgName) {
strFoundArgName = foundArgName[0];
// TODO: must be rewritten
strFoundArgName = strFoundArgName.replace(/["\][]}/g, '');
argValue = foundData[i].replace(strFoundArgName, '');
strFoundArgName = strFoundArgName.replace(/[<>]/g, '');
} else {
foundArgName = foundData[i].match(/<\w*\s/);
if (foundArgName) {
// TODO: must be rewritten
strFoundArgName = foundArgName[0];
strFoundArgName = strFoundArgName.replace(/["[\]<]/g, '').replace(/\s+$/, '');
argValue = foundData[i].replace(/<.*>/, '');
}
}
if (strFoundArgName !== null && strFoundArgName !== undefined) {
let argID = actionID + '.' + strFoundArgName;
addTask({
name: 'setState',
id: argID,
state: {val: argValue, ack: true},
cb: cb =>
//look for relatedStateVariable and setState
syncArgument(actionID, argID, argValue, cb)
});
}
}
processTasks();
} else {
adapter.log.debug('Nothing found: ' + JSON.stringify(body));
}
}
}
cb && cb();
});
}
// Sync Argument with relatedStateVariable
function syncArgument(actionID, argID, argValue, cb) {
adapter.getObject(argID, (err, obj) => {
if (obj) {
let relatedStateVariable = obj.native.relatedStateVariable;
let serviceID = actionID.replace(/\.\w*$/, '');
let relStateVarID = serviceID + '.' + relatedStateVariable;
let val = argValue;
if(obj.common.type === 'number'){
val = parseInt(argValue);
}
adapter.setState(relStateVarID, {val: argValue, ack: true}, cb);
} else {
cb && cb();
}
});
}
function nameFilter(name) {
if (typeof name === 'object' && name[0]) {
name = name[0];
}
let signs = [
String.fromCharCode(46),
String.fromCharCode(44),
String.fromCharCode(92),
String.fromCharCode(47),
String.fromCharCode(91),
String.fromCharCode(93),
String.fromCharCode(123),
String.fromCharCode(125),
String.fromCharCode(32),
String.fromCharCode(129),
String.fromCharCode(154),
String.fromCharCode(132),
String.fromCharCode(142),
String.fromCharCode(148),
String.fromCharCode(153),
String.fromCharCode(42),
String.fromCharCode(63),
String.fromCharCode(34),
String.fromCharCode(39),
String.fromCharCode(96)
];
//46=. 44=, 92=\ 47=/ 91=[ 93=] 123={ 125=} 32=Space 129=ü 154=Ü 132=ä 142=Ä 148=ö 153=Ö 42=* 63=? 34=" 39=' 96=`
signs.forEach((item, index) => {
let count = name.split(item).length - 1;
for (let i = 0; i < count; i++) {
name = name.replace(item, '_');
}
let result = name.search(/_$/);
if (result !== -1) {
name = name.replace(/_$/, '');
}
});
name = name.replace(/[*\[\]+?]+/g, '_');
return name;
}
function main() {
adapter.subscribeStates('*');
adapter.subscribeObjects('*');
adapter.log.info('Auto discover: ' + adapter.config.enableAutoDiscover);
readSchedules()
.then(() => {
if (adapter.config.enableAutoDiscover === true) {
sendBroadcast();
}
// read SIDs and Alive IDs
getIDs()
.then(result => {
adapter.log.debug(`Read ${result.sids.length} SIDs and ${result.alives.length} alives`);
// Filtering the Device description file addresses, timeout is necessary to wait for all answers
setTimeout(() => {
adapter.log.debug(`Found ${foundIPs.length} devices`);
if (adapter.config.rootXMLurl) {
firstDevLookup(adapter.config.rootXMLurl);
}
reschedule();
}, 5000);
//start the server
startServer();
});
});
}
// If started as allInOne mode => return function to create instance
if (module.parent) {
module.exports = startAdapter;
} else {
// or start the instance directly
startAdapter();
}
|
if(Bar.app("Início")) throw "Barra já existe!";
/*/LOADING BAR
$.get("http://hosts.medorc.org/xn--stio-vpa/json/bar.Home.json"),
function(data){
//if(Bar.app(data.name)) throw "Barra já existe!";
$('#header').bar({
toolbox: data,
callback: function(bar){
//(auto) load requested addon
(function(startHash){
if(startHash && startHash != '#!Home' && startHash != '#!Início'){
// gets bar addon (or loads addon script) before callback
Bar.getBar(Bar.urls(startHash), function(error, addon){
// error getting addon
if(error) throw error + " error getting addon " + startHash + " @bar.Home";
// route to addon (select addon tab)
Frontgate.router.route(addon.href);
//console.log('Bar.route', bar, route);
});
}
})(Remote.attr("requestHash"));
// mostrar item IE apenas se o utilizador for "daniel"
if(Situs.attr().user == "daniel") $("#isec-ei").show();
Situs.subscribeEvent('userChange', function(attr){
if(attr.user == "daniel") $("#isec-ei").show();
else $("#isec-ei").hide();
});
}
});
});
/*/
//AUTO LOADING BAR
Bar.load('#header', function(bar, data){
Frontgate.router.on("#Home", function(hash){
location.hash = "Início";
});
// mostrar item IE apenas se o utilizador for "daniel"
if(Frontgate.attr().user == "daniel") $("#isec-ei").show();
Frontgate.subscribeEvent('userChange', function(attr){
if(attr.user == "daniel") $("#isec-ei").show();
else $("#isec-ei").hide();
});
}, FILE);//*/
//------------------------------------------------------------------
// BUG:
// when addon items are not hash banged (#!ToolboxItem)
// the tab is added to the navigator but the toolbox is not selected
//------------------------------------------------------------------
|
System.config({
baseURL: "/",
defaultJSExtensions: true,
transpiler: "babel",
babelOptions: {
"optional": [
"runtime"
],
"stage": 1
},
paths: {
"github:*": "jspm_packages/github/*",
"npm:*": "jspm_packages/npm/*"
},
map: {
"angular2": "npm:[email protected]",
"babel": "npm:[email protected]",
"babel-runtime": "npm:[email protected]",
"clean-css": "npm:[email protected]",
"core-js": "npm:[email protected]",
"css": "github:systemjs/[email protected]",
"reflect-metadata": "npm:[email protected]",
"rxjs": "npm:[email protected]",
"zone.js": "npm:[email protected]",
"github:jspm/[email protected]": {
"assert": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"buffer": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"constants-browserify": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"crypto-browserify": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"events": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"Base64": "npm:[email protected]",
"events": "github:jspm/[email protected]",
"inherits": "npm:[email protected]",
"stream": "github:jspm/[email protected]",
"url": "github:jspm/[email protected]",
"util": "github:jspm/[email protected]"
},
"github:jspm/[email protected]": {
"https-browserify": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"os-browserify": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"path-browserify": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"process": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"stream-browserify": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"string_decoder": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"url": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"util": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"vm-browserify": "npm:[email protected]"
},
"npm:[email protected]": {
"fs": "github:jspm/[email protected]",
"module": "github:jspm/[email protected]",
"path": "github:jspm/[email protected]",
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"crypto": "github:jspm/[email protected]",
"es6-promise": "npm:[email protected]",
"es6-shim": "npm:[email protected]",
"process": "github:jspm/[email protected]",
"reflect-metadata": "npm:[email protected]",
"rxjs": "npm:[email protected]",
"zone.js": "npm:[email protected]"
},
"npm:[email protected]": {
"assert": "github:jspm/[email protected]",
"bn.js": "npm:[email protected]",
"buffer": "github:jspm/[email protected]",
"inherits": "npm:[email protected]",
"minimalistic-assert": "npm:[email protected]",
"vm": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"util": "npm:[email protected]"
},
"npm:[email protected]": {
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"buffer-xor": "npm:[email protected]",
"cipher-base": "npm:[email protected]",
"create-hash": "npm:[email protected]",
"crypto": "github:jspm/[email protected]",
"evp_bytestokey": "npm:[email protected]",
"fs": "github:jspm/[email protected]",
"inherits": "npm:[email protected]",
"systemjs-json": "github:systemjs/[email protected]"
},
"npm:[email protected]": {
"browserify-aes": "npm:[email protected]",
"browserify-des": "npm:[email protected]",
"buffer": "github:jspm/[email protected]",
"crypto": "github:jspm/[email protected]",
"evp_bytestokey": "npm:[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"cipher-base": "npm:[email protected]",
"crypto": "github:jspm/[email protected]",
"des.js": "npm:[email protected]",
"inherits": "npm:[email protected]"
},
"npm:[email protected]": {
"bn.js": "npm:[email protected]",
"buffer": "github:jspm/[email protected]",
"constants": "github:jspm/[email protected]",
"crypto": "github:jspm/[email protected]",
"randombytes": "npm:[email protected]"
},
"npm:[email protected]": {
"bn.js": "npm:[email protected]",
"browserify-rsa": "npm:[email protected]",
"buffer": "github:jspm/[email protected]",
"create-hash": "npm:[email protected]",
"create-hmac": "npm:[email protected]",
"crypto": "github:jspm/[email protected]",
"elliptic": "npm:[email protected]",
"inherits": "npm:[email protected]",
"parse-asn1": "npm:[email protected]",
"stream": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"systemjs-json": "github:systemjs/[email protected]"
},
"npm:[email protected]": {
"base64-js": "npm:[email protected]",
"child_process": "github:jspm/[email protected]",
"fs": "github:jspm/[email protected]",
"ieee754": "npm:[email protected]",
"isarray": "npm:[email protected]",
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"inherits": "npm:[email protected]",
"stream": "github:jspm/[email protected]",
"string_decoder": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"commander": "npm:[email protected]",
"fs": "github:jspm/[email protected]",
"http": "github:jspm/[email protected]",
"https": "github:jspm/[email protected]",
"os": "github:jspm/[email protected]",
"path": "github:jspm/[email protected]",
"process": "github:jspm/[email protected]",
"source-map": "npm:[email protected]",
"url": "github:jspm/[email protected]",
"util": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"child_process": "github:jspm/[email protected]",
"events": "github:jspm/[email protected]",
"fs": "github:jspm/[email protected]",
"graceful-readlink": "npm:[email protected]",
"path": "github:jspm/[email protected]",
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"systemjs-json": "github:systemjs/[email protected]"
},
"npm:[email protected]": {
"fs": "github:jspm/[email protected]",
"path": "github:jspm/[email protected]",
"process": "github:jspm/[email protected]",
"systemjs-json": "github:systemjs/[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"bn.js": "npm:[email protected]",
"buffer": "github:jspm/[email protected]",
"crypto": "github:jspm/[email protected]",
"elliptic": "npm:[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"cipher-base": "npm:[email protected]",
"crypto": "github:jspm/[email protected]",
"fs": "github:jspm/[email protected]",
"inherits": "npm:[email protected]",
"ripemd160": "npm:[email protected]",
"sha.js": "npm:[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"create-hash": "npm:[email protected]",
"crypto": "github:jspm/[email protected]",
"inherits": "npm:[email protected]",
"stream": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"browserify-cipher": "npm:[email protected]",
"browserify-sign": "npm:[email protected]",
"create-ecdh": "npm:[email protected]",
"create-hash": "npm:[email protected]",
"create-hmac": "npm:[email protected]",
"diffie-hellman": "npm:[email protected]",
"inherits": "npm:[email protected]",
"pbkdf2": "npm:[email protected]",
"public-encrypt": "npm:[email protected]",
"randombytes": "npm:[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"inherits": "npm:[email protected]",
"minimalistic-assert": "npm:[email protected]"
},
"npm:[email protected]": {
"bn.js": "npm:[email protected]",
"buffer": "github:jspm/[email protected]",
"crypto": "github:jspm/[email protected]",
"miller-rabin": "npm:[email protected]",
"randombytes": "npm:[email protected]",
"systemjs-json": "github:systemjs/[email protected]"
},
"npm:[email protected]": {
"bn.js": "npm:[email protected]",
"brorand": "npm:[email protected]",
"hash.js": "npm:[email protected]",
"inherits": "npm:[email protected]",
"systemjs-json": "github:systemjs/[email protected]"
},
"npm:[email protected]": {
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"create-hash": "npm:[email protected]",
"crypto": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"fs": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"inherits": "npm:[email protected]"
},
"npm:[email protected]": {
"http": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"util": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"bn.js": "npm:[email protected]",
"brorand": "npm:[email protected]"
},
"npm:[email protected]": {
"os": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"asn1.js": "npm:[email protected]",
"browserify-aes": "npm:[email protected]",
"buffer": "github:jspm/[email protected]",
"create-hash": "npm:[email protected]",
"evp_bytestokey": "npm:[email protected]",
"pbkdf2": "npm:[email protected]",
"systemjs-json": "github:systemjs/[email protected]"
},
"npm:[email protected]": {
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"child_process": "github:jspm/[email protected]",
"create-hmac": "npm:[email protected]",
"crypto": "github:jspm/[email protected]",
"path": "github:jspm/[email protected]",
"process": "github:jspm/[email protected]",
"systemjs-json": "github:systemjs/[email protected]"
},
"npm:[email protected]": {
"assert": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"bn.js": "npm:[email protected]",
"browserify-rsa": "npm:[email protected]",
"buffer": "github:jspm/[email protected]",
"create-hash": "npm:[email protected]",
"crypto": "github:jspm/[email protected]",
"parse-asn1": "npm:[email protected]",
"randombytes": "npm:[email protected]"
},
"npm:[email protected]": {
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"crypto": "github:jspm/[email protected]",
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"core-util-is": "npm:[email protected]",
"events": "github:jspm/[email protected]",
"inherits": "npm:[email protected]",
"isarray": "npm:[email protected]",
"process": "github:jspm/[email protected]",
"stream-browserify": "npm:[email protected]",
"string_decoder": "npm:[email protected]"
},
"npm:[email protected]": {
"assert": "github:jspm/[email protected]",
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"fs": "github:jspm/[email protected]",
"inherits": "npm:[email protected]",
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"amdefine": "npm:[email protected]",
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"events": "github:jspm/[email protected]",
"inherits": "npm:[email protected]",
"readable-stream": "npm:[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"assert": "github:jspm/[email protected]",
"punycode": "npm:[email protected]",
"querystring": "npm:[email protected]",
"util": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"inherits": "npm:[email protected]",
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"indexof": "npm:[email protected]"
},
"npm:[email protected]": {
"process": "github:jspm/[email protected]"
}
}
});
|
$(document).ready(function() {
$.getJSON('/backend/go/' + go_term['id'] + '/locus_details', function(data) {
create_go_table(data);
});
$.getJSON('/backend/go/' + go_term['id'] + '/ontology_graph', function(data) {
var cy = create_cytoscape_vis("cy", layout, graph_style, data, null, false, "goOntology");
create_cy_download_button(cy, "cy_download", go_term['display_name'] + '_ontology')
if(data['all_children'] != null && data['all_children'].length > 0) {
var children_div = document.getElementById("children");
var more_children_div = document.getElementById("children_see_more");
for(var i=0; i < data['all_children'].length; i++) {
var a = document.createElement('a');
a.innerHTML = data['all_children'][i]['display_name'];
a.href = data['all_children'][i]['link']
if(i < 20) {
children_div.appendChild(a);
}
else {
more_children_div.appendChild(a);
}
if(i != data['all_children'].length-1) {
var comma = document.createElement('span');
comma.innerHTML = ' • ';
if(i < 20) {
children_div.appendChild(comma);
}
else {
more_children_div.appendChild(comma);
}
}
}
if(data['all_children'].length <= 20) {
$("#children_see_more_button").hide();
}
}
else {
$("#children_wrapper").hide()
}
});
});
function create_go_table(data) {
var manualDatatable = [];
var manualGenes = {};
var htpDatatable = [];
var htpGenes = {};
var computationalDatatable = [];
var computationalGenes = {};
for (var i=0; i < data.length; i++) {
var type = data[i].annotation_type;
if (type === 'manually curated') {
manualDatatable.push(go_data_to_table(data[i], i));
manualGenes[data[i]["locus"]["id"]] = true;
} else if (type === 'high-throughput') {
htpDatatable.push(go_data_to_table(data[i], i));
htpGenes[data[i]["locus"]["id"]] = true;
} else if (type === 'computational') {
computationalDatatable.push(go_data_to_table(data[i], i));
computationalGenes[data[i]["locus"]["id"]] = true;
}
}
set_up_header('manual_go_table', manualDatatable.length, 'entry', 'entries', Object.keys(manualGenes).length, 'gene', 'genes');
set_up_header('htp_go_table', htpDatatable.length, 'entry', 'entries', Object.keys(htpGenes).length, 'gene', 'genes');
set_up_header('computational_go_table', computationalDatatable.length, 'entry', 'entries', Object.keys(computationalGenes).length, 'gene', 'genes');
var options = {};
options["bPaginate"] = true;
options["aaSorting"] = [[3, "asc"]];
options["bDestroy"] = true;
// options["oLanguage"] = {"sEmptyTable": "No genes annotated directly to " + go_term['display_name']};
options["aoColumns"] = [
//Use of mData
{"bSearchable":false, "bVisible":false,"aTargets":[0],"mData":0}, //evidence_id
{"bSearchable":false, "bVisible":false,"aTargets":[1],"mData":1}, //analyze_id
{"aTargets":[2],"mData":2}, //gene
{"bSearchable":false, "bVisible":false,"aTargets":[3],"mData":3}, //gene systematic name
{"aTargets":[4],"mData":4}, //gene ontology term -----> qualifier
{"bSearchable":false, "bVisible":false,"aTargets":[5],"mData":5}, //gene ontology term id
{"aTargets":[6],"mData":6}, //qualifier -----> gene ontology term
{"bSearchable":false, "bVisible":false,"aTargets":[7],"mData":7}, //aspect
{"aTargets":[8],"mData":8}, //evidence -----> annotation_extension
{"aTargets":[9],"mData":9}, //method -----> evidence
{"bSearchable":false,"bVisible":false,"aTargets":[10],"mData":10}, //source -----> method
{"aTargets":[11],"mData":11}, //assigned on -----> source
{"aTargets":[12],"mData":12}, //annotation_extension -----> assigned on
{"aTargets":[13],"mData":13} // reference
];
create_or_hide_table(manualDatatable, options, "manual_go_table", go_term["display_name"], go_term["link"], go_term["id"], "manually curated", data);
create_or_hide_table(htpDatatable, options, "htp_go_table", go_term["display_name"], go_term["link"], go_term["id"], "high-throughput", data);
create_or_hide_table(computationalDatatable, options, "computational_go_table", go_term["display_name"], go_term["link"], go_term["id"], "computational", data);
}
function create_or_hide_table(tableData, options, tableIdentifier, goName, goLink, goId, annotationType, originalData) {
if (tableData.length) {
var localOptions = $.extend({ aaData: tableData, oLanguage: { sEmptyTable: 'No genes annotated directly to ' + goName } }, options);
var table = create_table(tableIdentifier, localOptions);
create_analyze_button(tableIdentifier + "_analyze", table, "<a href='" + goLink + "' class='gene_name'>" + goName + "</a> genes", true);
create_download_button(tableIdentifier + "_download", table, goName + "_annotations");
if(go_term['descendant_locus_count'] > go_term['locus_count']) {
create_show_child_button(tableIdentifier + "_show_children", table, originalData, "/backend/go/" + goId + "/locus_details_all", go_data_to_table, function(table_data) {
var genes = {};
for (var i=0; i < table_data.length; i++) {
genes[table_data[i][1]] = true;
}
set_up_header(tableIdentifier, table_data.length, 'entry', 'entries', Object.keys(genes).length, 'gene', 'genes');
}, annotationType);
}
return table;
} else {
$("#" + tableIdentifier + "_header").remove();
var $parent = $("#" + tableIdentifier).parent();
var emptyMessage = "There are no " + annotationType + " annotations for " + goName + ".";
$parent.html(emptyMessage);
}
};
var graph_style = cytoscape.stylesheet()
.selector('node')
.css({
'content': 'data(name)',
'font-family': 'helvetica',
'font-size': 14,
'text-outline-width': 3,
'text-valign': 'center',
'width': 30,
'height': 30,
'border-color': '#fff',
'background-color': "#43a0df",
'text-outline-color': '#fff',
'color': '#888'
})
.selector('edge')
.css({
'content': 'data(name)',
'font-family': 'helvetica',
'font-size': 12,
'color': 'grey',
'width': 2,
'source-arrow-shape': 'triangle'
})
.selector("node[sub_type='FOCUS']")
.css({
'width': 30,
'height': 30,
'background-color': "#fade71",
'text-outline-color': '#fff',
'color': '#888'
})
.selector("node[id='NodeMoreChildren']")
.css({
'width': 30,
'height': 30,
'shape': 'rectangle'
});
// .selector("node[sub_type='HAS_CHILDREN']")
// .css(
// {'background-color': "#165782"
// })
// .selector("node[sub_type='HAS_DESCENDANTS']")
// .css(
// {'background-color': "#43a0df"
// })
// .selector("node[sub_type='NO_DESCENDANTS']")
// .css(
// {'background-color': "#c9e4f6"
// });
var layout = {
"name": "breadthfirst",
"fit": true,
"directed": true
};
|
// app.js
/*jslint node: true */
'use strict';
var compression = require('compression');
var express = require('express');
var passport = require('passport');
var mongoose = require('mongoose');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var hbs = require('hbs'); // Handlebars templating engine
var configDB = require('./config/database.js'); // Load our db configuration
mongoose.connect(configDB.url); // Connect to our db.
require('./config/passport')(passport); // Configure passport authentication
var app = express();
// Set up express app
app.use(compression({
threshold: 512
}));
app.set('json spaces', 0);
app.set('views', __dirname + '/views');
app.use(express.logger('dev'));
app.use(express.errorHandler());
app.use(express.methodOverride());
app.use(express.cookieParser('flyingfish'));
app.use(express.session());
app.set('view engine', 'html');
app.engine('html', hbs.__express);
app.use(express.static(__dirname + '/public'));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
require('./routes')(app, passport); // Load our routes and pass in our app and passport
app.listen(process.env.PORT || 3000); |
!function($) {
$(document).on("keydown", 'input[data-type="numeric"]', function (e)
{
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
return (
key == 8 ||
key == 9 ||
key == 46 ||
(key >= 37 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
});
}(window.jQuery || window.ender); |
import Chip from '../../components/Chip'
import { vueTest } from '../utils'
describe('Chip', () => {
let vm
before((done) => {
vm = vueTest(Chip)
vm.$nextTick(done)
})
it('renders with text', () => {
const el = vm.$('#chip')
el.should.contain.text('Basic chip')
el.should.not.have.class('mdl-chip--contact')
el.should.not.have.class('mdl-chip--deletable')
})
it('renders with close button', () => {
const el = vm.$('#delete')
el.should.contain.text('Deletable chip')
el.should.not.have.class('mdl-chip--contact')
el.should.have.class('mdl-chip--deletable')
const action = vm.$('#delete .mdl-chip__action')
action.should.exist
action.should.have.text('cancel')
})
it('has custom icon', (done) => {
const action = vm.$('#delete .mdl-chip__action')
action.should.have.text('cancel')
vm.deleteIcon = 'star'
vm.nextTick()
.then(() => {
action.should.have.text('star')
})
.then(done, done)
})
it('emits close event', (done) => {
vm.deleted.should.be.false
const action = vm.$('#delete .mdl-chip__action')
action.click()
vm.nextTick()
.then(() => {
vm.deleted.should.be.true
vm.deleted = false
return vm.nextTick()
})
.then(done, done)
})
it('renders text inside circle', (done) => {
vm.$('#contact').should.have.class('mdl-chip--contact')
const el = vm.$('#contact .mdl-chip__contact')
el.should.contain.text(vm.contact)
el.should.not.have.class('mdl-chip--deletable')
vm.contact = 'A'
vm.nextTick()
.then(() => {
el.should.have.text('A')
})
.then(done, done)
})
it('renders image inside circle', () => {
vm.$('#image').should.have.class('mdl-chip--contact')
const el = vm.$('#image .mdl-chip__contact')
el.should.have.attr('src', 'https://getmdl.io/templates/dashboard/images/user.jpg')
el.should.not.have.class('mdl-chip--deletable')
})
})
|
import { hashHistory } from 'react-router'
import { auth } from 'lib/firebase'
export const redirect = path => hashHistory.push(path)
export const signInWithGoogle = () => {
const provider = new auth.GoogleAuthProvider()
provider.addScope('https://www.googleapis.com/auth/userinfo.profile')
return auth().signInWithPopup(provider)
}
export const signInWithFacebook = () => {
const provider = new auth.FacebookAuthProvider()
return auth().signInWithPopup(provider)
}
export const signOut = () => {
return auth().signOut()
}
export const getCurrentUser = () => {
return Promise.resolve(auth().currentUser)
}
|
var request = require('supertest');
var should = require('should');
var express = require('express');
var expressRouter = require('../index.js');
var mockPath = 'mock.js';
describe('register routes', function(){
var app;
before(function(){
app = express();
expressRouter.sync(app, mockPath);
});
it('should have register: GET /api/collection', function(done){
request(app)
.get('/api/collection')
.expect(200)
.expect('OK', done);
});
it('should have register: GET /api/entity/:id', function(done){
request(app)
.get('/api/entity/1')
.expect(200)
.expect('OK', done);
});
it('should have register: POST /api/test', function(done){
request(app)
.post('/api/test')
.expect(201)
.expect('Created', done);
});
});
|
/**
* @author: @AngularClass
*/
const helpers = require('./helpers');
const webpackMerge = require('webpack-merge'); // used to merge webpack configs
const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev
/**
* Webpack Plugins
*/
const DefinePlugin = require('webpack/lib/DefinePlugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const IgnorePlugin = require('webpack/lib/IgnorePlugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const ProvidePlugin = require('webpack/lib/ProvidePlugin');
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');
const OptimizeJsPlugin = require('optimize-js-plugin');
/**
* Webpack Constants
*/
const ENV = process.env.NODE_ENV = process.env.ENV = 'production';
const HOST = process.env.HOST || 'localhost';
const PORT = process.env.PORT || 8080;
const METADATA = webpackMerge(commonConfig({
env: ENV
}).metadata, {
host: HOST,
port: PORT,
ENV: ENV,
HMR: false
});
module.exports = function (env) {
return webpackMerge(commonConfig({
env: ENV
}), {
/**
* Developer tool to enhance debugging
*
* See: http://webpack.github.io/docs/configuration.html#devtool
* See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps
*/
devtool: 'source-map',
/**
* Options affecting the output of the compilation.
*
* See: http://webpack.github.io/docs/configuration.html#output
*/
output: {
/**
* The output directory as absolute path (required).
*
* See: http://webpack.github.io/docs/configuration.html#output-path
*/
path: helpers.root('dist'),
/**
* Specifies the name of each output file on disk.
* IMPORTANT: You must not specify an absolute path here!
*
* See: http://webpack.github.io/docs/configuration.html#output-filename
*/
filename: '[name].[chunkhash].bundle.js',
/**
* The filename of the SourceMaps for the JavaScript files.
* They are inside the output.path directory.
*
* See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
*/
sourceMapFilename: '[name].[chunkhash].bundle.map',
/**
* The filename of non-entry chunks as relative path
* inside the output.path directory.
*
* See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
*/
chunkFilename: '[id].[chunkhash].chunk.js'
},
module: {
rules: [
/*
* Extract CSS files from .src/styles directory to external CSS file
*/
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader'
}),
include: [helpers.root('src', 'styles')]
},
/*
* Extract and compile SCSS files from .src/styles directory to external CSS file
*/
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader!sass-loader'
}),
include: [helpers.root('src', 'styles')]
},
]
},
/**
* Add additional plugins to the compiler.
*
* See: http://webpack.github.io/docs/configuration.html#plugins
*/
plugins: [
/**
* Webpack plugin to optimize a JavaScript file for faster initial load
* by wrapping eagerly-invoked functions.
*
* See: https://github.com/vigneshshanmugam/optimize-js-plugin
*/
new OptimizeJsPlugin({
sourceMap: false
}),
/**
* Plugin: ExtractTextPlugin
* Description: Extracts imported CSS files into external stylesheet
*
* See: https://github.com/webpack/extract-text-webpack-plugin
*/
new ExtractTextPlugin('[name].[contenthash].css'),
/**
* Plugin: DefinePlugin
* Description: Define free variables.
* Useful for having development builds with debug logging or adding global constants.
*
* Environment helpers
*
* See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
*/
// NOTE: when adding more properties make sure you include them in custom-typings.d.ts
new DefinePlugin({
'ENV': JSON.stringify(METADATA.ENV),
'HMR': METADATA.HMR,
'process.env': {
'ENV': JSON.stringify(METADATA.ENV),
'NODE_ENV': JSON.stringify(METADATA.ENV),
'HMR': METADATA.HMR,
}
}),
/**
* Plugin: UglifyJsPlugin
* Description: Minimize all JavaScript output of chunks.
* Loaders are switched into minimizing mode.
*
* See: https://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
*/
// NOTE: To debug prod builds uncomment //debug lines and comment //prod lines
new UglifyJsPlugin({
// beautify: true, //debug
// mangle: false, //debug
// dead_code: false, //debug
// unused: false, //debug
// deadCode: false, //debug
// compress: {
// screw_ie8: true,
// keep_fnames: true,
// drop_debugger: false,
// dead_code: false,
// unused: false
// }, // debug
// comments: true, //debug
beautify: false, //prod
output: {
comments: false
}, //prod
mangle: {
screw_ie8: true
}, //prod
compress: {
screw_ie8: true,
warnings: false,
conditionals: true,
unused: true,
comparisons: true,
sequences: true,
dead_code: true,
evaluate: true,
if_return: true,
join_vars: true,
negate_iife: false // we need this for lazy v8
},
}),
/**
* Plugin: NormalModuleReplacementPlugin
* Description: Replace resources that matches resourceRegExp with newResource
*
* See: http://webpack.github.io/docs/list-of-plugins.html#normalmodulereplacementplugin
*/
new NormalModuleReplacementPlugin(
/angular2-hmr/,
helpers.root('config/empty.js')
),
new NormalModuleReplacementPlugin(
/zone\.js(\\|\/)dist(\\|\/)long-stack-trace-zone/,
helpers.root('config/empty.js')
),
// AoT
// new NormalModuleReplacementPlugin(
// /@angular(\\|\/)upgrade/,
// helpers.root('config/empty.js')
// ),
// new NormalModuleReplacementPlugin(
// /@angular(\\|\/)compiler/,
// helpers.root('config/empty.js')
// ),
// new NormalModuleReplacementPlugin(
// /@angular(\\|\/)platform-browser-dynamic/,
// helpers.root('config/empty.js')
// ),
// new NormalModuleReplacementPlugin(
// /dom(\\|\/)debug(\\|\/)ng_probe/,
// helpers.root('config/empty.js')
// ),
// new NormalModuleReplacementPlugin(
// /dom(\\|\/)debug(\\|\/)by/,
// helpers.root('config/empty.js')
// ),
// new NormalModuleReplacementPlugin(
// /src(\\|\/)debug(\\|\/)debug_node/,
// helpers.root('config/empty.js')
// ),
// new NormalModuleReplacementPlugin(
// /src(\\|\/)debug(\\|\/)debug_renderer/,
// helpers.root('config/empty.js')
// ),
/**
* Plugin: CompressionPlugin
* Description: Prepares compressed versions of assets to serve
* them with Content-Encoding
*
* See: https://github.com/webpack/compression-webpack-plugin
*/
// install compression-webpack-plugin
// new CompressionPlugin({
// regExp: /\.css$|\.html$|\.js$|\.map$/,
// threshold: 2 * 1024
// })
/**
* Plugin LoaderOptionsPlugin (experimental)
*
* See: https://gist.github.com/sokra/27b24881210b56bbaff7
*/
new LoaderOptionsPlugin({
minimize: true,
debug: false,
options: {
/**
* Html loader advanced options
*
* See: https://github.com/webpack/html-loader#advanced-options
*/
// TODO: Need to workaround Angular 2's html syntax => #id [bind] (event) *ngFor
htmlLoader: {
minimize: false,
removeAttributeQuotes: false,
caseSensitive: true,
customAttrSurround: [
[/#/, /(?:)/],
[/\*/, /(?:)/],
[/\[?\(?/, /(?:)/]
],
customAttrAssign: [/\)?\]?=/]
},
}
}),
/**
* Plugin: BundleAnalyzerPlugin
* Description: Webpack plugin and CLI utility that represents
* bundle content as convenient interactive zoomable treemap
*
* `npm run build:prod -- --env.analyze` to use
*
* See: https://github.com/th0r/webpack-bundle-analyzer
*/
],
/*
* Include polyfills or mocks for various node stuff
* Description: Node configuration
*
* See: https://webpack.github.io/docs/configuration.html#node
*/
node: {
global: true,
crypto: 'empty',
process: false,
module: false,
clearImmediate: false,
setImmediate: false
}
});
}
|
jest.mock('send')
import { GraphQLSchema, GraphQLObjectType, GraphQLString } from 'graphql'
import { $$pgClient } from '../../../postgres/inventory/pgClientFromContext'
import createPostGraphQLHttpRequestHandler, { graphiqlDirectory } from '../createPostGraphQLHttpRequestHandler'
const path = require('path')
const http = require('http')
const request = require('supertest')
const connect = require('connect')
const express = require('express')
const sendFile = require('send')
const event = require('events')
sendFile.mockImplementation(() => {
const stream = new event.EventEmitter()
stream.pipe = jest.fn(res => process.nextTick(() => res.end()))
process.nextTick(() => stream.emit('end'))
return stream
})
const gqlSchema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
hello: {
type: GraphQLString,
resolve: () => 'world',
},
greetings: {
type: GraphQLString,
args: {
name: { type: GraphQLString },
},
resolve: (source, { name }) => `Hello, ${name}!`,
},
query: {
type: GraphQLString,
resolve: (source, args, context) =>
context[$$pgClient].query('EXECUTE'),
},
},
}),
mutation: new GraphQLObjectType({
name: 'Mutation',
fields: {
hello: {
type: GraphQLString,
resolve: () => 'world',
},
},
}),
})
const pgClient = {
query: jest.fn(() => Promise.resolve()),
release: jest.fn(),
}
const pgPool = {
connect: jest.fn(() => pgClient),
}
const defaultOptions = {
getGqlSchema: () => gqlSchema,
pgPool,
disableQueryLog: true,
}
const serverCreators = new Map([
['http', handler => {
return http.createServer(handler)
}],
['connect', handler => {
const app = connect()
app.use(handler)
return http.createServer(app)
}],
['express', handler => {
const app = express()
app.use(handler)
return http.createServer(app)
}],
])
// Parse out the Node.js version number. The version will be in a semantic
// versioning format with maybe a `v` in front. We remove that `v`, split by
// `.`, get the first item in the split array, and parse that as an integer to
// get the Node.js major version number.
const nodeMajorVersion = parseInt(process.version.replace(/^v/, '').split('.')[0], 10)
// Only test Koa in version of Node.js greater than 4 because the Koa source
// code has some ES2015 syntax in it which breaks in Node.js 4 and lower. Koa is
// not meant to be used in Node.js 4 anyway so this is fine.
if (nodeMajorVersion > 4) {
const Koa = require('koa') // tslint:disable-line variable-name
serverCreators.set('koa', handler => {
const app = new Koa()
app.use(handler)
return http.createServer(app.callback())
})
}
for (const [name, createServerFromHandler] of Array.from(serverCreators)) {
const createServer = options =>
createServerFromHandler(createPostGraphQLHttpRequestHandler(Object.assign({}, defaultOptions, options)))
describe(name, () => {
test('will 404 for route other than that specified', async () => {
const server1 = createServer()
const server2 = createServer({ graphqlRoute: '/x' })
await (
request(server1)
.post('/x')
.expect(404)
)
await (
request(server2)
.post('/graphql')
.expect(404)
)
})
test('will respond to queries on a different route', async () => {
const server = createServer({ graphqlRoute: '/x' })
await (
request(server)
.post('/x')
.send({ query: '{hello}' })
.expect(200)
.expect('Content-Type', /json/)
.expect({ data: { hello: 'world' } })
)
})
test('will always respond with CORS to an OPTIONS request when enabled', async () => {
const server = createServer({ enableCors: true })
await (
request(server)
.options('/graphql')
.expect(200)
.expect('Access-Control-Allow-Origin', '*')
.expect('Access-Control-Request-Method', 'HEAD, GET, POST')
.expect('Access-Control-Allow-Headers', /Accept, Authorization/)
.expect('')
)
})
test('will always respond to any request with CORS headers when enabled', async () => {
const server = createServer({ enableCors: true })
await (
request(server)
.post('/graphql')
.expect('Access-Control-Allow-Origin', '*')
.expect('Access-Control-Request-Method', 'HEAD, GET, POST')
.expect('Access-Control-Allow-Headers', /Accept, Authorization/)
)
})
test('will not allow requests other than POST', async () => {
const server = createServer()
await (
request(server)
.get('/graphql')
.expect(405)
.expect('Allow', 'POST, OPTIONS')
)
await (
request(server)
.delete('/graphql')
.expect(405)
.expect('Allow', 'POST, OPTIONS')
)
await (
request(server)
.put('/graphql')
.expect(405)
.expect('Allow', 'POST, OPTIONS')
)
})
test('will run a query on a POST request with JSON data', async () => {
const server = createServer()
await (
request(server)
.post('/graphql')
.set('Content-Type', 'application/json')
.send(JSON.stringify({ query: '{hello}' }))
.expect(200)
.expect('Content-Type', /json/)
.expect({ data: { hello: 'world' } })
)
})
test('will run a query on a POST request with form data', async () => {
const server = createServer()
await (
request(server)
.post('/graphql')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(`query=${encodeURIComponent('{hello}')}`)
.expect(200)
.expect('Content-Type', /json/)
.expect({ data: { hello: 'world' } })
)
})
test('will run a query on a POST request with GraphQL data', async () => {
const server = createServer()
await (
request(server)
.post('/graphql')
.set('Content-Type', 'application/graphql')
.send('{hello}')
.expect(200)
.expect('Content-Type', /json/)
.expect({ data: { hello: 'world' } })
)
})
test('will error if query parse fails', async () => {
const server = createServer()
await (
request(server)
.post('/graphql')
.send({ query: '{' })
.expect(400)
.expect('Content-Type', /json/)
.expect({ errors: [{ message: 'Syntax Error GraphQL Http Request (1:2) Expected Name, found <EOF>\n\n1: {\n ^\n', locations: [{ line: 1, column: 2 }] }] })
)
})
test('will error if validation fails', async () => {
const server = createServer()
await (
request(server)
.post('/graphql')
.send({ query: '{notFound}' })
.expect(400)
.expect('Content-Type', /json/)
.expect({ errors: [{ message: 'Cannot query field "notFound" on type "Query".', locations: [{ line: 1, column: 2 }] }] })
)
})
test('will allow mutations with POST', async () => {
const server = createServer()
await (
request(server)
.post('/graphql')
.send({ query: 'mutation {hello}' })
.expect(200)
.expect('Content-Type', /json/)
.expect({ data: { hello: 'world' } })
)
})
test('will connect and release a Postgres client from the pool on every request', async () => {
pgPool.connect.mockClear()
pgClient.query.mockClear()
pgClient.release.mockClear()
const server = createServer()
await (
request(server)
.post('/graphql')
.send({ query: '{hello}' })
.expect(200)
.expect('Content-Type', /json/)
.expect({ data: { hello: 'world' } })
)
expect(pgPool.connect.mock.calls).toEqual([[]])
expect(pgClient.query.mock.calls).toEqual([['begin'], ['commit']])
expect(pgClient.release.mock.calls).toEqual([[]])
})
test('will setup a transaction for requests that use the Postgres client', async () => {
pgPool.connect.mockClear()
pgClient.query.mockClear()
pgClient.release.mockClear()
const server = createServer()
await (
request(server)
.post('/graphql')
.send({ query: '{query}' })
.expect(200)
.expect('Content-Type', /json/)
.expect({ data: { query: null } })
)
expect(pgPool.connect.mock.calls).toEqual([[]])
expect(pgClient.query.mock.calls).toEqual([['begin'], ['EXECUTE'], ['commit']])
expect(pgClient.release.mock.calls).toEqual([[]])
})
test('will setup a transaction and pass down options for requests that use the Postgres client', async () => {
pgPool.connect.mockClear()
pgClient.query.mockClear()
pgClient.release.mockClear()
const jwtSecret = 'secret'
const pgDefaultRole = 'pg_default_role'
const server = createServer({ jwtSecret, pgDefaultRole })
await (
request(server)
.post('/graphql')
.send({ query: '{query}' })
.expect(200)
.expect('Content-Type', /json/)
.expect({ data: { query: null } })
)
expect(pgPool.connect.mock.calls).toEqual([[]])
expect(pgClient.query.mock.calls).toEqual([
['begin'],
[{ text: 'select set_config($1, $2, true)', values: ['role', 'pg_default_role'] }],
['EXECUTE'],
['commit'],
])
expect(pgClient.release.mock.calls).toEqual([[]])
})
test('will respect an operation name', async () => {
const server = createServer()
await (
request(server)
.post('/graphql')
.send({ query: 'query A { a: hello } query B { b: hello }', operationName: 'A' })
.expect(200)
.expect('Content-Type', /json/)
.expect({ data: { a: 'world' } })
)
await (
request(server)
.post('/graphql')
.send({ query: 'query A { a: hello } query B { b: hello }', operationName: 'B' })
.expect(200)
.expect('Content-Type', /json/)
.expect({ data: { b: 'world' } })
)
})
test('will use variables', async () => {
const server = createServer()
await (
request(server)
.post('/graphql')
.send({ query: 'query A($name: String!) { greetings(name: $name) }', variables: JSON.stringify({ name: 'Joe' }), operationName: 'A' })
.expect(200)
.expect('Content-Type', /json/)
.expect({ data: { greetings: 'Hello, Joe!' } })
)
await (
request(server)
.post('/graphql')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(`operationName=A&query=${encodeURIComponent('query A($name: String!) { greetings(name: $name) }')}&variables=${encodeURIComponent(JSON.stringify({ name: 'Joe' }))}`)
.expect(200)
.expect('Content-Type', /json/)
.expect({ data: { greetings: 'Hello, Joe!' } })
)
})
test('will ignore empty string variables', async () => {
const server = createServer()
await (
request(server)
.post('/graphql')
.send({ query: '{hello}', variables: '' })
.expect(200)
.expect({ data: { hello: 'world' } })
)
})
test('will error with variables of the incorrect type', async () => {
const server = createServer()
await (
request(server)
.post('/graphql')
.send({ query: '{hello}', variables: 2 })
.expect(400)
.expect({ errors: [{ message: 'Variables must be an object, not \'number\'.' }] })
)
})
test('will error with an operation name of the incorrect type', async () => {
const server = createServer()
await (
request(server)
.post('/graphql')
.send({ query: '{hello}', operationName: 2 })
.expect(400)
.expect({ errors: [{ message: 'Operation name must be a string, not \'number\'.' }] })
)
})
test('will serve a favicon when graphiql is enabled', async () => {
const server1 = createServer({ graphiql: true })
const server2 = createServer({ graphiql: true, route: '/graphql' })
await (
request(server1)
.get('/favicon.ico')
.expect(200)
.expect('Cache-Control', 'public, max-age=86400')
.expect('Content-Type', 'image/x-icon')
)
await (
request(server2)
.get('/favicon.ico')
.expect(200)
.expect('Cache-Control', 'public, max-age=86400')
.expect('Content-Type', 'image/x-icon')
)
})
test('will not serve a favicon when graphiql is disabled', async () => {
const server1 = createServer({ graphiql: false })
const server2 = createServer({ graphiql: false, route: '/graphql' })
await (
request(server1)
.get('/favicon.ico')
.expect(404)
)
await (
request(server2)
.get('/favicon.ico')
.expect(404)
)
})
test('will serve any assets for graphiql', async () => {
sendFile.mockClear()
const server = createServer({ graphiql: true })
await (
request(server)
.get('/_postgraphql/graphiql/anything.css')
.expect(200)
)
await (
request(server)
.get('/_postgraphql/graphiql/something.js')
.expect(200)
)
await (
request(server)
.get('/_postgraphql/graphiql/very/deeply/nested')
.expect(200)
)
expect(sendFile.mock.calls.map(([res, filepath, options]) => [path.relative(graphiqlDirectory, filepath), options]))
.toEqual([
['anything.css', { index: false }],
['something.js', { index: false }],
['very/deeply/nested', { index: false }],
])
})
test('will not serve some graphiql assets', async () => {
const server = createServer({ graphiql: true })
await (
request(server)
.get('/_postgraphql/graphiql/index.html')
.expect(404)
)
await (
request(server)
.get('/_postgraphql/graphiql/asset-manifest.json')
.expect(404)
)
})
test('will not serve any assets for graphiql when disabled', async () => {
sendFile.mockClear()
const server = createServer({ graphiql: false })
await (
request(server)
.get('/_postgraphql/graphiql/anything.css')
.expect(404)
)
await (
request(server)
.get('/_postgraphql/graphiql/something.js')
.expect(404)
)
expect(sendFile.mock.calls.length).toEqual(0)
})
test('will not allow if no text/event-stream headers are set', async () => {
const server = createServer({ graphiql: true })
await (
request(server)
.get('/_postgraphql/stream')
.expect(405)
)
})
test('will render GraphiQL if enabled', async () => {
const server1 = createServer()
const server2 = createServer({ graphiql: true })
await (
request(server1)
.get('/graphiql')
.expect(404)
)
await (
request(server2)
.get('/graphiql')
.expect(200)
.expect('Content-Type', 'text/html; charset=utf-8')
)
})
test('will render GraphiQL on another route if desired', async () => {
const server1 = createServer({ graphiqlRoute: '/x' })
const server2 = createServer({ graphiql: true, graphiqlRoute: '/x' })
const server3 = createServer({ graphiql: false, graphiqlRoute: '/x' })
await (
request(server1)
.get('/x')
.expect(404)
)
await (
request(server2)
.get('/x')
.expect(200)
.expect('Content-Type', 'text/html; charset=utf-8')
)
await (
request(server3)
.get('/x')
.expect(404)
)
await (
request(server3)
.get('/graphiql')
.expect(404)
)
})
test('cannot use a rejected GraphQL schema', async () => {
const rejectedGraphQLSchema = Promise.reject(new Error('Uh oh!'))
// We don’t want Jest to complain about uncaught promise rejections.
rejectedGraphQLSchema.catch(() => { /* noop */ })
const server = createServer({ getGqlSchema: () => rejectedGraphQLSchema })
// We want to hide `console.error` warnings because we are intentionally
// generating some here.
const origConsoleError = console.error
console.error = () => { /* noop */ }
try {
await (
request(server)
.post('/graphql')
.send({ query: '{hello}' })
.expect(500)
)
}
finally {
console.error = origConsoleError
}
})
test('will correctly hand over pgSettings to the withPostGraphQLContext call', async () => {
pgPool.connect.mockClear()
pgClient.query.mockClear()
pgClient.release.mockClear()
const server = createServer({
pgSettings: {
'foo.string': 'test1',
'foo.number': 42,
'foo.boolean': true,
},
})
await (
request(server)
.post('/graphql')
.send({ query: '{hello}' })
.expect(200)
.expect('Content-Type', /json/)
.expect({ data: { hello: 'world' } })
)
expect(pgPool.connect.mock.calls).toEqual([[]])
expect(pgClient.query.mock.calls).toEqual([
['begin'],
[
{
text: 'select set_config($1, $2, true), set_config($3, $4, true), set_config($5, $6, true)',
values: [
'foo.string', 'test1',
'foo.number', '42',
'foo.boolean', 'true',
],
},
],
['commit'],
])
expect(pgClient.release.mock.calls).toEqual([[]])
})
})
}
|
/* eslint no-console: warn */
const _ = require('lodash');
const { processScore } = require('../helpers/game.js');
const getRandomQuiz = require('../../app/helpers/quizRandomizer.js');
module.exports = function socketHandler(io) {
const players = [];
const game = io.of('/game');
game.on('connect', function (socket) {
socket.join('gameRoom');
console.log('connected !!');
console.log('socket ID', socket.id);
console.log('players', players);
socket.on('score update', broadcastScore.bind(null, socket));
socket.on('spectator join', sendPlayers.bind(null, socket, players));
socket.on('player join', handleGame.bind(null, socket));
socket.on('player input', broadcastPlayerCode.bind(null, socket));
});
game.on('disconnect', (socket) => {
console.log('disconnected', socket.id);
});
const handleGame = (socket, player ) => {
console.log('handling game', player);
addPlayer(players, player);
sendPlayers(socket, players);
// if all players ready
if (players.length >= 2) {
// send randomCodeQuizURL
game.emit('quiz url', getRandomQuiz());
}
};
const broadcastScore = (socket, { id, score, passCount, failCount }) => {
console.log('broadcasting score');
socket.to('gameRoom').emit('score update', { id, score: processScore(score), passCount, failCount });
};
const broadcastPlayerCode = (socket, { id, randomCode, code }) => {
socket.to('gameRoom').emit('player input', { id, randomCode, code });
};
const sendPlayers = (socket, players) => {
console.log('sending players');
socket.to('gameRoom').emit('player join', { players });
};
};
function addPlayer(players, newPlayer) {
// !_.some(players, player => _.includes(player, newPlayer.id)) && players.push(newPlayer);
players[newPlayer.id - 1] = newPlayer;
}
|
'use strict';
import Component from './component';
import VolumeAttachment from './volume-attachment';
import Port from './port';
import {isString} from './util';
const Server = function (properties) {
if (!(this instanceof Server)) {
return new Server(properties);
}
Component.call(this, {
ports: [],
...properties
});
};
Server.prototype = Object.create(Component.prototype);
Server.prototype.constructor = Server;
Server.prototype.getDependencies = function () {
return [
...this.dependencies,
...this.properties.ports
]
};
Server.prototype.attachVolume = function (volume, mountPoint) {
const attachment = new VolumeAttachment({
id: `${isString(volume) ? volume : volume.properties.id}-attachment`,
server: this,
volume,
mountPoint
});
this.dependencies.push(attachment);
return this;
};
Server.prototype.attachPort = function (port) {
this.properties.ports.push(port);
return this;
};
Server.prototype.getSchema = function () {
return {
zone: {
type: String
},
name: {
type: String
},
image: {
type: String,
required: true
},
flavor: {
type: String,
required: true
},
keyPair: {
type: String
},
ports: {
type: Array,
items: [String, Port]
}
};
};
Server.prototype.getResources = function () {
const {
id, zone, name, flavor,
keyPair, image, ports
} = this.properties;
const networks = ports.map(port => ({
port: Component.resolve(port)
}));
const properties = {
flavor,
image
};
Object.assign(
properties,
name ? {name} : {},
zone ? {zone} : {},
keyPair ? {key_name: keyPair} : {},
networks.length ? {networks} : {}
);
return {
[id]: {
type: 'OS::Nova::Server',
properties
}
};
};
export default Server;
|
define([
'./src/vertebrae'
], function(Vertebrae) {
return Vertebrae;
}); |
import Ember from 'ember';
import StatefulMixin from './mixins/stateful';
export default Ember.Object.extend(StatefulMixin);
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
Animated,
Easing,
View,
} from 'react-native';
const INDETERMINATE_WIDTH_FACTOR = 0.3;
const BAR_WIDTH_ZERO_POSITION = INDETERMINATE_WIDTH_FACTOR / (1 + INDETERMINATE_WIDTH_FACTOR);
export default class ProgressBar extends Component {
static propTypes = {
animated: PropTypes.bool,
borderColor: PropTypes.string,
borderRadius: PropTypes.number,
borderWidth: PropTypes.number,
children: PropTypes.node,
color: PropTypes.string,
height: PropTypes.number,
indeterminate: PropTypes.bool,
progress: PropTypes.number,
style: View.propTypes.style,
unfilledColor: PropTypes.string,
width: PropTypes.number,
};
static defaultProps = {
animated: true,
borderRadius: 4,
borderWidth: 1,
color: 'rgba(0, 122, 255, 1)',
height: 6,
indeterminate: false,
progress: 0,
width: 150,
};
constructor(props) {
super(props);
const progress = Math.min(Math.max(props.progress, 0), 1);
this.state = {
progress: new Animated.Value(props.indeterminate ? INDETERMINATE_WIDTH_FACTOR : progress),
animationValue: new Animated.Value(BAR_WIDTH_ZERO_POSITION),
};
}
componentDidMount() {
if (this.props.indeterminate) {
this.animate();
}
}
componentWillReceiveProps(props) {
if (props.indeterminate !== this.props.indeterminate) {
if (props.indeterminate) {
this.animate();
} else {
Animated.spring(this.state.animationValue, {
toValue: BAR_WIDTH_ZERO_POSITION,
}).start();
}
}
if (
props.indeterminate !== this.props.indeterminate ||
props.progress !== this.props.progress
) {
const progress = (props.indeterminate
? INDETERMINATE_WIDTH_FACTOR
: Math.min(Math.max(props.progress, 0), 1)
);
if (props.animated) {
Animated.spring(this.state.progress, {
toValue: progress,
bounciness: 0,
}).start();
} else {
this.state.progress.setValue(progress);
}
}
}
animate() {
this.state.animationValue.setValue(0);
Animated.timing(this.state.animationValue, {
toValue: 1,
duration: 1000,
easing: Easing.linear,
isInteraction: false,
}).start((endState) => {
if (endState.finished) {
this.animate();
}
});
}
render() {
const {
borderColor,
borderRadius,
borderWidth,
children,
color,
height,
style,
unfilledColor,
width,
...restProps
} = this.props;
const innerWidth = width - (borderWidth * 2);
const containerStyle = {
width,
borderWidth,
borderColor: borderColor || color,
borderRadius,
overflow: 'hidden',
backgroundColor: unfilledColor,
};
const progressStyle = {
backgroundColor: color,
height,
width: innerWidth,
transform: [{
translateX: this.state.animationValue.interpolate({
inputRange: [0, 1],
outputRange: [innerWidth * -INDETERMINATE_WIDTH_FACTOR, innerWidth],
}),
}, {
translateX: this.state.progress.interpolate({
inputRange: [0, 1],
outputRange: [innerWidth / -2, 0],
}),
}, {
scaleX: this.state.progress,
}],
};
return (
<View style={[containerStyle, style]} {...restProps}>
<Animated.View style={progressStyle} />
{children}
</View>
);
}
}
|
import './accounts-config.js';
import './i18n.js';
import './routes.js';
import '../../ui/iso3d/phaser-plugin-isometric.min.js';
|
const basicJson = require('./basic.json')
export const jsonExport = {
basicJson
}
|
/*
* wjquery.calendar 0.1.1
* by composite ([email protected])
* http://www.wonchu.net
* This project licensed under a MIT License.
0.1.0 : 최초작성
0.1.1 : 소스정리
*/
(function ($) {
const WCALENDAR_SV = {
ns: "wcalendar",
dateFormat: "YYYYMMDD",
lang: {
ko: {
week: ["일", "월", "화", "수", "목", "금", "토"]
}
}
};
$.fn.wcalendar = function (method) {
let result, _arguments = arguments;
this.each(function (i, element) {
const $element = $(element);
let $container,
_option = {};
if ($element.prop("tagName").toLowerCase() == "input") {
if ($element.attr("data-wrap-id")) {
$container = $("#" + $element.attr("data-wrap-id"));
} else {
const _id = "wcalendar_" + new Date().getTime();
$element.after("<div id=\"" + _id + "\" />");
_option.element = $element;
$element.attr("data-wrap-id", _id);
$container = $("#" + _id);
}
} else {
$container = $element;
}
const plugin = $container.data(WCALENDAR_SV.ns);
if (plugin && typeof method === 'string') {
if (plugin[method]) {
result = plugin[method].apply(this, Array.prototype.slice.call(_arguments, 1));
} else {
alert('Method ' + method + ' does not exist on jQuery.wcalendar');
}
} else if (!plugin && (typeof method === 'object' || !method)) {
let wcalendar = new WCALENDAR();
$container.data(WCALENDAR_SV.ns, wcalendar);
wcalendar.init($container, $.extend(_option, $.fn.wcalendar.defaultSettings, method || {}));
}
});
return result ? result : $(this);
};
$.fn.wcalendar.defaultSettings = {
width: "200px",
locale: "ko",
dateFormat: "YYYY.MM.DD",
showPrevNextDays: true,
dateIconClass: "wcalendar-dateicon",
mdHoliday: {
"0101": {
ko: "신정"
},
"0505": {
ko: "어린이날"
}
},
holiday: {
"20210519": {
ko: "부처님오신날"
}
}
};
function WCALENDAR() {
let $container, options;
function init(_container, _options) {
$container = _container;
options = _options;
if (options.selectDate) {
options.selectDate = moment(options.selectDate, options.dateFormat);
} else {
if (options.element && options.element.val() != "") {
options.selectDate = moment(options.element.val(), options.dateFormat);
} else {
options.selectDate = moment();
}
}
options.targetDate = options.selectDate.clone();
_WCALENDAR.init($container, options);
}
function draw() {
_WCALENDAR.draw($container, options);
}
function prev() {
options.targetDate = options.targetDate.add(-1, "months");
_WCALENDAR.draw($container, options);
}
function next() {
options.targetDate = options.targetDate.add(1, "months");
_WCALENDAR.draw($container, options);
}
function set(dt) {
options.targetDate = moment(dt, options.dateFormat);
_WCALENDAR.draw($container, options);
}
function select() {
options.targetDate = moment($(".wcalendar-month .title-year", $container).val() + $.pad($(".wcalendar-month .title-month", $container).val(), 2) + "01", "YYYYMMDD");
_WCALENDAR.draw($container, options);
}
function click() {
const _index = $(".wcalendar-undock").index($container);
$(".wcalendar-undock").each(function () {
if ($(".wcalendar-undock").index(this) != _index && $(this).is(":visible")) {
$(this).hide();
}
});
if ($container.is(":visible")) {
$container.hide();
} else {
if (options.element && options.element.val() != "") {
options.selectDate = moment(options.element.val(), options.dateFormat);
options.hasVal = "Y";
} else {
options.selectDate = moment();
options.hasVal = "N";
}
options.targetDate = options.selectDate.clone();
_WCALENDAR.draw($container, options);
$container.show();
}
}
function destory() {
if (options.element) {
options.element.removeClass("wcalendar-input");
if (options.element.next("." + options.dateIconClass)) {
options.element.next("." + options.dateIconClass).remove();
}
}
$container.remove();
}
return {
init: init,
draw: draw,
prev: prev,
next: next,
set: set,
select: select,
click: click,
destory: destory
};
}
var _WCALENDAR = {
init: function ($container, options) {
if (options.element) {
options.element.addClass("wcalendar-input");
$container.addClass("wcalendar-undock").css({
"top": options.element.position().top + options.element.outerHeight(),
"left": options.element.position().left,
"width": options.width
});
const $icon = $("<span class=\"" + options.dateIconClass + "\" />");
options.element.after($icon);
$icon.click(function () {
$container.wcalendar("click");
});
options.element.click(function () {
$container.wcalendar("click");
});
$(document).on("click.wcalendar-undock", function (event) {
if ($(event.target).closest(".wcalendar-wrap, .wcalendar-input, ." + options.dateIconClass).length === 0) {
$container.hide();
}
});
}
$container.html(
"<div class=\"wcalendar-wrap\">" +
" <div class=\"wcalendar-month\">" +
" <ul>" +
" <li class=\"prev\"><a href=\"javascript:;\"><span>❮</span></a></li>" +
" <li class=\"next\"><a href=\"javascript:;\"><span>❯</span></a></li>" +
" <li><select class=\"title-year\"></select> <select class=\"title-month\"></select></li>" +
" </ul>" +
" </div>" +
" <ul class=\"wcalendar-weekdays\"></ul>" +
" <ul class=\"wcalendar-days\"></ul>" +
"</div>"
);
this.draw($container, options);
$(".wcalendar-month li>a", $container).click(function () {
$container.wcalendar($(this).parent().attr("class"));
});
$container.find(".wcalendar-days").on("click", "a", function () {
var $t = $(this);
$t.parent().siblings().find("a.active").removeClass("active");
$t.addClass("active");
if (options.callback) {
options.callback($(this).attr("data-val"));
} else if (options.element) {
options.element.val($(this).attr("data-val"));
$container.hide();
}
});
},
draw: function ($container, options) {
const curentDate = moment(),
selectDate = options.selectDate,
targetDate = options.targetDate,
firstDate = targetDate.clone().startOf("month"),
lastDate = targetDate.clone().endOf("month");
let _prevDate, _targetDate, _nextDate;
this.makeSelectOption($(".wcalendar-month .title-year", $container), targetDate.year() - 10, targetDate.year() + 10, targetDate.year());
this.makeSelectOption($(".wcalendar-month .title-month", $container), 1, 12, options.targetDate.month() + 1);
$(".wcalendar-month .title-month, .wcalendar-month .title-year", $container).off("change").on("change", function () {
$container.wcalendar("select");
});
let _weekdays = [];
for (let n = 0; n < 7; n++) {
_weekdays.push("<li>" + WCALENDAR_SV.lang[options.locale].week[n] + "</li>");
}
$container.find(".wcalendar-weekdays").empty().append(_weekdays.join(""));
let _days = [];
for (let i = firstDate.day(); i > 0; i--) {
if (options.showPrevNextDays) {
_prevDate = firstDate.clone().add(-i, "days");
_days.push(this.makeItem(options, "prev", _prevDate, curentDate, selectDate));
} else {
_days.push("<li> </li>");
}
}
for (let j = 0; j < lastDate.date(); j++) {
_targetDate = firstDate.clone().add(j, "days");
_days.push(this.makeItem(options, "target", _targetDate, curentDate, selectDate));
}
for (let k = 1; k <= (6 - lastDate.day()); k++) {
if (options.showPrevNextDays) {
_nextDate = lastDate.clone().add(k, "days");
_days.push(this.makeItem(options, "next", _nextDate, curentDate, selectDate));
} else {
_days.push("<li> </li>");
}
}
$container.find(".wcalendar-days").empty().append(_days.join(""));
},
makeItem: function (options, mode, dt, dt2, dt3) {
let classNames = [],
titles = [],
_classNames = "",
_titles = "";
const dtf = dt.format(WCALENDAR_SV.dateFormat),
dtfmd = dt.format("MMDD"),
dtf2 = dt2.format(WCALENDAR_SV.dateFormat),
dtf3 = dt3.format(WCALENDAR_SV.dateFormat);
classNames.push(mode);
if (dtf2 == dtf) {
classNames.push("today");
}
if (dtf3 == dtf ) {
if(options.hasVal && options.hasVal=="N"){
//nothing
}else{
classNames.push("active");
}
}
if (options.mdHoliday && options.mdHoliday[dtfmd]) {
classNames.push("md-holiday");
titles.push(options.mdHoliday[dtfmd][options.locale]);
}
if (options.holiday && options.holiday[dtf]) {
classNames.push("holiday");
titles.push(options.holiday[dtf][options.locale]);
}
if (classNames.length > 0) {
_classNames = " class=\"" + (classNames.join(" ")) + "\"";
}
if (titles.length > 0) {
_titles = " title=\"" + (titles.join(" ")) + "\"";
}
return "<li>" +
" <a href=\"javascript:;\" data-val=\"" + dt.format(options.dateFormat) + "\"" + _titles + _classNames + ">" + dt.date() + "</a>" +
"</li>";
},
makeSelectOption: function ($t, start, end, v) {
let _options = [];
for (let i = start; i <= end; i++) {
_options.push("<option value=\"" + i + "\"" + (i == v ? " selected=\"selected\"" : "") + ">" + i + "</option>");
}
$t.empty().append(_options.join(""));
}
}
})(jQuery); |
describe("OCombo:", function () {
var wtest, $p;
beforeEach(function () {
wtest = frames[0];
$p = wtest.$p;
});
it("Конствуктор должен возвращать объект типа OCombo", function () {
expect(typeof $p).toBe("object");
});
}); |
import { exec } from "child_process"
import test from "tape"
import cliBin from "./utils/cliBin"
test("--watch error if no input files", (t) => {
exec(
`${ cliBin }/testBin --watch`,
(err, stdout, stderr) => {
t.ok(
err,
"should return an error when <input> or <output> are missing when " +
"`--watch` option passed"
)
t.ok(
stderr.includes("--watch requires"),
"should show an explanation when <input> or <output> are missing when" +
" `--watch` option passed"
)
t.end()
}
)
})
|
var searchData=
[
['t',['T',['../all__17_8js.html#adf1f3edb9115acb0a1e04209b7a9937b',1,'T(): all_17.js'],['../all__8_8js.html#adf1f3edb9115acb0a1e04209b7a9937b',1,'T(): all_8.js'],['../enumvalues__7_8js.html#adf1f3edb9115acb0a1e04209b7a9937b',1,'T(): enumvalues_7.js'],['../functions__3_8js.html#adf1f3edb9115acb0a1e04209b7a9937b',1,'T(): functions_3.js'],['../functions__7_8js.html#adf1f3edb9115acb0a1e04209b7a9937b',1,'T(): functions_7.js']]],
['t_5ff',['t_f',['../classvo.html#a59a051419df095f766905047916cf7a0',1,'vo']]],
['test_5f2main_5f8cpp',['test_2main_8cpp',['../test__2main__8cpp_8js.html#a616ce37741695e70aeb42c09bf11e83d',1,'test_2main_8cpp.js']]],
['test_5f8cpp',['test_8cpp',['../test__8cpp_8js.html#ac745c2a6c95dd92c7473e1d8486549bf',1,'test_8cpp.js']]],
['tokenize_5f8py',['tokenize_8py',['../tokenize__8py_8js.html#a29054f8eaff39510a045bf811b069903',1,'tokenize_8py.js']]],
['toprint',['ToPrint',['../classes__6_8js.html#ad81a47989c7025eaa75cb3cd6c05ca66',1,'classes_6.js']]]
];
|
(function(window, factory) {
if (typeof define === 'function' && define.amd) {
define([], function() {
return factory();
});
} else if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = factory();
} else {
(window.LocaleData || (window.LocaleData = {}))['de_LU@euro'] = factory();
}
}(typeof window !== "undefined" ? window : this, function() {
return {
"LC_ADDRESS": {
"postal_fmt": "%f%N%a%N%d%N%b%N%s %h %e %r%N%z %T%N%c%N",
"country_name": "Luxemburg",
"country_post": null,
"country_ab2": "LU",
"country_ab3": "LUX",
"country_num": 442,
"country_car": "L",
"country_isbn": null,
"lang_name": "Deutsch",
"lang_ab": "de",
"lang_term": "deu",
"lang_lib": "ger"
},
"LC_MEASUREMENT": {
"measurement": 1
},
"LC_MESSAGES": {
"yesexpr": "^[+1jJyY]",
"noexpr": "^[-0nN]",
"yesstr": "ja",
"nostr": "nein"
},
"LC_MONETARY": {
"currency_symbol": "\u20ac",
"mon_decimal_point": ",",
"mon_thousands_sep": ".",
"mon_grouping": [
3,
3
],
"positive_sign": "",
"negative_sign": "-",
"frac_digits": 2,
"p_cs_precedes": 1,
"p_sep_by_space": 1,
"n_cs_precedes": 1,
"n_sep_by_space": 1,
"p_sign_posn": 4,
"n_sign_posn": 4,
"int_curr_symbol": "EUR ",
"int_frac_digits": 2,
"int_p_cs_precedes": null,
"int_p_sep_by_space": null,
"int_n_cs_precedes": null,
"int_n_sep_by_space": null,
"int_p_sign_posn": null,
"int_n_sign_posn": null
},
"LC_NAME": {
"name_fmt": "%d%t%g%t%m%t%f",
"name_gen": null,
"name_mr": null,
"name_mrs": null,
"name_miss": null,
"name_ms": null
},
"LC_NUMERIC": {
"decimal_point": ",",
"thousands_sep": ".",
"grouping": [
3,
3
]
},
"LC_PAPER": {
"height": 297,
"width": 210
},
"LC_TELEPHONE": {
"tel_int_fmt": "+%c %a %l",
"tel_dom_fmt": null,
"int_select": "00",
"int_prefix": "352"
},
"LC_TIME": {
"date_fmt": "%a %b %e %H:%M:%S %Z %Y",
"abday": [
"So",
"Mo",
"Di",
"Mi",
"Do",
"Fr",
"Sa"
],
"day": [
"Sonntag",
"Montag",
"Dienstag",
"Mittwoch",
"Donnerstag",
"Freitag",
"Samstag"
],
"week": [
7,
19971130,
4
],
"abmon": [
"Jan",
"Feb",
"M\u00e4r",
"Apr",
"Mai",
"Jun",
"Jul",
"Aug",
"Sep",
"Okt",
"Nov",
"Dez"
],
"mon": [
"Januar",
"Februar",
"M\u00e4rz",
"April",
"Mai",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"Dezember"
],
"d_t_fmt": "%a %d %b %Y %T %Z",
"d_fmt": "%Y-%m-%d",
"t_fmt": "%T",
"am_pm": [
"",
""
],
"t_fmt_ampm": "",
"era": null,
"era_year": null,
"era_d_t_fmt": null,
"era_d_fmt": null,
"era_t_fmt": null,
"alt_digits": null,
"first_weekday": 2,
"first_workday": null,
"cal_direction": null,
"timezone": null
}
};
}));
|
// TODO: Add tests
import passport from 'passport';
import { OAuth2Strategy as GoogleStrategy } from 'passport-google-oauth';
import authConfig from '../credentials.json';
import init from '../init';
import { upsert } from '../../lib/util';
function passportInit() {
// serialize user into the session
init();
passport.use(new GoogleStrategy(
authConfig.google,
(accessToken, refreshToken, profile, done) => {
const params = {
email: profile.emails[0].value,
external_auth_type: 'google',
};
const data = {
first_name: profile.name.givenName,
last_name: profile.name.familyName,
email: profile.emails.length && profile.emails[0].value,
photo_url: profile.photos.length && profile.photos[0].value,
external_auth_type: 'google',
external_auth_id: profile.id,
};
upsert('/users', params, data)
.then(resp => done(null, resp))
.catch(err => done(err));
},
));
}
passportInit();
export default passport;
|
var React = require('react');
var _ = require('underscore');
var List = React.createClass({
render: function() {
var listItems = [];
_.each(this.props.value, function(data, index) {
listItems.push(<li>{JSON.stringify(data)}</li>);
});
return (
<div>
<strong>{this.props.title}:</strong>
<ol>{listItems}</ol>
</div>
);
}
});
module.exports = List; |
var Helper = require("@kaoscript/runtime").Helper;
module.exports = function() {
var path = require("path");
require("../require/require.string.ks")(Helper.cast(path.join(__dirname, "foobar.txt"), "String", false, null, "String"));
}; |
var phonecatControllers = angular.module('phonecatControllers', []);
phonecatControllers.controller('PhoneListCtrl', ['$scope', '$http',
function ($scope, $http) {
$http.get('phones/phones.json').success(function(data) {
$scope.phones = data;
});
$scope.orderProp = 'age';
}]);
phonecatControllers.controller('PhoneDetailCtrl', ['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http) {
$http.get('phones/' + $routeParams.phoneId + '.json').success(function(data) {
$scope.phone = data;
$scope.mainImageUrl = data.images[0];
});
$scope.setImage = function(imageUrl) {
$scope.mainImageUrl = imageUrl;
}
}]);
|
var elixir = require('laravel-elixir');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Sass
| file for our application, as well as publishing vendor resources.
|
*/
elixir(function(mix) {
mix.sass('app.scss');
});
elixir(function(mix) {
mix.scriptsIn('resources/assets/js/');
}); |
import Vue from 'vue';
import Router from 'vue-router';
import Home from '@/views/Home.vue';
import Sms from '@/views/SMS.vue';
import Services from '@/views/Services.vue';
import Settings from '@/views/Settings.vue';
import Wlan from '@/views/settings/wlan.vue';
import DialUp from '@/views/settings/dialup.vue';
import AppSettings from '@/views/AppSettings.vue';
Vue.use(Router);
export default new Router({
routes: [
{
path: '/',
redirect: { name: 'home' },
},
{
path: '/home',
name: 'home',
component: Home,
},
{
path: '/sms',
name: 'sms',
component: Sms,
},
{
path: '/statistics',
name: 'statistics',
},
{
path: '/services',
name: 'services',
component: Services,
},
{
path: '/settings',
name: 'settings',
component: Settings,
redirect: { name: 'settings/wlan' },
children: [
{
path: 'wlan',
name: 'settings/wlan',
component: Wlan,
label: 'WLAN',
},
{
path: 'dialup',
name: 'settings/dialup',
component: DialUp,
label: 'Dial-up',
},
],
},
{
path: '/app-settings',
name: 'appSettings',
component: AppSettings,
},
],
});
|
const Promise = require('bluebird');
const fs = require('fs-extra');
const debug = require('ghost-ignition').debug('api:themes');
const common = require('../../lib/common');
const themeService = require('../../services/themes');
const settingsCache = require('../../services/settings/cache');
const models = require('../../models');
module.exports = {
docName: 'themes',
browse: {
permissions: true,
query() {
return themeService.toJSON();
}
},
activate: {
headers: {
cacheInvalidate: true
},
options: [
'name'
],
validation: {
options: {
name: {
required: true
}
}
},
permissions: true,
query(frame) {
let themeName = frame.options.name;
let checkedTheme;
const newSettings = [{
key: 'active_theme',
value: themeName
}];
const loadedTheme = themeService.list.get(themeName);
if (!loadedTheme) {
return Promise.reject(new common.errors.ValidationError({
message: common.i18n.t('notices.data.validation.index.themeCannotBeActivated', {themeName: themeName}),
errorDetails: newSettings
}));
}
return themeService.validate.checkSafe(loadedTheme)
.then((_checkedTheme) => {
checkedTheme = _checkedTheme;
// @NOTE: we use the model, not the API here, as we don't want to trigger permissions
return models.Settings.edit(newSettings, frame.options);
})
.then(() => {
debug('Activating theme (method B on API "activate")', themeName);
themeService.activate(loadedTheme, checkedTheme);
return themeService.toJSON(themeName, checkedTheme);
});
}
},
upload: {
headers: {},
permissions: {
method: 'add'
},
query(frame) {
// @NOTE: consistent filename uploads
frame.options.originalname = frame.file.originalname.toLowerCase();
let zip = {
path: frame.file.path,
name: frame.file.originalname,
shortName: themeService.storage.getSanitizedFileName(frame.file.originalname.split('.zip')[0])
};
let checkedTheme;
// check if zip name is casper.zip
if (zip.name === 'casper.zip') {
throw new common.errors.ValidationError({
message: common.i18n.t('errors.api.themes.overrideCasper')
});
}
return themeService.validate.checkSafe(zip, true)
.then((_checkedTheme) => {
checkedTheme = _checkedTheme;
return themeService.storage.exists(zip.shortName);
})
.then((themeExists) => {
// CASE: delete existing theme
if (themeExists) {
return themeService.storage.delete(zip.shortName);
}
})
.then(() => {
// CASE: store extracted theme
return themeService.storage.save({
name: zip.shortName,
path: checkedTheme.path
});
})
.then(() => {
// CASE: loads the theme from the fs & sets the theme on the themeList
return themeService.loadOne(zip.shortName);
})
.then((loadedTheme) => {
// CASE: if this is the active theme, we are overriding
if (zip.shortName === settingsCache.get('active_theme')) {
debug('Activating theme (method C, on API "override")', zip.shortName);
themeService.activate(loadedTheme, checkedTheme);
// CASE: clear cache
this.headers.cacheInvalidate = true;
}
common.events.emit('theme.uploaded');
// @TODO: unify the name across gscan and Ghost!
return themeService.toJSON(zip.shortName, checkedTheme);
})
.finally(() => {
// @TODO: we should probably do this as part of saving the theme
// CASE: remove extracted dir from gscan
// happens in background
if (checkedTheme) {
fs.remove(checkedTheme.path)
.catch((err) => {
common.logging.error(new common.errors.GhostError({err: err}));
});
}
});
}
},
download: {
options: [
'name'
],
validation: {
options: {
name: {
required: true
}
}
},
permissions: {
method: 'read'
},
query(frame) {
let themeName = frame.options.name;
const theme = themeService.list.get(themeName);
if (!theme) {
return Promise.reject(new common.errors.BadRequestError({
message: common.i18n.t('errors.api.themes.invalidThemeName')
}));
}
return themeService.storage.serve({
name: themeName
});
}
},
destroy: {
statusCode: 204,
headers: {
cacheInvalidate: true
},
options: [
'name'
],
validation: {
options: {
name: {
required: true
}
}
},
permissions: true,
query(frame) {
let themeName = frame.options.name;
if (themeName === 'casper') {
throw new common.errors.ValidationError({
message: common.i18n.t('errors.api.themes.destroyCasper')
});
}
if (themeName === settingsCache.get('active_theme')) {
throw new common.errors.ValidationError({
message: common.i18n.t('errors.api.themes.destroyActive')
});
}
const theme = themeService.list.get(themeName);
if (!theme) {
throw new common.errors.NotFoundError({
message: common.i18n.t('errors.api.themes.themeDoesNotExist')
});
}
return themeService.storage.delete(themeName)
.then(() => {
themeService.list.del(themeName);
});
}
}
};
|
import React, {PropTypes, Component} from 'react';
import { NavGroup } from 'react-photonkit'
/*class NavGroup extends Component {
static propTypes = {
children: PropTypes.any
}
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<nav className="nav-group">
{this.props.children}
</nav>
);
}
}*/
export default NavGroup
|
var Vector;
(function (Vector) {
function clean(n) {
var vector = [];
for (var i = 0; i < n; i++) {
vector[i] = 0;
}
return vector;
}
Vector.clean = clean;
function create() {
var values = [];
for (var _i = 0; _i < arguments.length; _i++) {
values[_i - 0] = arguments[_i];
}
var vector = [];
for (var i = 0; i < values.length; i++) {
vector[i] = values[i];
}
return vector;
}
Vector.create = create;
function dot(vec1, vec2) {
var dot = 0;
for (var i = 0; i < vec1.length; i++) {
dot += vec1[i] * vec2[i];
}
return dot;
}
Vector.dot = dot;
function magnitude(vec) {
return Math.sqrt(Vector.dot(vec, vec));
}
Vector.magnitude = magnitude;
function angle(vec1, vec2) {
return Math.acos(Vector.dot(vec1, vec2) / (Vector.magnitude(vec1) * Vector.magnitude(vec2)));
}
Vector.angle = angle;
var Vec2;
(function (Vec2) {
function clean() {
return [0, 0];
}
Vec2.clean = clean;
function create(x, y) {
return [x, y];
}
Vec2.create = create;
function dot(vec1, vec2) {
return vec1[0] * vec2[0] + vec1[1] * vec2[1];
}
Vec2.dot = dot;
})(Vec2 = Vector.Vec2 || (Vector.Vec2 = {}));
var Vec3;
(function (Vec3) {
function clean() {
return [0, 0, 0];
}
Vec3.clean = clean;
function create(x, y, z) {
return [x, y, z];
}
Vec3.create = create;
function dot(vec1, vec2) {
return vec1[0] * vec2[0] + vec1[1] * vec2[1] + vec1[2] * vec2[2];
}
Vec3.dot = dot;
})(Vec3 = Vector.Vec3 || (Vector.Vec3 = {}));
var Vec4;
(function (Vec4) {
function clean() {
return [0, 0, 0, 0];
}
Vec4.clean = clean;
function create(x, y, z, w) {
return [x, y, z, w];
}
Vec4.create = create;
function dot(vec1, vec2) {
return vec1[0] * vec2[0] + vec1[1] * vec2[1] + vec1[2] * vec2[2] + vec1[3] * vec2[3];
}
Vec4.dot = dot;
})(Vec4 = Vector.Vec4 || (Vector.Vec4 = {}));
})(Vector || (Vector = {}));
var Matrix;
(function (Matrix) {
function clean(size) {
return Vector.clean(size * size);
}
Matrix.clean = clean;
function identity(size) {
var mat = [];
for (var i = 0; i < size * size; i++) {
mat[i] = (Math.floor(i / size) - i % size) == 0 ? 1 : 0;
}
return mat;
}
Matrix.identity = identity;
function copy(mat) {
return mat.slice();
}
Matrix.copy = copy;
function getRow(mat, row) {
var size = Matrix.size(mat);
var vec = [];
for (var i = 0; i < size; i++) {
vec[i] = mat[row + i * size];
}
return vec;
}
Matrix.getRow = getRow;
function getColom(mat, colom) {
var size = Matrix.size(mat);
var vec = [];
for (var i = 0; i < size; i++) {
vec[i] = mat[colom * size + i];
}
return vec;
}
Matrix.getColom = getColom;
function getValue(mat, row, colom) {
var size = Matrix.size(mat);
return mat[row + colom * size];
}
Matrix.getValue = getValue;
function setRow(mat, row, value) {
var size = Matrix.size(mat);
for (var i = 0; i < size; i++) {
mat[row + i * size] = value[i];
}
return mat;
}
Matrix.setRow = setRow;
function setColom(mat, colom, value) {
var size = Matrix.size(mat);
for (var i = 0; i < size; i++) {
mat[colom * size + i] = value[i];
}
return mat;
}
Matrix.setColom = setColom;
function setvalue(mat, row, colom, value) {
var size = Matrix.size(mat);
mat[row + colom * size] = value;
return mat;
}
Matrix.setvalue = setvalue;
function size(mat) {
return Math.sqrt(mat.length);
}
Matrix.size = size;
function getTranspose(mat) {
var size = Matrix.size(mat);
var matOut = Matrix.clean(size);
for (var i = 0; i < size; i++) {
Matrix.setColom(matOut, i, Matrix.getRow(mat, i));
}
return matOut;
}
Matrix.getTranspose = getTranspose;
var Mat4;
(function (Mat4) {
function identity() {
return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
}
Mat4.identity = identity;
function mul(mat1, mat2) {
return [
mat1[0] * mat2[0] + mat1[4] * mat2[1] + mat1[8] * mat2[2] + mat1[12] * mat2[3],
mat1[1] * mat2[0] + mat1[5] * mat2[1] + mat1[9] * mat2[2] + mat1[13] * mat2[3],
mat1[2] * mat2[0] + mat1[6] * mat2[1] + mat1[10] * mat2[2] + mat1[14] * mat2[3],
mat1[3] * mat2[0] + mat1[7] * mat2[1] + mat1[11] * mat2[2] + mat1[15] * mat2[3],
mat1[0] * mat2[4] + mat1[4] * mat2[5] + mat1[8] * mat2[6] + mat1[12] * mat2[7],
mat1[1] * mat2[4] + mat1[5] * mat2[5] + mat1[9] * mat2[6] + mat1[13] * mat2[7],
mat1[2] * mat2[4] + mat1[6] * mat2[5] + mat1[10] * mat2[6] + mat1[14] * mat2[7],
mat1[3] * mat2[4] + mat1[7] * mat2[5] + mat1[11] * mat2[6] + mat1[15] * mat2[7],
mat1[0] * mat2[8] + mat1[4] * mat2[9] + mat1[8] * mat2[10] + mat1[12] * mat2[11],
mat1[1] * mat2[8] + mat1[5] * mat2[9] + mat1[9] * mat2[10] + mat1[13] * mat2[11],
mat1[2] * mat2[8] + mat1[6] * mat2[9] + mat1[10] * mat2[10] + mat1[14] * mat2[11],
mat1[3] * mat2[8] + mat1[7] * mat2[9] + mat1[11] * mat2[10] + mat1[15] * mat2[11],
mat1[0] * mat2[12] + mat1[4] * mat2[13] + mat1[8] * mat2[14] + mat1[12] * mat2[15],
mat1[1] * mat2[12] + mat1[5] * mat2[13] + mat1[9] * mat2[14] + mat1[13] * mat2[15],
mat1[2] * mat2[12] + mat1[6] * mat2[13] + mat1[10] * mat2[14] + mat1[14] * mat2[15],
mat1[3] * mat2[12] + mat1[7] * mat2[13] + mat1[11] * mat2[14] + mat1[15] * mat2[15]
];
}
Mat4.mul = mul;
function translate(p1, p2, p3) {
if (typeof p3 == "number") {
var x = p2;
var y = p3;
var mat = p1;
var newColom = Vector.Vec4.create(mat[0] * x + mat[4] * y + mat[12], mat[1] * x + mat[5] * y + mat[13], mat[2] * x + mat[6] * y + mat[14], mat[3] * x + mat[7] * y + mat[15]);
return setColom(mat, 3, newColom);
}
else {
var x = p1;
var y = p2;
return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, 0, 1];
}
}
Mat4.translate = translate;
function scale(p1, p2, p3) {
if (typeof p3 == "number") {
var width = p2;
var height = p3;
var mat = p1;
var newColom1 = Vector.Vec4.create(mat[0] * width, mat[1] * width, mat[2] * width, mat[3] * width);
var newColom2 = Vector.Vec4.create(mat[4] * height, mat[5] * height, mat[6] * height, mat[7] * height);
setColom(mat, 0, newColom1);
setColom(mat, 1, newColom2);
return mat;
}
else {
var width = p1;
var height = p2;
return [width, 0, 0, 0, 0, height, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
}
}
Mat4.scale = scale;
function rotate(p1, p2) {
if (typeof p2 == "number") {
var rad = p2;
var mat = p1;
var newColom1 = Vector.Vec4.create(mat[0] * Math.cos(rad) + mat[4] * Math.sin(rad), mat[1] * Math.cos(rad) + mat[5] * Math.sin(rad), mat[2] * Math.cos(rad) + mat[6] * Math.sin(rad), mat[3] * Math.cos(rad) + mat[7] * Math.sin(rad));
var newColom2 = Vector.Vec4.create(mat[0] * -Math.sin(rad) + mat[4] * Math.cos(rad), mat[1] * -Math.sin(rad) + mat[5] * Math.cos(rad), mat[2] * -Math.sin(rad) + mat[6] * Math.cos(rad), mat[3] * -Math.sin(rad) + mat[7] * Math.cos(rad));
setColom(mat, 0, newColom1);
setColom(mat, 1, newColom2);
return mat;
}
else {
var rad = p1;
return [Math.cos(rad), Math.sin(rad), 0, 0, -Math.sin(rad), Math.cos(rad), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
}
}
Mat4.rotate = rotate;
function ortho(left, right, bottom, top) {
return [2 / (right - left), 0, 0, 0, 0, 2 / (top - bottom), 0, 0, 0, 0, -2 / (-1 - 1), 0, -(right + left) / (right - left), -(top + bottom) / (top - bottom), -(-1 + 1) / (-1 - 1), 1];
}
Mat4.ortho = ortho;
})(Mat4 = Matrix.Mat4 || (Matrix.Mat4 = {}));
var Mat3;
(function (Mat3) {
function identity() {
return [1, 0, 0, 0, 1, 0, 0, 0, 1];
}
Mat3.identity = identity;
function mul(mat1, mat2) {
return [
mat1[0] * mat2[0] + mat1[3] * mat2[1] + mat1[6] * mat2[2],
mat1[1] * mat2[0] + mat1[4] * mat2[1] + mat1[7] * mat2[2],
mat1[2] * mat2[0] + mat1[5] * mat2[1] + mat1[8] * mat2[2],
mat1[0] * mat2[3] + mat1[3] * mat2[4] + mat1[6] * mat2[5],
mat1[1] * mat2[3] + mat1[4] * mat2[4] + mat1[7] * mat2[5],
mat1[2] * mat2[3] + mat1[5] * mat2[4] + mat1[8] * mat2[5],
mat1[0] * mat2[6] + mat1[3] * mat2[7] + mat1[6] * mat2[8],
mat1[1] * mat2[6] + mat1[4] * mat2[7] + mat1[7] * mat2[8],
mat1[2] * mat2[6] + mat1[5] * mat2[7] + mat1[8] * mat2[8],
];
}
Mat3.mul = mul;
})(Mat3 = Matrix.Mat3 || (Matrix.Mat3 = {}));
var Mat2;
(function (Mat2) {
function identity() {
return [1, 0, 0, 1];
}
Mat2.identity = identity;
function mul(mat1, mat2) {
return [
mat1[0] * mat2[0] + mat1[2] * mat2[1],
mat1[1] * mat2[0] + mat1[3] * mat2[1],
mat1[0] * mat2[2] + mat1[2] * mat2[3],
mat1[1] * mat2[2] + mat1[3] * mat2[3],
];
}
Mat2.mul = mul;
})(Mat2 = Matrix.Mat2 || (Matrix.Mat2 = {}));
})(Matrix || (Matrix = {}));
var MMath;
(function (MMath) {
var SEED = 0;
var TO_RAD = (Math.PI * 2) / 360;
var TO_DEG = 360 / (Math.PI * 2);
function setRandomSeed(seed) {
SEED = seed;
}
MMath.setRandomSeed = setRandomSeed;
function random(min, max) {
if (min === void 0) { min = 0; }
if (max === void 0) { max = 1; }
SEED = (SEED * 9301 + 49297) % 233280;
var rnd = SEED / 233280;
return min + rnd * (max - min);
}
MMath.random = random;
function toRad(deg) {
return deg * TO_RAD;
}
MMath.toRad = toRad;
function toDeg(rad) {
return rad * TO_DEG;
}
MMath.toDeg = toDeg;
function mod(num, max) {
return ((num % max) + max) % max;
}
MMath.mod = mod;
function logN(base, num) {
return Math.log(num) / Math.log(base);
}
MMath.logN = logN;
function isPowerOf2(n) {
if (n == 0)
return false;
else
return (n & (n - 1)) == 0;
}
MMath.isPowerOf2 = isPowerOf2;
})(MMath || (MMath = {}));
//# sourceMappingURL=math.js.map |
'use strict';
/*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
const
$C = require('collection.js');
const
{getThemes} = include('build/ds'),
{getThemedPathChunks, checkDeprecated} = include('build/stylus/ds/helpers');
/**
* Returns a function to register Stylus plugins by the specified options
*
* @param {DesignSystem} ds - design system object prepared to use with Stylus
* @param {!Object} cssVariables - dictionary of CSS variables
* @param {boolean=} [useCSSVarsInRuntime] - true, if the design system object values provided
* to style files as css-variables
*
* @param {string=} [theme] - current theme value
* @param {(Array<string>|boolean)=} [includeThemes] - list of themes to include or
* `true` (will include all available themes)
*
* @param {Object=} [stylus] - link to a Stylus package instance
* @returns {!Function}
*/
module.exports = function getPlugins({
ds,
cssVariables,
useCSSVarsInRuntime,
theme,
includeThemes,
stylus = require('stylus')
}) {
const
isBuildHasTheme = Object.isString(theme),
themedFields = $C(ds).get('meta.themedFields') || undefined;
let
buildThemes = includeThemes;
if (!buildThemes) {
buildThemes = isBuildHasTheme ? [theme] : [];
}
const
themesList = getThemes(ds.raw, buildThemes),
isThemesIncluded = themesList != null && themesList.length > 0,
isOneTheme = Object.isArray(themesList) && themesList.length === 1 && themesList[0] === theme;
if (!isThemesIncluded) {
if (Object.isString(theme)) {
console.log(`[stylus] Warning: the design system package has no theme "${theme}"`);
}
if (includeThemes != null) {
console.log(
`[stylus] Warning: the design system package has no themes for the provided "includeThemes" value: "${includeThemes}"`
);
}
}
const
isFieldThemed = (name) => Object.isArray(themedFields) ? themedFields.includes(name) : true;
return function addPlugins(api) {
/**
* Injects additional options to component mixin options ($p)
*
* @param {string} string - component name
* @returns {!Object}
*
* @example
* ```stylus
* injector('bButton')
*
* // If `useCSSVarsInRuntime` is enabled
* //
* // {
* // values: {
* // mods: {
* // size: {
* // s: {
* // offset: {
* // top: 'var(--bButton-mods-size-s-offset-top)'
* // }
* // }
* // }
* // }
* // }
*
* // Otherwise
* //
* // {
* // values: {
* // mods: {
* // size: {
* // s: {
* // offset: {
* // top: 5px
* // }
* // }
* // }
* // }
* // }
* ```
*/
api.define('injector', ({string}) => {
const
values = $C(useCSSVarsInRuntime || isThemesIncluded ? cssVariables : ds).get(`components.${string}`);
if (values) {
const
__diffVars__ = $C(cssVariables).get(`diff.components.${string}`);
return stylus.utils.coerce({
values,
__diffVars__
}, true);
}
return {};
});
/**
* Returns design system CSS variables with their values
*
* @param {string} [theme]
* @returns {!Object}
*
* @example
* ```stylus
* getDSVariables()
*
* // {
* // '--colors-primary': #0F9
* // }
* ```
*/
api.define('getDSVariables', ({string: theme} = {}) => {
const
obj = {},
iterator = Object.isString(theme) ? cssVariables.map[theme] : cssVariables.map;
Object.forEach(iterator, (val) => {
const [key, value] = val;
obj[key] = value;
});
return stylus.utils.coerce(obj, true);
});
/**
* Returns a value from the design system by the specified group and path.
* If passed only the first argument, the function returns parameters for the whole group,
* but not just the one value. If no arguments are passed, it returns the whole design system object.
*
* @param {string} [group] - first level field name (colors, rounding, etc.)
* @param {!Object} [path] - dot-delimited path to the value
* @returns {!Object}
*
* @example
* ```stylus
* getDSValue(colors "green.0") // rgba(0, 255, 0, 1)
* ```
*/
api.define('getDSValue', ({string: group} = {}, {string: path} = {}) => {
if (group === undefined) {
return ds;
}
checkDeprecated(ds, group);
const
getCSSVar = () => $C(cssVariables).get([].concat([group], path || []).join('.'));
if (isOneTheme || !isBuildHasTheme) {
return useCSSVarsInRuntime ?
stylus.utils.coerce(getCSSVar()) :
$C(ds).get([].concat(getThemedPathChunks(group, theme, isFieldThemed(group)), path || []).join('.'));
}
return stylus.utils.coerce(getCSSVar());
});
/**
* Returns an object with text styles for the specified style name
*
* @param {string} name
* @returns {!Object}
*
* @example
* ```stylus
* getDSTextStyles(Small)
*
* // Notice, all values are Stylus types
* //
* // {
* // fontFamily: 'Roboto',
* // fontWeight: 400,
* // fontSize: '14px',
* // lineHeight: '16px'
* // }
* ```
*/
api.define('getDSTextStyles', ({string: name}) => {
const
head = 'text',
isThemed = isFieldThemed(head),
path = [...getThemedPathChunks(head, theme, isThemed), name];
checkDeprecated(ds, path);
if (!isOneTheme && isThemesIncluded && isThemed) {
const
initial = $C(ds).get(path);
if (!Object.isDictionary(initial)) {
throw new Error(`getDSTextStyles: the design system has no "${theme}" styles for the specified name: ${name}`);
}
const
res = {};
Object.forEach(initial, (value, key) => {
res[key] = $C(cssVariables).get([head, name, key]);
});
return stylus.utils.coerce(res, true);
}
const
from = useCSSVarsInRuntime ? cssVariables : ds;
return stylus.utils.coerce($C(from).get(path), true);
});
/**
* Returns color(s) from the design system by the specified name and identifier (optional)
*
* @param {!Object} name
* @param {!Object} [id]
* @returns {(!Object|!Array)}
*
* @example
* ```stylus
* getDSColor("blue", 1) // rgba(0, 0, 255, 1)
* ```
*/
api.define('getDSColor', (name, id) => {
name = name.string || name.name;
if (!name) {
return;
}
const
path = isOneTheme ? getThemedPathChunks('colors', theme, isFieldThemed('colors')) : ['colors'];
if (id) {
id = id.string || id.val;
if (Object.isNumber(id)) {
id -= 1;
}
}
path.push(name);
if (id !== undefined) {
path.push(String(id));
}
checkDeprecated(ds, path);
return isThemesIncluded || useCSSVarsInRuntime ?
stylus.utils.coerce($C(cssVariables).get(path)) :
$C(ds).get(path);
});
/**
* Returns the current theme value
* @returns {!string}
*/
api.define('defaultTheme', () => theme);
/**
* Returns a list of available themes
* @returns {!Array<string>}
*/
api.define('availableThemes', () => themesList);
};
};
|
var model = require('model');
var adapter = require('./..').adapter;
var Issue = function () {
this.adapter = adapter;
this.property('assignees','string');
this.property('htmlUrl','string');
this.property('number','number');
this.property('state','string');
this.property('title','string');
this.property('body','string');
this.property('user','object');
this.property('labels','object');
this.property('assignee','object');
this.property('milestone','object');
this.property('comments','number');
this.property('pullRequest','object');
this.property('closedAt','date');
this.property('createdAt','date');
this.property('updatedAt','date');
this.property('trckrState','string');
this.property('trckrLastReview','date');
this.property('trckrPingback','string'); // ping me back in a specific future
};
model.register('Issue', Issue); |
"use strict";
const RandomStrategy = require("../../../src/strategies/random");
const { extendExpect } = require("../utils");
extendExpect(expect);
describe("Test RandomStrategy", () => {
it("test with empty opts", () => {
const strategy = new RandomStrategy();
const list = [
{ a: "hello" },
{ b: "world" },
];
expect(strategy.select(list)).toBeAnyOf(list);
expect(strategy.select(list)).toBeAnyOf(list);
expect(strategy.select(list)).toBeAnyOf(list);
});
});
|
'use strict';
angular.module('core').controller('HomeController', ['$scope', 'Authentication',
function($scope, Authentication) {
// This provides Authentication context.
$scope.authentication = Authentication;
$scope.alerts = [
{
icon: 'glyphicon-user',
colour: 'btn-success',
total: '20,408',
description: 'TOTAL CUSTOMERS'
},
{
icon: 'glyphicon-calendar',
colour: 'btn-primary',
total: '8,382',
description: 'UPCOMING EVENTS'
},
{
icon: 'glyphicon-edit',
colour: 'btn-success',
total: '527',
description: 'NEW CUSTOMERS IN 24H'
},
{
icon: 'glyphicon-record',
colour: 'btn-info',
total: '85,000',
description: 'EMAILS SENT'
},
{
icon: 'glyphicon-eye-open',
colour: 'btn-warning',
total: '268',
description: 'FOLLOW UPS REQUIRED'
},
{
icon: 'glyphicon-flag',
colour: 'btn-danger',
total: '348',
description: 'REFERRALS TO MODERATE'
}
];
}
]); |
var Vector = function(values) {
// An N-Dimensional vector.
//
// Args:
// values: A list of values for each dimension of the vector.
var self = this;
self.values = values;
self.hash = function() {
// Generate a hash of the vector.
//
// Returns:
// A hash of the vector.
var r = '';
var i;
for (i = 0; i < self.values.length; i++) {
r += String(self.values[i]) + ','
}
return '[' + r + ']';
};
self.copy = function() {
// Get a duplicate vector.
return (new Vector(self.values.slice()));
};
self.divide = function(c) {
// Divide the vector by a constant.
//
// Args:
// c: A constant.
//
// Returns:
// A new vector with each value divided by c.
return self.multiply(1 / c);
};
self.multiply = function(c) {
// Multiply the vector by a constant.
//
// Args:
// c: A constant.
//
// Returns:
// A new vector with each value multiplied by c.
var copy = self.copy();
var i;
for (i = 0; i < self.values.length; i++) {
copy.values[i] *= c;
}
return copy;
};
self.add = function(other) {
// Add another vector to self.
//
// Args:
// other: Another vector.
//
// Returns:
// The resultant vector.
var values = [];
var i;
if (self.dimension() != other.dimension()) {
var msg = "Cannot add two vectors of different dimensionality.";
log(loglevel.error, msg);
throw (new Error(msg));
}
for (i = 0; i < self.values.length; i++) {
values.push(self.values[i] + other.values[i]);
}
return (new Vector(values));
};
self.subtract = function(other) {
// Subtract another vector from self.
//
// Args:
// other: Another vector.
//
// Returns:
// The resultant vector from other to self.
var values = [];
var i;
if (self.dimension() != other.dimension()) {
var msg = "Cannot subtract two vectors of different dimensionality.";
log(loglevel.error, msg);
throw (new Error(msg));
}
for (i = 0; i < self.values.length; i++) {
values.push(self.values[i] - other.values[i]);
}
return (new Vector(values));
};
self.dimension = function() {
// Get the dimension of the vector.
return self.values.length;
};
self.magnitude = function() {
// Get the magnitude of this vector.
var s = 0;
var i;
var dimension = self.dimension();
for (i = 0; i < self.values.length; i++) {
s += Math.pow(self.values[i], dimension)
}
return Math.pow(s, 1 / dimension);
};
self.unit = function() {
// Get a unit vector in the direction of this vector.
return self.divide(self.magnitude());
};
};
|
/**
* Plugin Name: Autocomplete for Textarea
* Author: Amir Harel
* Copyright: amir harel ([email protected])
* Twitter: @amir_harel
* Version 1.4
* Published at : http://www.amirharel.com/2011/03/07/implementing-autocomplete-jquery-plugin-for-textarea/
*/
(function($){
/**
* @param obj
* @attr wordCount {Number} the number of words the user want to for matching it with the dictionary
* @attr mode {String} set "outter" for using an autocomplete that is being displayed in the outter layout of the textarea, as opposed to inner display
* @attr on {Object} containing the followings:
* @attr query {Function} will be called to query if there is any match for the user input
*/
$.fn.autocomplete = function(obj){
if( typeof $.browser.msie != 'undefined' ) obj.mode = 'outter';
this.each(function(index,element){
if( element.nodeName == 'TEXTAREA' ){
makeAutoComplete(element,obj);
}
});
}
var browser = {isChrome: $.browser.webkit };
function getTextAreaSelectionEnd(ta) {
var textArea = ta;//document.getElementById('textarea1');
if (document.selection) { //IE
var bm = document.selection.createRange().getBookmark();
var sel = textArea.createTextRange();
sel.moveToBookmark(bm);
var sleft = textArea.createTextRange();
sleft.collapse(true);
sleft.setEndPoint("EndToStart", sel);
return sleft.text.length + sel.text.length;
}
return textArea.selectionEnd; //ff & chrome
}
function getDefaultCharArray(){
return {
'`':0,
'~':0,
'1':0,
'!':0,
'2':0,
'@':0,
'3':0,
'#':0,
'4':0,
'$':0,
'5':0,
'%':0,
'6':0,
'^':0,
'7':0,
'&':0,
'8':0,
'*':0,
'9':0,
'(':0,
'0':0,
')':0,
'-':0,
'_':0,
'=':0,
'+':0,
'q':0,
'Q':0,
'w':0,
'W':0,
'e':0,
'E':0,
'r':0,
'R':0,
't':0,
'T':0,
'y':0,
'Y':0,
'u':0,
'U':0,
'i':0,
'I':0,
'o':0,
'O':0,
'p':0,
'P':0,
'[':0,
'{':0,
']':0,
'}':0,
'a':0,
'A':0,
's':0,
'S':0,
'd':0,
'D':0,
'f':0,
'F':0,
'g':0,
'G':0,
'h':0,
'H':0,
'j':0,
'J':0,
'k':0,
'K':0,
'l':0,
'L':0,
';':0,
':':0,
'\'':0,
'"':0,
'\\':0,
'|':0,
'z':0,
'Z':0,
'x':0,
'X':0,
'c':0,
'C':0,
'v':0,
'V':0,
'b':0,
'B':0,
'n':0,
'N':0,
'm':0,
'M':0,
',':0,
'<':0,
'.':0,
'>':0,
'/':0,
'?':0,
' ':0
};
}
function setCharSize(data){
for( var ch in data.chars ){
if( ch == ' ' ) $(data.clone).html("<span id='test-width_"+data.id+"' style='line-block'> </span>");
else $(data.clone).html("<span id='test-width_"+data.id+"' style='line-block'>"+ch+"</span>");
var testWidth = $("#test-width_"+data.id).width();
data.chars[ch] = testWidth;
}
}
var _data = {};
var _count = 0;
function makeAutoComplete(ta,obj){
_count++;
_data[_count] = {
id:"auto_"+_count,
ta:ta,
wordCount:obj.wordCount,
wrap: obj.wrap,
on:obj.on,
clone:null,
lineHeight:0,
list:null,
charInLines:{},
mode:obj.mode,
chars:getDefaultCharArray()};
var clone = createClone(_count);
_data[_count].clone = clone;
setCharSize(_data[_count]);
//_data[_count].lineHeight = $(ta).css("font-size");
_data[_count].list = createList(_data[_count]);
registerEvents(_data[_count]);
}
function createList(data){
var ul = document.createElement("ul");
$(ul).addClass("auto-list");
document.body.appendChild(ul);
return ul;
}
function createClone(id){
var data = _data[id];
var div = document.createElement("div");
var offset = $(data.ta).offset();
offset.top = offset.top - parseInt($(data.ta).css("margin-top"));
offset.left = offset.left - parseInt($(data.ta).css("margin-left"));
//console.log("createClone: offset.top=",offset.top," offset.left=",offset.left);
$(div).css({
position:"absolute",
top: offset.top,
left: offset.left,
"overflow-x" : "hidden",
"overflow-y" : "hidden",
"z-index" : -10
});
data.chromeWidthFix = (data.ta.clientWidth - $(data.ta).width());
data.lineHeight = $(data.ta).css("line-height");
if( isNaN(parseInt(data.lineHeight)) ) data.lineHeight = parseInt($(data.ta).css("font-size"))+2;
document.body.appendChild(div);
return div;
}
function getWords(data){
var selectionEnd = getTextAreaSelectionEnd(data.ta);//.selectionEnd;
var text = data.ta.value;
text = text.substr(0,selectionEnd);
if( text.charAt(text.length-1) == ' ' || text.charAt(text.length-1) == '\n' ) return "";
var ret = [];
var wordsFound = 0;
var pos = text.length-1;
while( wordsFound < data.wordCount && pos >= 0 && text.charAt(pos) != '\n'){
ret.unshift(text.charAt(pos));
pos--;
if( text.charAt(pos) == ' ' || pos < 0 ){
wordsFound++;
}
}
return ret.join("");
}
function showList(data,list,text){
if( !data.listVisible ){
data.listVisible = true;
var pos = getCursorPosition(data);
$(data.list).css({
left: pos.left+"px",
top: pos.top+"px",
display: "block"
});
}
var html = "";
var regEx = new RegExp("("+text+")");
var taWidth = $(data.ta).width()-5;
var width = data.mode == "outter" ? "style='width:"+taWidth+"px;'" : "";
for( var i=0; i< list.length; i++ ){
//var a = list[i].replace(regEx,"<mark>$1</mark>");
html += "<li data-value='"+list[i]+"' "+width+">"+list[i].replace(regEx,"<mark>$1</mark>")+"</li>";
}
$(data.list).html(html);
}
function breakLines(text,data){
var lines = [];
var width = $(data.clone).width();
var line1 = "";
var line1Width = 0;
var line2Width = 0;
var line2 = "";
var chSize = data.chars;
var len = text.length;
for( var i=0; i<len; i++){
var ch = text.charAt(i);
line2 += ch.replace(" "," ");
var size = (typeof chSize[ch] == 'undefined' ) ? 0 : chSize[ch];
line2Width += size;
if( ch == ' '|| ch == '-' ){
if( line1Width + line2Width < width-1 ){
line1 = line1 + line2;
line1Width = line1Width + line2Width;
line2 = "";
line2Width = 0;
}
else{
lines.push(line1);
line1= line2;
line1Width = line2Width;
line2= "";
line2Width = 0;
}
}
if( ch == '\n'){
if( line1Width + line2Width < width-1 ){
lines.push(line1 + line2);
}
else{
lines.push(line1);
lines.push(line2);
}
line1 = "";
line2 = "";
line1Width = 0;
line2Width = 0;
}
//else{
//line2 += ch;
//}
}
if( line1Width + line2Width < width-1 ){
lines.push(line1 + line2);
}
else{
lines.push(line1);
lines.push(line2);
}
return lines;
}
function getCursorPosition(data){
if( data.mode == "outter" ){
return getOuterPosition(data);
}
//console.log("getCursorPosition: ta width=",$(data.ta).css("width")," ta clientWidth=",data.ta.clientWidth, "scrollWidth=",data.ta.scrollWidth," offsetWidth=",data.ta.offsetWidth," jquery.width=",$(data.ta).width());
if( browser.isChrome ){
$(data.clone).width(data.ta.clientWidth-data.chromeWidthFix);
}
else{
$(data.clone).width(data.ta.clientWidth);
}
var ta = data.ta;
var selectionEnd = getTextAreaSelectionEnd(data.ta);
var text = ta.value;//.replace(/ /g," ");
var subText = text.substr(0,selectionEnd);
var restText = text.substr(selectionEnd,text.length);
var lines = breakLines(subText,data);//subText.split("\n");
var miror = $(data.clone);
miror.html("");
for( var i=0; i< lines.length-1; i++){
miror.append("<div style='height:"+(parseInt(data.lineHeight))+"px"+";'>"+lines[i]+"</div>");
}
miror.append("<span id='"+data.id+"' style='display:inline-block;'>"+lines[lines.length-1]+"</span>");
miror.append("<span id='rest' style='max-width:'"+data.ta.clientWidth+"px'>"+restText.replace(/\n/g,"<br/>")+" </span>");
miror.get(0).scrollTop = ta.scrollTop;
var span = miror.children("#"+data.id);
var offset = span.offset();
return {top:offset.top+span.height(),left:offset.left+span.width()};
}
function getOuterPosition(data){
var offset = $(data.ta).offset();
return {top:offset.top+$(data.ta).height()+8,left:offset.left};
}
function hideList(data){
if( data.listVisible ){
$(data.list).css("display","none");
data.listVisible = false;
}
}
function setSelected(dir,data){
var selected = $(data.list).find("[data-selected=true]");
if( selected.length != 1 ){
if( dir > 0 ) $(data.list).find("li:first-child").attr("data-selected","true");
else $(data.list).find("li:last-child").attr("data-selected","true");
return;
}
selected.attr("data-selected","false");
if( dir > 0 ){
selected.next().attr("data-selected","true");
}
else{
selected.prev().attr("data-selected","true");
}
}
function getCurrentSelected(data){
var selected = $(data.list).find("[data-selected=true]");
if( selected.length == 1) return selected.get(0);
return null;
}
function onUserSelected(li,data){
var seletedText = $(li).attr("data-value");
var selectionEnd = getTextAreaSelectionEnd(data.ta);//.selectionEnd;
var text = data.ta.value;
text = text.substr(0,selectionEnd);
//if( text.charAt(text.length-1) == ' ' || text.charAt(text.length-1) == '\n' ) return "";
//var ret = [];
var wordsFound = 0;
var pos = text.length-1;
while( wordsFound < data.wordCount && pos >= 0 && text.charAt(pos) != '\n'){
//ret.unshift(text.charAt(pos));
pos--;
if( text.charAt(pos) == ' ' || pos < 0 ){
wordsFound++;
}
}
var a = data.ta.value.substr(0,pos+1);
var c = data.ta.value.substr(selectionEnd,data.ta.value.length);
var scrollTop = data.ta.scrollTop;
if(data.wrap.length > 0){
seletedText = "["+data.wrap+"]"+seletedText+"[/"+data.wrap+"] ";
}
data.ta.value = a+seletedText+c;
data.ta.scrollTop = scrollTop;
data.ta.selectionEnd = pos+1+seletedText.length;
hideList(data);
$(data.ta).focus();
}
function registerEvents(data){
$(data.list).delegate("li","click",function(e){
var li = this;
onUserSelected(li,data);
e.stopPropagation();
e.preventDefault();
return false;
});
$(data.ta).blur(function(e){
setTimeout(function(){
hideList(data);
},400);
});
$(data.ta).click(function(e){
hideList(data);
});
$(data.ta).keydown(function(e){
//console.log("keydown keycode="+e.keyCode);
if( data.listVisible ){
switch(e.keyCode){
case 13:
case 40:
case 38:
e.stopImmediatePropagation();
e.preventDefault();
return false;
case 27: //esc
hideList(data);
}
}
});
$(data.ta).keyup(function(e){
if( data.listVisible ){
//console.log("keCode=",e.keyCode);
if( e.keyCode == 40 ){//down key
setSelected(+1,data);
e.stopImmediatePropagation();
e.preventDefault();
return false;
}
if( e.keyCode == 38 ){//up key
setSelected(-1,data);
e.stopImmediatePropagation();
e.preventDefault();
return false;
}
if( e.keyCode == 13 ){//enter key
var li = getCurrentSelected(data);
if( li ){
e.stopImmediatePropagation();
e.preventDefault();
hideList(data);
onUserSelected(li,data);
return false;
}
hideList(data);
}
if( e.keyCode == 27 ){
e.stopImmediatePropagation();
e.preventDefault();
return false;
}
}
switch( e.keyCode ){
case 27:
return true;
}
var text = getWords(data);
//console.log("getWords return ",text);
if( text != "" ){
data.on.query(text,function(list){
//console.log("got list = ",list);
if( list.length ){
showList(data,list,text);
}
else{
hideList(data);
}
});
}
else{
hideList(data);
}
});
$(data.ta).scroll(function(e){
var ta = e.target;
var miror = $(data.clone);
miror.get(0).scrollTop = ta.scrollTop;
});
}
})(jQuery);
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = fn;
var _includes = require('utilise/includes');
var _includes2 = _interopRequireDefault(_includes);
var _client = require('utilise/client');
var _client2 = _interopRequireDefault(_client);
var _all = require('utilise/all');
var _all2 = _interopRequireDefault(_all);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// register custom element prototype (render is automatic)
function fn(ripple) {
return function (res) {
if (!customs || !customEl(res) || registered(res)) return (0, _all2.default)(res.name + ':not([inert])\n ,[is="' + res.name + '"]:not([inert])').map(ripple.draw);
var proto = Object.create(HTMLElement.prototype),
opts = { prototype: proto };
proto.attachedCallback = ripple.draw;
document.registerElement(res.name, opts);
};
}
var registered = function registered(res) {
return document.createElement(res.name).attachedCallback;
};
var customs = _client2.default && !!document.registerElement,
customEl = function customEl(d) {
return (0, _includes2.default)('-')(d.name);
}; |
'use strict';
/* jshint -W098 */
angular.module('mean.rules').controller('RulesController', ['$scope', '$stateParams', '$location', '$http','Global', 'Rules', 'MeanUser','Circles','Groups',
function($scope, $stateParams, $location, $http, Global, Rules, MeanUser,Circles,Groups) {
$scope.global = Global;
$scope.rules = {};
$scope.rule = {};
$scope.groups={};
$scope.sortType = 'name'; // set the default sort type
$scope.sortReverse = false; // set the default sort order
$scope.searchFish = ''; // set the default search/filter term
$scope.hasAuthorization = function(rule) {
if (!rule || !rule.user) return false;
return MeanUser.isAdmin || rule.user._id === MeanUser.user._id;
};
$scope.popup1 = {
opened: false
};
$scope.testdataerror=false;
$scope.popup2 = {
opened: false
};
$scope.testdataresult='';
$scope.openpicker1 = function() {
$scope.popup1.opened = true;
};
$scope.openpicker2 = function() {
$scope.popup2.opened = true;
};
$scope.availableCircles = [];
Circles.mine(function(acl) {
$scope.availableCircles = acl.allowed;
$scope.allDescendants = acl.descendants;
});
$scope.showDescendants = function(permission) {
var temp = $('.ui-select-container .btn-primary').text().split(' ');
temp.shift(); //remove close icon
var selected = temp.join(' ');
$scope.descendants = $scope.allDescendants[selected];
};
$scope.selectPermission = function() {
$scope.descendants = [];
};
$scope.create = function(isValid) {
if (isValid) {
// $scope.article.permissions.push('test test');
var rule = new Rules($scope.rule);
rule.$save(function(response) {
$location.path('rules/' + response._id);
});
$scope.rules = {};
} else {
$scope.submitted = true;
}
};
$scope.remove = function(rule) {
if (rule) {
rule.$remove(function(response) {
for (var i in $scope.rules) {
if ($scope.rules[i] === rule) {
$scope.rules.splice(i, 1);
}
}
$location.path('rules');
});
} else {
$scope.rules.$remove(function(response) {
$location.path('rules');
});
}
};
$scope.update = function(isValid) {
if (isValid) {
var rule = $scope.rule;
if (!rule.updated) {
rule.updated = [];
}
rule.updated.push(new Date().getTime());
rule.$update(function() {
$location.path('rules/' + rule._id);
});
} else {
$scope.submitted = true;
}
};
$scope.findGroups = function() {
Groups.query(function(groups) {
$scope.groups = groups;
});
};
$scope.find = function() {
Rules.query(function(rules) {
$scope.rules = rules;
});
};
$scope.findOne = function() {
Rules.get({
ruleId: $stateParams.ruleId
}, function(rule) {
$scope.rule = rule;
});
};
$scope.documentupdate = function(testdata) {
$scope.testdataerror=false;
try{
testdata = JSON.parse(testdata);
} catch (ex) {
$scope.testdataerror=true;
}
}
$scope.cmdtestdata = function (testdata,execIf,execThen,execElse) {
var td={};
$scope.testdataerror=false;
try{
td = JSON.parse(testdata);
} catch (ex) {
$scope.testdataerror=true;
return;
}
$scope.testdataresult = '';
$http({
method: 'PUT',
url: '/api/rulesprocessor/testdata' ,
headers: {
'Content-Type': 'application/json'
},
data: {
"document": td,
"execIf":execIf,
"execThen":execThen,
"execElse":execElse
}
}).then(function successCallback(response) {
if (response.data === undefined) {
$scope.testdataresult = '';
} else {
$scope.testdataresult = '' +
'IF() evaluated to: ' + response.data.resExecIf.var0 +
'\nThen() evaluated to: ' + JSON.stringify(response.data.resExecThen) +
'\nElse() evaluated to: ' + JSON.stringify(response.data.resExecElse);
}
}, function errorCallback(response) {
$scope.testdataresult = 'Error: (HTTP ' + response.status + ') ' + response.data.error;
});
}
}
]); |
var utilities = (function(window, $){
/**
* Draws a rounded rectangle using the current state of the canvas.
* If you omit the last three params, it will draw a rectangle
* outline with a 5 pixel border radius
* @param {CanvasRenderingContext2D} ctx
* @param {Number} x The top left x coordinate
* @param {Number} y The top left y coordinate
* @param {Number} width The width of the rectangle
* @param {Number} height The height of the rectangle
* @param {Number} radius The corner radius. Defaults to 5;
* @param {Boolean} fill Whether to fill the rectangle. Defaults to false.
* @param {Boolean} stroke Whether to stroke the rectangle. Defaults to true.
*/
function roundRect(ctx, x, y, width, height, radius, fill, stroke) {
if (typeof stroke == "undefined" ) {
stroke = true;
}
if (typeof radius === "undefined") {
radius = 5;
}
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
if (stroke) {
ctx.stroke();
}
if (fill) {
ctx.fill();
}
}
/**
* Draws a rounded rectangle using the current state of the canvas.
* If you omit the last three params, it will draw a rectangle
* outline with a 5 pixel border radius
* @param {CanvasRenderingContext2D} ctx
* @param {Number} x The top left x coordinate
* @param {Number} y The top left y coordinate
* @param {Number} width The width of the rectangle
* @param {Number} height The height of the rectangle
* @param {Number} radius The corner radius. Defaults to 5;
* @param {Boolean} fill Whether to fill the rectangle. Defaults to false.
* @param {Boolean} stroke Whether to stroke the rectangle. Defaults to true.
*/
function topHalfRoundRect(ctx, x, y, width, height, radius, fill, stroke) {
if (typeof stroke == "undefined" ) {
stroke = true;
}
if (typeof radius === "undefined") {
radius = 5;
}
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + width, y);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y);
ctx.closePath();
if (stroke) {
ctx.stroke();
}
if (fill) {
ctx.fill();
}
}
/**
* Draws a rounded rectangle using the current state of the canvas.
* If you omit the last three params, it will draw a rectangle
* outline with a 5 pixel border radius
* @param {CanvasRenderingContext2D} ctx
* @param {Number} x The top left x coordinate
* @param {Number} y The top left y coordinate
* @param {Number} width The width of the rectangle
* @param {Number} height The height of the rectangle
* @param {Number} radius The corner radius. Defaults to 5;
* @param {Boolean} fill Whether to fill the rectangle. Defaults to false.
* @param {Boolean} stroke Whether to stroke the rectangle. Defaults to true.
*/
function bottomHalfRoundRect(ctx, x, y, width, height, radius, fill, stroke) {
if (typeof stroke == "undefined" ) {
stroke = true;
}
if (typeof radius === "undefined") {
radius = 5;
}
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height);
ctx.lineTo(x, y + height);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
if (stroke) {
ctx.stroke();
}
if (fill) {
ctx.fill();
}
}
return {
drawRoundRect: roundRect,
drawTopHalfRoundRect: topHalfRoundRect,
drawBottomHalfRoundRect: bottomHalfRoundRect
}
})(window, $); |
var c = require("./config").twitter;
var Twit = require('twit');
//console.log(c);
console.log(c.apiKey);
console.log(c.apiSecret);
console.log(c.accessToken);
console.log(c.accessTokenSecret);
var T = new Twit({
consumer_key: c.apiKey,
consumer_secret: c.apiSecret,
access_token: c.accessToken,
access_token_secret: c.accessTokenSecret
});
/*
T.post('statuses/update', { status: 'hello world!' }, function(err, data, response) {
console.log(err);
})
*/
//console.log(T);
//
// tweet 'hello world!'
//
T.get('search/tweets', { q: 'banana since:2011-11-11', count: 100 }, function(err, data, res) {
console.log(data);
//console.log(err);
//console.log(res);
});
|
// These are the pages you can go to.
// They are all wrapped in the App component, which should contain the navbar etc
// See http://blog.mxstbr.com/2016/01/react-apps-with-pages for more information
// about the code splitting business
import { getAsyncInjectors } from './utils/asyncInjectors';
const errorLoading = (err) => {
console.error('Dynamic page loading failed', err); // eslint-disable-line no-console
};
const loadModule = (cb) => (componentModule) => {
cb(null, componentModule.default);
};
export default function createRoutes(store) {
// create reusable async injectors using getAsyncInjectors factory
const { injectReducer, injectSagas } = getAsyncInjectors(store);
return [
{
path: '/',
name: 'home',
getComponent(nextState, cb) {
const importModules = Promise.all([
import('containers/HomePage/reducer'),
import('containers/HomePage/sagas'),
import('containers/HomePage'),
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('home', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '/features',
name: 'features',
getComponent(nextState, cb) {
import('containers/FeaturePage')
.then(loadModule(cb))
.catch(errorLoading);
},
}, {
path: '/login',
name: 'login',
getComponent(nextState, cb) {
const importModules = Promise.all([
import('containers/LoginPage/reducer'),
import('containers/LoginPage/sagas'),
import('containers/LoginPage'),
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('loginPage', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '/signup',
name: 'signup',
getComponent(nextState, cb) {
const importModules = Promise.all([
import('containers/SignupPage/reducer'),
import('containers/SignupPage/sagas'),
import('containers/SignupPage'),
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('signupPage', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '/restorepassword',
name: 'restorepassword',
getComponent(nextState, cb) {
const importModules = Promise.all([
import('containers/PasswordRestorePage/reducer'),
import('containers/PasswordRestorePage/sagas'),
import('containers/PasswordRestorePage'),
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('passwordRestorePage', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '/trackingpage',
name: 'trackingpage',
getComponent(nextState, cb) {
const importModules = Promise.all([
import('containers/TrackingPage/reducer'),
import('containers/TrackingPage/sagas'),
import('containers/TrackingPage'),
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('trackingPage', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '/userprofile',
name: 'userprofilepage',
getComponent(nextState, cb) {
const importModules = Promise.all([
import('containers/UserProfilePage/reducer'),
import('containers/UserProfilePage/sagas'),
import('containers/UserProfilePage'),
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('userProfilePage', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '*',
name: 'notfound',
getComponent(nextState, cb) {
import('containers/NotFoundPage')
.then(loadModule(cb))
.catch(errorLoading);
},
},
];
}
|
/**
* Fac.js
* (c) 2017 Owen Luke
* https://github.com/tasjs/fac
* Released under the MIT License.
*/
var copy = require('./copy');
var chain = require('./chain');
var super_ = require('./super');
var core = {
new: function(options){
typeof options === 'string' && (options = {name: options});
var obj = chain.create(this, options);
obj.protoName = this.name;
obj.model = this;
obj.super = super_;
chain.init(obj.parent, options, obj);
return obj;
},
extends: function(proto, p1){
var obj = chain.create(this, {});
var options = proto;
if (typeof p1 !== 'undefined') {
var args = Array.prototype.slice.call(arguments);
for (var i = 0, len = args.length - 1; i < len; i ++) {
options = args[i];
copy.do(obj, options);
}
options = args[i];
}
copy.do(obj, options);
obj.protoName = options.name;
obj.super = super_;
typeof options.default === 'function' && options.default.call(obj, options);
return obj;
},
ext: function(options){
copy.do(this, options);
return this;
},
spawn: function(options) {
typeof options === 'string' && (options = {name: options});
var obj = Object.create(this);
copy.do(obj, options);
chain.init(this, options, obj);
return obj;
},
isChildOf: function(obj){
return chain.isChildOf(obj, this);
},
isParentOf: function(obj){
return chain.isParentOf(obj, this);
},
isAncestorOf: function(obj){
return chain.isAncestorOf(obj, this);
},
isDescendantOf: function(obj){
return chain.isDescendantOf(obj, this);
},
isModelOf: function(obj){
return this === obj.model;
},
isCopyOf: function(obj){
return this.model === obj;
}
};
module.exports = core;
|
const express = require('express');
const path = require('path');
const fs = require('fs');
const bodyParser = require('body-parser')
// const formidable = require('formidable');
// const createTorrent = require('create-torrent');
// const WebTorrent = require('webtorrent');
const socketController = require('./socketController');
// max # of sockets to keep open
const socketLimit = 1;
// takes in Node Server instance and returns Express Router
module.exports = function nileServer(server) {
// Pass server instance to use socket controller
const socket = new socketController(server, socketLimit);
// create nile.js mini-app through express Router
const nileServer = express.Router();
// endpoint for receiving magnet URI from Broadcaster
nileServer.post('/magnet', (req, res, next) => {
socket.emitNewMagnet(req.body.magnetURI);
res.sendStatus(200);
});
return nileServer;
} |
const path = require('path')
module.exports = {
context: __dirname,
entry: './js/ClientApp.js',
devtool: 'eval',
output: {
path: path.join(__dirname, '/public'),
publicPath: '/public/',
filename: 'bundle.js'
},
devServer: {
publicPath: '/public/',
historyApiFallback: true
},
resolve: {
extensions: ['.js', '.json']
},
stats: {
colors: true,
reasons: true,
chunks: true
},
module: {
rules: [
{
enforce: 'pre',
test: /\.js$/,
loader: 'eslint-loader',
exclude: /node_modlues/
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
include: path.resolve(__dirname, 'js'),
test: /\.js$/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
url: false
}
}
]
},
{
test: /\.scss$/,
loader: 'style-loader!css-loader!autoprefixer-loader!sass-loader'
},
{
test: /\.otf$/,
loader: 'file-loader?name=fonts/[name].[ext]'
}
]
}
}
|
import SqSortableList from 'sq-ember-inputs/components/sq-sortable-list';
export default SqSortableList;
|
(function() {
"use strict";
angular.module('common.dragdrop', [])
.factory('DragDropHandler', [function() {
return {
dragObject: undefined,
addObject: function(object, objects, to) {
objects.splice(to, 0, object);
},
moveObject: function(objects, from, to) {
objects.splice(to, 0, objects.splice(from, 1)[0]);
}
};
}])
.directive('draggable', ['DragDropHandler', function(DragDropHandler) {
return {
scope: {
draggable: '='
},
link: function(scope, element, attrs){
element.draggable({
connectToSortable: attrs.draggableTarget,
helper: "clone",
revert: "invalid",
start: function() {
DragDropHandler.dragObject = scope.draggable;
},
stop: function() {
DragDropHandler.dragObject = undefined;
}
});
element.disableSelection();
}
};
}])
.directive('droppable', ['DragDropHandler', function(DragDropHandler) {
return {
scope: {
droppable: '=',
ngMove: '&',
ngCreate: '&'
},
link: function(scope, element, attrs){
element.sortable({
connectWith: ['.draggable','.sortable'],
});
element.disableSelection();
element.on("sortdeactivate", function(event, ui) {
var from = (angular.element(ui.item).scope()) ? angular.element(ui.item).scope().$index : undefined;
var to = element.children().index(ui.item);
var list = element.attr('id');
if (to >= 0 ){
scope.$apply(function(){
if (from >= 0) {
//item is coming from a sortable
if (!ui.sender || ui.sender[0] === element[0]) {
//item is coming from this sortable
DragDropHandler.moveObject(scope.droppable, from, to);
} else {
//item is coming from another sortable
scope.ngMove({
from: from,
to: to,
fromList: ui.sender.attr('id'),
toList: list
});
ui.item.remove();
}
} else {
//item is coming from a draggable
scope.ngCreate({
object: DragDropHandler.dragObject,
to: to,
list: list
});
ui.item.remove();
}
});
}
});
}
};
}])
;})();
|
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _functionalCurry = require('../functional/curry');
var lt = (0, _functionalCurry.curry)(function (a, b) {
return a < b;
});
exports.lt = lt; |
/**
* Blog-api.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/#!documentation/models
*/
module.exports = {
attributes: {
}
};
|
/**
* Palindromic Substrings
*
* Given a string, your task is to count how many palindromic substrings in this string.
*
* The substrings with different start indexes or end indexes are counted as different substrings even they consist of
* same characters.
*
* Example 1:
*
* Input: "abc"
* Output: 3
* Explanation: Three palindromic strings: "a", "b", "c".
*
* Example 2:
*
* Input: "aaa"
* Output: 6
* Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
*
* Note:
* The input string length won't exceed 1000.
*/
/**
* @param {string} s
* @return {number}
*/
const countSubstrings = s => {
const extendPalindrome = (s, left, right) => {
while (left >= 0 && right < s.length && s[left] === s[right]) {
count++;
left--;
right++;
}
};
if (!s || s.length === 0) {
return 0;
}
let count = 0;
for (let i = 0; i < s.length; i++) {
// i is the mid point
extendPalindrome(s, i, i); // odd length;
extendPalindrome(s, i, i + 1); // even length
}
return count;
};
export { countSubstrings };
|
jest.unmock('../../src/filtering/filter');
import React from 'react';
import {shallow} from 'enzyme';
import {Filter} from '../../src/filtering/filter';
describe('Filter', () => {
it('has empty filtering text by default', () => {
// when
const filter = shallow(
<Filter/>
);
// then
expect(filter.props().value).toEqual('');
});
it('changes provided filtering text', () => {
// given
const state = {
textToUse : 'abc'
};
const filter = shallow(
<Filter filteringText={state.textToUse}
onFilteringTextChange={text => state.textToUse = text}/>
);
// when
filter.simulate('change', { target : { value : 'def' } });
expect(state.textToUse).toEqual('def');
});
}); |
/* eslint-env jest */
import fs from 'fs-extra'
import { join } from 'path'
import {
killApp,
findPort,
launchApp,
nextStart,
nextBuild,
fetchViaHTTP,
} from 'next-test-utils'
import webdriver from 'next-webdriver'
import cheerio from 'cheerio'
jest.setTimeout(1000 * 60 * 2)
const appDir = join(__dirname, '../')
const gip404Err = /`pages\/404` can not have getInitialProps\/getServerSideProps/
let appPort
let app
describe('404 Page Support with _app', () => {
describe('production mode', () => {
afterAll(() => killApp(app))
it('should build successfully', async () => {
const { code, stderr, stdout } = await nextBuild(appDir, [], {
stderr: true,
stdout: true,
})
expect(code).toBe(0)
expect(stderr).not.toMatch(gip404Err)
expect(stdout).not.toMatch(gip404Err)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
it('should not output static 404 if _app has getInitialProps', async () => {
const browser = await webdriver(appPort, '/404')
const isAutoExported = await browser.eval('__NEXT_DATA__.autoExport')
expect(isAutoExported).toBe(null)
})
it('specify to use the 404 page still in the routes-manifest', async () => {
const manifest = await fs.readJSON(
join(appDir, '.next/routes-manifest.json')
)
expect(manifest.pages404).toBe(true)
})
it('should still use 404 page', async () => {
const res = await fetchViaHTTP(appPort, '/abc')
expect(res.status).toBe(404)
const $ = cheerio.load(await res.text())
expect($('#404-title').text()).toBe('Hi There')
})
})
describe('dev mode', () => {
let stderr = ''
let stdout = ''
beforeAll(async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort, {
onStderr(msg) {
stderr += msg
},
onStdout(msg) {
stdout += msg
},
})
})
afterAll(() => killApp(app))
it('should not show pages/404 GIP error if _app has GIP', async () => {
const res = await fetchViaHTTP(appPort, '/abc')
expect(res.status).toBe(404)
const $ = cheerio.load(await res.text())
expect($('#404-title').text()).toBe('Hi There')
expect(stderr).not.toMatch(gip404Err)
expect(stdout).not.toMatch(gip404Err)
})
})
})
|
'use strict';
const sinon = require('sinon'),
q = require('q'),
mockery = require('mockery'),
_ = require('lodash'),
should = require('chai').should();
describe('Create episode', () => {
const idsGeneratorStub = () => '123';
it('Should call the next callback', done => {
let deferred = q.defer();
let promise = deferred.promise;
let persistEpisodeInStorage = sinon.stub();
persistEpisodeInStorage.returns(promise);
const createEpisode = getCreateEpisodeMiddleware(idsGeneratorStub, persistEpisodeInStorage);
createEpisode(mockRequest('book-id-123'), mockResponse(), done);
deferred.resolve();
});
it('Should return 201 created', done => {
const responseMock = mockResponse();
const responseSpy = sinon.spy(responseMock, 'json');
let deferred = q.defer();
let promise = deferred.promise;
let persistEpisodeInStorage = sinon.stub();
persistEpisodeInStorage.returns(promise);
const createEpisode = getCreateEpisodeMiddleware(idsGeneratorStub, persistEpisodeInStorage);
createEpisode(mockRequest('book-id-123'), responseMock, checkResponse);
function checkResponse() {
responseSpy.args[0][0].should.equal(201);
done();
}
deferred.resolve();
});
it('Should return an id property with the scenario id', done => {
const responseMock = mockResponse();
const responseSpy = sinon.spy(responseMock, 'json');
let deferred = q.defer();
let promise = deferred.promise;
let persistEpisodeInStorage = sinon.stub();
persistEpisodeInStorage.returns(promise);
const createEpisode = getCreateEpisodeMiddleware(idsGeneratorStub, persistEpisodeInStorage);
createEpisode(mockRequest('book-id-123'), responseMock, checkResponse);
function checkResponse() {
const body = responseSpy.args[0][1];
body.should.deep.equal({id: idsGeneratorStub()});
done();
}
deferred.resolve();
});
it('Should store the scenario data and id', done => {
let deferred = q.defer();
let promise = deferred.promise;
let persistEpisodeInStorage = sinon.stub();
persistEpisodeInStorage.returns(promise);
const bookId = 'abc1234';
const mockedRequest = mockRequest(bookId);
const createEpisode = getCreateEpisodeMiddleware(idsGeneratorStub, persistEpisodeInStorage);
createEpisode(mockedRequest, mockResponse(), checkResponse);
deferred.resolve();
function checkResponse() {
persistEpisodeInStorage.calledOnce.should.equal(true);
persistEpisodeInStorage.args[0][0].should.equal(bookId);
persistEpisodeInStorage.args[0][1].should.deep.equal(_.assign({id: idsGeneratorStub()}, mockedRequest.body));
done();
}
});
afterEach(() => {
mockery.deregisterAll();
mockery.disable();
});
});
function getCreateEpisodeMiddleware(idsMock, persistEpisodeInStorage) {
mockery.registerMock('../idsGenerator/generateId.js', idsMock);
mockery.registerMock('./persistEpisodeInStorage.js', persistEpisodeInStorage);
mockery.enable({
useCleanCache: true,
warnOnReplace: false,
warnOnUnregistered: false
});
return require('../../src/episodes/createEpisode.js');
}
function mockResponse() {
return { json: () => {} };
}
function mockRequest(bookId) {
return {
context: {
bookId: bookId
},
body: {
a: 1,
b: 2
}
};
}
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M4 17h6v2H4zm13-6H4v2h13.25c1.1 0 2 .9 2 2s-.9 2-2 2H15v-2l-3 3 3 3v-2h2c2.21 0 4-1.79 4-4s-1.79-4-4-4zM4 5h16v2H4z" />
, 'WrapTextTwoTone');
|
import React from 'react';
import {shallow} from 'enzyme';
import {BareCheckSuiteView} from '../../lib/views/check-suite-view';
import CheckRunView from '../../lib/views/check-run-view';
import checkSuiteQuery from '../../lib/views/__generated__/checkSuiteView_checkSuite.graphql';
import {checkSuiteBuilder} from '../builder/graphql/timeline';
describe('CheckSuiteView', function() {
function buildApp(override = {}) {
const props = {
checkSuite: checkSuiteBuilder(checkSuiteQuery).build(),
checkRuns: [],
switchToIssueish: () => {},
...override,
};
return <BareCheckSuiteView {...props} />;
}
it('renders the summarized suite information', function() {
const checkSuite = checkSuiteBuilder(checkSuiteQuery)
.app(a => a.name('app'))
.status('COMPLETED')
.conclusion('SUCCESS')
.build();
const wrapper = shallow(buildApp({checkSuite}));
const icon = wrapper.find('Octicon');
assert.strictEqual(icon.prop('icon'), 'check');
assert.isTrue(icon.hasClass('github-PrStatuses--success'));
assert.strictEqual(wrapper.find('.github-PrStatuses-list-item-context strong').text(), 'app');
});
it('omits app information when the app is no longer present', function() {
const checkSuite = checkSuiteBuilder(checkSuiteQuery)
.nullApp()
.build();
const wrapper = shallow(buildApp({checkSuite}));
assert.isTrue(wrapper.exists('Octicon'));
assert.isFalse(wrapper.exists('.github-PrStatuses-list-item-context'));
});
it('renders a CheckRun for each run within the suite', function() {
const checkRuns = [{id: 0}, {id: 1}, {id: 2}];
const wrapper = shallow(buildApp({checkRuns}));
assert.deepEqual(wrapper.find(CheckRunView).map(v => v.prop('checkRun')), checkRuns);
});
});
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var minus = exports.minus = { "viewBox": "0 0 20 20", "children": [{ "name": "path", "attribs": { "d": "M16,10c0,0.553-0.048,1-0.601,1H4.601C4.049,11,4,10.553,4,10c0-0.553,0.049-1,0.601-1h10.799C15.952,9,16,9.447,16,10z" } }] }; |
export const ic_settings_system_daydream = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M9 16h6.5c1.38 0 2.5-1.12 2.5-2.5S16.88 11 15.5 11h-.05c-.24-1.69-1.69-3-3.45-3-1.4 0-2.6.83-3.16 2.02h-.16C7.17 10.18 6 11.45 6 13c0 1.66 1.34 3 3 3zM21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16.01H3V4.99h18v14.02z"},"children":[]}]}; |
/*!
* jQuery JavaScript Library v1.11.2
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-12-17T15:27Z
*/
(function( global, factory ) {
if ( typeof module === "object" && typeof module.exports === "object" ) {
// For CommonJS and CommonJS-like environments where a proper window is present,
// execute the factory and get jQuery
// For environments that do not inherently posses a window with a document
// (such as Node.js), expose a jQuery-making factory as module.exports
// This accentuates the need for the creation of a real window
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else {
factory( global );
}
// Pass this if window is not defined yet
}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
// 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+
//
var deletedIds = [];
var slice = deletedIds.slice;
var concat = deletedIds.concat;
var push = deletedIds.push;
var indexOf = deletedIds.indexOf;
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var support = {};
var
version = "1.11.2",
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init( selector, context );
},
// Support: Android<4.1, IE<9
// Make sure we trim BOM and NBSP
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/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();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return 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 just the one element from the set
( num < 0 ? this[ num + this.length ] : this[ num ] ) :
// Return all the elements in a clean array
slice.call( this );
},
// 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 );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
slice: function() {
return this.pushStack( 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] ] : [] );
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: deletedIds.sort,
splice: deletedIds.splice
};
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;
// skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// 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 ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
// Assume jQuery is ready without the ready module
isReady: true,
error: function( msg ) {
throw new Error( msg );
},
noop: function() {},
// 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 ) {
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
// adding 1 corrects loss of precision from parseFloat (#15100)
return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
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 &&
!hasOwn.call(obj, "constructor") &&
!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 ( support.ownLast ) {
for ( key in obj ) {
return 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 || hasOwn.call( obj, key );
},
type: function( obj ) {
if ( obj == null ) {
return obj + "";
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call(obj) ] || "object" :
typeof obj;
},
// 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;
},
// Support: Android<4.1, IE<9
trim: 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 {
push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( indexOf ) {
return 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 len = +second.length,
j = 0,
i = first.length;
while ( j < len ) {
first[ i++ ] = second[ j++ ];
}
// Support: IE<9
// Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists)
if ( len !== len ) {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, invert ) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
callbackInverse = !callback( elems[ i ], i );
if ( callbackInverse !== callbackExpect ) {
matches.push( elems[ i ] );
}
}
return matches;
},
// 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 new values
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
}
// Flatten any nested arrays
return 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 = slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
now: function() {
return +( new Date() );
},
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
});
// 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 ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
* Sizzle CSS Selector Engine v2.2.0-pre
* http://sizzlejs.com/
*
* Copyright 2008, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-12-16
*/
(function( window ) {
var i,
support,
Expr,
getText,
isXML,
tokenize,
compile,
select,
outermostContext,
sortInput,
hasDuplicate,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + 1 * new Date(),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
}
return 0;
},
// General-purpose constants
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 as it's faster than native
// http://jsperf.com/thor-indexof-vs-for/5
indexOf = function( list, elem ) {
var i = 0,
len = list.length;
for ( ; i < len; i++ ) {
if ( list[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#" ),
// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace +
// Operator (capture 2)
"*([*^$|!~]?=)" + whitespace +
// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
"*\\]",
pseudos = ":(" + characterEncoding + ")(?:\\((" +
// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
// 1. quoted (capture 3; capture 4 or capture 5)
"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
// 2. simple (capture 6)
"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
// 3. anything else (capture 2)
".*" +
")\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rwhitespace = new RegExp( whitespace + "+", "g" ),
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + 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" )
},
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rsibling = /[+~]/,
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<24
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
high < 0 ?
// BMP codepoint
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
},
// Used for iframes
// See setDocument()
// Removing the function wrapper causes a "Permission Denied"
// error in IE
unloadHandler = function() {
setDocument();
};
// 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 || [];
nodeType = context.nodeType;
if ( typeof selector !== "string" || !selector ||
nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
return results;
}
if ( !seed && documentIsHTML ) {
// Try to shortcut find operations when possible (e.g., not under DocumentFragment)
if ( nodeType !== 11 && (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 (jQuery #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 ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// QSA path
if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
nid = old = expando;
newContext = context;
newSelector = nodeType !== 1 && 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 ) && testContext( 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]);
}
}
});
});
}
/**
* Checks a node for validity as a Sizzle context
* @param {Element|Object=} context
* @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
*/
function testContext( context ) {
return context && typeof context.getElementsByTagName !== "undefined" && context;
}
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Detects XML nodes
* @param {Element|Object} elem An element or a document
* @returns {Boolean} True iff elem is a non-HTML XML node
*/
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;
};
/**
* 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 hasCompare, parent,
doc = node ? node.ownerDocument || node : preferredDoc;
// 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;
parent = doc.defaultView;
// 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 !== parent.top ) {
// IE11 does not have attachEvent, so all must suffer
if ( parent.addEventListener ) {
parent.addEventListener( "unload", unloadHandler, false );
} else if ( parent.attachEvent ) {
parent.attachEvent( "onunload", unloadHandler );
}
}
/* Support tests
---------------------------------------------------------------------- */
documentIsHTML = !isXML( doc );
/* 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;
});
// Support: IE<9
support.getElementsByClassName = rnative.test( doc.getElementsByClassName );
// 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 !== "undefined" && 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 !== "undefined" && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== "undefined" ) {
return context.getElementsByTagName( tag );
// DocumentFragment nodes don't have gEBTN
} else if ( support.qsa ) {
return context.querySelectorAll( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
// By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
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 ( 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
docElem.appendChild( div ).innerHTML = "<a id='" + expando + "'></a>" +
"<select id='" + expando + "-\f]' msallowcapture=''>" +
"<option selected=''></option></select>";
// Support: IE8, Opera 11-12.16
// Nothing should be selected when empty strings follow ^= or $= or *=
// The test attribute must be unknown in Opera but "safe" for WinRT
// http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
if ( div.querySelectorAll("[msallowcapture^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Support: Chrome<29, Android<4.2+, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.7+
if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
rbuggyQSA.push("~=");
}
// 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");
}
// Support: Safari 8+, iOS 8+
// https://bugs.webkit.org/show_bug.cgi?id=136851
// In-page `selector#id sibing-combinator selector` fails
if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) {
rbuggyQSA.push(".#.+[+~]");
}
});
assert(function( div ) {
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = doc.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "name", "D" );
// Support: IE8
// Enforce case-sensitivity of name attribute
if ( div.querySelectorAll("[name=d]").length ) {
rbuggyQSA.push( "name" + 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.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
---------------------------------------------------------------------- */
hasCompare = rnative.test( docElem.compareDocumentPosition );
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = hasCompare || rnative.test( docElem.contains ) ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
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 = hasCompare ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
// Sort on method existence if only one input has compareDocumentPosition
var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
if ( compare ) {
return compare;
}
// Calculate position if both inputs belong to the same document
compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
a.compareDocumentPosition( b ) :
// Otherwise we know they are disconnected
1;
// 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 || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
return -1;
}
if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
} :
function( a, b ) {
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Parentless nodes are either documents or disconnected
if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf( sortInput, a ) - indexOf( 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 ?
val :
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null;
};
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 );
}
}
// Clear input after sorting to release objects
// See https://github.com/jquery/sizzle/pull/225
sortInput = null;
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
while ( (node = elem[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 (jQuery #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[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[6] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] ) {
match[2] = match[4] || match[5] || "";
// 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 !== "undefined" && 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.replace( rwhitespace, " " ) + " " ).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( 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 );
// Don't keep the element (issue #299)
input[0] = null;
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
text = text.replace( runescape, funescape );
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 negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
// but not by others (comment: 8; processing instruction: 7; etc.)
// nodeType < 6 works because attributes (2) do not appear as children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeType < 6 ) {
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;
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
// Support: IE<8
// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
},
// 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();
tokenize = Sizzle.tokenize = function( 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 oldCache, outerCache,
newCache = [ 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 ( (oldCache = outerCache[ dir ]) &&
oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
// Assign to newCache so results back-propagate to previous elements
return (newCache[ 2 ] = oldCache[ 2 ]);
} else {
// Reuse newcache so results back-propagate to previous elements
outerCache[ dir ] = newCache;
// A match means we're done; a fail means we have to keep checking
if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
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 multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
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( 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( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
// Avoid hanging onto element (issue #299)
checkContext = null;
return ret;
} ];
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 ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, outermost ) {
var elem, j, matcher,
matchedCount = 0,
i = "0",
unmatched = seed && [],
setMatched = [],
contextBackup = outermostContext,
// We must always have either seed elements or outermost context
elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
len = elems.length;
if ( outermost ) {
outermostContext = context !== document && context;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
// Support: IE<9, Safari
// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
for ( ; i !== len && (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;
}
}
// 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, match /* 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 ( !match ) {
match = tokenize( selector );
}
i = match.length;
while ( i-- ) {
cached = matcherFromTokens( match[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
// Save selector and tokenization
cached.selector = selector;
}
return cached;
};
/**
* A low-level selection function that works with Sizzle's compiled
* selector functions
* @param {String|Function} selector A selector or a pre-compiled
* selector function built with Sizzle.compile
* @param {Element} context
* @param {Array} [results]
* @param {Array} [seed] A set of elements to match against
*/
select = Sizzle.select = function( selector, context, results, seed ) {
var i, tokens, token, type, find,
compiled = typeof selector === "function" && selector,
match = !seed && tokenize( (selector = compiled.selector || selector) );
results = results || [];
// Try to minimize operations if there is no seed and 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;
// Precompiled matchers will still verify ancestry, so step up a level
} else if ( compiled ) {
context = context.parentNode;
}
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 ) && testContext( 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 if one is not provided
// Provide `match` to avoid retokenization if we modified the selector above
( compiled || compile( selector, match ) )(
seed,
context,
!documentIsHTML,
results,
rsibling.test( selector ) && testContext( context.parentNode ) || context
);
return results;
};
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Support: Chrome 14-35+
// 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 elem[ name ] === true ? name.toLowerCase() :
(val = elem.getAttributeNode( name )) && val.specified ?
val.value :
null;
}
});
}
return Sizzle;
})( window );
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;
var rneedsContext = jQuery.expr.match.needsContext;
var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/);
var risSimple = /^.[^:#\[\.,]*$/;
// 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 ( risSimple.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;
});
}
jQuery.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;
}));
};
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;
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
not: function( selector ) {
return this.pushStack( winnow(this, selector || [], true) );
},
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;
}
});
// Initialize a jQuery object
// A central reference to the root jQuery(document)
var rootjQuery,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
// 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-]*))$/,
init = jQuery.fn.init = function( selector, context ) {
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
// Intentionally let the error be thrown if parseHTML is not present
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 typeof rootjQuery.ready !== "undefined" ?
rootjQuery.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
};
// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;
// Initialize central reference
rootjQuery = jQuery( document );
var rparentsprev = /^(?:parents|prev(?:Until|All))/,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.extend({
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;
}
});
jQuery.fn.extend({
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;
}
}
});
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector(cur, selectors)) ) {
matched.push( cur );
break;
}
}
}
return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return 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 ) {
return this.pushStack(
jQuery.unique(
jQuery.merge( this.get(), jQuery( selector, context ) )
)
);
},
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 );
};
});
var rnotwhite = (/\S+/g);
// 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( 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 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[ tuple[ 0 ] + "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 = 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 ? 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();
}
});
// The deferred used on DOM ready
var readyList;
jQuery.fn.ready = function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
};
jQuery.extend({
// 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.triggerHandler ) {
jQuery( document ).triggerHandler( "ready" );
jQuery( document ).off( "ready" );
}
}
});
/**
* Clean-up method for dom ready events
*/
function detach() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
}
/**
* The ready event handler and self cleanup method
*/
function completed() {
// 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();
}
}
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 );
};
var strundefined = typeof undefined;
// Support: IE<9
// Iteration over object's inherited properties before its own
var i;
for ( i in jQuery( support ) ) {
break;
}
support.ownLast = i !== "0";
// Note: most support tests are defined in their respective modules.
// false until the test is run
support.inlineBlockNeedsLayout = false;
// Execute ASAP in case we need to set body.style.zoom
jQuery(function() {
// Minified: var a,b,c,d
var val, div, body, container;
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body || !body.style ) {
// Return for frameset docs that don't have a body
return;
}
// Setup
div = document.createElement( "div" );
container = document.createElement( "div" );
container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
body.appendChild( container ).appendChild( div );
if ( typeof div.style.zoom !== 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.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1";
support.inlineBlockNeedsLayout = val = div.offsetWidth === 3;
if ( val ) {
// 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 );
});
(function() {
var div = document.createElement( "div" );
// Execute the test only if not already executed in another module.
if (support.deleteExpando == null) {
// Support: IE<9
support.deleteExpando = true;
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
}
// Null elements to avoid leaks in IE.
div = null;
})();
/**
* Determines whether an object can have data
*/
jQuery.acceptData = function( elem ) {
var noData = jQuery.noData[ (elem.nodeName + " ").toLowerCase() ],
nodeType = +elem.nodeType || 1;
// Do not set data on non-element DOM nodes because it will not be cleared (#8335).
return nodeType !== 1 && nodeType !== 9 ?
false :
// Nodes accept data unless otherwise specified; rejection can be conditional
!noData || noData !== true && elem.getAttribute("classid") === noData;
};
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
rmultiDash = /([A-Z])/g;
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;
}
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 ] = 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 ( 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 (space-suffixed to avoid Object.prototype collisions)
// throw uncatchable exceptions if you attempt to set expando properties
noData: {
"applet ": true,
"embed ": true,
// ...but Flash objects (which have this classid) *can* 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 );
}
});
jQuery.fn.extend({
data: function( key, value ) {
var i, name, data,
elem = this[0],
attrs = elem && elem.attributes;
// 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" ) ) {
i = attrs.length;
while ( i-- ) {
// Support: IE11+
// The attrs elements can be null (#14894)
if ( attrs[ 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 ) ) : undefined;
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
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 );
});
},
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 pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source;
var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
var isHidden = function( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
};
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = jQuery.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;
};
var rcheckableType = (/^(?:checkbox|radio)$/i);
(function() {
// Minified: var a,b,c
var input = document.createElement( "input" ),
div = document.createElement( "div" ),
fragment = document.createDocumentFragment();
// Setup
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// 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;
// 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>";
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
input.type = "checkbox";
input.checked = true;
fragment.appendChild( input );
support.appendChecked = input.checked;
// Make sure textarea (and checkbox) defaultValue is properly cloned
// Support: IE6-IE11+
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
// #11217 - WebKit loses check when the name is after the checked attribute
fragment.appendChild( div );
div.innerHTML = "<input type='radio' checked='checked' name='t'/>";
// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
// old WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.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()
support.noCloneEvent = true;
if ( div.attachEvent ) {
div.attachEvent( "onclick", function() {
support.noCloneEvent = false;
});
div.cloneNode( true ).click();
}
// Execute the test only if not already executed in another module.
if (support.deleteExpando == null) {
// Support: IE<9
support.deleteExpando = true;
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
}
})();
(function() {
var i, eventName,
div = document.createElement( "div" );
// Support: IE<9 (lack submit/change bubble), Firefox 23+ (lack focusin event)
for ( i in { submit: true, change: true, focusin: true }) {
eventName = "on" + i;
if ( !(support[ i + "Bubbles" ] = eventName in window) ) {
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
div.setAttribute( eventName, "t" );
support[ i + "Bubbles" ] = div.attributes[ eventName ].expando === false;
}
}
// Null elements to avoid leaks in IE.
div = null;
})();
var rformElems = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|pointer|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 !== 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( 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( 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 = hasOwn.call( event, "type" ) ? event.type : event,
namespaces = 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 && handle.apply && jQuery.acceptData( cur ) ) {
event.result = handle.apply( cur, data );
if ( event.result === 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 = 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 ) {
// Support: Firefox 20+
// Firefox doesn't alert if the returnValue field is not set.
if ( event.result !== undefined && event.originalEvent ) {
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 ] === 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.defaultPrevented === undefined &&
// Support: IE < 9, Android < 4.0
src.returnValue === false ?
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() {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
if ( e && e.stopImmediatePropagation ) {
e.stopImmediatePropagation();
}
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout",
pointerenter: "pointerover",
pointerleave: "pointerout"
}, 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 ( !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 ( !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 ( !support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler on the document while someone wants focusin/focusout
var handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
var doc = this.ownerDocument || this,
attaches = jQuery._data( doc, fix );
if ( !attaches ) {
doc.addEventListener( orig, handler, true );
}
jQuery._data( doc, fix, ( attaches || 0 ) + 1 );
},
teardown: function() {
var doc = this.ownerDocument || this,
attaches = jQuery._data( doc, fix ) - 1;
if ( !attaches ) {
doc.removeEventListener( orig, handler, true );
jQuery._removeData( doc, fix );
} else {
jQuery._data( doc, fix, attaches );
}
}
};
});
}
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 );
}
}
});
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,
// 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: 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;
function getAll( context, tag ) {
var elems, elem,
i = 0,
found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== 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 ( rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
// Support: IE<8
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType !== 11 ? 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 ( !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 ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.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.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var destElements, node, clone, i, srcElements,
inPage = jQuery.contains( elem.ownerDocument, elem );
if ( 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 ( (!support.noCloneEvent || !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 ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !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 ( !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 = 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 !== strundefined ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
deletedIds.push( id );
}
}
}
}
}
});
jQuery.fn.extend({
text: function( value ) {
return 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 );
}
});
},
remove: function( selector, keepData /* Internal Use Only */ ) {
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 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 ) &&
( support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( 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 arg = arguments[ 0 ];
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
arg = this.parentNode;
jQuery.cleanData( getAll( this ) );
if ( arg ) {
arg.replaceChild( elem, this );
}
});
// Force removal if there was no new content (e.g., from empty arguments)
return arg && (arg.length || arg.nodeType) ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback ) {
// Flatten any nested arrays
args = 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" &&
!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 );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, 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 ) {
// Optional AJAX dependency, but won't run scripts if not present
if ( jQuery._evalUrl ) {
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;
}
});
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()
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
var iframe,
elemdisplay = {};
/**
* Retrieve the actual display of a element
* @param {String} name nodeName of the element
* @param {Object} doc Document object
*/
// Called only from within defaultDisplay
function actualDisplay( name, doc ) {
var style,
elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
// getDefaultComputedStyle might be reliably used only on attached element
display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ?
// Use of this method is a temporary fix (more like optmization) until something better comes along,
// since it was removed from specification and supported only in FF
style.display : jQuery.css( elem[ 0 ], "display" );
// We don't have any data stored on the element,
// so use "detach" method as fast way to get rid of the element
elem.detach();
return display;
}
/**
* Try to determine the default display value of an element
* @param {String} nodeName
*/
function defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[ 0 ].contentWindow || iframe[ 0 ].contentDocument ).document;
// Support: IE
doc.write();
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
(function() {
var shrinkWrapBlocksVal;
support.shrinkWrapBlocks = function() {
if ( shrinkWrapBlocksVal != null ) {
return shrinkWrapBlocksVal;
}
// Will be changed later if needed.
shrinkWrapBlocksVal = false;
// Minified: var b,c,d
var div, body, container;
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body || !body.style ) {
// Test fired too early or in an unsupported environment, exit.
return;
}
// Setup
div = document.createElement( "div" );
container = document.createElement( "div" );
container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
body.appendChild( container ).appendChild( div );
// Support: IE6
// Check if elements with layout shrink-wrap their children
if ( typeof div.style.zoom !== strundefined ) {
// Reset CSS: box-sizing; display; margin; border
div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
"box-sizing:content-box;display:block;margin:0;border:0;" +
"padding:1px;width:1px;zoom:1";
div.appendChild( document.createElement( "div" ) ).style.width = "5px";
shrinkWrapBlocksVal = div.offsetWidth !== 3;
}
body.removeChild( container );
return shrinkWrapBlocksVal;
};
})();
var rmargin = (/^margin/);
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
var getStyles, curCSS,
rposition = /^(top|right|bottom|left)$/;
if ( window.getComputedStyle ) {
getStyles = function( elem ) {
// Support: IE<=11+, Firefox<=30+ (#15098, #14150)
// IE throws on elements created in popups
// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
if ( elem.ownerDocument.defaultView.opener ) {
return elem.ownerDocument.defaultView.getComputedStyle( elem, null );
}
return window.getComputedStyle( elem, null );
};
curCSS = function( elem, name, computed ) {
var width, minWidth, maxWidth, ret,
style = elem.style;
computed = computed || getStyles( elem );
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined;
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
// Support: IE
// IE returns zIndex value as an integer.
return ret === undefined ?
ret :
ret + "";
};
} else if ( document.documentElement.currentStyle ) {
getStyles = function( elem ) {
return elem.currentStyle;
};
curCSS = function( elem, name, computed ) {
var left, rs, rsLeft, ret,
style = elem.style;
computed = computed || getStyles( elem );
ret = computed ? computed[ name ] : undefined;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rs = elem.runtimeStyle;
rsLeft = rs && rs.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
rs.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
rs.left = rsLeft;
}
}
// Support: IE
// IE returns zIndex value as an integer.
return ret === undefined ?
ret :
ret + "" || "auto";
};
}
function addGetHookIf( conditionFn, hookFn ) {
// Define the hook, we'll check on the first run if it's really needed.
return {
get: function() {
var condition = conditionFn();
if ( condition == null ) {
// The test was not ready at this point; screw the hook this time
// but check again when needed next time.
return;
}
if ( condition ) {
// Hook not needed (or it's not possible to use it due to missing dependency),
// remove it.
// Since there are no other hooks for marginRight, remove the whole object.
delete this.get;
return;
}
// Hook needed; redefine it so that the support test is not executed again.
return (this.get = hookFn).apply( this, arguments );
}
};
}
(function() {
// Minified: var b,c,d,e,f,g, h,i
var div, style, a, pixelPositionVal, boxSizingReliableVal,
reliableHiddenOffsetsVal, reliableMarginRightVal;
// Setup
div = document.createElement( "div" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
a = div.getElementsByTagName( "a" )[ 0 ];
style = a && a.style;
// Finish early in limited (non-browser) environments
if ( !style ) {
return;
}
style.cssText = "float:left;opacity:.5";
// Support: IE<9
// Make sure that element opacity exists (as opposed to filter)
support.opacity = style.opacity === "0.5";
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
support.cssFloat = !!style.cssFloat;
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
support.boxSizing = style.boxSizing === "" || style.MozBoxSizing === "" ||
style.WebkitBoxSizing === "";
jQuery.extend(support, {
reliableHiddenOffsets: function() {
if ( reliableHiddenOffsetsVal == null ) {
computeStyleTests();
}
return reliableHiddenOffsetsVal;
},
boxSizingReliable: function() {
if ( boxSizingReliableVal == null ) {
computeStyleTests();
}
return boxSizingReliableVal;
},
pixelPosition: function() {
if ( pixelPositionVal == null ) {
computeStyleTests();
}
return pixelPositionVal;
},
// Support: Android 2.3
reliableMarginRight: function() {
if ( reliableMarginRightVal == null ) {
computeStyleTests();
}
return reliableMarginRightVal;
}
});
function computeStyleTests() {
// Minified: var b,c,d,j
var div, body, container, contents;
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body || !body.style ) {
// Test fired too early or in an unsupported environment, exit.
return;
}
// Setup
div = document.createElement( "div" );
container = document.createElement( "div" );
container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
body.appendChild( container ).appendChild( div );
div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" +
"box-sizing:border-box;display:block;margin-top:1%;top:1%;" +
"border:1px;padding:1px;width:4px;position:absolute";
// Support: IE<9
// Assume reasonable values in the absence of getComputedStyle
pixelPositionVal = boxSizingReliableVal = false;
reliableMarginRightVal = true;
// Check for getComputedStyle so that this code is not run in IE<9.
if ( window.getComputedStyle ) {
pixelPositionVal = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
boxSizingReliableVal =
( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Support: Android 2.3
// Div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container (#3333)
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
contents = div.appendChild( document.createElement( "div" ) );
// Reset CSS: box-sizing; display; margin; border; padding
contents.style.cssText = div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
"box-sizing:content-box;display:block;margin:0;border:0;padding:0";
contents.style.marginRight = contents.style.width = "0";
div.style.width = "1px";
reliableMarginRightVal =
!parseFloat( ( window.getComputedStyle( contents, null ) || {} ).marginRight );
div.removeChild( contents );
}
// 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>";
contents = div.getElementsByTagName( "td" );
contents[ 0 ].style.cssText = "margin:0;border:0;padding:0;display:none";
reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0;
if ( reliableHiddenOffsetsVal ) {
contents[ 0 ].style.display = "";
contents[ 1 ].style.display = "none";
reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0;
}
body.removeChild( container );
}
})();
// A method for quickly swapping in/out CSS properties to get correct calculations.
jQuery.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;
};
var
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity\s*=\s*([^)]*)/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ),
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: "0",
fontWeight: "400"
},
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
} else {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"flexGrow": true,
"flexShrink": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"order": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that null and NaN values aren't set. See: #7116
if ( value == null || value !== value ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if ( !support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Support: IE
// Swallow errors from 'invalid' CSS values (#5509)
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var num, val, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
}
});
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
if ( !support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
// if value === "", then remove inline opacity #12685
if ( ( value >= 1 || value === "" ) &&
jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there is no filter style applied in a css rule or unset inline opacity, we are done
if ( value === "" || currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
function( elem, computed ) {
if ( computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
);
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
jQuery.fn.extend({
css: function( name, value ) {
return access( this, function( elem, name, value ) {
var styles, len,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
if ( typeof state === "boolean" ) {
return state ? this.show() : this.hide();
}
return this.each(function() {
if ( isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Support: IE <=9
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p * Math.PI ) / 2;
}
};
jQuery.fx = Tween.prototype.init;
// Back Compat <1.8 extension point
jQuery.fx.step = {};
var
fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [ function( prop, value ) {
var tween = this.createTween( prop, value ),
target = tween.cur(),
parts = rfxnum.exec( value ),
unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
rfxnum.exec( jQuery.css( tween.elem, prop ) ),
scale = 1,
maxIterations = 20;
if ( start && start[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || start[ 3 ];
// Make sure we update the tween properties later on
parts = parts || [];
// Iteratively approximate from a nonzero starting point
start = +target || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
// Update tween properties
if ( parts ) {
start = tween.start = +start || +target || 0;
tween.unit = unit;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[ 1 ] ?
start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+parts[ 2 ];
}
return tween;
} ]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
});
return ( fxNow = jQuery.now() );
}
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth ? 1 : 0;
for ( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
function createTween( value, prop, animation ) {
var tween,
collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( (tween = collection[ index ].call( animation, prop, value )) ) {
// we're done with this property
return tween;
}
}
}
function defaultPrefilter( elem, props, opts ) {
/* jshint validthis: true */
var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHidden( elem ),
dataShow = jQuery._data( elem, "fxshow" );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
display = jQuery.css( elem, "display" );
// Test default display if display is currently "none"
checkDisplay = display === "none" ?
jQuery._data( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display;
if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !support.inlineBlockNeedsLayout || defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !support.shrinkWrapBlocks() ) {
anim.always(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.exec( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
// If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden
if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
hidden = true;
} else {
continue;
}
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
// Any non-fx value stops us from restoring the original display value
} else {
display = undefined;
}
}
if ( !jQuery.isEmptyObject( orig ) ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = jQuery._data( elem, "fxshow", {} );
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
jQuery._removeData( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( prop in orig ) {
tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
// If this is a noop like .hide().hide(), restore an overwritten display value
} else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) {
style.display = display;
}
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations, or finishing resolves immediately
if ( empty || jQuery._data( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each(function() {
var index,
data = jQuery._data( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// enable finishing flag on private data
data.finish = true;
// empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.stop ) {
hooks.stop.call( this, true );
}
// look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// turn off finishing flag
delete data.finish;
});
}
});
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.timers = [];
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
jQuery.timers.push( timer );
if ( timer() ) {
jQuery.fx.start();
} else {
jQuery.timers.pop();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.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 );
};
});
};
(function() {
// Minified: var a,b,c,d,e
var input, div, select, a, opt;
// Setup
div = document.createElement( "div" );
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
a = div.getElementsByTagName("a")[ 0 ];
// First batch of tests.
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px";
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
support.getSetAttribute = div.className !== "t";
// 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";
// 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;
// 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: IE8 only
// 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";
})();
var rreturn = /\r/g;
jQuery.fn.extend({
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map( val, function( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
// Support: IE10-11+
// option.text throws exceptions (#14686, #14858)
jQuery.trim( jQuery.text( elem ) );
}
},
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
( 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 ( jQuery.inArray( jQuery.valHooks.option.get( option ), values ) >= 0 ) {
// Support: IE6
// When new option element is added to select box we need to
// force reflow of newly added node in order to workaround delay
// of initialization properties
try {
option.selected = optionSet = true;
} catch ( _ ) {
// Will be executed only in IE6
option.scrollHeight;
}
} else {
option.selected = false;
}
}
// Force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return options;
}
}
}
});
// 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 ( !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 nodeHook, boolHook,
attrHandle = jQuery.expr.attrHandle,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = support.getSetAttribute,
getSetInput = support.input;
jQuery.fn.extend({
attr: function( name, value ) {
return access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
}
});
jQuery.extend({
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 === 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( 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 ( !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;
}
}
}
}
});
// Hook 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;
}
};
// Retrieve booleans specially
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = attrHandle[ name ] || jQuery.find.attr;
attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ?
function( elem, name, isXML ) {
var ret, handle;
if ( !isXML ) {
// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[ name ];
attrHandle[ name ] = ret;
ret = getter( elem, name, isXML ) != null ?
name.toLowerCase() :
null;
attrHandle[ name ] = handle;
}
return ret;
} :
function( elem, name, isXML ) {
if ( !isXML ) {
return 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)
if ( name === "value" || value === elem.getAttribute( name ) ) {
return value;
}
}
};
// Some attributes are constructed with empty-string values when not defined
attrHandle.id = attrHandle.name = attrHandle.coords =
function( elem, name, isXML ) {
var ret;
if ( !isXML ) {
return (ret = elem.getAttributeNode( name )) && ret.value !== "" ?
ret.value :
null;
}
};
// Fixing value retrieval on a button requires this module
jQuery.valHooks.button = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
if ( ret && ret.specified ) {
return ret.value;
}
},
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;
}
}
};
});
}
if ( !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 + "" );
}
};
}
var rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i;
jQuery.fn.extend({
prop: function( name, value ) {
return 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 ) {}
});
}
});
jQuery.extend({
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;
}
}
}
});
// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !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 );
}
};
});
}
// Support: Safari, IE9+
// mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !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 ( !support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
var rclass = /[\t\r\n\f]/g;
jQuery.fn.extend({
addClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
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( 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 + " ";
}
}
// only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim( cur );
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
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( 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 + " ", " " );
}
}
// only assign if different to avoid unneeded rendering.
finalValue = value ? jQuery.trim( cur ) : "";
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
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( 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 === 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;
}
});
// Return jQuery for attributes-only inclusion
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 nonce = jQuery.now();
var rquery = (/\?/);
var rvalidtokens = /(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;
jQuery.parseJSON = function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
// Support: Android 2.3
// Workaround failure to string-cast null input
return window.JSON.parse( data + "" );
}
var requireNonComma,
depth = null,
str = jQuery.trim( data + "" );
// Guard against invalid (and possibly dangerous) input by ensuring that nothing remains
// after removing valid tokens
return str && !jQuery.trim( str.replace( rvalidtokens, function( token, comma, open, close ) {
// Force termination if we see a misplaced comma
if ( requireNonComma && comma ) {
depth = 0;
}
// Perform no more replacements after returning to outermost depth
if ( depth === 0 ) {
return token;
}
// Commas must not follow "[", "{", or ","
requireNonComma = open || comma;
// Determine new depth
// array/object open ("[" or "{"): depth += true - false (increment)
// array/object close ("]" or "}"): depth += false - true (decrement)
// other cases ("," or primitive): depth += true - true (numeric cast)
depth += !close - !open;
// Remove this token
return "";
}) ) ?
( Function( "return " + str ) )() :
jQuery.error( "Invalid JSON: " + data );
};
// Cross-browser xml parsing
jQuery.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;
};
var
// Document location
ajaxLocParts,
ajaxLocation,
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+)|)|)/,
/* 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( rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( (dataType = dataTypes[i++]) ) {
// Prepend if requested
if ( dataType.charAt( 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;
}
/* 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 };
}
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( 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
// Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
fireGlobals = jQuery.event && 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 += ( 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_=" + nonce++ ) :
// Otherwise add one to the end
cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + 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
});
};
});
jQuery._evalUrl = function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
};
jQuery.fn.extend({
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
}
});
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 ||
(!support.reliableHiddenOffsets() &&
((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
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 );
}
}
// 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, "+" );
};
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 || !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();
}
});
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject !== undefined ?
// Support: IE6+
function() {
// XHR cannot access local files, always use ActiveX for that case
return !this.isLocal &&
// Support: IE7-8
// oldIE XHR does not support non-RFC2616 methods (#13240)
// See http://msdn.microsoft.com/en-us/library/ie/ms536648(v=vs.85).aspx
// and http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9
// Although this check for six methods instead of eight
// since IE also does not support "trace" and "connect"
/^(get|post|head|put|delete|options)$/i.test( this.type ) &&
createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
var xhrId = 0,
xhrCallbacks = {},
xhrSupported = jQuery.ajaxSettings.xhr();
// Support: IE<10
// Open requests must be manually aborted on unload (#5280)
// See https://support.microsoft.com/kb/2856746 for more info
if ( window.attachEvent ) {
window.attachEvent( "onunload", function() {
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( undefined, true );
}
});
}
// Determine support properties
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
xhrSupported = support.ajax = !!xhrSupported;
// Create transport if the browser can provide an xhr
if ( xhrSupported ) {
jQuery.ajaxTransport(function( options ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !options.crossDomain || support.cors ) {
var callback;
return {
send: function( headers, complete ) {
var i,
xhr = options.xhr(),
id = ++xhrId;
// Open the socket
xhr.open( options.type, options.url, options.async, options.username, options.password );
// Apply custom fields if provided
if ( options.xhrFields ) {
for ( i in options.xhrFields ) {
xhr[ i ] = options.xhrFields[ i ];
}
}
// Override mime type if needed
if ( options.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( options.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !options.crossDomain && !headers["X-Requested-With"] ) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Set headers
for ( i in headers ) {
// Support: IE<9
// IE's ActiveXObject throws a 'Type Mismatch' exception when setting
// request header to a null-value.
//
// To keep consistent with other XHR implementations, cast the value
// to string and ignore `undefined`.
if ( headers[ i ] !== undefined ) {
xhr.setRequestHeader( i, headers[ i ] + "" );
}
}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( options.hasContent && options.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status, statusText, responses;
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Clean up
delete xhrCallbacks[ id ];
callback = undefined;
xhr.onreadystatechange = jQuery.noop;
// Abort manually if needed
if ( isAbort ) {
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
responses = {};
status = xhr.status;
// Support: IE<10
// Accessing binary-data responseText throws an exception
// (#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 && options.isLocal && !options.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, xhr.getAllResponseHeaders() );
}
};
if ( !options.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 {
// Add to the list of active xhr callbacks
xhr.onreadystatechange = xhrCallbacks[ id ] = callback;
}
},
abort: function() {
if ( callback ) {
callback( 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 ) {}
}
// 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 + "_" + ( 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 += ( 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";
}
});
// 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
jQuery.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 && scripts.length ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
};
// Keep a copy of the old load method
var _load = jQuery.fn.load;
/**
* Load a url into a page
*/
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 = jQuery.trim( 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.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
var docElem = window.document.documentElement;
/**
* Gets a window from an element
*/
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
jQuery.offset = {
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),
curElem = jQuery( elem ),
props = {};
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) &&
jQuery.inArray("auto", [ curCSSTop, curCSSLeft ] ) > -1;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
offset: function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ),
left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
};
},
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
parentOffset = { top: 0, left: 0 },
elem = this[ 0 ];
// fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// we assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
}
// Subtract parent offsets and element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true)
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || docElem;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docElem;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
);
});
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// 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.
// Note that for maximum portability, libraries that are not jQuery should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. jQuery is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function() {
return jQuery;
});
}
var
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$;
jQuery.noConflict = function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
};
// Expose jQuery and $ identifiers, even in
// AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( typeof noGlobal === strundefined ) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
}));
/* ========================================================================
* Bootstrap: affix.js v3.3.2
* http://getbootstrap.com/javascript/#affix
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// AFFIX CLASS DEFINITION
// ======================
var Affix = function (element, options) {
this.options = $.extend({}, Affix.DEFAULTS, options)
this.$target = $(this.options.target)
.on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))
this.$element = $(element)
this.affixed =
this.unpin =
this.pinnedOffset = null
this.checkPosition()
}
Affix.VERSION = '3.3.2'
Affix.RESET = 'affix affix-top affix-bottom'
Affix.DEFAULTS = {
offset: 0,
target: window
}
Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) {
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
var targetHeight = this.$target.height()
if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false
if (this.affixed == 'bottom') {
if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'
return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom'
}
var initializing = this.affixed == null
var colliderTop = initializing ? scrollTop : position.top
var colliderHeight = initializing ? targetHeight : height
if (offsetTop != null && scrollTop <= offsetTop) return 'top'
if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'
return false
}
Affix.prototype.getPinnedOffset = function () {
if (this.pinnedOffset) return this.pinnedOffset
this.$element.removeClass(Affix.RESET).addClass('affix')
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
return (this.pinnedOffset = position.top - scrollTop)
}
Affix.prototype.checkPositionWithEventLoop = function () {
setTimeout($.proxy(this.checkPosition, this), 1)
}
Affix.prototype.checkPosition = function () {
if (!this.$element.is(':visible')) return
var height = this.$element.height()
var offset = this.options.offset
var offsetTop = offset.top
var offsetBottom = offset.bottom
var scrollHeight = $('body').height()
if (typeof offset != 'object') offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element)
if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)
var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom)
if (this.affixed != affix) {
if (this.unpin != null) this.$element.css('top', '')
var affixType = 'affix' + (affix ? '-' + affix : '')
var e = $.Event(affixType + '.bs.affix')
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
this.affixed = affix
this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null
this.$element
.removeClass(Affix.RESET)
.addClass(affixType)
.trigger(affixType.replace('affix', 'affixed') + '.bs.affix')
}
if (affix == 'bottom') {
this.$element.offset({
top: scrollHeight - height - offsetBottom
})
}
}
// AFFIX PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.affix')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.affix
$.fn.affix = Plugin
$.fn.affix.Constructor = Affix
// AFFIX NO CONFLICT
// =================
$.fn.affix.noConflict = function () {
$.fn.affix = old
return this
}
// AFFIX DATA-API
// ==============
$(window).on('load', function () {
$('[data-spy="affix"]').each(function () {
var $spy = $(this)
var data = $spy.data()
data.offset = data.offset || {}
if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom
if (data.offsetTop != null) data.offset.top = data.offsetTop
Plugin.call($spy, data)
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: alert.js v3.3.2
* http://getbootstrap.com/javascript/#alerts
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// ALERT CLASS DEFINITION
// ======================
var dismiss = '[data-dismiss="alert"]'
var Alert = function (el) {
$(el).on('click', dismiss, this.close)
}
Alert.VERSION = '3.3.2'
Alert.TRANSITION_DURATION = 150
Alert.prototype.close = function (e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector)
if (e) e.preventDefault()
if (!$parent.length) {
$parent = $this.closest('.alert')
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented()) return
$parent.removeClass('in')
function removeElement() {
// detach from parent, fire event then clean up data
$parent.detach().trigger('closed.bs.alert').remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent
.one('bsTransitionEnd', removeElement)
.emulateTransitionEnd(Alert.TRANSITION_DURATION) :
removeElement()
}
// ALERT PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.alert')
if (!data) $this.data('bs.alert', (data = new Alert(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.alert
$.fn.alert = Plugin
$.fn.alert.Constructor = Alert
// ALERT NO CONFLICT
// =================
$.fn.alert.noConflict = function () {
$.fn.alert = old
return this
}
// ALERT DATA-API
// ==============
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
}(jQuery);
/* ========================================================================
* Bootstrap: button.js v3.3.2
* http://getbootstrap.com/javascript/#buttons
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// BUTTON PUBLIC CLASS DEFINITION
// ==============================
var Button = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Button.DEFAULTS, options)
this.isLoading = false
}
Button.VERSION = '3.3.2'
Button.DEFAULTS = {
loadingText: 'loading...'
}
Button.prototype.setState = function (state) {
var d = 'disabled'
var $el = this.$element
var val = $el.is('input') ? 'val' : 'html'
var data = $el.data()
state = state + 'Text'
if (data.resetText == null) $el.data('resetText', $el[val]())
// push to event loop to allow forms to submit
setTimeout($.proxy(function () {
$el[val](data[state] == null ? this.options[state] : data[state])
if (state == 'loadingText') {
this.isLoading = true
$el.addClass(d).attr(d, d)
} else if (this.isLoading) {
this.isLoading = false
$el.removeClass(d).removeAttr(d)
}
}, this), 0)
}
Button.prototype.toggle = function () {
var changed = true
var $parent = this.$element.closest('[data-toggle="buttons"]')
if ($parent.length) {
var $input = this.$element.find('input')
if ($input.prop('type') == 'radio') {
if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
else $parent.find('.active').removeClass('active')
}
if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
} else {
this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
}
if (changed) this.$element.toggleClass('active')
}
// BUTTON PLUGIN DEFINITION
// ========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.button')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.button', (data = new Button(this, options)))
if (option == 'toggle') data.toggle()
else if (option) data.setState(option)
})
}
var old = $.fn.button
$.fn.button = Plugin
$.fn.button.Constructor = Button
// BUTTON NO CONFLICT
// ==================
$.fn.button.noConflict = function () {
$.fn.button = old
return this
}
// BUTTON DATA-API
// ===============
$(document)
.on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
var $btn = $(e.target)
if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
Plugin.call($btn, 'toggle')
e.preventDefault()
})
.on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) {
$(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type))
})
}(jQuery);
/* ========================================================================
* Bootstrap: carousel.js v3.3.2
* http://getbootstrap.com/javascript/#carousel
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CAROUSEL CLASS DEFINITION
// =========================
var Carousel = function (element, options) {
this.$element = $(element)
this.$indicators = this.$element.find('.carousel-indicators')
this.options = options
this.paused =
this.sliding =
this.interval =
this.$active =
this.$items = null
this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this))
this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element
.on('mouseenter.bs.carousel', $.proxy(this.pause, this))
.on('mouseleave.bs.carousel', $.proxy(this.cycle, this))
}
Carousel.VERSION = '3.3.2'
Carousel.TRANSITION_DURATION = 600
Carousel.DEFAULTS = {
interval: 5000,
pause: 'hover',
wrap: true,
keyboard: true
}
Carousel.prototype.keydown = function (e) {
if (/input|textarea/i.test(e.target.tagName)) return
switch (e.which) {
case 37: this.prev(); break
case 39: this.next(); break
default: return
}
e.preventDefault()
}
Carousel.prototype.cycle = function (e) {
e || (this.paused = false)
this.interval && clearInterval(this.interval)
this.options.interval
&& !this.paused
&& (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
return this
}
Carousel.prototype.getItemIndex = function (item) {
this.$items = item.parent().children('.item')
return this.$items.index(item || this.$active)
}
Carousel.prototype.getItemForDirection = function (direction, active) {
var activeIndex = this.getItemIndex(active)
var willWrap = (direction == 'prev' && activeIndex === 0)
|| (direction == 'next' && activeIndex == (this.$items.length - 1))
if (willWrap && !this.options.wrap) return active
var delta = direction == 'prev' ? -1 : 1
var itemIndex = (activeIndex + delta) % this.$items.length
return this.$items.eq(itemIndex)
}
Carousel.prototype.to = function (pos) {
var that = this
var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active'))
if (pos > (this.$items.length - 1) || pos < 0) return
if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid"
if (activeIndex == pos) return this.pause().cycle()
return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos))
}
Carousel.prototype.pause = function (e) {
e || (this.paused = true)
if (this.$element.find('.next, .prev').length && $.support.transition) {
this.$element.trigger($.support.transition.end)
this.cycle(true)
}
this.interval = clearInterval(this.interval)
return this
}
Carousel.prototype.next = function () {
if (this.sliding) return
return this.slide('next')
}
Carousel.prototype.prev = function () {
if (this.sliding) return
return this.slide('prev')
}
Carousel.prototype.slide = function (type, next) {
var $active = this.$element.find('.item.active')
var $next = next || this.getItemForDirection(type, $active)
var isCycling = this.interval
var direction = type == 'next' ? 'left' : 'right'
var that = this
if ($next.hasClass('active')) return (this.sliding = false)
var relatedTarget = $next[0]
var slideEvent = $.Event('slide.bs.carousel', {
relatedTarget: relatedTarget,
direction: direction
})
this.$element.trigger(slideEvent)
if (slideEvent.isDefaultPrevented()) return
this.sliding = true
isCycling && this.pause()
if (this.$indicators.length) {
this.$indicators.find('.active').removeClass('active')
var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)])
$nextIndicator && $nextIndicator.addClass('active')
}
var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid"
if ($.support.transition && this.$element.hasClass('slide')) {
$next.addClass(type)
$next[0].offsetWidth // force reflow
$active.addClass(direction)
$next.addClass(direction)
$active
.one('bsTransitionEnd', function () {
$next.removeClass([type, direction].join(' ')).addClass('active')
$active.removeClass(['active', direction].join(' '))
that.sliding = false
setTimeout(function () {
that.$element.trigger(slidEvent)
}, 0)
})
.emulateTransitionEnd(Carousel.TRANSITION_DURATION)
} else {
$active.removeClass('active')
$next.addClass('active')
this.sliding = false
this.$element.trigger(slidEvent)
}
isCycling && this.cycle()
return this
}
// CAROUSEL PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.carousel')
var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
var action = typeof option == 'string' ? option : options.slide
if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
if (typeof option == 'number') data.to(option)
else if (action) data[action]()
else if (options.interval) data.pause().cycle()
})
}
var old = $.fn.carousel
$.fn.carousel = Plugin
$.fn.carousel.Constructor = Carousel
// CAROUSEL NO CONFLICT
// ====================
$.fn.carousel.noConflict = function () {
$.fn.carousel = old
return this
}
// CAROUSEL DATA-API
// =================
var clickHandler = function (e) {
var href
var $this = $(this)
var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7
if (!$target.hasClass('carousel')) return
var options = $.extend({}, $target.data(), $this.data())
var slideIndex = $this.attr('data-slide-to')
if (slideIndex) options.interval = false
Plugin.call($target, options)
if (slideIndex) {
$target.data('bs.carousel').to(slideIndex)
}
e.preventDefault()
}
$(document)
.on('click.bs.carousel.data-api', '[data-slide]', clickHandler)
.on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler)
$(window).on('load', function () {
$('[data-ride="carousel"]').each(function () {
var $carousel = $(this)
Plugin.call($carousel, $carousel.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: collapse.js v3.3.2
* http://getbootstrap.com/javascript/#collapse
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// COLLAPSE PUBLIC CLASS DEFINITION
// ================================
var Collapse = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Collapse.DEFAULTS, options)
this.$trigger = $(this.options.trigger).filter('[href="#' + element.id + '"], [data-target="#' + element.id + '"]')
this.transitioning = null
if (this.options.parent) {
this.$parent = this.getParent()
} else {
this.addAriaAndCollapsedClass(this.$element, this.$trigger)
}
if (this.options.toggle) this.toggle()
}
Collapse.VERSION = '3.3.2'
Collapse.TRANSITION_DURATION = 350
Collapse.DEFAULTS = {
toggle: true,
trigger: '[data-toggle="collapse"]'
}
Collapse.prototype.dimension = function () {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
Collapse.prototype.show = function () {
if (this.transitioning || this.$element.hasClass('in')) return
var activesData
var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing')
if (actives && actives.length) {
activesData = actives.data('bs.collapse')
if (activesData && activesData.transitioning) return
}
var startEvent = $.Event('show.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
if (actives && actives.length) {
Plugin.call(actives, 'hide')
activesData || actives.data('bs.collapse', null)
}
var dimension = this.dimension()
this.$element
.removeClass('collapse')
.addClass('collapsing')[dimension](0)
.attr('aria-expanded', true)
this.$trigger
.removeClass('collapsed')
.attr('aria-expanded', true)
this.transitioning = 1
var complete = function () {
this.$element
.removeClass('collapsing')
.addClass('collapse in')[dimension]('')
this.transitioning = 0
this.$element
.trigger('shown.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
var scrollSize = $.camelCase(['scroll', dimension].join('-'))
this.$element
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize])
}
Collapse.prototype.hide = function () {
if (this.transitioning || !this.$element.hasClass('in')) return
var startEvent = $.Event('hide.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
var dimension = this.dimension()
this.$element[dimension](this.$element[dimension]())[0].offsetHeight
this.$element
.addClass('collapsing')
.removeClass('collapse in')
.attr('aria-expanded', false)
this.$trigger
.addClass('collapsed')
.attr('aria-expanded', false)
this.transitioning = 1
var complete = function () {
this.transitioning = 0
this.$element
.removeClass('collapsing')
.addClass('collapse')
.trigger('hidden.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
this.$element
[dimension](0)
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)
}
Collapse.prototype.toggle = function () {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
Collapse.prototype.getParent = function () {
return $(this.options.parent)
.find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]')
.each($.proxy(function (i, element) {
var $element = $(element)
this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element)
}, this))
.end()
}
Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) {
var isOpen = $element.hasClass('in')
$element.attr('aria-expanded', isOpen)
$trigger
.toggleClass('collapsed', !isOpen)
.attr('aria-expanded', isOpen)
}
function getTargetFromTrigger($trigger) {
var href
var target = $trigger.attr('data-target')
|| (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7
return $(target)
}
// COLLAPSE PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.collapse')
var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data && options.toggle && option == 'show') options.toggle = false
if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.collapse
$.fn.collapse = Plugin
$.fn.collapse.Constructor = Collapse
// COLLAPSE NO CONFLICT
// ====================
$.fn.collapse.noConflict = function () {
$.fn.collapse = old
return this
}
// COLLAPSE DATA-API
// =================
$(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) {
var $this = $(this)
if (!$this.attr('data-target')) e.preventDefault()
var $target = getTargetFromTrigger($this)
var data = $target.data('bs.collapse')
var option = data ? 'toggle' : $.extend({}, $this.data(), { trigger: this })
Plugin.call($target, option)
})
}(jQuery);
/* ========================================================================
* Bootstrap: dropdown.js v3.3.2
* http://getbootstrap.com/javascript/#dropdowns
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// DROPDOWN CLASS DEFINITION
// =========================
var backdrop = '.dropdown-backdrop'
var toggle = '[data-toggle="dropdown"]'
var Dropdown = function (element) {
$(element).on('click.bs.dropdown', this.toggle)
}
Dropdown.VERSION = '3.3.2'
Dropdown.prototype.toggle = function (e) {
var $this = $(this)
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
clearMenus()
if (!isActive) {
if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
// if mobile we use a backdrop because click events don't delegate
$('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus)
}
var relatedTarget = { relatedTarget: this }
$parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this
.trigger('focus')
.attr('aria-expanded', 'true')
$parent
.toggleClass('open')
.trigger('shown.bs.dropdown', relatedTarget)
}
return false
}
Dropdown.prototype.keydown = function (e) {
if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return
var $this = $(this)
e.preventDefault()
e.stopPropagation()
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
if ((!isActive && e.which != 27) || (isActive && e.which == 27)) {
if (e.which == 27) $parent.find(toggle).trigger('focus')
return $this.trigger('click')
}
var desc = ' li:not(.divider):visible a'
var $items = $parent.find('[role="menu"]' + desc + ', [role="listbox"]' + desc)
if (!$items.length) return
var index = $items.index(e.target)
if (e.which == 38 && index > 0) index-- // up
if (e.which == 40 && index < $items.length - 1) index++ // down
if (!~index) index = 0
$items.eq(index).trigger('focus')
}
function clearMenus(e) {
if (e && e.which === 3) return
$(backdrop).remove()
$(toggle).each(function () {
var $this = $(this)
var $parent = getParent($this)
var relatedTarget = { relatedTarget: this }
if (!$parent.hasClass('open')) return
$parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this.attr('aria-expanded', 'false')
$parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget)
})
}
function getParent($this) {
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = selector && $(selector)
return $parent && $parent.length ? $parent : $this.parent()
}
// DROPDOWN PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.dropdown')
if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.dropdown
$.fn.dropdown = Plugin
$.fn.dropdown.Constructor = Dropdown
// DROPDOWN NO CONFLICT
// ====================
$.fn.dropdown.noConflict = function () {
$.fn.dropdown = old
return this
}
// APPLY TO STANDARD DROPDOWN ELEMENTS
// ===================================
$(document)
.on('click.bs.dropdown.data-api', clearMenus)
.on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
.on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
.on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown)
.on('keydown.bs.dropdown.data-api', '[role="menu"]', Dropdown.prototype.keydown)
.on('keydown.bs.dropdown.data-api', '[role="listbox"]', Dropdown.prototype.keydown)
}(jQuery);
/* ========================================================================
* Bootstrap: tab.js v3.3.2
* http://getbootstrap.com/javascript/#tabs
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TAB CLASS DEFINITION
// ====================
var Tab = function (element) {
this.element = $(element)
}
Tab.VERSION = '3.3.2'
Tab.TRANSITION_DURATION = 150
Tab.prototype.show = function () {
var $this = this.element
var $ul = $this.closest('ul:not(.dropdown-menu)')
var selector = $this.data('target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
if ($this.parent('li').hasClass('active')) return
var $previous = $ul.find('.active:last a')
var hideEvent = $.Event('hide.bs.tab', {
relatedTarget: $this[0]
})
var showEvent = $.Event('show.bs.tab', {
relatedTarget: $previous[0]
})
$previous.trigger(hideEvent)
$this.trigger(showEvent)
if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return
var $target = $(selector)
this.activate($this.closest('li'), $ul)
this.activate($target, $target.parent(), function () {
$previous.trigger({
type: 'hidden.bs.tab',
relatedTarget: $this[0]
})
$this.trigger({
type: 'shown.bs.tab',
relatedTarget: $previous[0]
})
})
}
Tab.prototype.activate = function (element, container, callback) {
var $active = container.find('> .active')
var transition = callback
&& $.support.transition
&& (($active.length && $active.hasClass('fade')) || !!container.find('> .fade').length)
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
.end()
.find('[data-toggle="tab"]')
.attr('aria-expanded', false)
element
.addClass('active')
.find('[data-toggle="tab"]')
.attr('aria-expanded', true)
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if (element.parent('.dropdown-menu')) {
element
.closest('li.dropdown')
.addClass('active')
.end()
.find('[data-toggle="tab"]')
.attr('aria-expanded', true)
}
callback && callback()
}
$active.length && transition ?
$active
.one('bsTransitionEnd', next)
.emulateTransitionEnd(Tab.TRANSITION_DURATION) :
next()
$active.removeClass('in')
}
// TAB PLUGIN DEFINITION
// =====================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tab')
if (!data) $this.data('bs.tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tab
$.fn.tab = Plugin
$.fn.tab.Constructor = Tab
// TAB NO CONFLICT
// ===============
$.fn.tab.noConflict = function () {
$.fn.tab = old
return this
}
// TAB DATA-API
// ============
var clickHandler = function (e) {
e.preventDefault()
Plugin.call($(this), 'show')
}
$(document)
.on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler)
.on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler)
}(jQuery);
/* ========================================================================
* Bootstrap: transition.js v3.3.2
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
WebkitTransition : 'webkitTransitionEnd',
MozTransition : 'transitionend',
OTransition : 'oTransitionEnd otransitionend',
transition : 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function (duration) {
var called = false
var $el = this
$(this).one('bsTransitionEnd', function () { called = true })
var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
setTimeout(callback, duration)
return this
}
$(function () {
$.support.transition = transitionEnd()
if (!$.support.transition) return
$.event.special.bsTransitionEnd = {
bindType: $.support.transition.end,
delegateType: $.support.transition.end,
handle: function (e) {
if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
}
}
})
}(jQuery);
/* ========================================================================
* Bootstrap: scrollspy.js v3.3.2
* http://getbootstrap.com/javascript/#scrollspy
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// SCROLLSPY CLASS DEFINITION
// ==========================
function ScrollSpy(element, options) {
var process = $.proxy(this.process, this)
this.$body = $('body')
this.$scrollElement = $(element).is('body') ? $(window) : $(element)
this.options = $.extend({}, ScrollSpy.DEFAULTS, options)
this.selector = (this.options.target || '') + ' .nav li > a'
this.offsets = []
this.targets = []
this.activeTarget = null
this.scrollHeight = 0
this.$scrollElement.on('scroll.bs.scrollspy', process)
this.refresh()
this.process()
}
ScrollSpy.VERSION = '3.3.2'
ScrollSpy.DEFAULTS = {
offset: 10
}
ScrollSpy.prototype.getScrollHeight = function () {
return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight)
}
ScrollSpy.prototype.refresh = function () {
var offsetMethod = 'offset'
var offsetBase = 0
if (!$.isWindow(this.$scrollElement[0])) {
offsetMethod = 'position'
offsetBase = this.$scrollElement.scrollTop()
}
this.offsets = []
this.targets = []
this.scrollHeight = this.getScrollHeight()
var self = this
this.$body
.find(this.selector)
.map(function () {
var $el = $(this)
var href = $el.data('target') || $el.attr('href')
var $href = /^#./.test(href) && $(href)
return ($href
&& $href.length
&& $href.is(':visible')
&& [[$href[offsetMethod]().top + offsetBase, href]]) || null
})
.sort(function (a, b) { return a[0] - b[0] })
.each(function () {
self.offsets.push(this[0])
self.targets.push(this[1])
})
}
ScrollSpy.prototype.process = function () {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
var scrollHeight = this.getScrollHeight()
var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height()
var offsets = this.offsets
var targets = this.targets
var activeTarget = this.activeTarget
var i
if (this.scrollHeight != scrollHeight) {
this.refresh()
}
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets[targets.length - 1]) && this.activate(i)
}
if (activeTarget && scrollTop < offsets[0]) {
this.activeTarget = null
return this.clear()
}
for (i = offsets.length; i--;) {
activeTarget != targets[i]
&& scrollTop >= offsets[i]
&& (!offsets[i + 1] || scrollTop <= offsets[i + 1])
&& this.activate(targets[i])
}
}
ScrollSpy.prototype.activate = function (target) {
this.activeTarget = target
this.clear()
var selector = this.selector +
'[data-target="' + target + '"],' +
this.selector + '[href="' + target + '"]'
var active = $(selector)
.parents('li')
.addClass('active')
if (active.parent('.dropdown-menu').length) {
active = active
.closest('li.dropdown')
.addClass('active')
}
active.trigger('activate.bs.scrollspy')
}
ScrollSpy.prototype.clear = function () {
$(this.selector)
.parentsUntil(this.options.target, '.active')
.removeClass('active')
}
// SCROLLSPY PLUGIN DEFINITION
// ===========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.scrollspy')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.scrollspy
$.fn.scrollspy = Plugin
$.fn.scrollspy.Constructor = ScrollSpy
// SCROLLSPY NO CONFLICT
// =====================
$.fn.scrollspy.noConflict = function () {
$.fn.scrollspy = old
return this
}
// SCROLLSPY DATA-API
// ==================
$(window).on('load.bs.scrollspy.data-api', function () {
$('[data-spy="scroll"]').each(function () {
var $spy = $(this)
Plugin.call($spy, $spy.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: modal.js v3.3.2
* http://getbootstrap.com/javascript/#modals
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// MODAL CLASS DEFINITION
// ======================
var Modal = function (element, options) {
this.options = options
this.$body = $(document.body)
this.$element = $(element)
this.$backdrop =
this.isShown = null
this.scrollbarWidth = 0
if (this.options.remote) {
this.$element
.find('.modal-content')
.load(this.options.remote, $.proxy(function () {
this.$element.trigger('loaded.bs.modal')
}, this))
}
}
Modal.VERSION = '3.3.2'
Modal.TRANSITION_DURATION = 300
Modal.BACKDROP_TRANSITION_DURATION = 150
Modal.DEFAULTS = {
backdrop: true,
keyboard: true,
show: true
}
Modal.prototype.toggle = function (_relatedTarget) {
return this.isShown ? this.hide() : this.show(_relatedTarget)
}
Modal.prototype.show = function (_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.checkScrollbar()
this.setScrollbar()
this.$body.addClass('modal-open')
this.escape()
this.resize()
this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
this.backdrop(function () {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(that.$body) // don't move modals dom position
}
that.$element
.show()
.scrollTop(0)
if (that.options.backdrop) that.adjustBackdrop()
that.adjustDialog()
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element
.addClass('in')
.attr('aria-hidden', false)
that.enforceFocus()
var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
transition ?
that.$element.find('.modal-dialog') // wait for modal to slide in
.one('bsTransitionEnd', function () {
that.$element.trigger('focus').trigger(e)
})
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
that.$element.trigger('focus').trigger(e)
})
}
Modal.prototype.hide = function (e) {
if (e) e.preventDefault()
e = $.Event('hide.bs.modal')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.escape()
this.resize()
$(document).off('focusin.bs.modal')
this.$element
.removeClass('in')
.attr('aria-hidden', true)
.off('click.dismiss.bs.modal')
$.support.transition && this.$element.hasClass('fade') ?
this.$element
.one('bsTransitionEnd', $.proxy(this.hideModal, this))
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
this.hideModal()
}
Modal.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
this.$element.trigger('focus')
}
}, this))
}
Modal.prototype.escape = function () {
if (this.isShown && this.options.keyboard) {
this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) {
e.which == 27 && this.hide()
}, this))
} else if (!this.isShown) {
this.$element.off('keydown.dismiss.bs.modal')
}
}
Modal.prototype.resize = function () {
if (this.isShown) {
$(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this))
} else {
$(window).off('resize.bs.modal')
}
}
Modal.prototype.hideModal = function () {
var that = this
this.$element.hide()
this.backdrop(function () {
that.$body.removeClass('modal-open')
that.resetAdjustments()
that.resetScrollbar()
that.$element.trigger('hidden.bs.modal')
})
}
Modal.prototype.removeBackdrop = function () {
this.$backdrop && this.$backdrop.remove()
this.$backdrop = null
}
Modal.prototype.backdrop = function (callback) {
var that = this
var animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
.prependTo(this.$element)
.on('click.dismiss.bs.modal', $.proxy(function (e) {
if (e.target !== e.currentTarget) return
this.options.backdrop == 'static'
? this.$element[0].focus.call(this.$element[0])
: this.hide.call(this)
}, this))
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
if (!callback) return
doAnimate ?
this.$backdrop
.one('bsTransitionEnd', callback)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
var callbackRemove = function () {
that.removeBackdrop()
callback && callback()
}
$.support.transition && this.$element.hasClass('fade') ?
this.$backdrop
.one('bsTransitionEnd', callbackRemove)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callbackRemove()
} else if (callback) {
callback()
}
}
// these following methods are used to handle overflowing modals
Modal.prototype.handleUpdate = function () {
if (this.options.backdrop) this.adjustBackdrop()
this.adjustDialog()
}
Modal.prototype.adjustBackdrop = function () {
this.$backdrop
.css('height', 0)
.css('height', this.$element[0].scrollHeight)
}
Modal.prototype.adjustDialog = function () {
var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight
this.$element.css({
paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '',
paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : ''
})
}
Modal.prototype.resetAdjustments = function () {
this.$element.css({
paddingLeft: '',
paddingRight: ''
})
}
Modal.prototype.checkScrollbar = function () {
this.bodyIsOverflowing = document.body.scrollHeight > document.documentElement.clientHeight
this.scrollbarWidth = this.measureScrollbar()
}
Modal.prototype.setScrollbar = function () {
var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
}
Modal.prototype.resetScrollbar = function () {
this.$body.css('padding-right', '')
}
Modal.prototype.measureScrollbar = function () { // thx walsh
var scrollDiv = document.createElement('div')
scrollDiv.className = 'modal-scrollbar-measure'
this.$body.append(scrollDiv)
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
this.$body[0].removeChild(scrollDiv)
return scrollbarWidth
}
// MODAL PLUGIN DEFINITION
// =======================
function Plugin(option, _relatedTarget) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.modal')
var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option](_relatedTarget)
else if (options.show) data.show(_relatedTarget)
})
}
var old = $.fn.modal
$.fn.modal = Plugin
$.fn.modal.Constructor = Modal
// MODAL NO CONFLICT
// =================
$.fn.modal.noConflict = function () {
$.fn.modal = old
return this
}
// MODAL DATA-API
// ==============
$(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
var href = $this.attr('href')
var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
if ($this.is('a')) e.preventDefault()
$target.one('show.bs.modal', function (showEvent) {
if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
$target.one('hidden.bs.modal', function () {
$this.is(':visible') && $this.trigger('focus')
})
})
Plugin.call($target, option, this)
})
}(jQuery);
/* ========================================================================
* Bootstrap: tooltip.js v3.3.2
* http://getbootstrap.com/javascript/#tooltip
* Inspired by the original jQuery.tipsy by Jason Frame
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TOOLTIP PUBLIC CLASS DEFINITION
// ===============================
var Tooltip = function (element, options) {
this.type =
this.options =
this.enabled =
this.timeout =
this.hoverState =
this.$element = null
this.init('tooltip', element, options)
}
Tooltip.VERSION = '3.3.2'
Tooltip.TRANSITION_DURATION = 150
Tooltip.DEFAULTS = {
animation: true,
placement: 'top',
selector: false,
template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
trigger: 'hover focus',
title: '',
delay: 0,
html: false,
container: false,
viewport: {
selector: 'body',
padding: 0
}
}
Tooltip.prototype.init = function (type, element, options) {
this.enabled = true
this.type = type
this.$element = $(element)
this.options = this.getOptions(options)
this.$viewport = this.options.viewport && $(this.options.viewport.selector || this.options.viewport)
var triggers = this.options.trigger.split(' ')
for (var i = triggers.length; i--;) {
var trigger = triggers[i]
if (trigger == 'click') {
this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
} else if (trigger != 'manual') {
var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin'
var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'
this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
}
}
this.options.selector ?
(this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
this.fixTitle()
}
Tooltip.prototype.getDefaults = function () {
return Tooltip.DEFAULTS
}
Tooltip.prototype.getOptions = function (options) {
options = $.extend({}, this.getDefaults(), this.$element.data(), options)
if (options.delay && typeof options.delay == 'number') {
options.delay = {
show: options.delay,
hide: options.delay
}
}
return options
}
Tooltip.prototype.getDelegateOptions = function () {
var options = {}
var defaults = this.getDefaults()
this._options && $.each(this._options, function (key, value) {
if (defaults[key] != value) options[key] = value
})
return options
}
Tooltip.prototype.enter = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (self && self.$tip && self.$tip.is(':visible')) {
self.hoverState = 'in'
return
}
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
clearTimeout(self.timeout)
self.hoverState = 'in'
if (!self.options.delay || !self.options.delay.show) return self.show()
self.timeout = setTimeout(function () {
if (self.hoverState == 'in') self.show()
}, self.options.delay.show)
}
Tooltip.prototype.leave = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
clearTimeout(self.timeout)
self.hoverState = 'out'
if (!self.options.delay || !self.options.delay.hide) return self.hide()
self.timeout = setTimeout(function () {
if (self.hoverState == 'out') self.hide()
}, self.options.delay.hide)
}
Tooltip.prototype.show = function () {
var e = $.Event('show.bs.' + this.type)
if (this.hasContent() && this.enabled) {
this.$element.trigger(e)
var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0])
if (e.isDefaultPrevented() || !inDom) return
var that = this
var $tip = this.tip()
var tipId = this.getUID(this.type)
this.setContent()
$tip.attr('id', tipId)
this.$element.attr('aria-describedby', tipId)
if (this.options.animation) $tip.addClass('fade')
var placement = typeof this.options.placement == 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement
var autoToken = /\s?auto?\s?/i
var autoPlace = autoToken.test(placement)
if (autoPlace) placement = placement.replace(autoToken, '') || 'top'
$tip
.detach()
.css({ top: 0, left: 0, display: 'block' })
.addClass(placement)
.data('bs.' + this.type, this)
this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
var pos = this.getPosition()
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (autoPlace) {
var orgPlacement = placement
var $container = this.options.container ? $(this.options.container) : this.$element.parent()
var containerDim = this.getPosition($container)
placement = placement == 'bottom' && pos.bottom + actualHeight > containerDim.bottom ? 'top' :
placement == 'top' && pos.top - actualHeight < containerDim.top ? 'bottom' :
placement == 'right' && pos.right + actualWidth > containerDim.width ? 'left' :
placement == 'left' && pos.left - actualWidth < containerDim.left ? 'right' :
placement
$tip
.removeClass(orgPlacement)
.addClass(placement)
}
var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
this.applyPlacement(calculatedOffset, placement)
var complete = function () {
var prevHoverState = that.hoverState
that.$element.trigger('shown.bs.' + that.type)
that.hoverState = null
if (prevHoverState == 'out') that.leave(that)
}
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
}
}
Tooltip.prototype.applyPlacement = function (offset, placement) {
var $tip = this.tip()
var width = $tip[0].offsetWidth
var height = $tip[0].offsetHeight
// manually read margins because getBoundingClientRect includes difference
var marginTop = parseInt($tip.css('margin-top'), 10)
var marginLeft = parseInt($tip.css('margin-left'), 10)
// we must check for NaN for ie 8/9
if (isNaN(marginTop)) marginTop = 0
if (isNaN(marginLeft)) marginLeft = 0
offset.top = offset.top + marginTop
offset.left = offset.left + marginLeft
// $.fn.offset doesn't round pixel values
// so we use setOffset directly with our own function B-0
$.offset.setOffset($tip[0], $.extend({
using: function (props) {
$tip.css({
top: Math.round(props.top),
left: Math.round(props.left)
})
}
}, offset), 0)
$tip.addClass('in')
// check to see if placing tip in new offset caused the tip to resize itself
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (placement == 'top' && actualHeight != height) {
offset.top = offset.top + height - actualHeight
}
var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)
if (delta.left) offset.left += delta.left
else offset.top += delta.top
var isVertical = /top|bottom/.test(placement)
var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight'
$tip.offset(offset)
this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical)
}
Tooltip.prototype.replaceArrow = function (delta, dimension, isHorizontal) {
this.arrow()
.css(isHorizontal ? 'left' : 'top', 50 * (1 - delta / dimension) + '%')
.css(isHorizontal ? 'top' : 'left', '')
}
Tooltip.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
$tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
$tip.removeClass('fade in top bottom left right')
}
Tooltip.prototype.hide = function (callback) {
var that = this
var $tip = this.tip()
var e = $.Event('hide.bs.' + this.type)
function complete() {
if (that.hoverState != 'in') $tip.detach()
that.$element
.removeAttr('aria-describedby')
.trigger('hidden.bs.' + that.type)
callback && callback()
}
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$tip.removeClass('in')
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
this.hoverState = null
return this
}
Tooltip.prototype.fixTitle = function () {
var $e = this.$element
if ($e.attr('title') || typeof ($e.attr('data-original-title')) != 'string') {
$e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
}
}
Tooltip.prototype.hasContent = function () {
return this.getTitle()
}
Tooltip.prototype.getPosition = function ($element) {
$element = $element || this.$element
var el = $element[0]
var isBody = el.tagName == 'BODY'
var elRect = el.getBoundingClientRect()
if (elRect.width == null) {
// width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093
elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top })
}
var elOffset = isBody ? { top: 0, left: 0 } : $element.offset()
var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() }
var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null
return $.extend({}, elRect, scroll, outerDims, elOffset)
}
Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
/* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }
}
Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) {
var delta = { top: 0, left: 0 }
if (!this.$viewport) return delta
var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
var viewportDimensions = this.getPosition(this.$viewport)
if (/right|left/.test(placement)) {
var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll
var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
if (topEdgeOffset < viewportDimensions.top) { // top overflow
delta.top = viewportDimensions.top - topEdgeOffset
} else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
}
} else {
var leftEdgeOffset = pos.left - viewportPadding
var rightEdgeOffset = pos.left + viewportPadding + actualWidth
if (leftEdgeOffset < viewportDimensions.left) { // left overflow
delta.left = viewportDimensions.left - leftEdgeOffset
} else if (rightEdgeOffset > viewportDimensions.width) { // right overflow
delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
}
}
return delta
}
Tooltip.prototype.getTitle = function () {
var title
var $e = this.$element
var o = this.options
title = $e.attr('data-original-title')
|| (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
return title
}
Tooltip.prototype.getUID = function (prefix) {
do prefix += ~~(Math.random() * 1000000)
while (document.getElementById(prefix))
return prefix
}
Tooltip.prototype.tip = function () {
return (this.$tip = this.$tip || $(this.options.template))
}
Tooltip.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
}
Tooltip.prototype.enable = function () {
this.enabled = true
}
Tooltip.prototype.disable = function () {
this.enabled = false
}
Tooltip.prototype.toggleEnabled = function () {
this.enabled = !this.enabled
}
Tooltip.prototype.toggle = function (e) {
var self = this
if (e) {
self = $(e.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(e.currentTarget, this.getDelegateOptions())
$(e.currentTarget).data('bs.' + this.type, self)
}
}
self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
}
Tooltip.prototype.destroy = function () {
var that = this
clearTimeout(this.timeout)
this.hide(function () {
that.$element.off('.' + that.type).removeData('bs.' + that.type)
})
}
// TOOLTIP PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tooltip')
var options = typeof option == 'object' && option
if (!data && option == 'destroy') return
if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tooltip
$.fn.tooltip = Plugin
$.fn.tooltip.Constructor = Tooltip
// TOOLTIP NO CONFLICT
// ===================
$.fn.tooltip.noConflict = function () {
$.fn.tooltip = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: popover.js v3.3.2
* http://getbootstrap.com/javascript/#popovers
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// POPOVER PUBLIC CLASS DEFINITION
// ===============================
var Popover = function (element, options) {
this.init('popover', element, options)
}
if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')
Popover.VERSION = '3.3.2'
Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, {
placement: 'right',
trigger: 'click',
content: '',
template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
})
// NOTE: POPOVER EXTENDS tooltip.js
// ================================
Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)
Popover.prototype.constructor = Popover
Popover.prototype.getDefaults = function () {
return Popover.DEFAULTS
}
Popover.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
var content = this.getContent()
$tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
$tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events
this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text'
](content)
$tip.removeClass('fade top bottom left right in')
// IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
// this manually by checking the contents.
if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
}
Popover.prototype.hasContent = function () {
return this.getTitle() || this.getContent()
}
Popover.prototype.getContent = function () {
var $e = this.$element
var o = this.options
return $e.attr('data-content')
|| (typeof o.content == 'function' ?
o.content.call($e[0]) :
o.content)
}
Popover.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.arrow'))
}
Popover.prototype.tip = function () {
if (!this.$tip) this.$tip = $(this.options.template)
return this.$tip
}
// POPOVER PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.popover')
var options = typeof option == 'object' && option
if (!data && option == 'destroy') return
if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.popover
$.fn.popover = Plugin
$.fn.popover.Constructor = Popover
// POPOVER NO CONFLICT
// ===================
$.fn.popover.noConflict = function () {
$.fn.popover = old
return this
}
}(jQuery);
|
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var React = require("react");
var Utilities_1 = require("../../Utilities");
var stylesImport = require("./Check.scss");
var styles = stylesImport;
var Check = (function (_super) {
__extends(Check, _super);
function Check() {
return _super !== null && _super.apply(this, arguments) || this;
}
Check.prototype.shouldComponentUpdate = function (newProps) {
return this.props.isChecked !== newProps.isChecked || this.props.checked !== newProps.checked;
};
Check.prototype.render = function () {
var _a = this.props, isChecked = _a.isChecked, checked = _a.checked;
isChecked = isChecked || checked;
return (React.createElement("div", { className: Utilities_1.css('ms-Check', styles.root, (_b = {},
_b['is-checked ' + styles.rootIsChecked] = isChecked,
_b)) },
React.createElement("div", { className: Utilities_1.css('ms-Icon ms-Check-background', styles.background) }),
React.createElement("i", { className: Utilities_1.css('ms-Check-check ms-Icon ms-Icon--CheckMark', styles.check) })));
var _b;
};
return Check;
}(Utilities_1.BaseComponent));
Check.defaultProps = {
isChecked: false
};
exports.Check = Check;
//# sourceMappingURL=Check.js.map
|
var Buffer = require('buffer').Buffer,
Jpeg = require('jpeg').Jpeg;
function randomColorComponent() {
return Math.floor(Math.random() * 256);
}
/**
* Creates a random image
*/
module.exports = function(width, height, callback) {
var buffer = new Buffer(width * height * 3);
for (var x = 0; x < width; x++) {
for (var y = 0; y < height; y++) {
var pixelStart = x * width * 3 + y * 3;
buffer[pixelStart + 0] = randomColorComponent();
buffer[pixelStart + 1] = randomColorComponent();
buffer[pixelStart + 2] = randomColorComponent();
}
}
var image = new Jpeg(buffer, width, height);
image.encode(function(result) {
callback(null, result);
});
};
|
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import themed from '@rentpath/react-themed'
import clsx from 'clsx'
import isEqual from 'lodash/isEqual'
import { randomId } from '@rentpath/react-ui-utils'
import SubmitButton from './SubmitButton'
import Header from './Header'
import {
Form,
Field,
Name,
Message,
Email,
Phone,
RadioGroup,
OptInNewsLetter,
TermsOfService,
} from '../Form'
const FIELD_MAPPING = {
header: Header,
name: Name,
message: Message,
email: Email,
phone: Phone,
tos: TermsOfService,
submit: SubmitButton,
opt_in_newsletter: OptInNewsLetter,
terms_of_service: TermsOfService,
}
const FIELDS = [
{ name: 'header' },
{ name: 'message' },
{ name: 'name' },
{ name: 'email' },
{ name: 'phone' },
{ name: 'submit' },
{ name: 'opt_in_newsletter' },
{ name: 'terms_of_service' },
]
@themed(/^(LeadForm|Field)/)
export default class LeadForm extends Component {
static propTypes = {
theme: PropTypes.object,
className: PropTypes.string,
fields: PropTypes.arrayOf(
PropTypes.shape({
name: PropTypes.string,
field: PropTypes.oneOfType([
PropTypes.func,
PropTypes.node,
]),
}),
),
children: PropTypes.node,
}
static defaultProps = {
theme: {},
fields: FIELDS,
}
constructor(props) {
super(props)
this.generateRandomId()
}
componentWillReceiveProps() {
this.generateRandomId()
}
shouldComponentUpdate(nextProps) {
return !isEqual(this.props.fields, nextProps.fields)
}
get fields() {
const { fields } = this.props
return fields.map(fieldComposition => {
const {
field,
className,
...props
} = fieldComposition
const name = props.name
const FormField = field || FIELD_MAPPING[name] || this.fallbackField(props.type)
return (
<FormField
data-tid={`lead-form-${name}`}
key={`${this.id}-${name}`}
{...props}
/>
)
})
}
generateRandomId() {
this.id = randomId('leadform')
}
fallbackField(type) {
return type === 'radiogroup' ? RadioGroup : Field
}
render() {
const {
className,
theme,
fields,
children,
...props
} = this.props
return (
<Form
className={clsx(
theme.LeadForm,
className,
)}
{...props}
>
{this.fields}
{children}
</Form>
)
}
}
|
export * from './user';
export * from './template'; |
var gulp = require("gulp"),
del = require("del"),
ts = require("gulp-typescript"),
tsProject = ts.createProject("tsconfig.json")
typedoc = require("gulp-typedoc");
var compileTS = function () {
return tsProject.src()
.pipe(tsProject())
.js.pipe(gulp.dest("app"));
};
gulp.task("doc", function() {
return gulp
.src(["src/**/*.ts"])
.pipe(typedoc({
module: "commonjs",
target: "es5",
out: "docs/",
name: "My project title"
}))
;
});
gulp.task("ts", compileTS);
gulp.task("cleanup", function() {
return del([__dirname + "/app"]);
});
gulp.task("default", ["cleanup", "ts"], function () {
compileTS();
gulp.watch("src/**/*.ts", ["ts"]);
}); |
/* global describe, it, beforeEach */
'use strict';
process.env.NODE_ENV = 'test';
var sharedModule = require('../lib/module-shared');
var instance1;
var instance2;
var should = require('should');
var stubs = {};
describe('Private Module Tests', function () {
beforeEach(function (done) {
for (var stub in stubs) {
try {
stubs[stub].restore();
}
catch (err) {}
}
done();
});
describe('Initializing', function () {
describe('when creating a new instance of the module', function () {
it('should not have an error', function (done) {
var x = sharedModule({
mocking: true
});
x.should.have.property('initializeModule');
should.not.exist(x.initialized);
done();
});
});
});
describe('Function Calls', function () {
describe('when calling "initializeModule"', function () {
it('should not have an error', function (done) {
var x = sharedModule({
mocking: {}
});
x.should.have.property('initializeModule');
should.not.exist(x.initialized);
x.initializeModule(x);
should.exist(x.initialized);
done();
});
});
describe('when creating more than one instance', function () {
describe('and the module is already initialized', function () {
it('the new instance should return the first created instance', function (done) {
instance1 = sharedModule({
mocking: true
});
instance2 = sharedModule({
mocking: true
});
should.exist(instance1.initialized);
instance1.initialized.should.equal(true);
done();
});
});
describe('if we add .name = "instance1" to the first instance', function () {
it('"instance2" should have a name', function (done) {
delete instance1.name;
delete instance2.name;
instance1.name = 'instance1';
instance1.name.should.equal('instance1');
instance2.name.should.equal('instance1');
done();
});
});
describe('if we add .name = "instance2" to the second instance', function () {
it('"instance1" should have a name', function (done) {
delete instance1.name;
delete instance2.name;
instance2.name = 'instance2';
instance2.name.should.equal('instance2');
instance1.name.should.equal('instance2');
done();
});
});
describe('if we add .name to both instances and they are different names', function () {
it('they should still have the same names', function (done) {
delete instance1.name;
delete instance2.name;
instance1.name = 'instance1';
instance1.name.should.equal('instance1');
instance2.name.should.equal('instance1');
instance2.name = 'instance2';
instance1.name.should.equal('instance2');
instance2.name.should.equal('instance2');
instance1.name.should.equal(instance2.name);
instance2.name.should.equal(instance1.name);
done();
});
});
});
});
});
|
Subsets and Splits