code
stringlengths 2
1.05M
|
---|
import {
isArray,
isMaybeThenable
} from './utils';
import {
noop,
reject,
fulfill,
subscribe,
FULFILLED,
REJECTED,
PENDING,
handleMaybeThenable
} from './-internal';
import then from './then';
import Promise from './promise';
import originalResolve from './promise/resolve';
import originalThen from './then';
import { makePromise, PROMISE_ID } from './-internal';
function validationError() {
return new Error('Array Methods must be provided an Array');
};
export default class Enumerator {
constructor(Constructor, input) {
this._instanceConstructor = Constructor;
this.promise = new Constructor(noop);
if (!this.promise[PROMISE_ID]) {
makePromise(this.promise);
}
if (isArray(input)) {
this.length = input.length;
this._remaining = input.length;
this._result = new Array(this.length);
if (this.length === 0) {
fulfill(this.promise, this._result);
} else {
this.length = this.length || 0;
this._enumerate(input);
if (this._remaining === 0) {
fulfill(this.promise, this._result);
}
}
} else {
reject(this.promise, validationError());
}
}
_enumerate(input) {
for (let i = 0; this._state === PENDING && i < input.length; i++) {
this._eachEntry(input[i], i);
}
}
_eachEntry(entry, i) {
let c = this._instanceConstructor;
let { resolve } = c;
if (resolve === originalResolve) {
let then;
let error;
let didError = false;
try {
then = entry.then;
} catch (e) {
didError = true;
error = e;
}
if (then === originalThen &&
entry._state !== PENDING) {
this._settledAt(entry._state, i, entry._result);
} else if (typeof then !== 'function') {
this._remaining--;
this._result[i] = entry;
} else if (c === Promise) {
let promise = new c(noop);
if (didError) {
reject(promise, error);
} else {
handleMaybeThenable(promise, entry, then);
}
this._willSettleAt(promise, i);
} else {
this._willSettleAt(new c(resolve => resolve(entry)), i);
}
} else {
this._willSettleAt(resolve(entry), i);
}
}
_settledAt(state, i, value) {
let { promise } = this;
if (promise._state === PENDING) {
this._remaining--;
if (state === REJECTED) {
reject(promise, value);
} else {
this._result[i] = value;
}
}
if (this._remaining === 0) {
fulfill(promise, this._result);
}
}
_willSettleAt(promise, i) {
let enumerator = this;
subscribe(
promise, undefined,
value => enumerator._settledAt(FULFILLED, i, value),
reason => enumerator._settledAt(REJECTED, i, reason)
);
}
};
|
/*
This file is part of Ext JS 4
Copyright (c) 2011 Sencha Inc
Contact: http://www.sencha.com/contact
GNU General Public License Usage
This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file. Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.
If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
*/
/**
* @class Ext.fx.target.CompositeElementCSS
* @extends Ext.fx.target.CompositeElement
*
* This class represents a animation target for a {@link Ext.CompositeElement}, where the
* constituent elements support CSS based animation. It allows each {@link Ext.core.Element} in
* the group to be animated as a whole. In general this class will not be created directly,
* the {@link Ext.CompositeElement} will be passed to the animation and the appropriate target
* will be created.
*/
Ext.define('Ext.fx.target.CompositeElementCSS', {
/* Begin Definitions */
extend: 'Ext.fx.target.CompositeElement',
requires: ['Ext.fx.target.ElementCSS'],
/* End Definitions */
setAttr: function() {
return Ext.fx.target.ElementCSS.prototype.setAttr.apply(this, arguments);
}
});
|
/*! jQuery UI - v1.9.2 - 2014-06-04
* http://jqueryui.com
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(e){e.datepicker.regional.he={closeText:"סגור",prevText:"<הקודם",nextText:"הבא>",currentText:"היום",monthNames:["ינואר","פברואר","מרץ","אפריל","מאי","יוני","יולי","אוגוסט","ספטמבר","אוקטובר","נובמבר","דצמבר"],monthNamesShort:["ינו","פבר","מרץ","אפר","מאי","יוני","יולי","אוג","ספט","אוק","נוב","דצמ"],dayNames:["ראשון","שני","שלישי","רביעי","חמישי","שישי","שבת"],dayNamesShort:["א'","ב'","ג'","ד'","ה'","ו'","שבת"],dayNamesMin:["א'","ב'","ג'","ד'","ה'","ו'","שבת"],weekHeader:"Wk",dateFormat:"dd/mm/yy",firstDay:0,isRTL:!0,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional.he)});
|
/*
* Copyright (c) 2006-2007 Erin Catto http:
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked, and must not be
* misrepresented the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
// The pair manager is used by the broad-phase to quickly add/remove/find pairs
// of overlapping proxies. It is based closely on code provided by Pierre Terdiman.
// http:
var b2Pair = Class.create();
b2Pair.prototype =
{
SetBuffered: function() { this.status |= b2Pair.e_pairBuffered; },
ClearBuffered: function() { this.status &= ~b2Pair.e_pairBuffered; },
IsBuffered: function(){ return (this.status & b2Pair.e_pairBuffered) == b2Pair.e_pairBuffered; },
SetRemoved: function() { this.status |= b2Pair.e_pairRemoved; },
ClearRemoved: function() { this.status &= ~b2Pair.e_pairRemoved; },
IsRemoved: function(){ return (this.status & b2Pair.e_pairRemoved) == b2Pair.e_pairRemoved; },
SetFinal: function() { this.status |= b2Pair.e_pairFinal; },
IsFinal: function(){ return (this.status & b2Pair.e_pairFinal) == b2Pair.e_pairFinal; },
userData: null,
proxyId1: 0,
proxyId2: 0,
next: 0,
status: 0,
// STATIC
// enum
initialize: function() {}};
b2Pair.b2_nullPair = b2Settings.USHRT_MAX;
b2Pair.b2_nullProxy = b2Settings.USHRT_MAX;
b2Pair.b2_tableCapacity = b2Settings.b2_maxPairs;
b2Pair.b2_tableMask = b2Pair.b2_tableCapacity - 1;
b2Pair.e_pairBuffered = 0x0001;
b2Pair.e_pairRemoved = 0x0002;
b2Pair.e_pairFinal = 0x0004;
|
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0): carousel.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Carousel = function ($) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'carousel';
var VERSION = '4.0.0';
var DATA_KEY = 'bs.carousel';
var EVENT_KEY = "." + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var TRANSITION_DURATION = 600;
var ARROW_LEFT_KEYCODE = 37; // KeyboardEvent.which value for left arrow key
var ARROW_RIGHT_KEYCODE = 39; // KeyboardEvent.which value for right arrow key
var TOUCHEVENT_COMPAT_WAIT = 500; // Time for mouse compat events to fire after touch
var Default = {
interval: 5000,
keyboard: true,
slide: false,
pause: 'hover',
wrap: true
};
var DefaultType = {
interval: '(number|boolean)',
keyboard: 'boolean',
slide: '(boolean|string)',
pause: '(string|boolean)',
wrap: 'boolean'
};
var Direction = {
NEXT: 'next',
PREV: 'prev',
LEFT: 'left',
RIGHT: 'right'
};
var Event = {
SLIDE: "slide" + EVENT_KEY,
SLID: "slid" + EVENT_KEY,
KEYDOWN: "keydown" + EVENT_KEY,
MOUSEENTER: "mouseenter" + EVENT_KEY,
MOUSELEAVE: "mouseleave" + EVENT_KEY,
TOUCHEND: "touchend" + EVENT_KEY,
LOAD_DATA_API: "load" + EVENT_KEY + DATA_API_KEY,
CLICK_DATA_API: "click" + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
CAROUSEL: 'carousel',
ACTIVE: 'active',
SLIDE: 'slide',
RIGHT: 'carousel-item-right',
LEFT: 'carousel-item-left',
NEXT: 'carousel-item-next',
PREV: 'carousel-item-prev',
ITEM: 'carousel-item'
};
var Selector = {
ACTIVE: '.active',
ACTIVE_ITEM: '.active.carousel-item',
ITEM: '.carousel-item',
NEXT_PREV: '.carousel-item-next, .carousel-item-prev',
INDICATORS: '.carousel-indicators',
DATA_SLIDE: '[data-slide], [data-slide-to]',
DATA_RIDE: '[data-ride="carousel"]'
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
};
var Carousel =
/*#__PURE__*/
function () {
function Carousel(element, config) {
this._items = null;
this._interval = null;
this._activeElement = null;
this._isPaused = false;
this._isSliding = false;
this.touchTimeout = null;
this._config = this._getConfig(config);
this._element = $(element)[0];
this._indicatorsElement = $(this._element).find(Selector.INDICATORS)[0];
this._addEventListeners();
} // Getters
var _proto = Carousel.prototype;
// Public
_proto.next = function next() {
if (!this._isSliding) {
this._slide(Direction.NEXT);
}
};
_proto.nextWhenVisible = function nextWhenVisible() {
// Don't call next when the page isn't visible
// or the carousel or its parent isn't visible
if (!document.hidden && $(this._element).is(':visible') && $(this._element).css('visibility') !== 'hidden') {
this.next();
}
};
_proto.prev = function prev() {
if (!this._isSliding) {
this._slide(Direction.PREV);
}
};
_proto.pause = function pause(event) {
if (!event) {
this._isPaused = true;
}
if ($(this._element).find(Selector.NEXT_PREV)[0] && Util.supportsTransitionEnd()) {
Util.triggerTransitionEnd(this._element);
this.cycle(true);
}
clearInterval(this._interval);
this._interval = null;
};
_proto.cycle = function cycle(event) {
if (!event) {
this._isPaused = false;
}
if (this._interval) {
clearInterval(this._interval);
this._interval = null;
}
if (this._config.interval && !this._isPaused) {
this._interval = setInterval((document.visibilityState ? this.nextWhenVisible : this.next).bind(this), this._config.interval);
}
};
_proto.to = function to(index) {
var _this = this;
this._activeElement = $(this._element).find(Selector.ACTIVE_ITEM)[0];
var activeIndex = this._getItemIndex(this._activeElement);
if (index > this._items.length - 1 || index < 0) {
return;
}
if (this._isSliding) {
$(this._element).one(Event.SLID, function () {
return _this.to(index);
});
return;
}
if (activeIndex === index) {
this.pause();
this.cycle();
return;
}
var direction = index > activeIndex ? Direction.NEXT : Direction.PREV;
this._slide(direction, this._items[index]);
};
_proto.dispose = function dispose() {
$(this._element).off(EVENT_KEY);
$.removeData(this._element, DATA_KEY);
this._items = null;
this._config = null;
this._element = null;
this._interval = null;
this._isPaused = null;
this._isSliding = null;
this._activeElement = null;
this._indicatorsElement = null;
}; // Private
_proto._getConfig = function _getConfig(config) {
config = _extends({}, Default, config);
Util.typeCheckConfig(NAME, config, DefaultType);
return config;
};
_proto._addEventListeners = function _addEventListeners() {
var _this2 = this;
if (this._config.keyboard) {
$(this._element).on(Event.KEYDOWN, function (event) {
return _this2._keydown(event);
});
}
if (this._config.pause === 'hover') {
$(this._element).on(Event.MOUSEENTER, function (event) {
return _this2.pause(event);
}).on(Event.MOUSELEAVE, function (event) {
return _this2.cycle(event);
});
if ('ontouchstart' in document.documentElement) {
// If it's a touch-enabled device, mouseenter/leave are fired as
// part of the mouse compatibility events on first tap - the carousel
// would stop cycling until user tapped out of it;
// here, we listen for touchend, explicitly pause the carousel
// (as if it's the second time we tap on it, mouseenter compat event
// is NOT fired) and after a timeout (to allow for mouse compatibility
// events to fire) we explicitly restart cycling
$(this._element).on(Event.TOUCHEND, function () {
_this2.pause();
if (_this2.touchTimeout) {
clearTimeout(_this2.touchTimeout);
}
_this2.touchTimeout = setTimeout(function (event) {
return _this2.cycle(event);
}, TOUCHEVENT_COMPAT_WAIT + _this2._config.interval);
});
}
}
};
_proto._keydown = function _keydown(event) {
if (/input|textarea/i.test(event.target.tagName)) {
return;
}
switch (event.which) {
case ARROW_LEFT_KEYCODE:
event.preventDefault();
this.prev();
break;
case ARROW_RIGHT_KEYCODE:
event.preventDefault();
this.next();
break;
default:
}
};
_proto._getItemIndex = function _getItemIndex(element) {
this._items = $.makeArray($(element).parent().find(Selector.ITEM));
return this._items.indexOf(element);
};
_proto._getItemByDirection = function _getItemByDirection(direction, activeElement) {
var isNextDirection = direction === Direction.NEXT;
var isPrevDirection = direction === Direction.PREV;
var activeIndex = this._getItemIndex(activeElement);
var lastItemIndex = this._items.length - 1;
var isGoingToWrap = isPrevDirection && activeIndex === 0 || isNextDirection && activeIndex === lastItemIndex;
if (isGoingToWrap && !this._config.wrap) {
return activeElement;
}
var delta = direction === Direction.PREV ? -1 : 1;
var itemIndex = (activeIndex + delta) % this._items.length;
return itemIndex === -1 ? this._items[this._items.length - 1] : this._items[itemIndex];
};
_proto._triggerSlideEvent = function _triggerSlideEvent(relatedTarget, eventDirectionName) {
var targetIndex = this._getItemIndex(relatedTarget);
var fromIndex = this._getItemIndex($(this._element).find(Selector.ACTIVE_ITEM)[0]);
var slideEvent = $.Event(Event.SLIDE, {
relatedTarget: relatedTarget,
direction: eventDirectionName,
from: fromIndex,
to: targetIndex
});
$(this._element).trigger(slideEvent);
return slideEvent;
};
_proto._setActiveIndicatorElement = function _setActiveIndicatorElement(element) {
if (this._indicatorsElement) {
$(this._indicatorsElement).find(Selector.ACTIVE).removeClass(ClassName.ACTIVE);
var nextIndicator = this._indicatorsElement.children[this._getItemIndex(element)];
if (nextIndicator) {
$(nextIndicator).addClass(ClassName.ACTIVE);
}
}
};
_proto._slide = function _slide(direction, element) {
var _this3 = this;
var activeElement = $(this._element).find(Selector.ACTIVE_ITEM)[0];
var activeElementIndex = this._getItemIndex(activeElement);
var nextElement = element || activeElement && this._getItemByDirection(direction, activeElement);
var nextElementIndex = this._getItemIndex(nextElement);
var isCycling = Boolean(this._interval);
var directionalClassName;
var orderClassName;
var eventDirectionName;
if (direction === Direction.NEXT) {
directionalClassName = ClassName.LEFT;
orderClassName = ClassName.NEXT;
eventDirectionName = Direction.LEFT;
} else {
directionalClassName = ClassName.RIGHT;
orderClassName = ClassName.PREV;
eventDirectionName = Direction.RIGHT;
}
if (nextElement && $(nextElement).hasClass(ClassName.ACTIVE)) {
this._isSliding = false;
return;
}
var slideEvent = this._triggerSlideEvent(nextElement, eventDirectionName);
if (slideEvent.isDefaultPrevented()) {
return;
}
if (!activeElement || !nextElement) {
// Some weirdness is happening, so we bail
return;
}
this._isSliding = true;
if (isCycling) {
this.pause();
}
this._setActiveIndicatorElement(nextElement);
var slidEvent = $.Event(Event.SLID, {
relatedTarget: nextElement,
direction: eventDirectionName,
from: activeElementIndex,
to: nextElementIndex
});
if (Util.supportsTransitionEnd() && $(this._element).hasClass(ClassName.SLIDE)) {
$(nextElement).addClass(orderClassName);
Util.reflow(nextElement);
$(activeElement).addClass(directionalClassName);
$(nextElement).addClass(directionalClassName);
$(activeElement).one(Util.TRANSITION_END, function () {
$(nextElement).removeClass(directionalClassName + " " + orderClassName).addClass(ClassName.ACTIVE);
$(activeElement).removeClass(ClassName.ACTIVE + " " + orderClassName + " " + directionalClassName);
_this3._isSliding = false;
setTimeout(function () {
return $(_this3._element).trigger(slidEvent);
}, 0);
}).emulateTransitionEnd(TRANSITION_DURATION);
} else {
$(activeElement).removeClass(ClassName.ACTIVE);
$(nextElement).addClass(ClassName.ACTIVE);
this._isSliding = false;
$(this._element).trigger(slidEvent);
}
if (isCycling) {
this.cycle();
}
}; // Static
Carousel._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var data = $(this).data(DATA_KEY);
var _config = _extends({}, Default, $(this).data());
if (typeof config === 'object') {
_config = _extends({}, _config, config);
}
var action = typeof config === 'string' ? config : _config.slide;
if (!data) {
data = new Carousel(this, _config);
$(this).data(DATA_KEY, data);
}
if (typeof config === 'number') {
data.to(config);
} else if (typeof action === 'string') {
if (typeof data[action] === 'undefined') {
throw new TypeError("No method named \"" + action + "\"");
}
data[action]();
} else if (_config.interval) {
data.pause();
data.cycle();
}
});
};
Carousel._dataApiClickHandler = function _dataApiClickHandler(event) {
var selector = Util.getSelectorFromElement(this);
if (!selector) {
return;
}
var target = $(selector)[0];
if (!target || !$(target).hasClass(ClassName.CAROUSEL)) {
return;
}
var config = _extends({}, $(target).data(), $(this).data());
var slideIndex = this.getAttribute('data-slide-to');
if (slideIndex) {
config.interval = false;
}
Carousel._jQueryInterface.call($(target), config);
if (slideIndex) {
$(target).data(DATA_KEY).to(slideIndex);
}
event.preventDefault();
};
_createClass(Carousel, null, [{
key: "VERSION",
get: function get() {
return VERSION;
}
}, {
key: "Default",
get: function get() {
return Default;
}
}]);
return Carousel;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$(document).on(Event.CLICK_DATA_API, Selector.DATA_SLIDE, Carousel._dataApiClickHandler);
$(window).on(Event.LOAD_DATA_API, function () {
$(Selector.DATA_RIDE).each(function () {
var $carousel = $(this);
Carousel._jQueryInterface.call($carousel, $carousel.data());
});
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Carousel._jQueryInterface;
$.fn[NAME].Constructor = Carousel;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Carousel._jQueryInterface;
};
return Carousel;
}($);
//# sourceMappingURL=carousel.js.map
|
ej.addCulture( "ar-BH",{
name: "ar-BH",
englishName: "Arabic (Bahrain)",
nativeName: "العربية (البحرين)",
language: "ar",
isRTL: true,
numberFormat: {
pattern: ["n-"],
decimals: 3,
"NaN": "ليس برقم",
negativeInfinity: "-لا نهاية",
positiveInfinity: "+لا نهاية",
percent: {
decimals: 3
},
currency: {
pattern: ["$n-","$ n"],
decimals: 3,
symbol: "د.ب.\u200f"
}
},
calendars: {
standard: {
firstDay: 6,
days: {
names: ["الأحد","الإثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"],
namesAbbr: ["الأحد","الإثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"],
namesShort: ["ح","ن","ث","ر","خ","ج","س"]
},
months: {
names: ["يناير","فبراير","مارس","أبريل","مايو","يونيو","يوليه","أغسطس","سبتمبر","أكتوبر","نوفمبر","ديسمبر",""],
namesAbbr: ["يناير","فبراير","مارس","ابريل","مايو","يونيو","يوليو","اغسطس","سبتمبر","اكتوبر","نوفمبر","ديسمبر",""]
},
AM: ["ص","ص","ص"],
PM: ["م","م","م"],
patterns: {
d: "dd/MM/yyyy",
D: "dd MMMM, yyyy",
t: "hh:mm tt",
T: "hh:mm:ss tt",
f: "dd MMMM, yyyy hh:mm tt",
F: "dd MMMM, yyyy hh:mm:ss tt",
M: "dd MMMM",
Y: "MMMM, yyyy"
}
},
UmAlQura: {
name: "UmAlQura",
firstDay: 6,
days: {
names: ["الأحد","الإثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"],
namesAbbr: ["الأحد","الإثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"],
namesShort: ["ح","ن","ث","ر","خ","ج","س"]
},
months: {
names: ["محرم","صفر","ربيع الأول","ربيع الثاني","جمادى الأولى","جمادى الثانية","رجب","شعبان","رمضان","شوال","ذو القعدة","ذو الحجة",""],
namesAbbr: ["محرم","صفر","ربيع الأول","ربيع الثاني","جمادى الأولى","جمادى الثانية","رجب","شعبان","رمضان","شوال","ذو القعدة","ذو الحجة",""]
},
AM: ["ص","ص","ص"],
PM: ["م","م","م"],
twoDigitYearMax: 1451,
patterns: {
d: "dd/MM/yy",
D: "dd/MMMM/yyyy",
t: "hh:mm tt",
T: "hh:mm:ss tt",
f: "dd/MMMM/yyyy hh:mm tt",
F: "dd/MMMM/yyyy hh:mm:ss tt",
M: "dd MMMM",
Y: "MMMM, yyyy"
},
convert: {
_yearInfo: [
// MonthLengthFlags, Gregorian Date
[746, -2198707200000],
[1769, -2168121600000],
[3794, -2137449600000],
[3748, -2106777600000],
[3402, -2076192000000],
[2710, -2045606400000],
[1334, -2015020800000],
[2741, -1984435200000],
[3498, -1953763200000],
[2980, -1923091200000],
[2889, -1892505600000],
[2707, -1861920000000],
[1323, -1831334400000],
[2647, -1800748800000],
[1206, -1770076800000],
[2741, -1739491200000],
[1450, -1708819200000],
[3413, -1678233600000],
[3370, -1647561600000],
[2646, -1616976000000],
[1198, -1586390400000],
[2397, -1555804800000],
[748, -1525132800000],
[1749, -1494547200000],
[1706, -1463875200000],
[1365, -1433289600000],
[1195, -1402704000000],
[2395, -1372118400000],
[698, -1341446400000],
[1397, -1310860800000],
[2994, -1280188800000],
[1892, -1249516800000],
[1865, -1218931200000],
[1621, -1188345600000],
[683, -1157760000000],
[1371, -1127174400000],
[2778, -1096502400000],
[1748, -1065830400000],
[3785, -1035244800000],
[3474, -1004572800000],
[3365, -973987200000],
[2637, -943401600000],
[685, -912816000000],
[1389, -882230400000],
[2922, -851558400000],
[2898, -820886400000],
[2725, -790300800000],
[2635, -759715200000],
[1175, -729129600000],
[2359, -698544000000],
[694, -667872000000],
[1397, -637286400000],
[3434, -606614400000],
[3410, -575942400000],
[2710, -545356800000],
[2349, -514771200000],
[605, -484185600000],
[1245, -453600000000],
[2778, -422928000000],
[1492, -392256000000],
[3497, -361670400000],
[3410, -330998400000],
[2730, -300412800000],
[1238, -269827200000],
[2486, -239241600000],
[884, -208569600000],
[1897, -177984000000],
[1874, -147312000000],
[1701, -116726400000],
[1355, -86140800000],
[2731, -55555200000],
[1370, -24883200000],
[2773, 5702400000],
[3538, 36374400000],
[3492, 67046400000],
[3401, 97632000000],
[2709, 128217600000],
[1325, 158803200000],
[2653, 189388800000],
[1370, 220060800000],
[2773, 250646400000],
[1706, 281318400000],
[1685, 311904000000],
[1323, 342489600000],
[2647, 373075200000],
[1198, 403747200000],
[2422, 434332800000],
[1388, 465004800000],
[2901, 495590400000],
[2730, 526262400000],
[2645, 556848000000],
[1197, 587433600000],
[2397, 618019200000],
[730, 648691200000],
[1497, 679276800000],
[3506, 709948800000],
[2980, 740620800000],
[2890, 771206400000],
[2645, 801792000000],
[693, 832377600000],
[1397, 862963200000],
[2922, 893635200000],
[3026, 924307200000],
[3012, 954979200000],
[2953, 985564800000],
[2709, 1016150400000],
[1325, 1046736000000],
[1453, 1077321600000],
[2922, 1107993600000],
[1748, 1138665600000],
[3529, 1169251200000],
[3474, 1199923200000],
[2726, 1230508800000],
[2390, 1261094400000],
[686, 1291680000000],
[1389, 1322265600000],
[874, 1352937600000],
[2901, 1383523200000],
[2730, 1414195200000],
[2381, 1444780800000],
[1181, 1475366400000],
[2397, 1505952000000],
[698, 1536624000000],
[1461, 1567209600000],
[1450, 1597881600000],
[3413, 1628467200000],
[2714, 1659139200000],
[2350, 1689724800000],
[622, 1720310400000],
[1373, 1750896000000],
[2778, 1781568000000],
[1748, 1812240000000],
[1701, 1842825600000],
[0, 1873411200000]
],
minDate: -2198707200000,
maxDate: 1873411199999,
toGregorian: function(hyear, hmonth, hday) {
var days = hday - 1,
gyear = hyear - 1318;
if (gyear < 0 || gyear >= this._yearInfo.length) return null;
var info = this._yearInfo[gyear],
gdate = new Date(info[1]),
monthLength = info[0];
// Date's ticks in javascript are always from the GMT time,
// but we are interested in the gregorian date in the same timezone,
// not what the gregorian date was at GMT time, so we adjust for the offset.
gdate.setMinutes(gdate.getMinutes() + gdate.getTimezoneOffset());
for (var i = 0; i < hmonth; i++) {
days += 29 + (monthLength & 1);
monthLength = monthLength >> 1;
}
gdate.setDate(gdate.getDate() + days);
return gdate;
},
fromGregorian: function(gdate) {
// Date's ticks in javascript are always from the GMT time,
// but we are interested in the hijri date in the same timezone,
// not what the hijri date was at GMT time, so we adjust for the offset.
var ticks = gdate - gdate.getTimezoneOffset() * 60000;
if (ticks < this.minDate || ticks > this.maxDate) return null;
var hyear = 0,
hmonth = 1;
// find the earliest gregorian date in the array that is greater than or equal to the given date
while (ticks > this._yearInfo[++hyear][1]) { }
if (ticks !== this._yearInfo[hyear][1]) {
hyear--;
}
var info = this._yearInfo[hyear],
// how many days has it been since the date we found in the array?
// 86400000 = ticks per day
days = Math.floor((ticks - info[1]) / 86400000),
monthLength = info[0];
hyear += 1318; // the Nth array entry corresponds to hijri year 1318+N
// now increment day/month based on the total days, considering
// how many days are in each month. We cannot run past the year
// mark since we would have found a different array entry in that case.
var daysInMonth = 29 + (monthLength & 1);
while (days >= daysInMonth) {
days -= daysInMonth;
monthLength = monthLength >> 1;
daysInMonth = 29 + (monthLength & 1);
hmonth++;
}
// remaining days is less than is in one month, thus is the day of the month we landed on
// hmonth-1 because in javascript months are zero based, stay consistent with that.
return [hyear, hmonth - 1, days + 1];
}
}
},
Hijri: {
name: "Hijri",
firstDay: 6,
days: {
names: ["الأحد","الإثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"],
namesAbbr: ["الأحد","الإثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"],
namesShort: ["ح","ن","ث","ر","خ","ج","س"]
},
months: {
names: ["محرم","صفر","ربيع الأول","ربيع الآخرة","جمادى الأولى","جمادى الآخرة","رجب","شعبان","رمضان","شوال","ذو القعدة","ذو الحجة",""],
namesAbbr: ["محرم","صفر","ربيع الأول","ربيع الآخرة","جمادى الأولى","جمادى الآخرة","رجب","شعبان","رمضان","شوال","ذو القعدة","ذو الحجة",""]
},
AM: ["ص","ص","ص"],
PM: ["م","م","م"],
twoDigitYearMax: 1451,
patterns: {
d: "dd/MM/yyyy",
D: "dd MMMM, yyyy",
t: "hh:mm tt",
T: "hh:mm:ss tt",
f: "dd MMMM, yyyy hh:mm tt",
F: "dd MMMM, yyyy hh:mm:ss tt",
M: "dd MMMM",
Y: "MMMM, yyyy"
},
convert: {
// Adapted to Script from System.Globalization.HijriCalendar
ticks1970: 62135596800000,
// number of days leading up to each month
monthDays: [0, 30, 59, 89, 118, 148, 177, 207, 236, 266, 295, 325, 355],
minDate: -42521673600000,
maxDate: 253402300799999,
// The number of days to add or subtract from the calendar to accommodate the variances
// in the start and the end of Ramadan and to accommodate the date difference between
// countries/regions. May be dynamically adjusted based on user preference, but should
// remain in the range of -2 to 2, inclusive.
hijriAdjustment: 0,
toGregorian: function(hyear, hmonth, hday) {
var daysSinceJan0101 = this.daysToYear(hyear) + this.monthDays[hmonth] + hday - 1 - this.hijriAdjustment;
// 86400000 = ticks per day
var gdate = new Date(daysSinceJan0101 * 86400000 - this.ticks1970);
// adjust for timezone, because we are interested in the gregorian date for the same timezone
// but ticks in javascript is always from GMT, unlike the server were ticks counts from the base
// date in the current timezone.
gdate.setMinutes(gdate.getMinutes() + gdate.getTimezoneOffset());
return gdate;
},
fromGregorian: function(gdate) {
if ((gdate < this.minDate) || (gdate > this.maxDate)) return null;
var ticks = this.ticks1970 + (gdate-0) - gdate.getTimezoneOffset() * 60000,
daysSinceJan0101 = Math.floor(ticks / 86400000) + 1 + this.hijriAdjustment;
// very particular formula determined by someone smart, adapted from the server-side implementation.
// it approximates the hijri year.
var hday, hmonth, hyear = Math.floor(((daysSinceJan0101 - 227013) * 30) / 10631) + 1,
absDays = this.daysToYear(hyear),
daysInYear = this.isLeapYear(hyear) ? 355 : 354;
// hyear is just approximate, it may need adjustment up or down by 1.
if (daysSinceJan0101 < absDays) {
hyear--;
absDays -= daysInYear;
}
else if (daysSinceJan0101 === absDays) {
hyear--;
absDays = this.daysToYear(hyear);
}
else {
if (daysSinceJan0101 > (absDays + daysInYear)) {
absDays += daysInYear;
hyear++;
}
}
// determine month by looking at how many days into the hyear we are
// monthDays contains the number of days up to each month.
hmonth = 0;
var daysIntoYear = daysSinceJan0101 - absDays;
while (hmonth <= 11 && daysIntoYear > this.monthDays[hmonth]) {
hmonth++;
}
hmonth--;
hday = daysIntoYear - this.monthDays[hmonth];
return [hyear, hmonth, hday];
},
daysToYear: function(year) {
// calculates how many days since Jan 1, 0001
var yearsToYear30 = Math.floor((year - 1) / 30) * 30,
yearsInto30 = year - yearsToYear30 - 1,
days = Math.floor((yearsToYear30 * 10631) / 30) + 227013;
while (yearsInto30 > 0) {
days += (this.isLeapYear(yearsInto30) ? 355 : 354);
yearsInto30--;
}
return days;
},
isLeapYear: function(year) {
return ((((year * 11) + 14) % 30) < 11);
}
}
},
Gregorian_MiddleEastFrench: {
name: "Gregorian_MiddleEastFrench",
firstDay: 6,
days: {
names: ["dimanche","lundi","mardi","mercredi","jeudi","vendredi","samedi"],
namesAbbr: ["dim.","lun.","mar.","mer.","jeu.","ven.","sam."],
namesShort: ["di","lu","ma","me","je","ve","sa"]
},
months: {
names: ["janvier","février","mars","avril","mai","juin","juillet","août","septembre","octobre","novembre","décembre",""],
namesAbbr: ["janv.","févr.","mars","avr.","mai","juin","juil.","août","sept.","oct.","nov.","déc.",""]
},
AM: ["ص","ص","ص"],
PM: ["م","م","م"],
patterns: {
d: "MM/dd/yyyy",
D: "dddd, MMMM dd, yyyy",
t: "hh:mm tt",
T: "hh:mm:ss tt",
f: "dddd, MMMM dd, yyyy hh:mm tt",
F: "dddd, MMMM dd, yyyy hh:mm:ss tt",
M: "dd MMMM",
Y: "MMMM, yyyy"
}
},
Gregorian_Arabic: {
name: "Gregorian_Arabic",
firstDay: 6,
days: {
names: ["الأحد","الإثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"],
namesAbbr: ["الأحد","الإثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"],
namesShort: ["ح","ن","ث","ر","خ","ج","س"]
},
months: {
names: ["كانون الثاني","شباط","آذار","نيسان","أيار","حزيران","تموز","آب","أيلول","تشرين الأول","تشرين الثاني","كانون الأول",""],
namesAbbr: ["كانون الثاني","شباط","آذار","نيسان","أيار","حزيران","تموز","آب","أيلول","تشرين الأول","تشرين الثاني","كانون الأول",""]
},
AM: ["ص","ص","ص"],
PM: ["م","م","م"],
patterns: {
d: "MM/dd/yyyy",
D: "dddd, MMMM dd, yyyy",
t: "hh:mm tt",
T: "hh:mm:ss tt",
f: "dddd, MMMM dd, yyyy hh:mm tt",
F: "dddd, MMMM dd, yyyy hh:mm:ss tt",
M: "dd MMMM",
Y: "MMMM, yyyy"
}
},
Gregorian_TransliteratedFrench: {
name: "Gregorian_TransliteratedFrench",
firstDay: 6,
days: {
names: ["الأحد","الإثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"],
namesAbbr: ["الأحد","الإثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"],
namesShort: ["ح","ن","ث","ر","خ","ج","س"]
},
months: {
names: ["جانفييه","فيفرييه","مارس","أفريل","مي","جوان","جوييه","أوت","سبتمبر","اكتوبر","نوفمبر","ديسمبر",""],
namesAbbr: ["جانفييه","فيفرييه","مارس","أفريل","مي","جوان","جوييه","أوت","سبتمبر","اكتوبر","نوفمبر","ديسمبر",""]
},
AM: ["ص","ص","ص"],
PM: ["م","م","م"],
patterns: {
d: "MM/dd/yyyy",
D: "dddd, MMMM dd, yyyy",
t: "hh:mm tt",
T: "hh:mm:ss tt",
f: "dddd, MMMM dd, yyyy hh:mm tt",
F: "dddd, MMMM dd, yyyy hh:mm:ss tt",
M: "dd MMMM",
Y: "MMMM, yyyy"
}
}
}
});
|
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'quicktable', 'bs', {
more: 'Više...'
} );
|
// npm build command
// everything about the installation after the creation of
// the .npm/{name}/{version}/package folder.
// linking the modules into the npm.root,
// resolving dependencies, etc.
// This runs AFTER install or link are completed.
var npm = require("./npm.js")
, log = require("npmlog")
, chain = require("slide").chain
, fs = require("graceful-fs")
, path = require("path")
, lifecycle = require("./utils/lifecycle.js")
, readJson = require("read-package-json")
, link = require("./utils/link.js")
, linkIfExists = link.ifExists
, cmdShim = require("cmd-shim")
, cmdShimIfExists = cmdShim.ifExists
, asyncMap = require("slide").asyncMap
, ini = require("ini")
, writeFile = require("write-file-atomic")
module.exports = build
build.usage = "npm build <folder>\n(this is plumbing)"
build._didBuild = {}
build._noLC = {}
function build (args, global, didPre, didRB, cb) {
if (typeof cb !== "function") cb = didRB, didRB = false
if (typeof cb !== "function") cb = didPre, didPre = false
if (typeof cb !== "function") {
cb = global, global = npm.config.get("global")
}
// it'd be nice to asyncMap these, but actually, doing them
// in parallel generally munges up the output from node-waf
var builder = build_(global, didPre, didRB)
chain(args.map(function (arg) { return function (cb) {
builder(arg, cb)
}}), cb)
}
function build_ (global, didPre, didRB) { return function (folder, cb) {
folder = path.resolve(folder)
if (build._didBuild[folder]) log.info("build", "already built", folder)
build._didBuild[folder] = true
log.info("build", folder)
readJson(path.resolve(folder, "package.json"), function (er, pkg) {
if (er) return cb(er)
chain
( [ !didPre && [lifecycle, pkg, "preinstall", folder]
, [linkStuff, pkg, folder, global, didRB]
, [writeBuiltinConf, pkg, folder]
, didPre !== build._noLC && [lifecycle, pkg, "install", folder]
, didPre !== build._noLC && [lifecycle, pkg, "postinstall", folder]
, didPre !== build._noLC
&& npm.config.get("npat")
&& [lifecycle, pkg, "test", folder] ]
, cb )
})
}}
function writeBuiltinConf (pkg, folder, cb) {
// the builtin config is "sticky". Any time npm installs
// itself globally, it puts its builtin config file there
var parent = path.dirname(folder)
var dir = npm.globalDir
if (pkg.name !== "npm" ||
!npm.config.get("global") ||
!npm.config.usingBuiltin ||
dir !== parent) {
return cb()
}
var data = ini.stringify(npm.config.sources.builtin.data)
writeFile(path.resolve(folder, "npmrc"), data, cb)
}
function linkStuff (pkg, folder, global, didRB, cb) {
// allow to opt out of linking binaries.
if (npm.config.get("bin-links") === false) return cb()
// if it's global, and folder is in {prefix}/node_modules,
// then bins are in {prefix}/bin
// otherwise, then bins are in folder/../.bin
var parent = pkg.name[0] === "@" ? path.dirname(path.dirname(folder)) : path.dirname(folder)
, gnm = global && npm.globalDir
, gtop = parent === gnm
log.verbose("linkStuff", [global, gnm, gtop, parent])
log.info("linkStuff", pkg._id)
shouldWarn(pkg, folder, global, function() {
asyncMap( [linkBins, linkMans, !didRB && rebuildBundles]
, function (fn, cb) {
if (!fn) return cb()
log.verbose(fn.name, pkg._id)
fn(pkg, folder, parent, gtop, cb)
}, cb)
})
}
function shouldWarn(pkg, folder, global, cb) {
var parent = path.dirname(folder)
, top = parent === npm.dir
, cwd = npm.localPrefix
readJson(path.resolve(cwd, "package.json"), function(er, topPkg) {
if (er) return cb(er)
var linkedPkg = path.basename(cwd)
, currentPkg = path.basename(folder)
// current searched package is the linked package on first call
if (linkedPkg !== currentPkg) {
if (!topPkg.dependencies) return cb()
// don't generate a warning if it's listed in dependencies
if (Object.keys(topPkg.dependencies).indexOf(currentPkg) === -1) {
if (top && pkg.preferGlobal && !global) {
log.warn("prefer global", pkg._id + " should be installed with -g")
}
}
}
cb()
})
}
function rebuildBundles (pkg, folder, parent, gtop, cb) {
if (!npm.config.get("rebuild-bundle")) return cb()
var deps = Object.keys(pkg.dependencies || {})
.concat(Object.keys(pkg.devDependencies || {}))
, bundles = pkg.bundleDependencies || pkg.bundledDependencies || []
fs.readdir(path.resolve(folder, "node_modules"), function (er, files) {
// error means no bundles
if (er) return cb()
log.verbose("rebuildBundles", files)
// don't asyncMap these, because otherwise build script output
// gets interleaved and is impossible to read
chain(files.filter(function (file) {
// rebuild if:
// not a .folder, like .bin or .hooks
return !file.match(/^[\._-]/)
// not some old 0.x style bundle
&& file.indexOf("@") === -1
// either not a dep, or explicitly bundled
&& (deps.indexOf(file) === -1 || bundles.indexOf(file) !== -1)
}).map(function (file) {
file = path.resolve(folder, "node_modules", file)
return function (cb) {
if (build._didBuild[file]) return cb()
log.verbose("rebuild bundle", file)
// if file is not a package dir, then don't do it.
fs.lstat(path.resolve(file, "package.json"), function (er) {
if (er) return cb()
build_(false)(file, cb)
})
}}), cb)
})
}
function linkBins (pkg, folder, parent, gtop, cb) {
if (!pkg.bin || !gtop && path.basename(parent) !== "node_modules") {
return cb()
}
var binRoot = gtop ? npm.globalBin
: path.resolve(parent, ".bin")
log.verbose("link bins", [pkg.bin, binRoot, gtop])
asyncMap(Object.keys(pkg.bin), function (b, cb) {
linkBin( path.resolve(folder, pkg.bin[b])
, path.resolve(binRoot, b)
, gtop && folder
, function (er) {
if (er) return cb(er)
// bins should always be executable.
// XXX skip chmod on windows?
var src = path.resolve(folder, pkg.bin[b])
fs.chmod(src, npm.modes.exec, function (er) {
if (er && er.code === "ENOENT" && npm.config.get("ignore-scripts")) {
return cb()
}
if (er || !gtop) return cb(er)
var dest = path.resolve(binRoot, b)
, out = npm.config.get("parseable")
? dest + "::" + src + ":BINFILE"
: dest + " -> " + src
console.log(out)
cb()
})
})
}, cb)
}
function linkBin (from, to, gently, cb) {
if (process.platform !== "win32") {
return linkIfExists(from, to, gently, cb)
} else {
return cmdShimIfExists(from, to, cb)
}
}
function linkMans (pkg, folder, parent, gtop, cb) {
if (!pkg.man || !gtop || process.platform === "win32") return cb()
var manRoot = path.resolve(npm.config.get("prefix"), "share", "man")
log.verbose("linkMans", "man files are", pkg.man, "in", manRoot)
// make sure that the mans are unique.
// otherwise, if there are dupes, it'll fail with EEXIST
var set = pkg.man.reduce(function (acc, man) {
acc[path.basename(man)] = man
return acc
}, {})
pkg.man = pkg.man.filter(function (man) {
return set[path.basename(man)] === man
})
asyncMap(pkg.man, function (man, cb) {
if (typeof man !== "string") return cb()
log.silly("linkMans", "preparing to link", man)
var parseMan = man.match(/(.*\.([0-9]+)(\.gz)?)$/)
if (!parseMan) {
return cb(new Error(
man+" is not a valid name for a man file. " +
"Man files must end with a number, " +
"and optionally a .gz suffix if they are compressed."
))
}
var stem = parseMan[1]
var sxn = parseMan[2]
var bn = path.basename(stem)
var manSrc = path.resolve(folder, man)
var manDest = path.join(manRoot, "man" + sxn, bn)
linkIfExists(manSrc, manDest, gtop && folder, cb)
}, cb)
}
|
/*! algoliasearch 3.22.1 | © 2014, 2015 Algolia SAS | github.com/algolia/algoliasearch-client-js */
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.algoliasearch = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
(function (process){
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require(2);
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
&& 'undefined' != typeof chrome.storage
? chrome.storage.local
: localstorage();
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && 'WebkitAppearance' in document.documentElement.style) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(window.console && (console.firebug || (console.exception && console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (err) {
return '[UnexpectedJSONParseError]: ' + err.message;
}
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs() {
var args = arguments;
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return args;
var c = 'color: ' + this.color;
args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
return args;
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// this hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return 'object' === typeof console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
exports.storage.removeItem('debug');
} else {
exports.storage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
return exports.storage.debug;
} catch(e) {}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (typeof process !== 'undefined' && 'env' in process) {
return process.env.DEBUG;
}
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage(){
try {
return window.localStorage;
} catch (e) {}
}
}).call(this,require(11))
},{"11":11,"2":2}],2:[function(require,module,exports){
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = debug.debug = debug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = require(8);
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lowercased letter, i.e. "n".
*/
exports.formatters = {};
/**
* Previously assigned color.
*/
var prevColor = 0;
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
*
* @return {Number}
* @api private
*/
function selectColor() {
return exports.colors[prevColor++ % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function debug(namespace) {
// define the `disabled` version
function disabled() {
}
disabled.enabled = false;
// define the `enabled` version
function enabled() {
var self = enabled;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// add the `color` if not set
if (null == self.useColors) self.useColors = exports.useColors();
if (null == self.color && self.useColors) self.color = selectColor();
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %o
args = ['%o'].concat(args);
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// apply env-specific formatting
args = exports.formatArgs.apply(self, args);
var logFn = enabled.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
enabled.enabled = true;
var fn = exports.enabled(namespace) ? enabled : disabled;
fn.namespace = namespace;
return fn;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
var split = (namespaces || '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/[\\^$+?.()|[\]{}]/g, '\\$&').replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
},{"8":8}],3:[function(require,module,exports){
(function (process,global){
/*!
* @overview es6-promise - a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
* @version 4.0.5
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.ES6Promise = factory());
}(this, (function () { 'use strict';
function objectOrFunction(x) {
return typeof x === 'function' || typeof x === 'object' && x !== null;
}
function isFunction(x) {
return typeof x === 'function';
}
var _isArray = undefined;
if (!Array.isArray) {
_isArray = function (x) {
return Object.prototype.toString.call(x) === '[object Array]';
};
} else {
_isArray = Array.isArray;
}
var isArray = _isArray;
var len = 0;
var vertxNext = undefined;
var customSchedulerFn = undefined;
var asap = function asap(callback, arg) {
queue[len] = callback;
queue[len + 1] = arg;
len += 2;
if (len === 2) {
// If len is 2, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
if (customSchedulerFn) {
customSchedulerFn(flush);
} else {
scheduleFlush();
}
}
};
function setScheduler(scheduleFn) {
customSchedulerFn = scheduleFn;
}
function setAsap(asapFn) {
asap = asapFn;
}
var browserWindow = typeof window !== 'undefined' ? window : undefined;
var browserGlobal = browserWindow || {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';
// test for web worker but not in IE10
var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
// node
function useNextTick() {
// node version 0.10.x displays a deprecation warning when nextTick is used recursively
// see https://github.com/cujojs/when/issues/410 for details
return function () {
return process.nextTick(flush);
};
}
// vertx
function useVertxTimer() {
if (typeof vertxNext !== 'undefined') {
return function () {
vertxNext(flush);
};
}
return useSetTimeout();
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function () {
node.data = iterations = ++iterations % 2;
};
}
// web worker
function useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = flush;
return function () {
return channel.port2.postMessage(0);
};
}
function useSetTimeout() {
// Store setTimeout reference so es6-promise will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
var globalSetTimeout = setTimeout;
return function () {
return globalSetTimeout(flush, 1);
};
}
var queue = new Array(1000);
function flush() {
for (var i = 0; i < len; i += 2) {
var callback = queue[i];
var arg = queue[i + 1];
callback(arg);
queue[i] = undefined;
queue[i + 1] = undefined;
}
len = 0;
}
function attemptVertx() {
try {
var r = require;
var vertx = r('vertx');
vertxNext = vertx.runOnLoop || vertx.runOnContext;
return useVertxTimer();
} catch (e) {
return useSetTimeout();
}
}
var scheduleFlush = undefined;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else if (isWorker) {
scheduleFlush = useMessageChannel();
} else if (browserWindow === undefined && typeof require === 'function') {
scheduleFlush = attemptVertx();
} else {
scheduleFlush = useSetTimeout();
}
function then(onFulfillment, onRejection) {
var _arguments = arguments;
var parent = this;
var child = new this.constructor(noop);
if (child[PROMISE_ID] === undefined) {
makePromise(child);
}
var _state = parent._state;
if (_state) {
(function () {
var callback = _arguments[_state - 1];
asap(function () {
return invokeCallback(_state, child, callback, parent._result);
});
})();
} else {
subscribe(parent, child, onFulfillment, onRejection);
}
return child;
}
/**
`Promise.resolve` returns a promise that will become resolved with the
passed `value`. It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
resolve(1);
});
promise.then(function(value){
// value === 1
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.resolve(1);
promise.then(function(value){
// value === 1
});
```
@method resolve
@static
@param {Any} value value that the returned promise will be resolved with
Useful for tooling.
@return {Promise} a promise that will become fulfilled with the given
`value`
*/
function resolve(object) {
/*jshint validthis:true */
var Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
var promise = new Constructor(noop);
_resolve(promise, object);
return promise;
}
var PROMISE_ID = Math.random().toString(36).substring(16);
function noop() {}
var PENDING = void 0;
var FULFILLED = 1;
var REJECTED = 2;
var GET_THEN_ERROR = new ErrorObject();
function selfFulfillment() {
return new TypeError("You cannot resolve a promise with itself");
}
function cannotReturnOwn() {
return new TypeError('A promises callback cannot return that same promise.');
}
function getThen(promise) {
try {
return promise.then;
} catch (error) {
GET_THEN_ERROR.error = error;
return GET_THEN_ERROR;
}
}
function tryThen(then, value, fulfillmentHandler, rejectionHandler) {
try {
then.call(value, fulfillmentHandler, rejectionHandler);
} catch (e) {
return e;
}
}
function handleForeignThenable(promise, thenable, then) {
asap(function (promise) {
var sealed = false;
var error = tryThen(then, thenable, function (value) {
if (sealed) {
return;
}
sealed = true;
if (thenable !== value) {
_resolve(promise, value);
} else {
fulfill(promise, value);
}
}, function (reason) {
if (sealed) {
return;
}
sealed = true;
_reject(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && error) {
sealed = true;
_reject(promise, error);
}
}, promise);
}
function handleOwnThenable(promise, thenable) {
if (thenable._state === FULFILLED) {
fulfill(promise, thenable._result);
} else if (thenable._state === REJECTED) {
_reject(promise, thenable._result);
} else {
subscribe(thenable, undefined, function (value) {
return _resolve(promise, value);
}, function (reason) {
return _reject(promise, reason);
});
}
}
function handleMaybeThenable(promise, maybeThenable, then$$) {
if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) {
handleOwnThenable(promise, maybeThenable);
} else {
if (then$$ === GET_THEN_ERROR) {
_reject(promise, GET_THEN_ERROR.error);
} else if (then$$ === undefined) {
fulfill(promise, maybeThenable);
} else if (isFunction(then$$)) {
handleForeignThenable(promise, maybeThenable, then$$);
} else {
fulfill(promise, maybeThenable);
}
}
}
function _resolve(promise, value) {
if (promise === value) {
_reject(promise, selfFulfillment());
} else if (objectOrFunction(value)) {
handleMaybeThenable(promise, value, getThen(value));
} else {
fulfill(promise, value);
}
}
function publishRejection(promise) {
if (promise._onerror) {
promise._onerror(promise._result);
}
publish(promise);
}
function fulfill(promise, value) {
if (promise._state !== PENDING) {
return;
}
promise._result = value;
promise._state = FULFILLED;
if (promise._subscribers.length !== 0) {
asap(publish, promise);
}
}
function _reject(promise, reason) {
if (promise._state !== PENDING) {
return;
}
promise._state = REJECTED;
promise._result = reason;
asap(publishRejection, promise);
}
function subscribe(parent, child, onFulfillment, onRejection) {
var _subscribers = parent._subscribers;
var length = _subscribers.length;
parent._onerror = null;
_subscribers[length] = child;
_subscribers[length + FULFILLED] = onFulfillment;
_subscribers[length + REJECTED] = onRejection;
if (length === 0 && parent._state) {
asap(publish, parent);
}
}
function publish(promise) {
var subscribers = promise._subscribers;
var settled = promise._state;
if (subscribers.length === 0) {
return;
}
var child = undefined,
callback = undefined,
detail = promise._result;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
invokeCallback(settled, child, callback, detail);
} else {
callback(detail);
}
}
promise._subscribers.length = 0;
}
function ErrorObject() {
this.error = null;
}
var TRY_CATCH_ERROR = new ErrorObject();
function tryCatch(callback, detail) {
try {
return callback(detail);
} catch (e) {
TRY_CATCH_ERROR.error = e;
return TRY_CATCH_ERROR;
}
}
function invokeCallback(settled, promise, callback, detail) {
var hasCallback = isFunction(callback),
value = undefined,
error = undefined,
succeeded = undefined,
failed = undefined;
if (hasCallback) {
value = tryCatch(callback, detail);
if (value === TRY_CATCH_ERROR) {
failed = true;
error = value.error;
value = null;
} else {
succeeded = true;
}
if (promise === value) {
_reject(promise, cannotReturnOwn());
return;
}
} else {
value = detail;
succeeded = true;
}
if (promise._state !== PENDING) {
// noop
} else if (hasCallback && succeeded) {
_resolve(promise, value);
} else if (failed) {
_reject(promise, error);
} else if (settled === FULFILLED) {
fulfill(promise, value);
} else if (settled === REJECTED) {
_reject(promise, value);
}
}
function initializePromise(promise, resolver) {
try {
resolver(function resolvePromise(value) {
_resolve(promise, value);
}, function rejectPromise(reason) {
_reject(promise, reason);
});
} catch (e) {
_reject(promise, e);
}
}
var id = 0;
function nextId() {
return id++;
}
function makePromise(promise) {
promise[PROMISE_ID] = id++;
promise._state = undefined;
promise._result = undefined;
promise._subscribers = [];
}
function Enumerator(Constructor, input) {
this._instanceConstructor = Constructor;
this.promise = new Constructor(noop);
if (!this.promise[PROMISE_ID]) {
makePromise(this.promise);
}
if (isArray(input)) {
this._input = input;
this.length = input.length;
this._remaining = input.length;
this._result = new Array(this.length);
if (this.length === 0) {
fulfill(this.promise, this._result);
} else {
this.length = this.length || 0;
this._enumerate();
if (this._remaining === 0) {
fulfill(this.promise, this._result);
}
}
} else {
_reject(this.promise, validationError());
}
}
function validationError() {
return new Error('Array Methods must be provided an Array');
};
Enumerator.prototype._enumerate = function () {
var length = this.length;
var _input = this._input;
for (var i = 0; this._state === PENDING && i < length; i++) {
this._eachEntry(_input[i], i);
}
};
Enumerator.prototype._eachEntry = function (entry, i) {
var c = this._instanceConstructor;
var resolve$$ = c.resolve;
if (resolve$$ === resolve) {
var _then = getThen(entry);
if (_then === then && entry._state !== PENDING) {
this._settledAt(entry._state, i, entry._result);
} else if (typeof _then !== 'function') {
this._remaining--;
this._result[i] = entry;
} else if (c === Promise) {
var promise = new c(noop);
handleMaybeThenable(promise, entry, _then);
this._willSettleAt(promise, i);
} else {
this._willSettleAt(new c(function (resolve$$) {
return resolve$$(entry);
}), i);
}
} else {
this._willSettleAt(resolve$$(entry), i);
}
};
Enumerator.prototype._settledAt = function (state, i, value) {
var promise = this.promise;
if (promise._state === PENDING) {
this._remaining--;
if (state === REJECTED) {
_reject(promise, value);
} else {
this._result[i] = value;
}
}
if (this._remaining === 0) {
fulfill(promise, this._result);
}
};
Enumerator.prototype._willSettleAt = function (promise, i) {
var enumerator = this;
subscribe(promise, undefined, function (value) {
return enumerator._settledAt(FULFILLED, i, value);
}, function (reason) {
return enumerator._settledAt(REJECTED, i, reason);
});
};
/**
`Promise.all` accepts an array of promises, and returns a new promise which
is fulfilled with an array of fulfillment values for the passed promises, or
rejected with the reason of the first passed promise to be rejected. It casts all
elements of the passed iterable to promises as it runs this algorithm.
Example:
```javascript
let promise1 = resolve(1);
let promise2 = resolve(2);
let promise3 = resolve(3);
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// The array here would be [ 1, 2, 3 ];
});
```
If any of the `promises` given to `all` are rejected, the first promise
that is rejected will be given as an argument to the returned promises's
rejection handler. For example:
Example:
```javascript
let promise1 = resolve(1);
let promise2 = reject(new Error("2"));
let promise3 = reject(new Error("3"));
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// Code here never runs because there are rejected promises!
}, function(error) {
// error.message === "2"
});
```
@method all
@static
@param {Array} entries array of promises
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled when all `promises` have been
fulfilled, or rejected if any of them become rejected.
@static
*/
function all(entries) {
return new Enumerator(this, entries).promise;
}
/**
`Promise.race` returns a new promise which is settled in the same way as the
first passed promise to settle.
Example:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 2');
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// result === 'promise 2' because it was resolved before promise1
// was resolved.
});
```
`Promise.race` is deterministic in that only the state of the first
settled promise matters. For example, even if other promises given to the
`promises` array argument are resolved, but the first settled promise has
become rejected before the other promises became fulfilled, the returned
promise will become rejected:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
reject(new Error('promise 2'));
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// Code here never runs
}, function(reason){
// reason.message === 'promise 2' because promise 2 became rejected before
// promise 1 became fulfilled
});
```
An example real-world use case is implementing timeouts:
```javascript
Promise.race([ajax('foo.json'), timeout(5000)])
```
@method race
@static
@param {Array} promises array of promises to observe
Useful for tooling.
@return {Promise} a promise which settles in the same way as the first passed
promise to settle.
*/
function race(entries) {
/*jshint validthis:true */
var Constructor = this;
if (!isArray(entries)) {
return new Constructor(function (_, reject) {
return reject(new TypeError('You must pass an array to race.'));
});
} else {
return new Constructor(function (resolve, reject) {
var length = entries.length;
for (var i = 0; i < length; i++) {
Constructor.resolve(entries[i]).then(resolve, reject);
}
});
}
}
/**
`Promise.reject` returns a promise rejected with the passed `reason`.
It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
reject(new Error('WHOOPS'));
});
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.reject(new Error('WHOOPS'));
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
@method reject
@static
@param {Any} reason value that the returned promise will be rejected with.
Useful for tooling.
@return {Promise} a promise rejected with the given `reason`.
*/
function reject(reason) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor(noop);
_reject(promise, reason);
return promise;
}
function needsResolver() {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
function needsNew() {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
/**
Promise objects represent the eventual result of an asynchronous operation. The
primary way of interacting with a promise is through its `then` method, which
registers callbacks to receive either a promise's eventual value or the reason
why the promise cannot be fulfilled.
Terminology
-----------
- `promise` is an object or function with a `then` method whose behavior conforms to this specification.
- `thenable` is an object or function that defines a `then` method.
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
- `exception` is a value that is thrown using the throw statement.
- `reason` is a value that indicates why a promise was rejected.
- `settled` the final resting state of a promise, fulfilled or rejected.
A promise can be in one of three states: pending, fulfilled, or rejected.
Promises that are fulfilled have a fulfillment value and are in the fulfilled
state. Promises that are rejected have a rejection reason and are in the
rejected state. A fulfillment value is never a thenable.
Promises can also be said to *resolve* a value. If this value is also a
promise, then the original promise's settled state will match the value's
settled state. So a promise that *resolves* a promise that rejects will
itself reject, and a promise that *resolves* a promise that fulfills will
itself fulfill.
Basic Usage:
------------
```js
let promise = new Promise(function(resolve, reject) {
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then(function(value) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Advanced Usage:
---------------
Promises shine when abstracting away asynchronous interactions such as
`XMLHttpRequest`s.
```js
function getJSON(url) {
return new Promise(function(resolve, reject){
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
}
}
};
});
}
getJSON('/posts.json').then(function(json) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Unlike callbacks, promises are great composable primitives.
```js
Promise.all([
getJSON('/posts'),
getJSON('/comments')
]).then(function(values){
values[0] // => postsJSON
values[1] // => commentsJSON
return values;
});
```
@class Promise
@param {function} resolver
Useful for tooling.
@constructor
*/
function Promise(resolver) {
this[PROMISE_ID] = nextId();
this._result = this._state = undefined;
this._subscribers = [];
if (noop !== resolver) {
typeof resolver !== 'function' && needsResolver();
this instanceof Promise ? initializePromise(this, resolver) : needsNew();
}
}
Promise.all = all;
Promise.race = race;
Promise.resolve = resolve;
Promise.reject = reject;
Promise._setScheduler = setScheduler;
Promise._setAsap = setAsap;
Promise._asap = asap;
Promise.prototype = {
constructor: Promise,
/**
The primary way of interacting with a promise is through its `then` method,
which registers callbacks to receive either a promise's eventual value or the
reason why the promise cannot be fulfilled.
```js
findUser().then(function(user){
// user is available
}, function(reason){
// user is unavailable, and you are given the reason why
});
```
Chaining
--------
The return value of `then` is itself a promise. This second, 'downstream'
promise is resolved with the return value of the first promise's fulfillment
or rejection handler, or rejected if the handler throws an exception.
```js
findUser().then(function (user) {
return user.name;
}, function (reason) {
return 'default name';
}).then(function (userName) {
// If `findUser` fulfilled, `userName` will be the user's name, otherwise it
// will be `'default name'`
});
findUser().then(function (user) {
throw new Error('Found user, but still unhappy');
}, function (reason) {
throw new Error('`findUser` rejected and we're unhappy');
}).then(function (value) {
// never reached
}, function (reason) {
// if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
// If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
});
```
If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
```js
findUser().then(function (user) {
throw new PedagogicalException('Upstream error');
}).then(function (value) {
// never reached
}).then(function (value) {
// never reached
}, function (reason) {
// The `PedgagocialException` is propagated all the way down to here
});
```
Assimilation
------------
Sometimes the value you want to propagate to a downstream promise can only be
retrieved asynchronously. This can be achieved by returning a promise in the
fulfillment or rejection handler. The downstream promise will then be pending
until the returned promise is settled. This is called *assimilation*.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// The user's comments are now available
});
```
If the assimliated promise rejects, then the downstream promise will also reject.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// If `findCommentsByAuthor` fulfills, we'll have the value here
}, function (reason) {
// If `findCommentsByAuthor` rejects, we'll have the reason here
});
```
Simple Example
--------------
Synchronous Example
```javascript
let result;
try {
result = findResult();
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
findResult(function(result, err){
if (err) {
// failure
} else {
// success
}
});
```
Promise Example;
```javascript
findResult().then(function(result){
// success
}, function(reason){
// failure
});
```
Advanced Example
--------------
Synchronous Example
```javascript
let author, books;
try {
author = findAuthor();
books = findBooksByAuthor(author);
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
function foundBooks(books) {
}
function failure(reason) {
}
findAuthor(function(author, err){
if (err) {
failure(err);
// failure
} else {
try {
findBoooksByAuthor(author, function(books, err) {
if (err) {
failure(err);
} else {
try {
foundBooks(books);
} catch(reason) {
failure(reason);
}
}
});
} catch(error) {
failure(err);
}
// success
}
});
```
Promise Example;
```javascript
findAuthor().
then(findBooksByAuthor).
then(function(books){
// found books
}).catch(function(reason){
// something went wrong
});
```
@method then
@param {Function} onFulfilled
@param {Function} onRejected
Useful for tooling.
@return {Promise}
*/
then: then,
/**
`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
as the catch block of a try/catch statement.
```js
function findAuthor(){
throw new Error('couldn't find that author');
}
// synchronous
try {
findAuthor();
} catch(reason) {
// something went wrong
}
// async with promises
findAuthor().catch(function(reason){
// something went wrong
});
```
@method catch
@param {Function} onRejection
Useful for tooling.
@return {Promise}
*/
'catch': function _catch(onRejection) {
return this.then(null, onRejection);
}
};
function polyfill() {
var local = undefined;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof self !== 'undefined') {
local = self;
} else {
try {
local = Function('return this')();
} catch (e) {
throw new Error('polyfill failed because global object is unavailable in this environment');
}
}
var P = local.Promise;
if (P) {
var promiseToString = null;
try {
promiseToString = Object.prototype.toString.call(P.resolve());
} catch (e) {
// silently ignored
}
if (promiseToString === '[object Promise]' && !P.cast) {
return;
}
}
local.Promise = Promise;
}
// Strange compat..
Promise.polyfill = polyfill;
Promise.Promise = Promise;
return Promise;
})));
}).call(this,require(11),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"11":11}],4:[function(require,module,exports){
var hasOwn = Object.prototype.hasOwnProperty;
var toString = Object.prototype.toString;
module.exports = function forEach (obj, fn, ctx) {
if (toString.call(fn) !== '[object Function]') {
throw new TypeError('iterator must be a function');
}
var l = obj.length;
if (l === +l) {
for (var i = 0; i < l; i++) {
fn.call(ctx, obj[i], i, obj);
}
} else {
for (var k in obj) {
if (hasOwn.call(obj, k)) {
fn.call(ctx, obj[k], k, obj);
}
}
}
};
},{}],5:[function(require,module,exports){
(function (global){
if (typeof window !== "undefined") {
module.exports = window;
} else if (typeof global !== "undefined") {
module.exports = global;
} else if (typeof self !== "undefined"){
module.exports = self;
} else {
module.exports = {};
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],6:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],7:[function(require,module,exports){
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
},{}],8:[function(require,module,exports){
/**
* Helpers.
*/
var s = 1000
var m = s * 60
var h = m * 60
var d = h * 24
var y = d * 365.25
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} options
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function (val, options) {
options = options || {}
var type = typeof val
if (type === 'string' && val.length > 0) {
return parse(val)
} else if (type === 'number' && isNaN(val) === false) {
return options.long ?
fmtLong(val) :
fmtShort(val)
}
throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val))
}
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str)
if (str.length > 10000) {
return
}
var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str)
if (!match) {
return
}
var n = parseFloat(match[1])
var type = (match[2] || 'ms').toLowerCase()
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y
case 'days':
case 'day':
case 'd':
return n * d
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n
default:
return undefined
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
if (ms >= d) {
return Math.round(ms / d) + 'd'
}
if (ms >= h) {
return Math.round(ms / h) + 'h'
}
if (ms >= m) {
return Math.round(ms / m) + 'm'
}
if (ms >= s) {
return Math.round(ms / s) + 's'
}
return ms + 'ms'
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
return plural(ms, d, 'day') ||
plural(ms, h, 'hour') ||
plural(ms, m, 'minute') ||
plural(ms, s, 'second') ||
ms + ' ms'
}
/**
* Pluralization helper.
*/
function plural(ms, n, name) {
if (ms < n) {
return
}
if (ms < n * 1.5) {
return Math.floor(ms / n) + ' ' + name
}
return Math.ceil(ms / n) + ' ' + name + 's'
}
},{}],9:[function(require,module,exports){
'use strict';
// modified from https://github.com/es-shims/es5-shim
var has = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var slice = Array.prototype.slice;
var isArgs = require(10);
var isEnumerable = Object.prototype.propertyIsEnumerable;
var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
var dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
];
var equalsConstructorPrototype = function (o) {
var ctor = o.constructor;
return ctor && ctor.prototype === o;
};
var excludedKeys = {
$console: true,
$external: true,
$frame: true,
$frameElement: true,
$frames: true,
$innerHeight: true,
$innerWidth: true,
$outerHeight: true,
$outerWidth: true,
$pageXOffset: true,
$pageYOffset: true,
$parent: true,
$scrollLeft: true,
$scrollTop: true,
$scrollX: true,
$scrollY: true,
$self: true,
$webkitIndexedDB: true,
$webkitStorageInfo: true,
$window: true
};
var hasAutomationEqualityBug = (function () {
/* global window */
if (typeof window === 'undefined') { return false; }
for (var k in window) {
try {
if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
try {
equalsConstructorPrototype(window[k]);
} catch (e) {
return true;
}
}
} catch (e) {
return true;
}
}
return false;
}());
var equalsConstructorPrototypeIfNotBuggy = function (o) {
/* global window */
if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
return equalsConstructorPrototype(o);
}
try {
return equalsConstructorPrototype(o);
} catch (e) {
return false;
}
};
var keysShim = function keys(object) {
var isObject = object !== null && typeof object === 'object';
var isFunction = toStr.call(object) === '[object Function]';
var isArguments = isArgs(object);
var isString = isObject && toStr.call(object) === '[object String]';
var theKeys = [];
if (!isObject && !isFunction && !isArguments) {
throw new TypeError('Object.keys called on a non-object');
}
var skipProto = hasProtoEnumBug && isFunction;
if (isString && object.length > 0 && !has.call(object, 0)) {
for (var i = 0; i < object.length; ++i) {
theKeys.push(String(i));
}
}
if (isArguments && object.length > 0) {
for (var j = 0; j < object.length; ++j) {
theKeys.push(String(j));
}
} else {
for (var name in object) {
if (!(skipProto && name === 'prototype') && has.call(object, name)) {
theKeys.push(String(name));
}
}
}
if (hasDontEnumBug) {
var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
for (var k = 0; k < dontEnums.length; ++k) {
if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
theKeys.push(dontEnums[k]);
}
}
}
return theKeys;
};
keysShim.shim = function shimObjectKeys() {
if (Object.keys) {
var keysWorksWithArguments = (function () {
// Safari 5.0 bug
return (Object.keys(arguments) || '').length === 2;
}(1, 2));
if (!keysWorksWithArguments) {
var originalKeys = Object.keys;
Object.keys = function keys(object) {
if (isArgs(object)) {
return originalKeys(slice.call(object));
} else {
return originalKeys(object);
}
};
}
} else {
Object.keys = keysShim;
}
return Object.keys || keysShim;
};
module.exports = keysShim;
},{"10":10}],10:[function(require,module,exports){
'use strict';
var toStr = Object.prototype.toString;
module.exports = function isArguments(value) {
var str = toStr.call(value);
var isArgs = str === '[object Arguments]';
if (!isArgs) {
isArgs = str !== '[object Array]' &&
value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
toStr.call(value.callee) === '[object Function]';
}
return isArgs;
};
},{}],11:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],12:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
var stringifyPrimitive = function(v) {
switch (typeof v) {
case 'string':
return v;
case 'boolean':
return v ? 'true' : 'false';
case 'number':
return isFinite(v) ? v : '';
default:
return '';
}
};
module.exports = function(obj, sep, eq, name) {
sep = sep || '&';
eq = eq || '=';
if (obj === null) {
obj = undefined;
}
if (typeof obj === 'object') {
return map(objectKeys(obj), function(k) {
var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
if (isArray(obj[k])) {
return map(obj[k], function(v) {
return ks + encodeURIComponent(stringifyPrimitive(v));
}).join(sep);
} else {
return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
}
}).join(sep);
}
if (!name) return '';
return encodeURIComponent(stringifyPrimitive(name)) + eq +
encodeURIComponent(stringifyPrimitive(obj));
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
function map (xs, f) {
if (xs.map) return xs.map(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
res.push(f(xs[i], i));
}
return res;
}
var objectKeys = Object.keys || function (obj) {
var res = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
}
return res;
};
},{}],13:[function(require,module,exports){
(function (process){
module.exports = AlgoliaSearchCore;
var errors = require(24);
var exitPromise = require(25);
var IndexCore = require(14);
var store = require(30);
// We will always put the API KEY in the JSON body in case of too long API KEY,
// to avoid query string being too long and failing in various conditions (our server limit, browser limit,
// proxies limit)
var MAX_API_KEY_LENGTH = 500;
var RESET_APP_DATA_TIMER =
process.env.RESET_APP_DATA_TIMER && parseInt(process.env.RESET_APP_DATA_TIMER, 10) ||
60 * 2 * 1000; // after 2 minutes reset to first host
/*
* Algolia Search library initialization
* https://www.algolia.com/
*
* @param {string} applicationID - Your applicationID, found in your dashboard
* @param {string} apiKey - Your API key, found in your dashboard
* @param {Object} [opts]
* @param {number} [opts.timeout=2000] - The request timeout set in milliseconds,
* another request will be issued after this timeout
* @param {string} [opts.protocol='http:'] - The protocol used to query Algolia Search API.
* Set to 'https:' to force using https.
* Default to document.location.protocol in browsers
* @param {Object|Array} [opts.hosts={
* read: [this.applicationID + '-dsn.algolia.net'].concat([
* this.applicationID + '-1.algolianet.com',
* this.applicationID + '-2.algolianet.com',
* this.applicationID + '-3.algolianet.com']
* ]),
* write: [this.applicationID + '.algolia.net'].concat([
* this.applicationID + '-1.algolianet.com',
* this.applicationID + '-2.algolianet.com',
* this.applicationID + '-3.algolianet.com']
* ]) - The hosts to use for Algolia Search API.
* If you provide them, you will less benefit from our HA implementation
*/
function AlgoliaSearchCore(applicationID, apiKey, opts) {
var debug = require(1)('algoliasearch');
var clone = require(21);
var isArray = require(7);
var map = require(26);
var usage = 'Usage: algoliasearch(applicationID, apiKey, opts)';
if (opts._allowEmptyCredentials !== true && !applicationID) {
throw new errors.AlgoliaSearchError('Please provide an application ID. ' + usage);
}
if (opts._allowEmptyCredentials !== true && !apiKey) {
throw new errors.AlgoliaSearchError('Please provide an API key. ' + usage);
}
this.applicationID = applicationID;
this.apiKey = apiKey;
this.hosts = {
read: [],
write: []
};
opts = opts || {};
var protocol = opts.protocol || 'https:';
this._timeouts = opts.timeouts || {
connect: 1 * 1000, // 500ms connect is GPRS latency
read: 2 * 1000,
write: 30 * 1000
};
// backward compat, if opts.timeout is passed, we use it to configure all timeouts like before
if (opts.timeout) {
this._timeouts.connect = this._timeouts.read = this._timeouts.write = opts.timeout;
}
// while we advocate for colon-at-the-end values: 'http:' for `opts.protocol`
// we also accept `http` and `https`. It's a common error.
if (!/:$/.test(protocol)) {
protocol = protocol + ':';
}
if (opts.protocol !== 'http:' && opts.protocol !== 'https:') {
throw new errors.AlgoliaSearchError('protocol must be `http:` or `https:` (was `' + opts.protocol + '`)');
}
this._checkAppIdData();
if (!opts.hosts) {
var defaultHosts = map(this._shuffleResult, function(hostNumber) {
return applicationID + '-' + hostNumber + '.algolianet.com';
});
// no hosts given, compute defaults
this.hosts.read = [this.applicationID + '-dsn.algolia.net'].concat(defaultHosts);
this.hosts.write = [this.applicationID + '.algolia.net'].concat(defaultHosts);
} else if (isArray(opts.hosts)) {
// when passing custom hosts, we need to have a different host index if the number
// of write/read hosts are different.
this.hosts.read = clone(opts.hosts);
this.hosts.write = clone(opts.hosts);
} else {
this.hosts.read = clone(opts.hosts.read);
this.hosts.write = clone(opts.hosts.write);
}
// add protocol and lowercase hosts
this.hosts.read = map(this.hosts.read, prepareHost(protocol));
this.hosts.write = map(this.hosts.write, prepareHost(protocol));
this.extraHeaders = [];
// In some situations you might want to warm the cache
this.cache = opts._cache || {};
this._ua = opts._ua;
this._useCache = opts._useCache === undefined || opts._cache ? true : opts._useCache;
this._useFallback = opts.useFallback === undefined ? true : opts.useFallback;
this._setTimeout = opts._setTimeout;
debug('init done, %j', this);
}
/*
* Get the index object initialized
*
* @param indexName the name of index
* @param callback the result callback with one argument (the Index instance)
*/
AlgoliaSearchCore.prototype.initIndex = function(indexName) {
return new IndexCore(this, indexName);
};
/**
* Add an extra field to the HTTP request
*
* @param name the header field name
* @param value the header field value
*/
AlgoliaSearchCore.prototype.setExtraHeader = function(name, value) {
this.extraHeaders.push({
name: name.toLowerCase(), value: value
});
};
/**
* Augment sent x-algolia-agent with more data, each agent part
* is automatically separated from the others by a semicolon;
*
* @param algoliaAgent the agent to add
*/
AlgoliaSearchCore.prototype.addAlgoliaAgent = function(algoliaAgent) {
if (this._ua.indexOf(';' + algoliaAgent) === -1) {
this._ua += ';' + algoliaAgent;
}
};
/*
* Wrapper that try all hosts to maximize the quality of service
*/
AlgoliaSearchCore.prototype._jsonRequest = function(initialOpts) {
this._checkAppIdData();
var requestDebug = require(1)('algoliasearch:' + initialOpts.url);
var body;
var additionalUA = initialOpts.additionalUA || '';
var cache = initialOpts.cache;
var client = this;
var tries = 0;
var usingFallback = false;
var hasFallback = client._useFallback && client._request.fallback && initialOpts.fallback;
var headers;
if (
this.apiKey.length > MAX_API_KEY_LENGTH &&
initialOpts.body !== undefined &&
(initialOpts.body.params !== undefined || // index.search()
initialOpts.body.requests !== undefined) // client.search()
) {
initialOpts.body.apiKey = this.apiKey;
headers = this._computeRequestHeaders(additionalUA, false);
} else {
headers = this._computeRequestHeaders(additionalUA);
}
if (initialOpts.body !== undefined) {
body = safeJSONStringify(initialOpts.body);
}
requestDebug('request start');
var debugData = [];
function doRequest(requester, reqOpts) {
client._checkAppIdData();
var startTime = new Date();
var cacheID;
if (client._useCache) {
cacheID = initialOpts.url;
}
// as we sometime use POST requests to pass parameters (like query='aa'),
// the cacheID must also include the body to be different between calls
if (client._useCache && body) {
cacheID += '_body_' + reqOpts.body;
}
// handle cache existence
if (client._useCache && cache && cache[cacheID] !== undefined) {
requestDebug('serving response from cache');
return client._promise.resolve(JSON.parse(cache[cacheID]));
}
// if we reached max tries
if (tries >= client.hosts[initialOpts.hostType].length) {
if (!hasFallback || usingFallback) {
requestDebug('could not get any response');
// then stop
return client._promise.reject(new errors.AlgoliaSearchError(
'Cannot connect to the AlgoliaSearch API.' +
' Send an email to support@algolia.com to report and resolve the issue.' +
' Application id was: ' + client.applicationID, {debugData: debugData}
));
}
requestDebug('switching to fallback');
// let's try the fallback starting from here
tries = 0;
// method, url and body are fallback dependent
reqOpts.method = initialOpts.fallback.method;
reqOpts.url = initialOpts.fallback.url;
reqOpts.jsonBody = initialOpts.fallback.body;
if (reqOpts.jsonBody) {
reqOpts.body = safeJSONStringify(reqOpts.jsonBody);
}
// re-compute headers, they could be omitting the API KEY
headers = client._computeRequestHeaders(additionalUA);
reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType);
client._setHostIndexByType(0, initialOpts.hostType);
usingFallback = true; // the current request is now using fallback
return doRequest(client._request.fallback, reqOpts);
}
var currentHost = client._getHostByType(initialOpts.hostType);
var url = currentHost + reqOpts.url;
var options = {
body: reqOpts.body,
jsonBody: reqOpts.jsonBody,
method: reqOpts.method,
headers: headers,
timeouts: reqOpts.timeouts,
debug: requestDebug
};
requestDebug('method: %s, url: %s, headers: %j, timeouts: %d',
options.method, url, options.headers, options.timeouts);
if (requester === client._request.fallback) {
requestDebug('using fallback');
}
// `requester` is any of this._request or this._request.fallback
// thus it needs to be called using the client as context
return requester.call(client, url, options).then(success, tryFallback);
function success(httpResponse) {
// compute the status of the response,
//
// When in browser mode, using XDR or JSONP, we have no statusCode available
// So we rely on our API response `status` property.
// But `waitTask` can set a `status` property which is not the statusCode (it's the task status)
// So we check if there's a `message` along `status` and it means it's an error
//
// That's the only case where we have a response.status that's not the http statusCode
var status = httpResponse && httpResponse.body && httpResponse.body.message && httpResponse.body.status ||
// this is important to check the request statusCode AFTER the body eventual
// statusCode because some implementations (jQuery XDomainRequest transport) may
// send statusCode 200 while we had an error
httpResponse.statusCode ||
// When in browser mode, using XDR or JSONP
// we default to success when no error (no response.status && response.message)
// If there was a JSON.parse() error then body is null and it fails
httpResponse && httpResponse.body && 200;
requestDebug('received response: statusCode: %s, computed statusCode: %d, headers: %j',
httpResponse.statusCode, status, httpResponse.headers);
var httpResponseOk = Math.floor(status / 100) === 2;
var endTime = new Date();
debugData.push({
currentHost: currentHost,
headers: removeCredentials(headers),
content: body || null,
contentLength: body !== undefined ? body.length : null,
method: reqOpts.method,
timeouts: reqOpts.timeouts,
url: reqOpts.url,
startTime: startTime,
endTime: endTime,
duration: endTime - startTime,
statusCode: status
});
if (httpResponseOk) {
if (client._useCache && cache) {
cache[cacheID] = httpResponse.responseText;
}
return httpResponse.body;
}
var shouldRetry = Math.floor(status / 100) !== 4;
if (shouldRetry) {
tries += 1;
return retryRequest();
}
requestDebug('unrecoverable error');
// no success and no retry => fail
var unrecoverableError = new errors.AlgoliaSearchError(
httpResponse.body && httpResponse.body.message, {debugData: debugData, statusCode: status}
);
return client._promise.reject(unrecoverableError);
}
function tryFallback(err) {
// error cases:
// While not in fallback mode:
// - CORS not supported
// - network error
// While in fallback mode:
// - timeout
// - network error
// - badly formatted JSONP (script loaded, did not call our callback)
// In both cases:
// - uncaught exception occurs (TypeError)
requestDebug('error: %s, stack: %s', err.message, err.stack);
var endTime = new Date();
debugData.push({
currentHost: currentHost,
headers: removeCredentials(headers),
content: body || null,
contentLength: body !== undefined ? body.length : null,
method: reqOpts.method,
timeouts: reqOpts.timeouts,
url: reqOpts.url,
startTime: startTime,
endTime: endTime,
duration: endTime - startTime
});
if (!(err instanceof errors.AlgoliaSearchError)) {
err = new errors.Unknown(err && err.message, err);
}
tries += 1;
// stop the request implementation when:
if (
// we did not generate this error,
// it comes from a throw in some other piece of code
err instanceof errors.Unknown ||
// server sent unparsable JSON
err instanceof errors.UnparsableJSON ||
// max tries and already using fallback or no fallback
tries >= client.hosts[initialOpts.hostType].length &&
(usingFallback || !hasFallback)) {
// stop request implementation for this command
err.debugData = debugData;
return client._promise.reject(err);
}
// When a timeout occured, retry by raising timeout
if (err instanceof errors.RequestTimeout) {
return retryRequestWithHigherTimeout();
}
return retryRequest();
}
function retryRequest() {
requestDebug('retrying request');
client._incrementHostIndex(initialOpts.hostType);
return doRequest(requester, reqOpts);
}
function retryRequestWithHigherTimeout() {
requestDebug('retrying request with higher timeout');
client._incrementHostIndex(initialOpts.hostType);
client._incrementTimeoutMultipler();
reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType);
return doRequest(requester, reqOpts);
}
}
var promise = doRequest(
client._request, {
url: initialOpts.url,
method: initialOpts.method,
body: body,
jsonBody: initialOpts.body,
timeouts: client._getTimeoutsForRequest(initialOpts.hostType)
}
);
// either we have a callback
// either we are using promises
if (initialOpts.callback) {
promise.then(function okCb(content) {
exitPromise(function() {
initialOpts.callback(null, content);
}, client._setTimeout || setTimeout);
}, function nookCb(err) {
exitPromise(function() {
initialOpts.callback(err);
}, client._setTimeout || setTimeout);
});
} else {
return promise;
}
};
/*
* Transform search param object in query string
* @param {object} args arguments to add to the current query string
* @param {string} params current query string
* @return {string} the final query string
*/
AlgoliaSearchCore.prototype._getSearchParams = function(args, params) {
if (args === undefined || args === null) {
return params;
}
for (var key in args) {
if (key !== null && args[key] !== undefined && args.hasOwnProperty(key)) {
params += params === '' ? '' : '&';
params += key + '=' + encodeURIComponent(Object.prototype.toString.call(args[key]) === '[object Array]' ? safeJSONStringify(args[key]) : args[key]);
}
}
return params;
};
AlgoliaSearchCore.prototype._computeRequestHeaders = function(additionalUA, withAPIKey) {
var forEach = require(4);
var ua = additionalUA ?
this._ua + ';' + additionalUA :
this._ua;
var requestHeaders = {
'x-algolia-agent': ua,
'x-algolia-application-id': this.applicationID
};
// browser will inline headers in the url, node.js will use http headers
// but in some situations, the API KEY will be too long (big secured API keys)
// so if the request is a POST and the KEY is very long, we will be asked to not put
// it into headers but in the JSON body
if (withAPIKey !== false) {
requestHeaders['x-algolia-api-key'] = this.apiKey;
}
if (this.userToken) {
requestHeaders['x-algolia-usertoken'] = this.userToken;
}
if (this.securityTags) {
requestHeaders['x-algolia-tagfilters'] = this.securityTags;
}
if (this.extraHeaders) {
forEach(this.extraHeaders, function addToRequestHeaders(header) {
requestHeaders[header.name] = header.value;
});
}
return requestHeaders;
};
/**
* Search through multiple indices at the same time
* @param {Object[]} queries An array of queries you want to run.
* @param {string} queries[].indexName The index name you want to target
* @param {string} [queries[].query] The query to issue on this index. Can also be passed into `params`
* @param {Object} queries[].params Any search param like hitsPerPage, ..
* @param {Function} callback Callback to be called
* @return {Promise|undefined} Returns a promise if no callback given
*/
AlgoliaSearchCore.prototype.search = function(queries, opts, callback) {
var isArray = require(7);
var map = require(26);
var usage = 'Usage: client.search(arrayOfQueries[, callback])';
if (!isArray(queries)) {
throw new Error(usage);
}
if (typeof opts === 'function') {
callback = opts;
opts = {};
} else if (opts === undefined) {
opts = {};
}
var client = this;
var postObj = {
requests: map(queries, function prepareRequest(query) {
var params = '';
// allow query.query
// so we are mimicing the index.search(query, params) method
// {indexName:, query:, params:}
if (query.query !== undefined) {
params += 'query=' + encodeURIComponent(query.query);
}
return {
indexName: query.indexName,
params: client._getSearchParams(query.params, params)
};
})
};
var JSONPParams = map(postObj.requests, function prepareJSONPParams(request, requestId) {
return requestId + '=' +
encodeURIComponent(
'/1/indexes/' + encodeURIComponent(request.indexName) + '?' +
request.params
);
}).join('&');
var url = '/1/indexes/*/queries';
if (opts.strategy !== undefined) {
url += '?strategy=' + opts.strategy;
}
return this._jsonRequest({
cache: this.cache,
method: 'POST',
url: url,
body: postObj,
hostType: 'read',
fallback: {
method: 'GET',
url: '/1/indexes/*',
body: {
params: JSONPParams
}
},
callback: callback
});
};
/**
* Set the extra security tagFilters header
* @param {string|array} tags The list of tags defining the current security filters
*/
AlgoliaSearchCore.prototype.setSecurityTags = function(tags) {
if (Object.prototype.toString.call(tags) === '[object Array]') {
var strTags = [];
for (var i = 0; i < tags.length; ++i) {
if (Object.prototype.toString.call(tags[i]) === '[object Array]') {
var oredTags = [];
for (var j = 0; j < tags[i].length; ++j) {
oredTags.push(tags[i][j]);
}
strTags.push('(' + oredTags.join(',') + ')');
} else {
strTags.push(tags[i]);
}
}
tags = strTags.join(',');
}
this.securityTags = tags;
};
/**
* Set the extra user token header
* @param {string} userToken The token identifying a uniq user (used to apply rate limits)
*/
AlgoliaSearchCore.prototype.setUserToken = function(userToken) {
this.userToken = userToken;
};
/**
* Clear all queries in client's cache
* @return undefined
*/
AlgoliaSearchCore.prototype.clearCache = function() {
this.cache = {};
};
/**
* Set the number of milliseconds a request can take before automatically being terminated.
* @deprecated
* @param {Number} milliseconds
*/
AlgoliaSearchCore.prototype.setRequestTimeout = function(milliseconds) {
if (milliseconds) {
this._timeouts.connect = this._timeouts.read = this._timeouts.write = milliseconds;
}
};
/**
* Set the three different (connect, read, write) timeouts to be used when requesting
* @param {Object} timeouts
*/
AlgoliaSearchCore.prototype.setTimeouts = function(timeouts) {
this._timeouts = timeouts;
};
/**
* Get the three different (connect, read, write) timeouts to be used when requesting
* @param {Object} timeouts
*/
AlgoliaSearchCore.prototype.getTimeouts = function() {
return this._timeouts;
};
AlgoliaSearchCore.prototype._getAppIdData = function() {
var data = store.get(this.applicationID);
if (data !== null) this._cacheAppIdData(data);
return data;
};
AlgoliaSearchCore.prototype._setAppIdData = function(data) {
data.lastChange = (new Date()).getTime();
this._cacheAppIdData(data);
return store.set(this.applicationID, data);
};
AlgoliaSearchCore.prototype._checkAppIdData = function() {
var data = this._getAppIdData();
var now = (new Date()).getTime();
if (data === null || now - data.lastChange > RESET_APP_DATA_TIMER) {
return this._resetInitialAppIdData(data);
}
return data;
};
AlgoliaSearchCore.prototype._resetInitialAppIdData = function(data) {
var newData = data || {};
newData.hostIndexes = {read: 0, write: 0};
newData.timeoutMultiplier = 1;
newData.shuffleResult = newData.shuffleResult || shuffle([1, 2, 3]);
return this._setAppIdData(newData);
};
AlgoliaSearchCore.prototype._cacheAppIdData = function(data) {
this._hostIndexes = data.hostIndexes;
this._timeoutMultiplier = data.timeoutMultiplier;
this._shuffleResult = data.shuffleResult;
};
AlgoliaSearchCore.prototype._partialAppIdDataUpdate = function(newData) {
var foreach = require(4);
var currentData = this._getAppIdData();
foreach(newData, function(value, key) {
currentData[key] = value;
});
return this._setAppIdData(currentData);
};
AlgoliaSearchCore.prototype._getHostByType = function(hostType) {
return this.hosts[hostType][this._getHostIndexByType(hostType)];
};
AlgoliaSearchCore.prototype._getTimeoutMultiplier = function() {
return this._timeoutMultiplier;
};
AlgoliaSearchCore.prototype._getHostIndexByType = function(hostType) {
return this._hostIndexes[hostType];
};
AlgoliaSearchCore.prototype._setHostIndexByType = function(hostIndex, hostType) {
var clone = require(21);
var newHostIndexes = clone(this._hostIndexes);
newHostIndexes[hostType] = hostIndex;
this._partialAppIdDataUpdate({hostIndexes: newHostIndexes});
return hostIndex;
};
AlgoliaSearchCore.prototype._incrementHostIndex = function(hostType) {
return this._setHostIndexByType(
(this._getHostIndexByType(hostType) + 1) % this.hosts[hostType].length, hostType
);
};
AlgoliaSearchCore.prototype._incrementTimeoutMultipler = function() {
var timeoutMultiplier = Math.max(this._timeoutMultiplier + 1, 4);
return this._partialAppIdDataUpdate({timeoutMultiplier: timeoutMultiplier});
};
AlgoliaSearchCore.prototype._getTimeoutsForRequest = function(hostType) {
return {
connect: this._timeouts.connect * this._timeoutMultiplier,
complete: this._timeouts[hostType] * this._timeoutMultiplier
};
};
function prepareHost(protocol) {
return function prepare(host) {
return protocol + '//' + host.toLowerCase();
};
}
// Prototype.js < 1.7, a widely used library, defines a weird
// Array.prototype.toJSON function that will fail to stringify our content
// appropriately
// refs:
// - https://groups.google.com/forum/#!topic/prototype-core/E-SAVvV_V9Q
// - https://github.com/sstephenson/prototype/commit/038a2985a70593c1a86c230fadbdfe2e4898a48c
// - http://stackoverflow.com/a/3148441/147079
function safeJSONStringify(obj) {
/* eslint no-extend-native:0 */
if (Array.prototype.toJSON === undefined) {
return JSON.stringify(obj);
}
var toJSON = Array.prototype.toJSON;
delete Array.prototype.toJSON;
var out = JSON.stringify(obj);
Array.prototype.toJSON = toJSON;
return out;
}
function shuffle(array) {
var currentIndex = array.length;
var temporaryValue;
var randomIndex;
// While there remain elements to shuffle...
while (currentIndex !== 0) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function removeCredentials(headers) {
var newHeaders = {};
for (var headerName in headers) {
if (Object.prototype.hasOwnProperty.call(headers, headerName)) {
var value;
if (headerName === 'x-algolia-api-key' || headerName === 'x-algolia-application-id') {
value = '**hidden for security purposes**';
} else {
value = headers[headerName];
}
newHeaders[headerName] = value;
}
}
return newHeaders;
}
}).call(this,require(11))
},{"1":1,"11":11,"14":14,"21":21,"24":24,"25":25,"26":26,"30":30,"4":4,"7":7}],14:[function(require,module,exports){
var buildSearchMethod = require(20);
var deprecate = require(22);
var deprecatedMessage = require(23);
module.exports = IndexCore;
/*
* Index class constructor.
* You should not use this method directly but use initIndex() function
*/
function IndexCore(algoliasearch, indexName) {
this.indexName = indexName;
this.as = algoliasearch;
this.typeAheadArgs = null;
this.typeAheadValueOption = null;
// make sure every index instance has it's own cache
this.cache = {};
}
/*
* Clear all queries in cache
*/
IndexCore.prototype.clearCache = function() {
this.cache = {};
};
/*
* Search inside the index using XMLHttpRequest request (Using a POST query to
* minimize number of OPTIONS queries: Cross-Origin Resource Sharing).
*
* @param {string} [query] the full text query
* @param {object} [args] (optional) if set, contains an object with query parameters:
* - page: (integer) Pagination parameter used to select the page to retrieve.
* Page is zero-based and defaults to 0. Thus,
* to retrieve the 10th page you need to set page=9
* - hitsPerPage: (integer) Pagination parameter used to select the number of hits per page. Defaults to 20.
* - attributesToRetrieve: a string that contains the list of object attributes
* you want to retrieve (let you minimize the answer size).
* Attributes are separated with a comma (for example "name,address").
* You can also use an array (for example ["name","address"]).
* By default, all attributes are retrieved. You can also use '*' to retrieve all
* values when an attributesToRetrieve setting is specified for your index.
* - attributesToHighlight: a string that contains the list of attributes you
* want to highlight according to the query.
* Attributes are separated by a comma. You can also use an array (for example ["name","address"]).
* If an attribute has no match for the query, the raw value is returned.
* By default all indexed text attributes are highlighted.
* You can use `*` if you want to highlight all textual attributes.
* Numerical attributes are not highlighted.
* A matchLevel is returned for each highlighted attribute and can contain:
* - full: if all the query terms were found in the attribute,
* - partial: if only some of the query terms were found,
* - none: if none of the query terms were found.
* - attributesToSnippet: a string that contains the list of attributes to snippet alongside
* the number of words to return (syntax is `attributeName:nbWords`).
* Attributes are separated by a comma (Example: attributesToSnippet=name:10,content:10).
* You can also use an array (Example: attributesToSnippet: ['name:10','content:10']).
* By default no snippet is computed.
* - minWordSizefor1Typo: the minimum number of characters in a query word to accept one typo in this word.
* Defaults to 3.
* - minWordSizefor2Typos: the minimum number of characters in a query word
* to accept two typos in this word. Defaults to 7.
* - getRankingInfo: if set to 1, the result hits will contain ranking
* information in _rankingInfo attribute.
* - aroundLatLng: search for entries around a given
* latitude/longitude (specified as two floats separated by a comma).
* For example aroundLatLng=47.316669,5.016670).
* You can specify the maximum distance in meters with the aroundRadius parameter (in meters)
* and the precision for ranking with aroundPrecision
* (for example if you set aroundPrecision=100, two objects that are distant of
* less than 100m will be considered as identical for "geo" ranking parameter).
* At indexing, you should specify geoloc of an object with the _geoloc attribute
* (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}})
* - insideBoundingBox: search entries inside a given area defined by the two extreme points
* of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng).
* For example insideBoundingBox=47.3165,4.9665,47.3424,5.0201).
* At indexing, you should specify geoloc of an object with the _geoloc attribute
* (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}})
* - numericFilters: a string that contains the list of numeric filters you want to
* apply separated by a comma.
* The syntax of one filter is `attributeName` followed by `operand` followed by `value`.
* Supported operands are `<`, `<=`, `=`, `>` and `>=`.
* You can have multiple conditions on one attribute like for example numericFilters=price>100,price<1000.
* You can also use an array (for example numericFilters: ["price>100","price<1000"]).
* - tagFilters: filter the query by a set of tags. You can AND tags by separating them by commas.
* To OR tags, you must add parentheses. For example, tags=tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3).
* You can also use an array, for example tagFilters: ["tag1",["tag2","tag3"]]
* means tag1 AND (tag2 OR tag3).
* At indexing, tags should be added in the _tags** attribute
* of objects (for example {"_tags":["tag1","tag2"]}).
* - facetFilters: filter the query by a list of facets.
* Facets are separated by commas and each facet is encoded as `attributeName:value`.
* For example: `facetFilters=category:Book,author:John%20Doe`.
* You can also use an array (for example `["category:Book","author:John%20Doe"]`).
* - facets: List of object attributes that you want to use for faceting.
* Comma separated list: `"category,author"` or array `['category','author']`
* Only attributes that have been added in **attributesForFaceting** index setting
* can be used in this parameter.
* You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**.
* - queryType: select how the query words are interpreted, it can be one of the following value:
* - prefixAll: all query words are interpreted as prefixes,
* - prefixLast: only the last word is interpreted as a prefix (default behavior),
* - prefixNone: no query word is interpreted as a prefix. This option is not recommended.
* - optionalWords: a string that contains the list of words that should
* be considered as optional when found in the query.
* Comma separated and array are accepted.
* - distinct: If set to 1, enable the distinct feature (disabled by default)
* if the attributeForDistinct index setting is set.
* This feature is similar to the SQL "distinct" keyword: when enabled
* in a query with the distinct=1 parameter,
* all hits containing a duplicate value for the attributeForDistinct attribute are removed from results.
* For example, if the chosen attribute is show_name and several hits have
* the same value for show_name, then only the best
* one is kept and others are removed.
* - restrictSearchableAttributes: List of attributes you want to use for
* textual search (must be a subset of the attributesToIndex index setting)
* either comma separated or as an array
* @param {function} [callback] the result callback called with two arguments:
* error: null or Error('message'). If false, the content contains the error.
* content: the server answer that contains the list of results.
*/
IndexCore.prototype.search = buildSearchMethod('query');
/*
* -- BETA --
* Search a record similar to the query inside the index using XMLHttpRequest request (Using a POST query to
* minimize number of OPTIONS queries: Cross-Origin Resource Sharing).
*
* @param {string} [query] the similar query
* @param {object} [args] (optional) if set, contains an object with query parameters.
* All search parameters are supported (see search function), restrictSearchableAttributes and facetFilters
* are the two most useful to restrict the similar results and get more relevant content
*/
IndexCore.prototype.similarSearch = buildSearchMethod('similarQuery');
/*
* Browse index content. The response content will have a `cursor` property that you can use
* to browse subsequent pages for this query. Use `index.browseFrom(cursor)` when you want.
*
* @param {string} query - The full text query
* @param {Object} [queryParameters] - Any search query parameter
* @param {Function} [callback] - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the browse result
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* index.browse('cool songs', {
* tagFilters: 'public,comments',
* hitsPerPage: 500
* }, callback);
* @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation}
*/
IndexCore.prototype.browse = function(query, queryParameters, callback) {
var merge = require(27);
var indexObj = this;
var page;
var hitsPerPage;
// we check variadic calls that are not the one defined
// .browse()/.browse(fn)
// => page = 0
if (arguments.length === 0 || arguments.length === 1 && typeof arguments[0] === 'function') {
page = 0;
callback = arguments[0];
query = undefined;
} else if (typeof arguments[0] === 'number') {
// .browse(2)/.browse(2, 10)/.browse(2, fn)/.browse(2, 10, fn)
page = arguments[0];
if (typeof arguments[1] === 'number') {
hitsPerPage = arguments[1];
} else if (typeof arguments[1] === 'function') {
callback = arguments[1];
hitsPerPage = undefined;
}
query = undefined;
queryParameters = undefined;
} else if (typeof arguments[0] === 'object') {
// .browse(queryParameters)/.browse(queryParameters, cb)
if (typeof arguments[1] === 'function') {
callback = arguments[1];
}
queryParameters = arguments[0];
query = undefined;
} else if (typeof arguments[0] === 'string' && typeof arguments[1] === 'function') {
// .browse(query, cb)
callback = arguments[1];
queryParameters = undefined;
}
// otherwise it's a .browse(query)/.browse(query, queryParameters)/.browse(query, queryParameters, cb)
// get search query parameters combining various possible calls
// to .browse();
queryParameters = merge({}, queryParameters || {}, {
page: page,
hitsPerPage: hitsPerPage,
query: query
});
var params = this.as._getSearchParams(queryParameters, '');
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/browse',
body: {params: params},
hostType: 'read',
callback: callback
});
};
/*
* Continue browsing from a previous position (cursor), obtained via a call to `.browse()`.
*
* @param {string} query - The full text query
* @param {Object} [queryParameters] - Any search query parameter
* @param {Function} [callback] - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the browse result
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* index.browseFrom('14lkfsakl32', callback);
* @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation}
*/
IndexCore.prototype.browseFrom = function(cursor, callback) {
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/browse',
body: {cursor: cursor},
hostType: 'read',
callback: callback
});
};
/*
* Search for facet values
* https://www.algolia.com/doc/rest-api/search#search-for-facet-values
*
* @param {string} params.facetName Facet name, name of the attribute to search for values in.
* Must be declared as a facet
* @param {string} params.facetQuery Query for the facet search
* @param {string} [params.*] Any search parameter of Algolia,
* see https://www.algolia.com/doc/api-client/javascript/search#search-parameters
* Pagination is not supported. The page and hitsPerPage parameters will be ignored.
* @param callback (optional)
*/
IndexCore.prototype.searchForFacetValues = function(params, callback) {
var clone = require(21);
var omit = require(28);
var usage = 'Usage: index.searchForFacetValues({facetName, facetQuery, ...params}[, callback])';
if (params.facetName === undefined || params.facetQuery === undefined) {
throw new Error(usage);
}
var facetName = params.facetName;
var filteredParams = omit(clone(params), function(keyName) {
return keyName === 'facetName';
});
var searchParameters = this.as._getSearchParams(filteredParams, '');
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' +
encodeURIComponent(this.indexName) + '/facets/' + encodeURIComponent(facetName) + '/query',
hostType: 'read',
body: {params: searchParameters},
callback: callback
});
};
IndexCore.prototype.searchFacet = deprecate(function(params, callback) {
return this.searchForFacetValues(params, callback);
}, deprecatedMessage(
'index.searchFacet(params[, callback])',
'index.searchForFacetValues(params[, callback])'
));
IndexCore.prototype._search = function(params, url, callback, additionalUA) {
return this.as._jsonRequest({
cache: this.cache,
method: 'POST',
url: url || '/1/indexes/' + encodeURIComponent(this.indexName) + '/query',
body: {params: params},
hostType: 'read',
fallback: {
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(this.indexName),
body: {params: params}
},
callback: callback,
additionalUA: additionalUA
});
};
/*
* Get an object from this index
*
* @param objectID the unique identifier of the object to retrieve
* @param attrs (optional) if set, contains the array of attribute names to retrieve
* @param callback (optional) the result callback called with two arguments
* error: null or Error('message')
* content: the object to retrieve or the error message if a failure occured
*/
IndexCore.prototype.getObject = function(objectID, attrs, callback) {
var indexObj = this;
if (arguments.length === 1 || typeof attrs === 'function') {
callback = attrs;
attrs = undefined;
}
var params = '';
if (attrs !== undefined) {
params = '?attributes=';
for (var i = 0; i < attrs.length; ++i) {
if (i !== 0) {
params += ',';
}
params += attrs[i];
}
}
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID) + params,
hostType: 'read',
callback: callback
});
};
/*
* Get several objects from this index
*
* @param objectIDs the array of unique identifier of objects to retrieve
*/
IndexCore.prototype.getObjects = function(objectIDs, attributesToRetrieve, callback) {
var isArray = require(7);
var map = require(26);
var usage = 'Usage: index.getObjects(arrayOfObjectIDs[, callback])';
if (!isArray(objectIDs)) {
throw new Error(usage);
}
var indexObj = this;
if (arguments.length === 1 || typeof attributesToRetrieve === 'function') {
callback = attributesToRetrieve;
attributesToRetrieve = undefined;
}
var body = {
requests: map(objectIDs, function prepareRequest(objectID) {
var request = {
indexName: indexObj.indexName,
objectID: objectID
};
if (attributesToRetrieve) {
request.attributesToRetrieve = attributesToRetrieve.join(',');
}
return request;
})
};
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/*/objects',
hostType: 'read',
body: body,
callback: callback
});
};
IndexCore.prototype.as = null;
IndexCore.prototype.indexName = null;
IndexCore.prototype.typeAheadArgs = null;
IndexCore.prototype.typeAheadValueOption = null;
},{"20":20,"21":21,"22":22,"23":23,"26":26,"27":27,"28":28,"7":7}],15:[function(require,module,exports){
'use strict';
var AlgoliaSearchCore = require(13);
var createAlgoliasearch = require(16);
module.exports = createAlgoliasearch(AlgoliaSearchCore, '(lite) ');
},{"13":13,"16":16}],16:[function(require,module,exports){
(function (process){
'use strict';
var global = require(5);
var Promise = global.Promise || require(3).Promise;
// This is the standalone browser build entry point
// Browser implementation of the Algolia Search JavaScript client,
// using XMLHttpRequest, XDomainRequest and JSONP as fallback
module.exports = function createAlgoliasearch(AlgoliaSearch, uaSuffix) {
var inherits = require(6);
var errors = require(24);
var inlineHeaders = require(18);
var jsonpRequest = require(19);
var places = require(29);
uaSuffix = uaSuffix || '';
if (process.env.NODE_ENV === 'debug') {
require(1).enable('algoliasearch*');
}
function algoliasearch(applicationID, apiKey, opts) {
var cloneDeep = require(21);
var getDocumentProtocol = require(17);
opts = cloneDeep(opts || {});
if (opts.protocol === undefined) {
opts.protocol = getDocumentProtocol();
}
opts._ua = opts._ua || algoliasearch.ua;
return new AlgoliaSearchBrowser(applicationID, apiKey, opts);
}
algoliasearch.version = require(31);
algoliasearch.ua = 'Algolia for vanilla JavaScript ' + uaSuffix + algoliasearch.version;
algoliasearch.initPlaces = places(algoliasearch);
// we expose into window no matter how we are used, this will allow
// us to easily debug any website running algolia
global.__algolia = {
debug: require(1),
algoliasearch: algoliasearch
};
var support = {
hasXMLHttpRequest: 'XMLHttpRequest' in global,
hasXDomainRequest: 'XDomainRequest' in global
};
if (support.hasXMLHttpRequest) {
support.cors = 'withCredentials' in new XMLHttpRequest();
}
function AlgoliaSearchBrowser() {
// call AlgoliaSearch constructor
AlgoliaSearch.apply(this, arguments);
}
inherits(AlgoliaSearchBrowser, AlgoliaSearch);
AlgoliaSearchBrowser.prototype._request = function request(url, opts) {
return new Promise(function wrapRequest(resolve, reject) {
// no cors or XDomainRequest, no request
if (!support.cors && !support.hasXDomainRequest) {
// very old browser, not supported
reject(new errors.Network('CORS not supported'));
return;
}
url = inlineHeaders(url, opts.headers);
var body = opts.body;
var req = support.cors ? new XMLHttpRequest() : new XDomainRequest();
var reqTimeout;
var timedOut;
var connected = false;
reqTimeout = setTimeout(onTimeout, opts.timeouts.connect);
// we set an empty onprogress listener
// so that XDomainRequest on IE9 is not aborted
// refs:
// - https://github.com/algolia/algoliasearch-client-js/issues/76
// - https://social.msdn.microsoft.com/Forums/ie/en-US/30ef3add-767c-4436-b8a9-f1ca19b4812e/ie9-rtm-xdomainrequest-issued-requests-may-abort-if-all-event-handlers-not-specified?forum=iewebdevelopment
req.onprogress = onProgress;
if ('onreadystatechange' in req) req.onreadystatechange = onReadyStateChange;
req.onload = onLoad;
req.onerror = onError;
// do not rely on default XHR async flag, as some analytics code like hotjar
// breaks it and set it to false by default
if (req instanceof XMLHttpRequest) {
req.open(opts.method, url, true);
} else {
req.open(opts.method, url);
}
// headers are meant to be sent after open
if (support.cors) {
if (body) {
if (opts.method === 'POST') {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Simple_requests
req.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
} else {
req.setRequestHeader('content-type', 'application/json');
}
}
req.setRequestHeader('accept', 'application/json');
}
req.send(body);
// event object not received in IE8, at least
// but we do not use it, still important to note
function onLoad(/* event */) {
// When browser does not supports req.timeout, we can
// have both a load and timeout event, since handled by a dumb setTimeout
if (timedOut) {
return;
}
clearTimeout(reqTimeout);
var out;
try {
out = {
body: JSON.parse(req.responseText),
responseText: req.responseText,
statusCode: req.status,
// XDomainRequest does not have any response headers
headers: req.getAllResponseHeaders && req.getAllResponseHeaders() || {}
};
} catch (e) {
out = new errors.UnparsableJSON({
more: req.responseText
});
}
if (out instanceof errors.UnparsableJSON) {
reject(out);
} else {
resolve(out);
}
}
function onError(event) {
if (timedOut) {
return;
}
clearTimeout(reqTimeout);
// error event is trigerred both with XDR/XHR on:
// - DNS error
// - unallowed cross domain request
reject(
new errors.Network({
more: event
})
);
}
function onTimeout() {
timedOut = true;
req.abort();
reject(new errors.RequestTimeout());
}
function onConnect() {
connected = true;
clearTimeout(reqTimeout);
reqTimeout = setTimeout(onTimeout, opts.timeouts.complete);
}
function onProgress() {
if (!connected) onConnect();
}
function onReadyStateChange() {
if (!connected && req.readyState > 1) onConnect();
}
});
};
AlgoliaSearchBrowser.prototype._request.fallback = function requestFallback(url, opts) {
url = inlineHeaders(url, opts.headers);
return new Promise(function wrapJsonpRequest(resolve, reject) {
jsonpRequest(url, opts, function jsonpRequestDone(err, content) {
if (err) {
reject(err);
return;
}
resolve(content);
});
});
};
AlgoliaSearchBrowser.prototype._promise = {
reject: function rejectPromise(val) {
return Promise.reject(val);
},
resolve: function resolvePromise(val) {
return Promise.resolve(val);
},
delay: function delayPromise(ms) {
return new Promise(function resolveOnTimeout(resolve/* , reject*/) {
setTimeout(resolve, ms);
});
}
};
return algoliasearch;
};
}).call(this,require(11))
},{"1":1,"11":11,"17":17,"18":18,"19":19,"21":21,"24":24,"29":29,"3":3,"31":31,"5":5,"6":6}],17:[function(require,module,exports){
'use strict';
module.exports = getDocumentProtocol;
function getDocumentProtocol() {
var protocol = window.document.location.protocol;
// when in `file:` mode (local html file), default to `http:`
if (protocol !== 'http:' && protocol !== 'https:') {
protocol = 'http:';
}
return protocol;
}
},{}],18:[function(require,module,exports){
'use strict';
module.exports = inlineHeaders;
var encode = require(12);
function inlineHeaders(url, headers) {
if (/\?/.test(url)) {
url += '&';
} else {
url += '?';
}
return url + encode(headers);
}
},{"12":12}],19:[function(require,module,exports){
'use strict';
module.exports = jsonpRequest;
var errors = require(24);
var JSONPCounter = 0;
function jsonpRequest(url, opts, cb) {
if (opts.method !== 'GET') {
cb(new Error('Method ' + opts.method + ' ' + url + ' is not supported by JSONP.'));
return;
}
opts.debug('JSONP: start');
var cbCalled = false;
var timedOut = false;
JSONPCounter += 1;
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
var cbName = 'algoliaJSONP_' + JSONPCounter;
var done = false;
window[cbName] = function(data) {
removeGlobals();
if (timedOut) {
opts.debug('JSONP: Late answer, ignoring');
return;
}
cbCalled = true;
clean();
cb(null, {
body: data/* ,
// We do not send the statusCode, there's no statusCode in JSONP, it will be
// computed using data.status && data.message like with XDR
statusCode*/
});
};
// add callback by hand
url += '&callback=' + cbName;
// add body params manually
if (opts.jsonBody && opts.jsonBody.params) {
url += '&' + opts.jsonBody.params;
}
var ontimeout = setTimeout(timeout, opts.timeouts.complete);
// script onreadystatechange needed only for
// <= IE8
// https://github.com/angular/angular.js/issues/4523
script.onreadystatechange = readystatechange;
script.onload = success;
script.onerror = error;
script.async = true;
script.defer = true;
script.src = url;
head.appendChild(script);
function success() {
opts.debug('JSONP: success');
if (done || timedOut) {
return;
}
done = true;
// script loaded but did not call the fn => script loading error
if (!cbCalled) {
opts.debug('JSONP: Fail. Script loaded but did not call the callback');
clean();
cb(new errors.JSONPScriptFail());
}
}
function readystatechange() {
if (this.readyState === 'loaded' || this.readyState === 'complete') {
success();
}
}
function clean() {
clearTimeout(ontimeout);
script.onload = null;
script.onreadystatechange = null;
script.onerror = null;
head.removeChild(script);
}
function removeGlobals() {
try {
delete window[cbName];
delete window[cbName + '_loaded'];
} catch (e) {
window[cbName] = window[cbName + '_loaded'] = undefined;
}
}
function timeout() {
opts.debug('JSONP: Script timeout');
timedOut = true;
clean();
cb(new errors.RequestTimeout());
}
function error() {
opts.debug('JSONP: Script error');
if (done || timedOut) {
return;
}
clean();
cb(new errors.JSONPScriptError());
}
}
},{"24":24}],20:[function(require,module,exports){
module.exports = buildSearchMethod;
var errors = require(24);
/**
* Creates a search method to be used in clients
* @param {string} queryParam the name of the attribute used for the query
* @param {string} url the url
* @return {function} the search method
*/
function buildSearchMethod(queryParam, url) {
/**
* The search method. Prepares the data and send the query to Algolia.
* @param {string} query the string used for query search
* @param {object} args additional parameters to send with the search
* @param {function} [callback] the callback to be called with the client gets the answer
* @return {undefined|Promise} If the callback is not provided then this methods returns a Promise
*/
return function search(query, args, callback) {
// warn V2 users on how to search
if (typeof query === 'function' && typeof args === 'object' ||
typeof callback === 'object') {
// .search(query, params, cb)
// .search(cb, params)
throw new errors.AlgoliaSearchError('index.search usage is index.search(query, params, cb)');
}
// Normalizing the function signature
if (arguments.length === 0 || typeof query === 'function') {
// Usage : .search(), .search(cb)
callback = query;
query = '';
} else if (arguments.length === 1 || typeof args === 'function') {
// Usage : .search(query/args), .search(query, cb)
callback = args;
args = undefined;
}
// At this point we have 3 arguments with values
// Usage : .search(args) // careful: typeof null === 'object'
if (typeof query === 'object' && query !== null) {
args = query;
query = undefined;
} else if (query === undefined || query === null) { // .search(undefined/null)
query = '';
}
var params = '';
if (query !== undefined) {
params += queryParam + '=' + encodeURIComponent(query);
}
var additionalUA;
if (args !== undefined) {
if (args.additionalUA) {
additionalUA = args.additionalUA;
delete args.additionalUA;
}
// `_getSearchParams` will augment params, do not be fooled by the = versus += from previous if
params = this.as._getSearchParams(args, params);
}
return this._search(params, url, callback, additionalUA);
};
}
},{"24":24}],21:[function(require,module,exports){
module.exports = function clone(obj) {
return JSON.parse(JSON.stringify(obj));
};
},{}],22:[function(require,module,exports){
module.exports = function deprecate(fn, message) {
var warned = false;
function deprecated() {
if (!warned) {
/* eslint no-console:0 */
console.log(message);
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
},{}],23:[function(require,module,exports){
module.exports = function deprecatedMessage(previousUsage, newUsage) {
var githubAnchorLink = previousUsage.toLowerCase()
.replace('.', '')
.replace('()', '');
return 'algoliasearch: `' + previousUsage + '` was replaced by `' + newUsage +
'`. Please see https://github.com/algolia/algoliasearch-client-js/wiki/Deprecated#' + githubAnchorLink;
};
},{}],24:[function(require,module,exports){
'use strict';
// This file hosts our error definitions
// We use custom error "types" so that we can act on them when we need it
// e.g.: if error instanceof errors.UnparsableJSON then..
var inherits = require(6);
function AlgoliaSearchError(message, extraProperties) {
var forEach = require(4);
var error = this;
// try to get a stacktrace
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
} else {
error.stack = (new Error()).stack || 'Cannot get a stacktrace, browser is too old';
}
this.name = 'AlgoliaSearchError';
this.message = message || 'Unknown error';
if (extraProperties) {
forEach(extraProperties, function addToErrorObject(value, key) {
error[key] = value;
});
}
}
inherits(AlgoliaSearchError, Error);
function createCustomError(name, message) {
function AlgoliaSearchCustomError() {
var args = Array.prototype.slice.call(arguments, 0);
// custom message not set, use default
if (typeof args[0] !== 'string') {
args.unshift(message);
}
AlgoliaSearchError.apply(this, args);
this.name = 'AlgoliaSearch' + name + 'Error';
}
inherits(AlgoliaSearchCustomError, AlgoliaSearchError);
return AlgoliaSearchCustomError;
}
// late exports to let various fn defs and inherits take place
module.exports = {
AlgoliaSearchError: AlgoliaSearchError,
UnparsableJSON: createCustomError(
'UnparsableJSON',
'Could not parse the incoming response as JSON, see err.more for details'
),
RequestTimeout: createCustomError(
'RequestTimeout',
'Request timedout before getting a response'
),
Network: createCustomError(
'Network',
'Network issue, see err.more for details'
),
JSONPScriptFail: createCustomError(
'JSONPScriptFail',
'<script> was loaded but did not call our provided callback'
),
JSONPScriptError: createCustomError(
'JSONPScriptError',
'<script> unable to load due to an `error` event on it'
),
Unknown: createCustomError(
'Unknown',
'Unknown error occured'
)
};
},{"4":4,"6":6}],25:[function(require,module,exports){
// Parse cloud does not supports setTimeout
// We do not store a setTimeout reference in the client everytime
// We only fallback to a fake setTimeout when not available
// setTimeout cannot be override globally sadly
module.exports = function exitPromise(fn, _setTimeout) {
_setTimeout(fn, 0);
};
},{}],26:[function(require,module,exports){
var foreach = require(4);
module.exports = function map(arr, fn) {
var newArr = [];
foreach(arr, function(item, itemIndex) {
newArr.push(fn(item, itemIndex, arr));
});
return newArr;
};
},{"4":4}],27:[function(require,module,exports){
var foreach = require(4);
module.exports = function merge(destination/* , sources */) {
var sources = Array.prototype.slice.call(arguments);
foreach(sources, function(source) {
for (var keyName in source) {
if (source.hasOwnProperty(keyName)) {
if (typeof destination[keyName] === 'object' && typeof source[keyName] === 'object') {
destination[keyName] = merge({}, destination[keyName], source[keyName]);
} else if (source[keyName] !== undefined) {
destination[keyName] = source[keyName];
}
}
}
});
return destination;
};
},{"4":4}],28:[function(require,module,exports){
module.exports = function omit(obj, test) {
var keys = require(9);
var foreach = require(4);
var filtered = {};
foreach(keys(obj), function doFilter(keyName) {
if (test(keyName) !== true) {
filtered[keyName] = obj[keyName];
}
});
return filtered;
};
},{"4":4,"9":9}],29:[function(require,module,exports){
module.exports = createPlacesClient;
var buildSearchMethod = require(20);
function createPlacesClient(algoliasearch) {
return function places(appID, apiKey, opts) {
var cloneDeep = require(21);
opts = opts && cloneDeep(opts) || {};
opts.hosts = opts.hosts || [
'places-dsn.algolia.net',
'places-1.algolianet.com',
'places-2.algolianet.com',
'places-3.algolianet.com'
];
// allow initPlaces() no arguments => community rate limited
if (arguments.length === 0 || typeof appID === 'object' || appID === undefined) {
appID = '';
apiKey = '';
opts._allowEmptyCredentials = true;
}
var client = algoliasearch(appID, apiKey, opts);
var index = client.initIndex('places');
index.search = buildSearchMethod('query', '/1/places/query');
return index;
};
}
},{"20":20,"21":21}],30:[function(require,module,exports){
(function (global){
var debug = require(1)('algoliasearch:src/hostIndexState.js');
var localStorageNamespace = 'algoliasearch-client-js';
var store;
var moduleStore = {
state: {},
set: function(key, data) {
this.state[key] = data;
return this.state[key];
},
get: function(key) {
return this.state[key] || null;
}
};
var localStorageStore = {
set: function(key, data) {
moduleStore.set(key, data); // always replicate localStorageStore to moduleStore in case of failure
try {
var namespace = JSON.parse(global.localStorage[localStorageNamespace]);
namespace[key] = data;
global.localStorage[localStorageNamespace] = JSON.stringify(namespace);
return namespace[key];
} catch (e) {
return localStorageFailure(key, e);
}
},
get: function(key) {
try {
return JSON.parse(global.localStorage[localStorageNamespace])[key] || null;
} catch (e) {
return localStorageFailure(key, e);
}
}
};
function localStorageFailure(key, e) {
debug('localStorage failed with', e);
cleanup();
store = moduleStore;
return store.get(key);
}
store = supportsLocalStorage() ? localStorageStore : moduleStore;
module.exports = {
get: getOrSet,
set: getOrSet,
supportsLocalStorage: supportsLocalStorage
};
function getOrSet(key, data) {
if (arguments.length === 1) {
return store.get(key);
}
return store.set(key, data);
}
function supportsLocalStorage() {
try {
if ('localStorage' in global &&
global.localStorage !== null) {
if (!global.localStorage[localStorageNamespace]) {
// actual creation of the namespace
global.localStorage.setItem(localStorageNamespace, JSON.stringify({}));
}
return true;
}
return false;
} catch (_) {
return false;
}
}
// In case of any error on localStorage, we clean our own namespace, this should handle
// quota errors when a lot of keys + data are used
function cleanup() {
try {
global.localStorage.removeItem(localStorageNamespace);
} catch (_) {
// nothing to do
}
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"1":1}],31:[function(require,module,exports){
'use strict';
module.exports = '3.22.1';
},{}]},{},[15])(15)
});
|
var isObjectLike = require('../internal/isObjectLike');
/** `Object#toString` result references. */
var errorTag = '[object Error]';
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
* `SyntaxError`, `TypeError`, or `URIError` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an error object, else `false`.
* @example
*
* _.isError(new Error);
* // => true
*
* _.isError(Error);
* // => false
*/
function isError(value) {
return isObjectLike(value) && typeof value.message == 'string' && objToString.call(value) == errorTag;
}
module.exports = isError;
|
loadIonicon('<svg width="1em" height="1em" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M368 175.2c0-19.5-1-81.7-19.3-115.6C344.2 51.4 336.2 48 317 48H195c-19.3 0-27.2 3.4-31.7 11.6-18.3 33.9-19.3 96.5-19.3 116 0 91 32 93.1 32 167.8 0 36.7-16 66.7-16 92.7 0 25.1 9 27.8 32 27.8h128c23 0 32-2.9 32-27.9 0-26-16-55.7-16-92.4 0-74.7 32-77.4 32-168.4zM177.4 67c.5-.9.7-1 2-1.5 2-.8 6.4-1.5 15.6-1.5h122c9.1 0 13.5.7 15.6 1.5 1.4.5 1.6.7 2.1 1.6 7.1 13.1 12.2 33.8 15 59.9H162.4c2.8-26.1 7.9-47 15-60zm157.4 379.6c-1.4.6-5.2 1.4-14.8 1.4H192c-9.6 0-13.4-.8-14.9-1.4-.4-.9-1.1-3.8-1.1-10.5 0-9.8 3-21.2 6.4-34.3 4.5-17 9.6-36.3 9.6-58.3 0-38.5-8.1-59.8-15.9-80.4-8.3-21.9-16.1-42.7-16.1-87.5 0-11.4.4-22.3 1-32.5h190c.7 10.2 1 21 1 32.2 0 44.8-7.8 65.7-16.2 87.8-7.8 20.7-15.8 42.1-15.8 80.6 0 22 5.1 41.2 9.6 58.1 3.5 13.1 6.4 24.5 6.4 34.3 0 6.7-.8 9.6-1.2 10.5z"/></svg>','ios-pint-outline');
|
/**
* Model for a books review.
*/
Ext.define('Books.model.Review', {
extend: 'Ext.data.Model',
requires: ['Ext.data.association.HasMany', 'Ext.data.association.BelongsTo'],
fields: [
'product_id',
'author',
'rating',
'date',
'title',
'comment'
],
belongsTo: {
model: 'Books.model.Book',
getterName: 'getBook',
setterName: 'setBook'
}
});
|
export default from './Drawer';
|
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["VueMaterial"] = factory();
else
root["VueMaterial"] = factory();
})(this, (function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 468);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ (function(module, exports) {
/* globals __VUE_SSR_CONTEXT__ */
// this module is a runtime utility for cleaner component module output and will
// be included in the final webpack user bundle
module.exports = function normalizeComponent (
rawScriptExports,
compiledTemplate,
injectStyles,
scopeId,
moduleIdentifier /* server only */
) {
var esModule
var scriptExports = rawScriptExports = rawScriptExports || {}
// ES6 modules interop
var type = typeof rawScriptExports.default
if (type === 'object' || type === 'function') {
esModule = rawScriptExports
scriptExports = rawScriptExports.default
}
// Vue.extend constructor export interop
var options = typeof scriptExports === 'function'
? scriptExports.options
: scriptExports
// render functions
if (compiledTemplate) {
options.render = compiledTemplate.render
options.staticRenderFns = compiledTemplate.staticRenderFns
}
// scopedId
if (scopeId) {
options._scopeId = scopeId
}
var hook
if (moduleIdentifier) { // server build
hook = function (context) {
// 2.3 injection
context =
context || // cached call
(this.$vnode && this.$vnode.ssrContext) || // stateful
(this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional
// 2.2 with runInNewContext: true
if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
context = __VUE_SSR_CONTEXT__
}
// inject component styles
if (injectStyles) {
injectStyles.call(this, context)
}
// register component module identifier for async chunk inferrence
if (context && context._registeredComponents) {
context._registeredComponents.add(moduleIdentifier)
}
}
// used by ssr in case component is cached and beforeCreate
// never gets called
options._ssrRegister = hook
} else if (injectStyles) {
hook = injectStyles
}
if (hook) {
var functional = options.functional
var existing = functional
? options.render
: options.beforeCreate
if (!functional) {
// inject component registration as beforeCreate hook
options.beforeCreate = existing
? [].concat(existing, hook)
: [hook]
} else {
// register for functioal component in vue file
options.render = function renderWithStyleInjection (h, context) {
hook.call(context)
return existing(h, context)
}
}
}
return {
esModule: esModule,
exports: scriptExports,
options: options
}
}
/***/ }),
/***/ 1:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
// Theme mixin
// Grab the closest ancestor component's `md-theme` attribute OR grab the
// `md-name` attribute from an `<md-theme>` component.
function getAncestorThemeName(component) {
if (!component) {
return null;
}
var name = component.mdTheme;
if (!name && component.$options._componentTag === 'md-theme') {
name = component.mdName;
}
return name || getAncestorThemeName(component.$parent);
}
exports.default = {
props: {
mdTheme: String
},
computed: {
mdEffectiveTheme: function mdEffectiveTheme() {
return getAncestorThemeName(this) || this.$material.currentTheme;
},
themeClass: function themeClass() {
return this.$material.prefix + this.mdEffectiveTheme;
}
},
watch: {
mdTheme: function mdTheme(value) {
this.$material.useTheme(value);
}
},
beforeMount: function beforeMount() {
var localTheme = this.mdTheme;
this.$material.useTheme(localTheme ? localTheme : 'default');
}
};
module.exports = exports['default'];
/***/ }),
/***/ 10:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var getClosestVueParent = function getClosestVueParent($parent, cssClass) {
if (!$parent || !$parent.$el) {
return false;
}
if ($parent._uid === 0) {
return false;
}
if ($parent.$el.classList.contains(cssClass)) {
return $parent;
}
return getClosestVueParent($parent.$parent, cssClass);
};
exports.default = getClosestVueParent;
module.exports = exports["default"];
/***/ }),
/***/ 101:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = install;
var _mdSelect = __webpack_require__(347);
var _mdSelect2 = _interopRequireDefault(_mdSelect);
var _mdOption = __webpack_require__(346);
var _mdOption2 = _interopRequireDefault(_mdOption);
var _mdSelect3 = __webpack_require__(284);
var _mdSelect4 = _interopRequireDefault(_mdSelect3);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function install(Vue) {
Vue.component('md-select', _mdSelect2.default);
Vue.component('md-option', _mdOption2.default);
Vue.material.styles.push(_mdSelect4.default);
}
module.exports = exports['default'];
/***/ }),
/***/ 11:
/***/ (function(module, exports, __webpack_require__) {
var dP = __webpack_require__(9)
, createDesc = __webpack_require__(17);
module.exports = __webpack_require__(3) ? function(object, key, value){
return dP.f(object, key, createDesc(1, value));
} : function(object, key, value){
object[key] = value;
return object;
};
/***/ }),
/***/ 13:
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(6);
module.exports = function(it){
if(!isObject(it))throw TypeError(it + ' is not an object!');
return it;
};
/***/ }),
/***/ 14:
/***/ (function(module, exports) {
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function(it){
if(it == undefined)throw TypeError("Can't call method on " + it);
return it;
};
/***/ }),
/***/ 15:
/***/ (function(module, exports) {
// 7.1.4 ToInteger
var ceil = Math.ceil
, floor = Math.floor;
module.exports = function(it){
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
/***/ }),
/***/ 16:
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(2)
, core = __webpack_require__(4)
, ctx = __webpack_require__(28)
, hide = __webpack_require__(11)
, PROTOTYPE = 'prototype';
var $export = function(type, name, source){
var IS_FORCED = type & $export.F
, IS_GLOBAL = type & $export.G
, IS_STATIC = type & $export.S
, IS_PROTO = type & $export.P
, IS_BIND = type & $export.B
, IS_WRAP = type & $export.W
, exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
, expProto = exports[PROTOTYPE]
, target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
, key, own, out;
if(IS_GLOBAL)source = name;
for(key in source){
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
if(own && key in exports)continue;
// export native or passed
out = own ? target[key] : source[key];
// prevent global pollution for namespaces
exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
// bind timers to global for call from export context
: IS_BIND && own ? ctx(out, global)
// wrap global constructors for prevent change them in library
: IS_WRAP && target[key] == out ? (function(C){
var F = function(a, b, c){
if(this instanceof C){
switch(arguments.length){
case 0: return new C;
case 1: return new C(a);
case 2: return new C(a, b);
} return new C(a, b, c);
} return C.apply(this, arguments);
};
F[PROTOTYPE] = C[PROTOTYPE];
return F;
// make static versions for prototype methods
})(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
if(IS_PROTO){
(exports.virtual || (exports.virtual = {}))[key] = out;
// export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out);
}
}
};
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
/***/ }),
/***/ 17:
/***/ (function(module, exports) {
module.exports = function(bitmap, value){
return {
enumerable : !(bitmap & 1),
configurable: !(bitmap & 2),
writable : !(bitmap & 4),
value : value
};
};
/***/ }),
/***/ 176:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _getClosestVueParent = __webpack_require__(10);
var _getClosestVueParent2 = _interopRequireDefault(_getClosestVueParent);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = {
name: 'md-option',
props: {
value: [String, Boolean, Number, Object]
},
data: function data() {
return {
parentSelect: {},
check: false,
index: 0
};
},
computed: {
isSelected: function isSelected() {
if (this.value && this.parentSelect.value) {
var thisValue = this.value.toString();
if (this.parentSelect.multiple) {
return this.parentSelect.value.indexOf(thisValue) >= 0;
}
return this.value && this.parentSelect.value && thisValue === this.parentSelect.value.toString();
}
return false;
},
classes: function classes() {
return {
'md-selected': this.isSelected,
'md-checked': this.check
};
}
},
methods: {
isMultiple: function isMultiple() {
return this.parentSelect.multiple;
},
setParentOption: function setParentOption() {
if (!this.isMultiple()) {
this.parentSelect.selectOption(this.value, this.$refs.item.textContent, this.$el);
} else {
this.check = !this.check;
}
},
selectOption: function selectOption($event) {
if (this.disabled) {
return;
}
this.setParentOption();
this.$emit('selected', $event);
}
},
watch: {
isSelected: function isSelected(selected) {
if (this.isMultiple()) {
this.check = selected;
}
},
check: function check(_check) {
if (_check) {
this.parentSelect.selectMultiple(this.index, this.value, this.$refs.item.textContent);
} else {
this.parentSelect.selectMultiple(this.index);
}
}
},
mounted: function mounted() {
this.parentSelect = (0, _getClosestVueParent2.default)(this.$parent, 'md-select');
this.parentContent = (0, _getClosestVueParent2.default)(this.$parent, 'md-menu-content');
if (!this.parentSelect) {
throw new Error('You must wrap the md-option in a md-select');
}
this.parentSelect.optionsAmount++;
this.index = this.parentSelect.optionsAmount;
this.parentSelect.multipleOptions[this.index] = {};
this.parentSelect.options[this.index] = this;
if (this.isMultiple() && this.parentSelect.value.indexOf(this.value) >= 0 || this.parentSelect.value === this.value) {
this.setParentOption();
}
},
beforeDestroy: function beforeDestroy() {
if (this.parentSelect) {
delete this.parentSelect.options[this.index];
delete this.parentSelect.multipleOptions[this.index];
}
}
}; //
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
module.exports = exports['default'];
/***/ }),
/***/ 177:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _keys = __webpack_require__(38);
var _keys2 = _interopRequireDefault(_keys);
var _mixin = __webpack_require__(1);
var _mixin2 = _interopRequireDefault(_mixin);
var _getClosestVueParent = __webpack_require__(10);
var _getClosestVueParent2 = _interopRequireDefault(_getClosestVueParent);
var _isArray = __webpack_require__(66);
var _isArray2 = _interopRequireDefault(_isArray);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = {
name: 'md-select',
props: {
name: String,
id: String,
required: Boolean,
multiple: Boolean,
value: [String, Number, Array],
disabled: Boolean,
placeholder: String,
mdMenuClass: String,
mdMenuOptions: Object
},
mixins: [_mixin2.default],
data: function data() {
return {
lastSelected: null,
selectedValue: null,
selectedText: null,
multipleOptions: {},
options: {},
optionsAmount: 0
};
},
computed: {
classes: function classes() {
return {
'md-disabled': this.disabled,
'md-select-icon': this.hasIcon
};
},
contentClasses: function contentClasses() {
if (this.multiple) {
return 'md-multiple ' + this.mdMenuClass;
}
return this.mdMenuClass;
},
hasIcon: function hasIcon() {
return this.$slots['icon'];
},
valueStyle: function valueStyle() {
return this.hasIcon ? {
display: 'none'
} : {};
}
},
watch: {
value: function value(_value) {
this.setTextAndValue(_value);
if (this.multiple) {
this.selectOptions(_value);
}
},
disabled: function disabled() {
this.setParentDisabled();
},
required: function required() {
this.setParentRequired();
},
placeholder: function placeholder() {
this.setParentPlaceholder();
}
},
methods: {
onOpen: function onOpen() {
if (this.lastSelected) {
this.lastSelected.scrollIntoViewIfNeeded(true);
}
this.$emit('opened');
},
setParentDisabled: function setParentDisabled() {
this.parentContainer.isDisabled = this.disabled;
},
setParentRequired: function setParentRequired() {
this.parentContainer.isRequired = this.required;
},
setParentPlaceholder: function setParentPlaceholder() {
this.parentContainer.hasPlaceholder = !!this.placeholder;
},
selectOptions: function selectOptions(modelValue) {
var _this = this;
var optionsArray = (0, _keys2.default)(this.options).map((function (el) {
return _this.options[el];
}));
if (optionsArray && optionsArray.length) {
optionsArray.filter((function (el) {
return modelValue.indexOf(el.value) !== -1;
})).forEach((function (el) {
el.check = true;
}));
}
},
getSingleValue: function getSingleValue(value) {
var _this2 = this;
var output = {};
(0, _keys2.default)(this.options).forEach((function (index) {
var options = _this2.options[index];
if (options.value === value) {
output.value = value;
output.text = options.$refs.item.textContent, output.el = options.$refs.item;
}
}));
return output;
},
getMultipleValue: function getMultipleValue(modelValue) {
var _this3 = this;
if ((0, _isArray2.default)(this.value)) {
var outputText = [];
modelValue.forEach((function (value) {
(0, _keys2.default)(_this3.options).forEach((function (index) {
var options = _this3.options[index];
if (options.value === value) {
var text = options.$refs.item.textContent;
_this3.multipleOptions[index] = {
value: value,
text: text
};
outputText.push(text);
}
}));
}));
return {
value: modelValue,
text: outputText.join(', ')
};
}
return {};
},
setTextAndValue: function setTextAndValue(modelValue) {
var output = this.multiple ? this.getMultipleValue(modelValue) : this.getSingleValue(modelValue);
this.selectedValue = output.value;
this.selectedText = output.text;
this.lastSelected = output.el;
if (this.parentContainer) {
this.parentContainer.setValue(this.selectedText);
}
},
changeValue: function changeValue(value) {
this.$emit('input', value);
this.$emit('change', value);
this.$emit('selected', value);
},
selectMultiple: function selectMultiple(index, value, text) {
var values = [];
this.multipleOptions[index] = {
value: value,
text: text
};
for (var key in this.multipleOptions) {
if (this.multipleOptions.hasOwnProperty(key) && this.multipleOptions[key].value) {
values.push(this.multipleOptions[key].value);
}
}
this.changeValue(values);
},
selectOption: function selectOption(value, text, el) {
this.lastSelected = el;
this.selectedText = text;
this.setTextAndValue(value);
this.changeValue(value);
}
},
mounted: function mounted() {
this.parentContainer = (0, _getClosestVueParent2.default)(this.$parent, 'md-input-container');
if (this.parentContainer) {
this.setParentDisabled();
this.setParentRequired();
this.setParentPlaceholder();
this.parentContainer.hasSelect = true;
}
this.setTextAndValue(this.value);
},
beforeDestroy: function beforeDestroy() {
if (this.parentContainer) {
this.parentContainer.setValue('');
this.parentContainer.hasSelect = false;
}
}
}; //
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
module.exports = exports['default'];
/***/ }),
/***/ 18:
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = __webpack_require__(31)
, enumBugKeys = __webpack_require__(21);
module.exports = Object.keys || function keys(O){
return $keys(O, enumBugKeys);
};
/***/ }),
/***/ 19:
/***/ (function(module, exports, __webpack_require__) {
var shared = __webpack_require__(22)('keys')
, uid = __webpack_require__(20);
module.exports = function(key){
return shared[key] || (shared[key] = uid(key));
};
/***/ }),
/***/ 2:
/***/ (function(module, exports) {
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
/***/ }),
/***/ 20:
/***/ (function(module, exports) {
var id = 0
, px = Math.random();
module.exports = function(key){
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
/***/ }),
/***/ 21:
/***/ (function(module, exports) {
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
/***/ }),
/***/ 22:
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(2)
, SHARED = '__core-js_shared__'
, store = global[SHARED] || (global[SHARED] = {});
module.exports = function(key){
return store[key] || (store[key] = {});
};
/***/ }),
/***/ 23:
/***/ (function(module, exports, __webpack_require__) {
// 7.1.13 ToObject(argument)
var defined = __webpack_require__(14);
module.exports = function(it){
return Object(defined(it));
};
/***/ }),
/***/ 24:
/***/ (function(module, exports) {
var toString = {}.toString;
module.exports = function(it){
return toString.call(it).slice(8, -1);
};
/***/ }),
/***/ 25:
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(6)
, document = __webpack_require__(2).document
// in old IE typeof document.createElement is 'object'
, is = isObject(document) && isObject(document.createElement);
module.exports = function(it){
return is ? document.createElement(it) : {};
};
/***/ }),
/***/ 258:
/***/ (function(module, exports) {
// removed by extract-text-webpack-plugin
/***/ }),
/***/ 26:
/***/ (function(module, exports, __webpack_require__) {
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = __webpack_require__(24);
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){
return cof(it) == 'String' ? it.split('') : Object(it);
};
/***/ }),
/***/ 27:
/***/ (function(module, exports, __webpack_require__) {
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = __webpack_require__(6);
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function(it, S){
if(!isObject(it))return it;
var fn, val;
if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val;
if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
throw TypeError("Can't convert object to primitive value");
};
/***/ }),
/***/ 28:
/***/ (function(module, exports, __webpack_require__) {
// optional / simple context binding
var aFunction = __webpack_require__(33);
module.exports = function(fn, that, length){
aFunction(fn);
if(that === undefined)return fn;
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
case 2: return function(a, b){
return fn.call(that, a, b);
};
case 3: return function(a, b, c){
return fn.call(that, a, b, c);
};
}
return function(/* ...args */){
return fn.apply(that, arguments);
};
};
/***/ }),
/***/ 284:
/***/ (function(module, exports) {
module.exports = ".THEME_NAME.md-select:after {\n color: BACKGROUND-CONTRAST-0.54; }\n\n.THEME_NAME.md-select:after {\n color: BACKGROUND-CONTRAST-0.38; }\n\n.THEME_NAME.md-select-content .md-menu-item.md-selected, .THEME_NAME.md-select-content .md-menu-item.md-checked {\n color: PRIMARY-COLOR; }\n"
/***/ }),
/***/ 29:
/***/ (function(module, exports, __webpack_require__) {
// 7.1.15 ToLength
var toInteger = __webpack_require__(15)
, min = Math.min;
module.exports = function(it){
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
/***/ }),
/***/ 3:
/***/ (function(module, exports, __webpack_require__) {
// Thank's IE8 for his funny defineProperty
module.exports = !__webpack_require__(5)((function(){
return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
}));
/***/ }),
/***/ 30:
/***/ (function(module, exports, __webpack_require__) {
module.exports = !__webpack_require__(3) && !__webpack_require__(5)((function(){
return Object.defineProperty(__webpack_require__(25)('div'), 'a', {get: function(){ return 7; }}).a != 7;
}));
/***/ }),
/***/ 31:
/***/ (function(module, exports, __webpack_require__) {
var has = __webpack_require__(8)
, toIObject = __webpack_require__(7)
, arrayIndexOf = __webpack_require__(34)(false)
, IE_PROTO = __webpack_require__(19)('IE_PROTO');
module.exports = function(object, names){
var O = toIObject(object)
, i = 0
, result = []
, key;
for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while(names.length > i)if(has(O, key = names[i++])){
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
/***/ }),
/***/ 33:
/***/ (function(module, exports) {
module.exports = function(it){
if(typeof it != 'function')throw TypeError(it + ' is not a function!');
return it;
};
/***/ }),
/***/ 34:
/***/ (function(module, exports, __webpack_require__) {
// false -> Array#indexOf
// true -> Array#includes
var toIObject = __webpack_require__(7)
, toLength = __webpack_require__(29)
, toIndex = __webpack_require__(35);
module.exports = function(IS_INCLUDES){
return function($this, el, fromIndex){
var O = toIObject($this)
, length = toLength(O.length)
, index = toIndex(fromIndex, length)
, value;
// Array#includes uses SameValueZero equality algorithm
if(IS_INCLUDES && el != el)while(length > index){
value = O[index++];
if(value != value)return true;
// Array#toIndex ignores holes, Array#includes - not
} else for(;length > index; index++)if(IS_INCLUDES || index in O){
if(O[index] === el)return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
/***/ }),
/***/ 346:
/***/ (function(module, exports, __webpack_require__) {
var disposed = false
var Component = __webpack_require__(0)(
/* script */
__webpack_require__(176),
/* template */
__webpack_require__(423),
/* styles */
null,
/* scopeId */
null,
/* moduleIdentifier (server only) */
null
)
Component.options.__file = "/Users/pablohpsilva/Code/vue-material/src/components/mdSelect/mdOption.vue"
if (Component.esModule && Object.keys(Component.esModule).some((function (key) {return key !== "default" && key.substr(0, 2) !== "__"}))) {console.error("named exports are not supported in *.vue files.")}
if (Component.options.functional) {console.error("[vue-loader] mdOption.vue: functional components are not supported with templates, they should use render functions.")}
/* hot reload */
if (false) {(function () {
var hotAPI = require("vue-hot-reload-api")
hotAPI.install(require("vue"), false)
if (!hotAPI.compatible) return
module.hot.accept()
if (!module.hot.data) {
hotAPI.createRecord("data-v-6189afdd", Component.options)
} else {
hotAPI.reload("data-v-6189afdd", Component.options)
}
module.hot.dispose((function (data) {
disposed = true
}))
})()}
module.exports = Component.exports
/***/ }),
/***/ 347:
/***/ (function(module, exports, __webpack_require__) {
var disposed = false
function injectStyle (ssrContext) {
if (disposed) return
__webpack_require__(258)
}
var Component = __webpack_require__(0)(
/* script */
__webpack_require__(177),
/* template */
__webpack_require__(437),
/* styles */
injectStyle,
/* scopeId */
null,
/* moduleIdentifier (server only) */
null
)
Component.options.__file = "/Users/pablohpsilva/Code/vue-material/src/components/mdSelect/mdSelect.vue"
if (Component.esModule && Object.keys(Component.esModule).some((function (key) {return key !== "default" && key.substr(0, 2) !== "__"}))) {console.error("named exports are not supported in *.vue files.")}
if (Component.options.functional) {console.error("[vue-loader] mdSelect.vue: functional components are not supported with templates, they should use render functions.")}
/* hot reload */
if (false) {(function () {
var hotAPI = require("vue-hot-reload-api")
hotAPI.install(require("vue"), false)
if (!hotAPI.compatible) return
module.hot.accept()
if (!module.hot.data) {
hotAPI.createRecord("data-v-a6127e38", Component.options)
} else {
hotAPI.reload("data-v-a6127e38", Component.options)
}
module.hot.dispose((function (data) {
disposed = true
}))
})()}
module.exports = Component.exports
/***/ }),
/***/ 35:
/***/ (function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(15)
, max = Math.max
, min = Math.min;
module.exports = function(index, length){
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
/***/ }),
/***/ 38:
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(43), __esModule: true };
/***/ }),
/***/ 4:
/***/ (function(module, exports) {
var core = module.exports = {version: '2.4.0'};
if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
/***/ }),
/***/ 423:
/***/ (function(module, exports, __webpack_require__) {
module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _c('md-menu-item', {
staticClass: "md-option",
class: _vm.classes,
attrs: {
"tabindex": "-1"
},
on: {
"click": _vm.selectOption
}
}, [(_vm.parentSelect.multiple) ? _c('md-checkbox', {
staticClass: "md-primary",
model: {
value: (_vm.check),
callback: function($$v) {
_vm.check = $$v
},
expression: "check"
}
}, [_c('span', {
ref: "item"
}, [_vm._t("default")], 2)]) : _c('span', {
ref: "item"
}, [_vm._t("default")], 2)], 1)
},staticRenderFns: []}
module.exports.render._withStripped = true
if (false) {
module.hot.accept()
if (module.hot.data) {
require("vue-hot-reload-api").rerender("data-v-6189afdd", module.exports)
}
}
/***/ }),
/***/ 43:
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(48);
module.exports = __webpack_require__(4).Object.keys;
/***/ }),
/***/ 437:
/***/ (function(module, exports, __webpack_require__) {
module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _c('div', {
staticClass: "md-select",
class: [_vm.themeClass, _vm.classes]
}, [_c('md-menu', _vm._b({
attrs: {
"md-close-on-select": !_vm.multiple
},
on: {
"opened": function($event) {
_vm.$emit('open')
},
"closed": function($event) {
_vm.$emit('close')
}
}
}, 'md-menu', _vm.mdMenuOptions), [_vm._t("icon"), _vm._v(" "), _c('span', {
ref: "value",
staticClass: "md-select-value",
style: (_vm.valueStyle),
attrs: {
"md-menu-trigger": ""
}
}, [_vm._v(_vm._s(_vm.selectedText || _vm.placeholder))]), _vm._v(" "), _c('md-menu-content', {
staticClass: "md-select-content",
class: [_vm.themeClass, _vm.contentClasses]
}, [_vm._t("default")], 2)], 2), _vm._v(" "), _c('select', {
attrs: {
"name": _vm.name,
"id": _vm.id,
"required": _vm.required,
"disabled": _vm.disabled,
"tabindex": "-1"
}
}, [(!_vm.multiple) ? _c('option', {
attrs: {
"selected": "true"
},
domProps: {
"value": _vm.selectedValue
}
}, [_vm._v(_vm._s(_vm.selectedText))]) : _vm._e(), _vm._v(" "), _vm._l((_vm.multipleOptions), (function(option) {
return (option.value) ? _c('option', {
attrs: {
"selected": "true"
},
domProps: {
"value": option.value
}
}, [_vm._v(_vm._s(option.text))]) : _vm._e()
}))], 2)], 1)
},staticRenderFns: []}
module.exports.render._withStripped = true
if (false) {
module.hot.accept()
if (module.hot.data) {
require("vue-hot-reload-api").rerender("data-v-a6127e38", module.exports)
}
}
/***/ }),
/***/ 46:
/***/ (function(module, exports, __webpack_require__) {
// most Object methods by ES6 should accept primitives
var $export = __webpack_require__(16)
, core = __webpack_require__(4)
, fails = __webpack_require__(5);
module.exports = function(KEY, exec){
var fn = (core.Object || {})[KEY] || Object[KEY]
, exp = {};
exp[KEY] = exec(fn);
$export($export.S + $export.F * fails((function(){ fn(1); })), 'Object', exp);
};
/***/ }),
/***/ 468:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(101);
/***/ }),
/***/ 48:
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.14 Object.keys(O)
var toObject = __webpack_require__(23)
, $keys = __webpack_require__(18);
__webpack_require__(46)('keys', (function(){
return function keys(it){
return $keys(toObject(it));
};
}));
/***/ }),
/***/ 5:
/***/ (function(module, exports) {
module.exports = function(exec){
try {
return !!exec();
} catch(e){
return true;
}
};
/***/ }),
/***/ 6:
/***/ (function(module, exports) {
module.exports = function(it){
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
/***/ }),
/***/ 66:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var isArray = function isArray(value) {
return value && value.constructor === Array;
};
exports.default = isArray;
module.exports = exports["default"];
/***/ }),
/***/ 7:
/***/ (function(module, exports, __webpack_require__) {
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = __webpack_require__(26)
, defined = __webpack_require__(14);
module.exports = function(it){
return IObject(defined(it));
};
/***/ }),
/***/ 8:
/***/ (function(module, exports) {
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function(it, key){
return hasOwnProperty.call(it, key);
};
/***/ }),
/***/ 9:
/***/ (function(module, exports, __webpack_require__) {
var anObject = __webpack_require__(13)
, IE8_DOM_DEFINE = __webpack_require__(30)
, toPrimitive = __webpack_require__(27)
, dP = Object.defineProperty;
exports.f = __webpack_require__(3) ? Object.defineProperty : function defineProperty(O, P, Attributes){
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if(IE8_DOM_DEFINE)try {
return dP(O, P, Attributes);
} catch(e){ /* empty */ }
if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
if('value' in Attributes)O[P] = Attributes.value;
return O;
};
/***/ })
/******/ });
}));
|
;(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.squel = factory();
}
}(this, function() {
'use strict';
var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
// append to string if non-empty
function _pad(str, pad) {
return str.length ? str + pad : str;
}
// Extend given object's with other objects' properties, overriding existing ones if necessary
function _extend(dst) {
for (var _len = arguments.length, sources = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
sources[_key - 1] = arguments[_key];
}
if (dst && sources) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
var _loop = function _loop() {
var src = _step.value;
if ((typeof src === 'undefined' ? 'undefined' : _typeof(src)) === 'object') {
Object.getOwnPropertyNames(src).forEach(function (key) {
dst[key] = src[key];
});
}
};
for (var _iterator = sources[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
_loop();
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
return dst;
};
// get whether object is a plain object
function _isPlainObject(obj) {
return obj && obj.constructor.prototype === Object.prototype;
};
// get whether object is an array
function _isArray(obj) {
return obj && obj.constructor.prototype === Array.prototype;
};
// get class name of given object
function _getObjectClassName(obj) {
if (obj && obj.constructor && obj.constructor.toString) {
var arr = obj.constructor.toString().match(/function\s*(\w+)/);
if (arr && 2 === arr.length) {
return arr[1];
}
}
}
// clone given item
function _clone(src) {
if (!src) {
return src;
}
if (typeof src.clone === 'function') {
return src.clone();
} else if (_isPlainObject(src) || _isArray(src)) {
var _ret2 = function () {
var ret = new src.constructor();
Object.getOwnPropertyNames(src).forEach(function (key) {
if (typeof src[key] !== 'function') {
ret[key] = _clone(src[key]);
}
});
return {
v: ret
};
}();
if ((typeof _ret2 === 'undefined' ? 'undefined' : _typeof(_ret2)) === "object") return _ret2.v;
} else {
return JSON.parse(JSON.stringify(src));
}
};
/**
* Register a value type handler
*
* Note: this will override any existing handler registered for this value type.
*/
function _registerValueHandler(handlers, type, handler) {
var typeofType = typeof type === 'undefined' ? 'undefined' : _typeof(type);
if (typeofType !== 'function' && typeofType !== 'string') {
throw new Error("type must be a class constructor or string");
}
if (typeof handler !== 'function') {
throw new Error("handler must be a function");
}
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = handlers[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var typeHandler = _step2.value;
if (typeHandler.type === type) {
typeHandler.handler = handler;
return;
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
handlers.push({
type: type,
handler: handler
});
};
/**
* Get value type handler for given type
*/
function getValueHandler(value) {
for (var _len2 = arguments.length, handlerLists = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
handlerLists[_key2 - 1] = arguments[_key2];
}
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
try {
for (var _iterator3 = handlerLists[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var handlers = _step3.value;
var _iteratorNormalCompletion4 = true;
var _didIteratorError4 = false;
var _iteratorError4 = undefined;
try {
for (var _iterator4 = handlers[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
var typeHandler = _step4.value;
// if type is a string then use `typeof` or else use `instanceof`
if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === typeHandler.type || typeof typeHandler.type !== 'string' && value instanceof typeHandler.type) {
return typeHandler.handler;
}
}
} catch (err) {
_didIteratorError4 = true;
_iteratorError4 = err;
} finally {
try {
if (!_iteratorNormalCompletion4 && _iterator4.return) {
_iterator4.return();
}
} finally {
if (_didIteratorError4) {
throw _iteratorError4;
}
}
}
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
};
/**
* Build base squel classes and methods
*/
function _buildSquel() {
var flavour = arguments.length <= 0 || arguments[0] === undefined ? null : arguments[0];
var cls = {
_getObjectClassName: _getObjectClassName
};
// default query builder options
cls.DefaultQueryBuilderOptions = {
// If true then table names will be rendered inside quotes. The quote character used is configurable via the nameQuoteCharacter option.
autoQuoteTableNames: false,
// If true then field names will rendered inside quotes. The quote character used is configurable via the nameQuoteCharacter option.
autoQuoteFieldNames: false,
// If true then alias names will rendered inside quotes. The quote character used is configurable via the `tableAliasQuoteCharacter` and `fieldAliasQuoteCharacter` options.
autoQuoteAliasNames: true,
// If true then table alias names will rendered after AS keyword.
useAsForTableAliasNames: false,
// The quote character used for when quoting table and field names
nameQuoteCharacter: '`',
// The quote character used for when quoting table alias names
tableAliasQuoteCharacter: '`',
// The quote character used for when quoting table alias names
fieldAliasQuoteCharacter: '"',
// Custom value handlers where key is the value type and the value is the handler function
valueHandlers: [],
// Character used to represent a parameter value
parameterCharacter: '?',
// Numbered parameters returned from toParam() as $1, $2, etc.
numberedParameters: false,
// Numbered parameters prefix character(s)
numberedParametersPrefix: '$',
// Numbered parameters start at this number.
numberedParametersStartAt: 1,
// If true then replaces all single quotes within strings. The replacement string used is configurable via the `singleQuoteReplacement` option.
replaceSingleQuotes: false,
// The string to replace single quotes with in query strings
singleQuoteReplacement: '\'\'',
// String used to join individual blocks in a query when it's stringified
separator: ' ',
// Function for formatting string values prior to insertion into query string
stringFormatter: null
};
// Global custom value handlers for all instances of builder
cls.globalValueHandlers = [];
/*
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Custom value types
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
*/
// Register a new value handler
cls.registerValueHandler = function (type, handler) {
_registerValueHandler(cls.globalValueHandlers, type, handler);
};
/*
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Base classes
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
*/
// Base class for cloneable builders
cls.Cloneable = function () {
function _class() {
_classCallCheck(this, _class);
}
_createClass(_class, [{
key: 'clone',
/**
* Clone this builder
*/
value: function clone() {
var newInstance = new this.constructor();
return _extend(newInstance, _clone(_extend({}, this)));
}
}]);
return _class;
}();
// Base class for all builders
cls.BaseBuilder = function (_cls$Cloneable) {
_inherits(_class2, _cls$Cloneable);
/**
* Constructor.
* this.param {Object} options Overriding one or more of `cls.DefaultQueryBuilderOptions`.
*/
function _class2(options) {
_classCallCheck(this, _class2);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(_class2).call(this));
var defaults = JSON.parse(JSON.stringify(cls.DefaultQueryBuilderOptions));
_this.options = _extend({}, defaults, options);
return _this;
}
/**
* Register a custom value handler for this builder instance.
*
* Note: this will override any globally registered handler for this value type.
*/
_createClass(_class2, [{
key: 'registerValueHandler',
value: function registerValueHandler(type, handler) {
_registerValueHandler(this.options.valueHandlers, type, handler);
return this;
}
/**
* Sanitize given expression.
*/
}, {
key: '_sanitizeExpression',
value: function _sanitizeExpression(expr) {
// If it's not a base builder instance
if (!(expr instanceof cls.BaseBuilder)) {
// It must then be a string
if (typeof expr !== "string") {
throw new Error("expression must be a string or builder instance");
}
}
return expr;
}
/**
* Sanitize the given name.
*
* The 'type' parameter is used to construct a meaningful error message in case validation fails.
*/
}, {
key: '_sanitizeName',
value: function _sanitizeName(value, type) {
if (typeof value !== "string") {
throw new Error(type + ' must be a string');
}
return value;
}
}, {
key: '_sanitizeField',
value: function _sanitizeField(item) {
if (!(item instanceof cls.BaseBuilder)) {
item = this._sanitizeName(item, "field name");
}
return item;
}
}, {
key: '_sanitizeBaseBuilder',
value: function _sanitizeBaseBuilder(item) {
if (item instanceof cls.BaseBuilder) {
return item;
}
throw new Error("must be a builder instance");
}
}, {
key: '_sanitizeTable',
value: function _sanitizeTable(item) {
if (typeof item !== "string") {
try {
item = this._sanitizeBaseBuilder(item);
} catch (e) {
throw new Error("table name must be a string or a builder");
}
} else {
item = this._sanitizeName(item, 'table');
}
return item;
}
}, {
key: '_sanitizeTableAlias',
value: function _sanitizeTableAlias(item) {
return this._sanitizeName(item, "table alias");
}
}, {
key: '_sanitizeFieldAlias',
value: function _sanitizeFieldAlias(item) {
return this._sanitizeName(item, "field alias");
}
// Sanitize the given limit/offset value.
}, {
key: '_sanitizeLimitOffset',
value: function _sanitizeLimitOffset(value) {
value = parseInt(value);
if (0 > value || isNaN(value)) {
throw new Error("limit/offset must be >= 0");
}
return value;
}
// Santize the given field value
}, {
key: '_sanitizeValue',
value: function _sanitizeValue(item) {
var itemType = typeof item === 'undefined' ? 'undefined' : _typeof(item);
if (null === item) {
// null is allowed
} else if ("string" === itemType || "number" === itemType || "boolean" === itemType) {
// primitives are allowed
} else if (item instanceof cls.BaseBuilder) {
// Builders allowed
} else {
var typeIsValid = !!getValueHandler(item, this.options.valueHandlers, cls.globalValueHandlers);
if (!typeIsValid) {
throw new Error("field value must be a string, number, boolean, null or one of the registered custom value types");
}
}
return item;
}
// Escape a string value, e.g. escape quotes and other characters within it.
}, {
key: '_escapeValue',
value: function _escapeValue(value) {
return !this.options.replaceSingleQuotes ? value : value.replace(/\'/g, this.options.singleQuoteReplacement);
}
}, {
key: '_formatTableName',
value: function _formatTableName(item) {
if (this.options.autoQuoteTableNames) {
var quoteChar = this.options.nameQuoteCharacter;
item = '' + quoteChar + item + quoteChar;
}
return item;
}
}, {
key: '_formatFieldAlias',
value: function _formatFieldAlias(item) {
if (this.options.autoQuoteAliasNames) {
var quoteChar = this.options.fieldAliasQuoteCharacter;
item = '' + quoteChar + item + quoteChar;
}
return item;
}
}, {
key: '_formatTableAlias',
value: function _formatTableAlias(item) {
if (this.options.autoQuoteAliasNames) {
var quoteChar = this.options.tableAliasQuoteCharacter;
item = '' + quoteChar + item + quoteChar;
}
return this.options.useAsForTableAliasNames ? 'AS ' + item : item;
}
}, {
key: '_formatFieldName',
value: function _formatFieldName(item) {
var _this2 = this;
var formattingOptions = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
if (this.options.autoQuoteFieldNames) {
(function () {
var quoteChar = _this2.options.nameQuoteCharacter;
if (formattingOptions.ignorePeriodsForFieldNameQuotes) {
// a.b.c -> `a.b.c`
item = '' + quoteChar + item + quoteChar;
} else {
// a.b.c -> `a`.`b`.`c`
item = item.split('.').map(function (v) {
// treat '*' as special case (#79)
return '*' === v ? v : '' + quoteChar + v + quoteChar;
}).join('.');
}
})();
}
return item;
}
// Format the given custom value
}, {
key: '_formatCustomValue',
value: function _formatCustomValue(value) {
var asParam = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
// user defined custom handlers takes precedence
var customHandler = getValueHandler(value, this.options.valueHandlers, cls.globalValueHandlers);
// use the custom handler if available
if (customHandler) {
value = customHandler(value, asParam);
}
return {
formatted: !!customHandler,
value: value
};
}
/**
* Format given value for inclusion into parameter values array.
*/
}, {
key: '_formatValueForParamArray',
value: function _formatValueForParamArray(value) {
var _this3 = this;
if (_isArray(value)) {
return value.map(function (v) {
return _this3._formatValueForParamArray(v);
});
} else {
return this._formatCustomValue(value, true).value;
}
}
/**
* Format the given field value for inclusion into the query string
*/
}, {
key: '_formatValueForQueryString',
value: function _formatValueForQueryString(initialValue) {
var _this4 = this;
var formattingOptions = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var _formatCustomValue2 = this._formatCustomValue(initialValue);
var formatted = _formatCustomValue2.formatted;
var value = _formatCustomValue2.value;
// if formatting took place then return it directly
if (formatted) {
return this._applyNestingFormatting(value);
}
// if it's an array then format each element separately
if (_isArray(value)) {
value = value.map(function (v) {
return _this4._formatValueForQueryString(v);
});
value = this._applyNestingFormatting(value.join(', '));
} else {
var typeofValue = typeof value === 'undefined' ? 'undefined' : _typeof(value);
if (null === value) {
value = "NULL";
} else if (typeofValue === "boolean") {
value = value ? "TRUE" : "FALSE";
} else if (value instanceof cls.BaseBuilder) {
value = this._applyNestingFormatting(value.toString());
} else if (typeofValue !== "number") {
// if it's a string and we have custom string formatting turned on then use that
if ('string' === typeofValue && this.options.stringFormatter) {
return this.options.stringFormatter(value);
}
if (formattingOptions.dontQuote) {
value = '' + value;
} else {
var escapedValue = this._escapeValue(value);
value = '\'' + escapedValue + '\'';
}
}
}
return value;
}
}, {
key: '_applyNestingFormatting',
value: function _applyNestingFormatting(str) {
var nesting = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1];
if (str && typeof str === 'string' && nesting) {
// don't want to apply twice
if ('(' !== str.charAt(0) || ')' !== str.charAt(str.length - 1)) {
return '(' + str + ')';
}
}
return str;
}
/**
* Build given string and its corresponding parameter values into
* output.
*
* @param {String} str
* @param {Array} values
* @param {Object} [options] Additional options.
* @param {Boolean} [options.buildParameterized] Whether to build paramterized string. Default is false.
* @param {Boolean} [options.nested] Whether this expression is nested within another.
* @param {Boolean} [options.formattingOptions] Formatting options for values in query string.
* @return {Object}
*/
}, {
key: '_buildString',
value: function _buildString(str, values) {
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var nested = options.nested;
var buildParameterized = options.buildParameterized;
var formattingOptions = options.formattingOptions;
values = values || [];
str = str || '';
var formattedStr = '',
curValue = -1,
formattedValues = [];
var paramChar = this.options.parameterCharacter;
var idx = 0;
while (str.length > idx) {
// param char?
if (str.substr(idx, paramChar.length) === paramChar) {
var value = values[++curValue];
if (buildParameterized) {
if (value instanceof cls.BaseBuilder) {
var ret = value._toParamString({
buildParameterized: buildParameterized,
nested: true
});
formattedStr += ret.text;
formattedValues.push.apply(formattedValues, _toConsumableArray(ret.values));
} else {
value = this._formatValueForParamArray(value);
if (_isArray(value)) {
// Array(6) -> "(??, ??, ??, ??, ??, ??)"
var tmpStr = value.map(function () {
return paramChar;
}).join(', ');
formattedStr += '(' + tmpStr + ')';
formattedValues.push.apply(formattedValues, _toConsumableArray(value));
} else {
formattedStr += paramChar;
formattedValues.push(value);
}
}
} else {
formattedStr += this._formatValueForQueryString(value, formattingOptions);
}
idx += paramChar.length;
} else {
formattedStr += str.charAt(idx);
idx++;
}
}
return {
text: this._applyNestingFormatting(formattedStr, !!nested),
values: formattedValues
};
}
/**
* Build all given strings and their corresponding parameter values into
* output.
*
* @param {Array} strings
* @param {Array} strValues array of value arrays corresponding to each string.
* @param {Object} [options] Additional options.
* @param {Boolean} [options.buildParameterized] Whether to build paramterized string. Default is false.
* @param {Boolean} [options.nested] Whether this expression is nested within another.
* @return {Object}
*/
}, {
key: '_buildManyStrings',
value: function _buildManyStrings(strings, strValues) {
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var totalStr = [],
totalValues = [];
for (var idx = 0; strings.length > idx; ++idx) {
var inputString = strings[idx],
inputValues = strValues[idx];
var _buildString2 = this._buildString(inputString, inputValues, {
buildParameterized: options.buildParameterized,
nested: false
});
var text = _buildString2.text;
var values = _buildString2.values;
totalStr.push(text);
totalValues.push.apply(totalValues, _toConsumableArray(values));
}
totalStr = totalStr.join(this.options.separator);
return {
text: totalStr.length ? this._applyNestingFormatting(totalStr, !!options.nested) : '',
values: totalValues
};
}
/**
* Get parameterized representation of this instance.
*
* @param {Object} [options] Options.
* @param {Boolean} [options.buildParameterized] Whether to build paramterized string. Default is false.
* @param {Boolean} [options.nested] Whether this expression is nested within another.
* @return {Object}
*/
}, {
key: '_toParamString',
value: function _toParamString(options) {
throw new Error('Not yet implemented');
}
/**
* Get the expression string.
* @return {String}
*/
}, {
key: 'toString',
value: function toString() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
return this._toParamString(options).text;
}
/**
* Get the parameterized expression string.
* @return {Object}
*/
}, {
key: 'toParam',
value: function toParam() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
return this._toParamString(_extend({}, options, {
buildParameterized: true
}));
}
}]);
return _class2;
}(cls.Cloneable);
/*
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# cls.Expressions
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
*/
/**
* An SQL expression builder.
*
* SQL expressions are used in WHERE and ON clauses to filter data by various criteria.
*
* Expressions can be nested. Nested expression contains can themselves
* contain nested expressions. When rendered a nested expression will be
* fully contained within brackets.
*
* All the build methods in this object return the object instance for chained method calling purposes.
*/
cls.Expression = function (_cls$BaseBuilder) {
_inherits(_class3, _cls$BaseBuilder);
// Initialise the expression.
function _class3(options) {
_classCallCheck(this, _class3);
var _this5 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class3).call(this, options));
_this5._nodes = [];
return _this5;
}
// Combine the current expression with the given expression using the intersection operator (AND).
_createClass(_class3, [{
key: 'and',
value: function and(expr) {
for (var _len3 = arguments.length, params = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
params[_key3 - 1] = arguments[_key3];
}
expr = this._sanitizeExpression(expr);
this._nodes.push({
type: 'AND',
expr: expr,
para: params
});
return this;
}
// Combine the current expression with the given expression using the union operator (OR).
}, {
key: 'or',
value: function or(expr) {
for (var _len4 = arguments.length, params = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
params[_key4 - 1] = arguments[_key4];
}
expr = this._sanitizeExpression(expr);
this._nodes.push({
type: 'OR',
expr: expr,
para: params
});
return this;
}
}, {
key: '_toParamString',
value: function _toParamString() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var totalStr = [],
totalValues = [];
var _iteratorNormalCompletion5 = true;
var _didIteratorError5 = false;
var _iteratorError5 = undefined;
try {
for (var _iterator5 = this._nodes[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
var node = _step5.value;
var type = node.type;
var expr = node.expr;
var para = node.para;
var _ref = expr instanceof cls.BaseBuilder ? expr._toParamString({
buildParameterized: options.buildParameterized,
nested: true
}) : this._buildString(expr, para, {
buildParameterized: options.buildParameterized
});
var text = _ref.text;
var values = _ref.values;
if (totalStr.length) {
totalStr.push(type);
}
totalStr.push(text);
totalValues.push.apply(totalValues, _toConsumableArray(values));
}
} catch (err) {
_didIteratorError5 = true;
_iteratorError5 = err;
} finally {
try {
if (!_iteratorNormalCompletion5 && _iterator5.return) {
_iterator5.return();
}
} finally {
if (_didIteratorError5) {
throw _iteratorError5;
}
}
}
totalStr = totalStr.join(' ');
return {
text: this._applyNestingFormatting(totalStr, !!options.nested),
values: totalValues
};
}
}]);
return _class3;
}(cls.BaseBuilder);
/*
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# cls.Case
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
*/
/**
* An SQL CASE expression builder.
*
* SQL cases are used to select proper values based on specific criteria.
*/
cls.Case = function (_cls$BaseBuilder2) {
_inherits(_class4, _cls$BaseBuilder2);
function _class4(fieldName) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
_classCallCheck(this, _class4);
var _this6 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class4).call(this, options));
if (_isPlainObject(fieldName)) {
options = fieldName;
fieldName = null;
}
if (fieldName) {
_this6._fieldName = _this6._sanitizeField(fieldName);
}
_this6.options = _extend({}, cls.DefaultQueryBuilderOptions, options);
_this6._cases = [];
_this6._elseValue = null;
return _this6;
}
_createClass(_class4, [{
key: 'when',
value: function when(expression) {
for (var _len5 = arguments.length, values = Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
values[_key5 - 1] = arguments[_key5];
}
this._cases.unshift({
expression: expression,
values: values
});
return this;
}
}, {
key: 'then',
value: function then(result) {
if (this._cases.length == 0) {
throw new Error("when() needs to be called first");
}
this._cases[0].result = result;
return this;
}
}, {
key: 'else',
value: function _else(elseValue) {
this._elseValue = elseValue;
return this;
}
}, {
key: '_toParamString',
value: function _toParamString() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var totalStr = '',
totalValues = [];
var _iteratorNormalCompletion6 = true;
var _didIteratorError6 = false;
var _iteratorError6 = undefined;
try {
for (var _iterator6 = this._cases[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
var _step6$value = _step6.value;
var expression = _step6$value.expression;
var values = _step6$value.values;
var result = _step6$value.result;
totalStr = _pad(totalStr, ' ');
var ret = this._buildString(expression, values, {
buildParameterized: options.buildParameterized,
nested: true
});
totalStr += 'WHEN ' + ret.text + ' THEN ' + this._formatValueForQueryString(result);
totalValues.push.apply(totalValues, _toConsumableArray(ret.values));
}
} catch (err) {
_didIteratorError6 = true;
_iteratorError6 = err;
} finally {
try {
if (!_iteratorNormalCompletion6 && _iterator6.return) {
_iterator6.return();
}
} finally {
if (_didIteratorError6) {
throw _iteratorError6;
}
}
}
if (totalStr.length) {
totalStr += ' ELSE ' + this._formatValueForQueryString(this._elseValue) + ' END';
if (this._fieldName) {
totalStr = this._fieldName + ' ' + totalStr;
}
totalStr = 'CASE ' + totalStr;
} else {
totalStr = this._formatValueForQueryString(this._elseValue);
}
return {
text: totalStr,
values: totalValues
};
}
}]);
return _class4;
}(cls.BaseBuilder);
/*
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Building blocks
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
*/
/*
# A building block represents a single build-step within a query building process.
#
# Query builders consist of one or more building blocks which get run in a particular order. Building blocks can
# optionally specify methods to expose through the query builder interface. They can access all the input data for
# the query builder and manipulate it as necessary, as well as append to the final query string output.
#
# If you wish to customize how queries get built or add proprietary query phrases and content then it is recommended
# that you do so using one or more custom building blocks.
#
# Original idea posted in https://github.com/hiddentao/export/issues/10#issuecomment-15016427
*/
cls.Block = function (_cls$BaseBuilder3) {
_inherits(_class5, _cls$BaseBuilder3);
function _class5(options) {
_classCallCheck(this, _class5);
return _possibleConstructorReturn(this, Object.getPrototypeOf(_class5).call(this, options));
}
/**
# Get input methods to expose within the query builder.
#
# By default all methods except the following get returned:
# methods prefixed with _
# constructor and toString()
#
# @return Object key -> function pairs
*/
_createClass(_class5, [{
key: 'exposedMethods',
value: function exposedMethods() {
var ret = {};
var obj = this;
while (obj) {
Object.getOwnPropertyNames(obj).forEach(function (prop) {
if ('constructor' !== prop && typeof obj[prop] === "function" && prop.charAt(0) !== '_' && !cls.Block.prototype[prop]) {
ret[prop] = obj[prop];
}
});
obj = Object.getPrototypeOf(obj);
};
return ret;
}
}]);
return _class5;
}(cls.BaseBuilder);
// A fixed string which always gets output
cls.StringBlock = function (_cls$Block) {
_inherits(_class6, _cls$Block);
function _class6(options, str) {
_classCallCheck(this, _class6);
var _this8 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class6).call(this, options));
_this8._str = str;
return _this8;
}
_createClass(_class6, [{
key: '_toParamString',
value: function _toParamString() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
return {
text: this._str,
values: []
};
}
}]);
return _class6;
}(cls.Block);
// A function string block
cls.FunctionBlock = function (_cls$Block2) {
_inherits(_class7, _cls$Block2);
function _class7(options) {
_classCallCheck(this, _class7);
var _this9 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class7).call(this, options));
_this9._strings = [];
_this9._values = [];
return _this9;
}
_createClass(_class7, [{
key: 'function',
value: function _function(str) {
this._strings.push(str);
for (var _len6 = arguments.length, values = Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) {
values[_key6 - 1] = arguments[_key6];
}
this._values.push(values);
}
}, {
key: '_toParamString',
value: function _toParamString() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
return this._buildManyStrings(this._strings, this._values, options);
}
}]);
return _class7;
}(cls.Block);
// value handler for FunctionValueBlock objects
cls.registerValueHandler(cls.FunctionBlock, function (value) {
var asParam = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
return asParam ? value.toParam() : value.toString();
});
/*
# Table specifier base class
*/
cls.AbstractTableBlock = function (_cls$Block3) {
_inherits(_class8, _cls$Block3);
/**
* @param {Boolean} [options.singleTable] If true then only allow one table spec.
* @param {String} [options.prefix] String prefix for output.
*/
function _class8(options, prefix) {
_classCallCheck(this, _class8);
var _this10 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class8).call(this, options));
_this10._tables = [];
return _this10;
}
/**
# Update given table.
#
# An alias may also be specified for the table.
#
# Concrete subclasses should provide a method which calls this
*/
_createClass(_class8, [{
key: '_table',
value: function _table(table) {
var alias = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
alias = alias ? this._sanitizeTableAlias(alias) : alias;
table = this._sanitizeTable(table);
if (this.options.singleTable) {
this._tables = [];
}
this._tables.push({
table: table,
alias: alias
});
}
// get whether a table has been set
}, {
key: '_hasTable',
value: function _hasTable() {
return 0 < this._tables.length;
}
/**
* @override
*/
}, {
key: '_toParamString',
value: function _toParamString() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var totalStr = '',
totalValues = [];
if (this._hasTable()) {
// retrieve the parameterised queries
var _iteratorNormalCompletion7 = true;
var _didIteratorError7 = false;
var _iteratorError7 = undefined;
try {
for (var _iterator7 = this._tables[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
var _step7$value = _step7.value;
var table = _step7$value.table;
var alias = _step7$value.alias;
totalStr = _pad(totalStr, ', ');
var tableStr = void 0;
if (table instanceof cls.BaseBuilder) {
var _table$_toParamString = table._toParamString({
buildParameterized: options.buildParameterized,
nested: true
});
var text = _table$_toParamString.text;
var values = _table$_toParamString.values;
tableStr = text;
totalValues.push.apply(totalValues, _toConsumableArray(values));
} else {
tableStr = this._formatTableName(table);
}
if (alias) {
tableStr += ' ' + this._formatTableAlias(alias);
}
totalStr += tableStr;
}
} catch (err) {
_didIteratorError7 = true;
_iteratorError7 = err;
} finally {
try {
if (!_iteratorNormalCompletion7 && _iterator7.return) {
_iterator7.return();
}
} finally {
if (_didIteratorError7) {
throw _iteratorError7;
}
}
}
if (this.options.prefix) {
totalStr = this.options.prefix + ' ' + totalStr;
}
}
return {
text: totalStr,
values: totalValues
};
}
}]);
return _class8;
}(cls.Block);
// target table for DELETE queries, DELETE <??> FROM
cls.TargetTableBlock = function (_cls$AbstractTableBlo) {
_inherits(_class9, _cls$AbstractTableBlo);
function _class9() {
_classCallCheck(this, _class9);
return _possibleConstructorReturn(this, Object.getPrototypeOf(_class9).apply(this, arguments));
}
_createClass(_class9, [{
key: 'target',
value: function target(table) {
this._table(table);
}
}]);
return _class9;
}(cls.AbstractTableBlock);
// Update Table
cls.UpdateTableBlock = function (_cls$AbstractTableBlo2) {
_inherits(_class10, _cls$AbstractTableBlo2);
function _class10() {
_classCallCheck(this, _class10);
return _possibleConstructorReturn(this, Object.getPrototypeOf(_class10).apply(this, arguments));
}
_createClass(_class10, [{
key: 'table',
value: function table(_table2) {
var alias = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
this._table(_table2, alias);
}
}, {
key: '_toParamString',
value: function _toParamString() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
if (!this._hasTable()) {
throw new Error("table() needs to be called");
}
return _get(Object.getPrototypeOf(_class10.prototype), '_toParamString', this).call(this, options);
}
}]);
return _class10;
}(cls.AbstractTableBlock);
// FROM table
cls.FromTableBlock = function (_cls$AbstractTableBlo3) {
_inherits(_class11, _cls$AbstractTableBlo3);
function _class11(options) {
_classCallCheck(this, _class11);
return _possibleConstructorReturn(this, Object.getPrototypeOf(_class11).call(this, _extend({}, options, {
prefix: 'FROM'
})));
}
_createClass(_class11, [{
key: 'from',
value: function from(table) {
var alias = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
this._table(table, alias);
}
}]);
return _class11;
}(cls.AbstractTableBlock);
// INTO table
cls.IntoTableBlock = function (_cls$AbstractTableBlo4) {
_inherits(_class12, _cls$AbstractTableBlo4);
function _class12(options) {
_classCallCheck(this, _class12);
return _possibleConstructorReturn(this, Object.getPrototypeOf(_class12).call(this, _extend({}, options, {
prefix: 'INTO',
singleTable: true
})));
}
_createClass(_class12, [{
key: 'into',
value: function into(table) {
this._table(table);
}
}, {
key: '_toParamString',
value: function _toParamString() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
if (!this._hasTable()) {
throw new Error("into() needs to be called");
}
return _get(Object.getPrototypeOf(_class12.prototype), '_toParamString', this).call(this, options);
}
}]);
return _class12;
}(cls.AbstractTableBlock);
// (SELECT) Get field
cls.GetFieldBlock = function (_cls$Block4) {
_inherits(_class13, _cls$Block4);
function _class13(options) {
_classCallCheck(this, _class13);
var _this15 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class13).call(this, options));
_this15._fields = [];
return _this15;
}
/**
# Add the given fields to the final result set.
#
# The parameter is an Object containing field names (or database functions) as the keys and aliases for the fields
# as the values. If the value for a key is null then no alias is set for that field.
#
# Internally this method simply calls the field() method of this block to add each individual field.
#
# options.ignorePeriodsForFieldNameQuotes - whether to ignore period (.) when automatically quoting the field name
*/
_createClass(_class13, [{
key: 'fields',
value: function fields(_fields) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
if (_isArray(_fields)) {
var _iteratorNormalCompletion8 = true;
var _didIteratorError8 = false;
var _iteratorError8 = undefined;
try {
for (var _iterator8 = _fields[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {
var field = _step8.value;
this.field(field, null, options);
}
} catch (err) {
_didIteratorError8 = true;
_iteratorError8 = err;
} finally {
try {
if (!_iteratorNormalCompletion8 && _iterator8.return) {
_iterator8.return();
}
} finally {
if (_didIteratorError8) {
throw _iteratorError8;
}
}
}
} else {
for (var _field2 in _fields) {
var alias = _fields[_field2];
this.field(_field2, alias, options);
}
}
}
/**
# Add the given field to the final result set.
#
# The 'field' parameter does not necessarily have to be a fieldname. It can use database functions too,
# e.g. DATE_FORMAT(a.started, "%H")
#
# An alias may also be specified for this field.
#
# options.ignorePeriodsForFieldNameQuotes - whether to ignore period (.) when automatically quoting the field name
*/
}, {
key: 'field',
value: function field(_field) {
var alias = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
alias = alias ? this._sanitizeFieldAlias(alias) : alias;
_field = this._sanitizeField(_field);
// if field-alias combo already present then don't add
var existingField = this._fields.filter(function (f) {
return f.name === _field && f.alias === alias;
});
if (existingField.length) {
return this;
}
this._fields.push({
name: _field,
alias: alias,
options: options
});
}
}, {
key: '_toParamString',
value: function _toParamString() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var queryBuilder = options.queryBuilder;
var buildParameterized = options.buildParameterized;
var totalStr = '',
totalValues = [];
var _iteratorNormalCompletion9 = true;
var _didIteratorError9 = false;
var _iteratorError9 = undefined;
try {
for (var _iterator9 = this._fields[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {
var field = _step9.value;
totalStr = _pad(totalStr, ", ");
var name = field.name;
var alias = field.alias;
var _options = field.options;
if (typeof name === 'string') {
totalStr += this._formatFieldName(name, _options);
} else {
var ret = name._toParamString({
nested: true,
buildParameterized: buildParameterized
});
totalStr += ret.text;
totalValues.push.apply(totalValues, _toConsumableArray(ret.values));
}
if (alias) {
totalStr += ' AS ' + this._formatFieldAlias(alias);
}
}
} catch (err) {
_didIteratorError9 = true;
_iteratorError9 = err;
} finally {
try {
if (!_iteratorNormalCompletion9 && _iterator9.return) {
_iterator9.return();
}
} finally {
if (_didIteratorError9) {
throw _iteratorError9;
}
}
}
if (!totalStr.length) {
// if select query and a table is set then all fields wanted
var fromTableBlock = queryBuilder && queryBuilder.getBlock(cls.FromTableBlock);
if (fromTableBlock && fromTableBlock._hasTable()) {
totalStr = "*";
}
}
return {
text: totalStr,
values: totalValues
};
}
}]);
return _class13;
}(cls.Block);
// Base class for setting fields to values (used for INSERT and UPDATE queries)
cls.AbstractSetFieldBlock = function (_cls$Block5) {
_inherits(_class14, _cls$Block5);
function _class14(options) {
_classCallCheck(this, _class14);
var _this16 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class14).call(this, options));
_this16._reset();
return _this16;
}
_createClass(_class14, [{
key: '_reset',
value: function _reset() {
this._fields = [];
this._values = [[]];
this._valueOptions = [[]];
}
// Update the given field with the given value.
// This will override any previously set value for the given field.
}, {
key: '_set',
value: function _set(field, value) {
var valueOptions = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
if (this._values.length > 1) {
throw new Error("Cannot set multiple rows of fields this way.");
}
if (typeof value !== 'undefined') {
value = this._sanitizeValue(value);
}
field = this._sanitizeField(field);
// Explicity overwrite existing fields
var index = this._fields.indexOf(field);
// if field not defined before
if (-1 === index) {
this._fields.push(field);
index = this._fields.length - 1;
}
this._values[0][index] = value;
this._valueOptions[0][index] = valueOptions;
}
// Insert fields based on the key/value pairs in the given object
}, {
key: '_setFields',
value: function _setFields(fields) {
var valueOptions = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
if ((typeof fields === 'undefined' ? 'undefined' : _typeof(fields)) !== 'object') {
throw new Error("Expected an object but got " + (typeof fields === 'undefined' ? 'undefined' : _typeof(fields)));
}
for (var field in fields) {
this._set(field, fields[field], valueOptions);
}
}
// Insert multiple rows for the given fields. Accepts an array of objects.
// This will override all previously set values for every field.
}, {
key: '_setFieldsRows',
value: function _setFieldsRows(fieldsRows) {
var valueOptions = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
if (!_isArray(fieldsRows)) {
throw new Error("Expected an array of objects but got " + (typeof fieldsRows === 'undefined' ? 'undefined' : _typeof(fieldsRows)));
}
// Reset the objects stored fields and values
this._reset();
// for each row
for (var i = 0; fieldsRows.length > i; ++i) {
var fieldRow = fieldsRows[i];
// for each field
for (var field in fieldRow) {
var value = fieldRow[field];
field = this._sanitizeField(field);
value = this._sanitizeValue(value);
var index = this._fields.indexOf(field);
if (0 < i && -1 === index) {
throw new Error('All fields in subsequent rows must match the fields in the first row');
}
// Add field only if it hasn't been added before
if (-1 === index) {
this._fields.push(field);
index = this._fields.length - 1;
}
// The first value added needs to add the array
if (!_isArray(this._values[i])) {
this._values[i] = [];
this._valueOptions[i] = [];
}
this._values[i][index] = value;
this._valueOptions[i][index] = valueOptions;
}
}
}
}]);
return _class14;
}(cls.Block);
// (UPDATE) SET field=value
cls.SetFieldBlock = function (_cls$AbstractSetField) {
_inherits(_class15, _cls$AbstractSetField);
function _class15() {
_classCallCheck(this, _class15);
return _possibleConstructorReturn(this, Object.getPrototypeOf(_class15).apply(this, arguments));
}
_createClass(_class15, [{
key: 'set',
value: function set(field, value, options) {
this._set(field, value, options);
}
}, {
key: 'setFields',
value: function setFields(fields, valueOptions) {
this._setFields(fields, valueOptions);
}
}, {
key: '_toParamString',
value: function _toParamString() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var buildParameterized = options.buildParameterized;
if (0 >= this._fields.length) {
throw new Error("set() needs to be called");
}
var totalStr = '',
totalValues = [];
for (var i = 0; i < this._fields.length; ++i) {
totalStr = _pad(totalStr, ', ');
var field = this._formatFieldName(this._fields[i]);
var value = this._values[0][i];
// e.g. field can be an expression such as `count = count + 1`
if (0 > field.indexOf('=')) {
field = field + ' = ' + this.options.parameterCharacter;
}
var ret = this._buildString(field, [value], {
buildParameterized: buildParameterized,
formattingOptions: this._valueOptions[0][i]
});
totalStr += ret.text;
totalValues.push.apply(totalValues, _toConsumableArray(ret.values));
}
return {
text: 'SET ' + totalStr,
values: totalValues
};
}
}]);
return _class15;
}(cls.AbstractSetFieldBlock);
// (INSERT INTO) ... field ... value
cls.InsertFieldValueBlock = function (_cls$AbstractSetField2) {
_inherits(_class16, _cls$AbstractSetField2);
function _class16() {
_classCallCheck(this, _class16);
return _possibleConstructorReturn(this, Object.getPrototypeOf(_class16).apply(this, arguments));
}
_createClass(_class16, [{
key: 'set',
value: function set(field, value) {
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
this._set(field, value, options);
}
}, {
key: 'setFields',
value: function setFields(fields, valueOptions) {
this._setFields(fields, valueOptions);
}
}, {
key: 'setFieldsRows',
value: function setFieldsRows(fieldsRows, valueOptions) {
this._setFieldsRows(fieldsRows, valueOptions);
}
}, {
key: '_toParamString',
value: function _toParamString() {
var _this19 = this;
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var buildParameterized = options.buildParameterized;
var fieldString = this._fields.map(function (f) {
return _this19._formatFieldName(f);
}).join(', ');
var valueStrings = [],
totalValues = [];
for (var i = 0; i < this._values.length; ++i) {
valueStrings[i] = '';
for (var j = 0; j < this._values[i].length; ++j) {
var ret = this._buildString(this.options.parameterCharacter, [this._values[i][j]], {
buildParameterized: buildParameterized,
formattingOptions: this._valueOptions[i][j]
});
totalValues.push.apply(totalValues, _toConsumableArray(ret.values));
valueStrings[i] = _pad(valueStrings[i], ', ');
valueStrings[i] += ret.text;
}
}
return {
text: fieldString.length ? '(' + fieldString + ') VALUES (' + valueStrings.join('), (') + ')' : '',
values: totalValues
};
}
}]);
return _class16;
}(cls.AbstractSetFieldBlock);
// (INSERT INTO) ... field ... (SELECT ... FROM ...)
cls.InsertFieldsFromQueryBlock = function (_cls$Block6) {
_inherits(_class17, _cls$Block6);
function _class17(options) {
_classCallCheck(this, _class17);
var _this20 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class17).call(this, options));
_this20._fields = [];
_this20._query = null;
return _this20;
}
_createClass(_class17, [{
key: 'fromQuery',
value: function fromQuery(fields, selectQuery) {
var _this21 = this;
this._fields = fields.map(function (v) {
return _this21._sanitizeField(v);
});
this._query = this._sanitizeBaseBuilder(selectQuery);
}
}, {
key: '_toParamString',
value: function _toParamString() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var totalStr = '',
totalValues = [];
if (this._fields.length && this._query) {
var _query$_toParamString = this._query._toParamString({
buildParameterized: options.buildParameterized,
nested: true
});
var text = _query$_toParamString.text;
var values = _query$_toParamString.values;
totalStr = '(' + this._fields.join(', ') + ') ' + this._applyNestingFormatting(text);
totalValues = values;
}
return {
text: totalStr,
values: totalValues
};
}
}]);
return _class17;
}(cls.Block);
// DISTINCT
cls.DistinctBlock = function (_cls$Block7) {
_inherits(_class18, _cls$Block7);
function _class18() {
_classCallCheck(this, _class18);
return _possibleConstructorReturn(this, Object.getPrototypeOf(_class18).apply(this, arguments));
}
_createClass(_class18, [{
key: 'distinct',
// Add the DISTINCT keyword to the query.
value: function distinct() {
this._useDistinct = true;
}
}, {
key: '_toParamString',
value: function _toParamString() {
return {
text: this._useDistinct ? "DISTINCT" : "",
values: []
};
}
}]);
return _class18;
}(cls.Block);
// GROUP BY
cls.GroupByBlock = function (_cls$Block8) {
_inherits(_class19, _cls$Block8);
function _class19(options) {
_classCallCheck(this, _class19);
var _this23 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class19).call(this, options));
_this23._groups = [];
return _this23;
}
// Add a GROUP BY transformation for the given field.
_createClass(_class19, [{
key: 'group',
value: function group(field) {
this._groups.push(this._sanitizeField(field));
}
}, {
key: '_toParamString',
value: function _toParamString() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
return {
text: this._groups.length ? 'GROUP BY ' + this._groups.join(', ') : '',
values: []
};
}
}]);
return _class19;
}(cls.Block);
// OFFSET x
cls.OffsetBlock = function (_cls$Block9) {
_inherits(_class20, _cls$Block9);
function _class20(options) {
_classCallCheck(this, _class20);
var _this24 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class20).call(this, options));
_this24._offsets = null;
return _this24;
}
/**
# Set the OFFSET transformation.
#
# Call this will override the previously set offset for this query. Also note that Passing 0 for 'max' will remove
# the offset.
*/
_createClass(_class20, [{
key: 'offset',
value: function offset(start) {
this._offsets = this._sanitizeLimitOffset(start);
}
}, {
key: '_toParamString',
value: function _toParamString() {
return {
text: this._offsets ? 'OFFSET ' + this._offsets : '',
values: []
};
}
}]);
return _class20;
}(cls.Block);
// Abstract condition base class
cls.AbstractConditionBlock = function (_cls$Block10) {
_inherits(_class21, _cls$Block10);
/**
* @param {String} options.verb The condition verb.
*/
function _class21(options) {
_classCallCheck(this, _class21);
var _this25 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class21).call(this, options));
_this25._conditions = [];
return _this25;
}
/**
# Add a condition.
#
# When the final query is constructed all the conditions are combined using the intersection (AND) operator.
#
# Concrete subclasses should provide a method which calls this
*/
_createClass(_class21, [{
key: '_condition',
value: function _condition(condition) {
for (var _len7 = arguments.length, values = Array(_len7 > 1 ? _len7 - 1 : 0), _key7 = 1; _key7 < _len7; _key7++) {
values[_key7 - 1] = arguments[_key7];
}
condition = this._sanitizeExpression(condition);
this._conditions.push({
expr: condition,
values: values
});
}
}, {
key: '_toParamString',
value: function _toParamString() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var totalStr = [],
totalValues = [];
var _iteratorNormalCompletion10 = true;
var _didIteratorError10 = false;
var _iteratorError10 = undefined;
try {
for (var _iterator10 = this._conditions[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) {
var _step10$value = _step10.value;
var expr = _step10$value.expr;
var values = _step10$value.values;
var ret = expr instanceof cls.BaseBuilder ? expr._toParamString({
buildParameterized: options.buildParameterized
}) : this._buildString(expr, values, {
buildParameterized: options.buildParameterized
});
if (ret.text.length) {
totalStr.push(ret.text);
}
totalValues.push.apply(totalValues, _toConsumableArray(ret.values));
}
} catch (err) {
_didIteratorError10 = true;
_iteratorError10 = err;
} finally {
try {
if (!_iteratorNormalCompletion10 && _iterator10.return) {
_iterator10.return();
}
} finally {
if (_didIteratorError10) {
throw _iteratorError10;
}
}
}
if (totalStr.length) {
totalStr = totalStr.join(') AND (');
}
return {
text: totalStr.length ? this.options.verb + ' (' + totalStr + ')' : '',
values: totalValues
};
}
}]);
return _class21;
}(cls.Block);
// WHERE
cls.WhereBlock = function (_cls$AbstractConditio) {
_inherits(_class22, _cls$AbstractConditio);
function _class22(options) {
_classCallCheck(this, _class22);
return _possibleConstructorReturn(this, Object.getPrototypeOf(_class22).call(this, _extend({}, options, {
verb: 'WHERE'
})));
}
_createClass(_class22, [{
key: 'where',
value: function where(condition) {
for (var _len8 = arguments.length, values = Array(_len8 > 1 ? _len8 - 1 : 0), _key8 = 1; _key8 < _len8; _key8++) {
values[_key8 - 1] = arguments[_key8];
}
this._condition.apply(this, [condition].concat(values));
}
}]);
return _class22;
}(cls.AbstractConditionBlock);
// HAVING
cls.HavingBlock = function (_cls$AbstractConditio2) {
_inherits(_class23, _cls$AbstractConditio2);
function _class23(options) {
_classCallCheck(this, _class23);
return _possibleConstructorReturn(this, Object.getPrototypeOf(_class23).call(this, _extend({}, options, {
verb: 'HAVING'
})));
}
_createClass(_class23, [{
key: 'having',
value: function having(condition) {
for (var _len9 = arguments.length, values = Array(_len9 > 1 ? _len9 - 1 : 0), _key9 = 1; _key9 < _len9; _key9++) {
values[_key9 - 1] = arguments[_key9];
}
this._condition.apply(this, [condition].concat(values));
}
}]);
return _class23;
}(cls.AbstractConditionBlock);
// ORDER BY
cls.OrderByBlock = function (_cls$Block11) {
_inherits(_class24, _cls$Block11);
function _class24(options) {
_classCallCheck(this, _class24);
var _this28 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class24).call(this, options));
_this28._orders = [];
return _this28;
}
/**
# Add an ORDER BY transformation for the given field in the given order.
#
# To specify descending order pass false for the 'dir' parameter.
*/
_createClass(_class24, [{
key: 'order',
value: function order(field, dir) {
for (var _len10 = arguments.length, values = Array(_len10 > 2 ? _len10 - 2 : 0), _key10 = 2; _key10 < _len10; _key10++) {
values[_key10 - 2] = arguments[_key10];
}
field = this._sanitizeField(field);
if (!(typeof dir === 'string')) {
if (dir === undefined) {
dir = 'ASC'; // Default to asc
} else if (dir !== null) {
dir = dir ? 'ASC' : 'DESC'; // Convert truthy to asc
}
}
this._orders.push({
field: field,
dir: dir,
values: values
});
}
}, {
key: '_toParamString',
value: function _toParamString() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var totalStr = '',
totalValues = [];
var _iteratorNormalCompletion11 = true;
var _didIteratorError11 = false;
var _iteratorError11 = undefined;
try {
for (var _iterator11 = this._orders[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) {
var _step11$value = _step11.value;
var field = _step11$value.field;
var dir = _step11$value.dir;
var values = _step11$value.values;
totalStr = _pad(totalStr, ', ');
var ret = this._buildString(field, values, {
buildParameterized: options.buildParameterized
});
totalStr += ret.text, totalValues.push.apply(totalValues, _toConsumableArray(ret.values));
if (dir !== null) {
totalStr += ' ' + dir;
}
}
} catch (err) {
_didIteratorError11 = true;
_iteratorError11 = err;
} finally {
try {
if (!_iteratorNormalCompletion11 && _iterator11.return) {
_iterator11.return();
}
} finally {
if (_didIteratorError11) {
throw _iteratorError11;
}
}
}
return {
text: totalStr.length ? 'ORDER BY ' + totalStr : '',
values: totalValues
};
}
}]);
return _class24;
}(cls.Block);
// LIMIT
cls.LimitBlock = function (_cls$Block12) {
_inherits(_class25, _cls$Block12);
function _class25(options) {
_classCallCheck(this, _class25);
var _this29 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class25).call(this, options));
_this29._limit = null;
return _this29;
}
/**
# Set the LIMIT transformation.
#
# Call this will override the previously set limit for this query. Also note that Passing 0 for 'max' will remove
# the limit.
*/
_createClass(_class25, [{
key: 'limit',
value: function limit(_limit) {
this._limit = this._sanitizeLimitOffset(_limit);
}
}, {
key: '_toParamString',
value: function _toParamString() {
return {
text: null !== this._limit ? 'LIMIT ' + this._limit : '',
values: []
};
}
}]);
return _class25;
}(cls.Block);
// JOIN
cls.JoinBlock = function (_cls$Block13) {
_inherits(_class26, _cls$Block13);
function _class26(options) {
_classCallCheck(this, _class26);
var _this30 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class26).call(this, options));
_this30._joins = [];
return _this30;
}
/**
# Add a JOIN with the given table.
#
# 'table' is the name of the table to join with.
#
# 'alias' is an optional alias for the table name.
#
# 'condition' is an optional condition (containing an SQL expression) for the JOIN.
#
# 'type' must be either one of INNER, OUTER, LEFT or RIGHT. Default is 'INNER'.
#
*/
_createClass(_class26, [{
key: 'join',
value: function join(table) {
var alias = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
var condition = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];
var type = arguments.length <= 3 || arguments[3] === undefined ? 'INNER' : arguments[3];
table = this._sanitizeTable(table, true);
alias = alias ? this._sanitizeTableAlias(alias) : alias;
condition = condition ? this._sanitizeExpression(condition) : condition;
this._joins.push({
type: type,
table: table,
alias: alias,
condition: condition
});
}
}, {
key: 'left_join',
value: function left_join(table) {
var alias = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
var condition = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];
this.join(table, alias, condition, 'LEFT');
}
}, {
key: 'right_join',
value: function right_join(table) {
var alias = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
var condition = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];
this.join(table, alias, condition, 'RIGHT');
}
}, {
key: 'outer_join',
value: function outer_join(table) {
var alias = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
var condition = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];
this.join(table, alias, condition, 'OUTER');
}
}, {
key: 'left_outer_join',
value: function left_outer_join(table) {
var alias = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
var condition = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];
this.join(table, alias, condition, 'LEFT OUTER');
}
}, {
key: 'full_join',
value: function full_join(table) {
var alias = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
var condition = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];
this.join(table, alias, condition, 'FULL');
}
}, {
key: 'cross_join',
value: function cross_join(table) {
var alias = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
var condition = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];
this.join(table, alias, condition, 'CROSS');
}
}, {
key: '_toParamString',
value: function _toParamString() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var totalStr = "",
totalValues = [];
var _iteratorNormalCompletion12 = true;
var _didIteratorError12 = false;
var _iteratorError12 = undefined;
try {
for (var _iterator12 = this._joins[Symbol.iterator](), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) {
var _step12$value = _step12.value;
var type = _step12$value.type;
var table = _step12$value.table;
var alias = _step12$value.alias;
var condition = _step12$value.condition;
totalStr = _pad(totalStr, this.options.separator);
var tableStr = void 0;
if (table instanceof cls.BaseBuilder) {
var ret = table._toParamString({
buildParameterized: options.buildParameterized,
nested: true
});
totalValues.push.apply(totalValues, _toConsumableArray(ret.values));
tableStr = ret.text;
} else {
tableStr = this._formatTableName(table);
}
totalStr += type + ' JOIN ' + tableStr;
if (alias) {
totalStr += ' ' + this._formatTableAlias(alias);
}
if (condition) {
totalStr += ' ON ';
var _ret4 = void 0;
if (condition instanceof cls.BaseBuilder) {
_ret4 = condition._toParamString({
buildParameterized: options.buildParameterized
});
} else {
_ret4 = this._buildString(condition, [], {
buildParameterized: options.buildParameterized
});
}
totalStr += this._applyNestingFormatting(_ret4.text);
totalValues.push.apply(totalValues, _toConsumableArray(_ret4.values));
}
}
} catch (err) {
_didIteratorError12 = true;
_iteratorError12 = err;
} finally {
try {
if (!_iteratorNormalCompletion12 && _iterator12.return) {
_iterator12.return();
}
} finally {
if (_didIteratorError12) {
throw _iteratorError12;
}
}
}
return {
text: totalStr,
values: totalValues
};
}
}]);
return _class26;
}(cls.Block);
// UNION
cls.UnionBlock = function (_cls$Block14) {
_inherits(_class27, _cls$Block14);
function _class27(options) {
_classCallCheck(this, _class27);
var _this31 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class27).call(this, options));
_this31._unions = [];
return _this31;
}
/**
# Add a UNION with the given table/query.
#
# 'table' is the name of the table or query to union with.
#
# 'type' must be either one of UNION or UNION ALL.... Default is 'UNION'.
*/
_createClass(_class27, [{
key: 'union',
value: function union(table) {
var type = arguments.length <= 1 || arguments[1] === undefined ? 'UNION' : arguments[1];
table = this._sanitizeTable(table);
this._unions.push({
type: type,
table: table
});
}
// Add a UNION ALL with the given table/query.
}, {
key: 'union_all',
value: function union_all(table) {
this.union(table, 'UNION ALL');
}
}, {
key: '_toParamString',
value: function _toParamString() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var totalStr = '',
totalValues = [];
var _iteratorNormalCompletion13 = true;
var _didIteratorError13 = false;
var _iteratorError13 = undefined;
try {
for (var _iterator13 = this._unions[Symbol.iterator](), _step13; !(_iteratorNormalCompletion13 = (_step13 = _iterator13.next()).done); _iteratorNormalCompletion13 = true) {
var _step13$value = _step13.value;
var type = _step13$value.type;
var table = _step13$value.table;
totalStr = _pad(totalStr, this.options.separator);
var tableStr = void 0;
if (table instanceof cls.BaseBuilder) {
var ret = table._toParamString({
buildParameterized: options.buildParameterized,
nested: true
});
tableStr = ret.text;
totalValues.push.apply(totalValues, _toConsumableArray(ret.values));
} else {
totalStr = this._formatTableName(table);
}
totalStr += type + ' ' + tableStr;
}
} catch (err) {
_didIteratorError13 = true;
_iteratorError13 = err;
} finally {
try {
if (!_iteratorNormalCompletion13 && _iterator13.return) {
_iterator13.return();
}
} finally {
if (_didIteratorError13) {
throw _iteratorError13;
}
}
}
return {
text: totalStr,
values: totalValues
};
}
}]);
return _class27;
}(cls.Block);
/*
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Query builders
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
*/
/**
# Query builder base class
#
# Note that the query builder does not check the final query string for correctness.
#
# All the build methods in this object return the object instance for chained method calling purposes.
*/
cls.QueryBuilder = function (_cls$BaseBuilder4) {
_inherits(_class28, _cls$BaseBuilder4);
/**
# Constructor
#
# blocks - array of cls.BaseBuilderBlock instances to build the query with.
*/
function _class28(options, blocks) {
_classCallCheck(this, _class28);
var _this32 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class28).call(this, options));
_this32.blocks = blocks || [];
// Copy exposed methods into myself
var _iteratorNormalCompletion14 = true;
var _didIteratorError14 = false;
var _iteratorError14 = undefined;
try {
for (var _iterator14 = _this32.blocks[Symbol.iterator](), _step14; !(_iteratorNormalCompletion14 = (_step14 = _iterator14.next()).done); _iteratorNormalCompletion14 = true) {
var block = _step14.value;
var exposedMethods = block.exposedMethods();
for (var methodName in exposedMethods) {
var methodBody = exposedMethods[methodName];
if (undefined !== _this32[methodName]) {
throw new Error('Builder already has a builder method called: ' + methodName);
}
(function (block, name, body) {
_this32[name] = function () {
for (var _len11 = arguments.length, args = Array(_len11), _key11 = 0; _key11 < _len11; _key11++) {
args[_key11] = arguments[_key11];
}
body.call.apply(body, [block].concat(args));
return _this32;
};
})(block, methodName, methodBody);
}
}
} catch (err) {
_didIteratorError14 = true;
_iteratorError14 = err;
} finally {
try {
if (!_iteratorNormalCompletion14 && _iterator14.return) {
_iterator14.return();
}
} finally {
if (_didIteratorError14) {
throw _iteratorError14;
}
}
}
return _this32;
}
/**
# Register a custom value handler for this query builder and all its contained blocks.
#
# Note: This will override any globally registered handler for this value type.
*/
_createClass(_class28, [{
key: 'registerValueHandler',
value: function registerValueHandler(type, handler) {
var _iteratorNormalCompletion15 = true;
var _didIteratorError15 = false;
var _iteratorError15 = undefined;
try {
for (var _iterator15 = this.blocks[Symbol.iterator](), _step15; !(_iteratorNormalCompletion15 = (_step15 = _iterator15.next()).done); _iteratorNormalCompletion15 = true) {
var block = _step15.value;
block.registerValueHandler(type, handler);
}
} catch (err) {
_didIteratorError15 = true;
_iteratorError15 = err;
} finally {
try {
if (!_iteratorNormalCompletion15 && _iterator15.return) {
_iterator15.return();
}
} finally {
if (_didIteratorError15) {
throw _iteratorError15;
}
}
}
_get(Object.getPrototypeOf(_class28.prototype), 'registerValueHandler', this).call(this, type, handler);
return this;
}
/**
# Update query builder options
#
# This will update the options for all blocks too. Use this method with caution as it allows you to change the
# behaviour of your query builder mid-build.
*/
}, {
key: 'updateOptions',
value: function updateOptions(options) {
this.options = _extend({}, this.options, options);
var _iteratorNormalCompletion16 = true;
var _didIteratorError16 = false;
var _iteratorError16 = undefined;
try {
for (var _iterator16 = this.blocks[Symbol.iterator](), _step16; !(_iteratorNormalCompletion16 = (_step16 = _iterator16.next()).done); _iteratorNormalCompletion16 = true) {
var block = _step16.value;
block.options = _extend({}, block.options, options);
}
} catch (err) {
_didIteratorError16 = true;
_iteratorError16 = err;
} finally {
try {
if (!_iteratorNormalCompletion16 && _iterator16.return) {
_iterator16.return();
}
} finally {
if (_didIteratorError16) {
throw _iteratorError16;
}
}
}
}
// Get the final fully constructed query param obj.
}, {
key: '_toParamString',
value: function _toParamString() {
var _this33 = this,
_ref2;
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
options = _extend({}, this.options, options);
var blockResults = this.blocks.map(function (b) {
return b._toParamString({
buildParameterized: options.buildParameterized,
queryBuilder: _this33
});
});
var blockTexts = blockResults.map(function (b) {
return b.text;
});
var blockValues = blockResults.map(function (b) {
return b.values;
});
var totalStr = blockTexts.filter(function (v) {
return 0 < v.length;
}).join(options.separator);
var totalValues = (_ref2 = []).concat.apply(_ref2, _toConsumableArray(blockValues));
if (!options.nested) {
if (options.numberedParameters) {
(function () {
var i = undefined !== options.numberedParametersStartAt ? options.numberedParametersStartAt : 1;
// construct regex for searching
var regex = options.parameterCharacter.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
totalStr = totalStr.replace(new RegExp(regex, 'g'), function () {
return '' + options.numberedParametersPrefix + i++;
});
})();
}
}
return {
text: this._applyNestingFormatting(totalStr, !!options.nested),
values: totalValues
};
}
// Deep clone
}, {
key: 'clone',
value: function clone() {
var blockClones = this.blocks.map(function (v) {
return v.clone();
});
return new this.constructor(this.options, blockClones);
}
// Get a specific block
}, {
key: 'getBlock',
value: function getBlock(blockType) {
var filtered = this.blocks.filter(function (b) {
return b instanceof blockType;
});
return filtered[0];
}
}]);
return _class28;
}(cls.BaseBuilder);
// SELECT query builder.
cls.Select = function (_cls$QueryBuilder) {
_inherits(_class29, _cls$QueryBuilder);
function _class29(options) {
var blocks = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
_classCallCheck(this, _class29);
blocks = blocks || [new cls.StringBlock(options, 'SELECT'), new cls.FunctionBlock(options), new cls.DistinctBlock(options), new cls.GetFieldBlock(options), new cls.FromTableBlock(options), new cls.JoinBlock(options), new cls.WhereBlock(options), new cls.GroupByBlock(options), new cls.HavingBlock(options), new cls.OrderByBlock(options), new cls.LimitBlock(options), new cls.OffsetBlock(options), new cls.UnionBlock(options)];
return _possibleConstructorReturn(this, Object.getPrototypeOf(_class29).call(this, options, blocks));
}
return _class29;
}(cls.QueryBuilder);
// UPDATE query builder.
cls.Update = function (_cls$QueryBuilder2) {
_inherits(_class30, _cls$QueryBuilder2);
function _class30(options) {
var blocks = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
_classCallCheck(this, _class30);
blocks = blocks || [new cls.StringBlock(options, 'UPDATE'), new cls.UpdateTableBlock(options), new cls.SetFieldBlock(options), new cls.WhereBlock(options), new cls.OrderByBlock(options), new cls.LimitBlock(options)];
return _possibleConstructorReturn(this, Object.getPrototypeOf(_class30).call(this, options, blocks));
}
return _class30;
}(cls.QueryBuilder);
// DELETE query builder.
cls.Delete = function (_cls$QueryBuilder3) {
_inherits(_class31, _cls$QueryBuilder3);
function _class31(options) {
var blocks = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
_classCallCheck(this, _class31);
blocks = blocks || [new cls.StringBlock(options, 'DELETE'), new cls.TargetTableBlock(options), new cls.FromTableBlock(_extend({}, options, {
singleTable: true
})), new cls.JoinBlock(options), new cls.WhereBlock(options), new cls.OrderByBlock(options), new cls.LimitBlock(options)];
return _possibleConstructorReturn(this, Object.getPrototypeOf(_class31).call(this, options, blocks));
}
return _class31;
}(cls.QueryBuilder);
// An INSERT query builder.
cls.Insert = function (_cls$QueryBuilder4) {
_inherits(_class32, _cls$QueryBuilder4);
function _class32(options) {
var blocks = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
_classCallCheck(this, _class32);
blocks = blocks || [new cls.StringBlock(options, 'INSERT'), new cls.IntoTableBlock(options), new cls.InsertFieldValueBlock(options), new cls.InsertFieldsFromQueryBlock(options)];
return _possibleConstructorReturn(this, Object.getPrototypeOf(_class32).call(this, options, blocks));
}
return _class32;
}(cls.QueryBuilder);
var _squel = {
VERSION: '5.4.2',
flavour: flavour,
expr: function expr(options) {
return new cls.Expression(options);
},
case: function _case(name, options) {
return new cls.Case(name, options);
},
select: function select(options, blocks) {
return new cls.Select(options, blocks);
},
update: function update(options, blocks) {
return new cls.Update(options, blocks);
},
insert: function insert(options, blocks) {
return new cls.Insert(options, blocks);
},
delete: function _delete(options, blocks) {
return new cls.Delete(options, blocks);
},
str: function str() {
var inst = new cls.FunctionBlock();
inst.function.apply(inst, arguments);
return inst;
},
registerValueHandler: cls.registerValueHandler
};
// aliases
_squel.remove = _squel.delete;
// classes
_squel.cls = cls;
return _squel;
}
/**
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Exported instance (and for use by flavour definitions further down).
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
*/
var squel = _buildSquel();
/**
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Squel SQL flavours
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
*/
// Available flavours
squel.flavours = {};
// Setup Squel for a particular SQL flavour
squel.useFlavour = function () {
var flavour = arguments.length <= 0 || arguments[0] === undefined ? null : arguments[0];
if (!flavour) {
return squel;
}
if (squel.flavours[flavour] instanceof Function) {
var s = _buildSquel(flavour);
squel.flavours[flavour].call(null, s);
// add in flavour methods
s.flavours = squel.flavours;
s.useFlavour = squel.useFlavour;
return s;
} else {
throw new Error('Flavour not available: ' + flavour);
}
};
return squel;
}));
|
/**
* sp-pnp-js v1.0.2 - A reusable JavaScript library targeting SharePoint client-side development.
* Copyright (c) 2016 Microsoft
* MIT
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}(g.$pnp || (g.$pnp = {})).Provisioning = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
(function (factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(["require", "exports", "../utils/util"], factory);
}
})(function (require, exports) {
"use strict";
var util_1 = require("../utils/util");
var Dictionary = (function () {
function Dictionary() {
this.keys = [];
this.values = [];
}
Dictionary.prototype.get = function (key) {
var index = this.keys.indexOf(key);
if (index < 0) {
return null;
}
return this.values[index];
};
Dictionary.prototype.add = function (key, o) {
var index = this.keys.indexOf(key);
if (index > -1) {
this.values[index] = o;
}
else {
this.keys.push(key);
this.values.push(o);
}
};
Dictionary.prototype.merge = function (source) {
if (util_1.Util.isFunction(source["getKeys"])) {
var sourceAsDictionary = source;
var keys = sourceAsDictionary.getKeys();
var l = keys.length;
for (var i = 0; i < l; i++) {
this.add(keys[i], sourceAsDictionary.get(keys[i]));
}
}
else {
var sourceAsHash = source;
for (var key in sourceAsHash) {
if (sourceAsHash.hasOwnProperty(key)) {
this.add(key, source[key]);
}
}
}
};
Dictionary.prototype.remove = function (key) {
var index = this.keys.indexOf(key);
if (index < 0) {
return null;
}
var val = this.values[index];
this.keys.splice(index, 1);
this.values.splice(index, 1);
return val;
};
Dictionary.prototype.getKeys = function () {
return this.keys;
};
Dictionary.prototype.getValues = function () {
return this.values;
};
Dictionary.prototype.clear = function () {
this.keys = [];
this.values = [];
};
Dictionary.prototype.count = function () {
return this.keys.length;
};
return Dictionary;
}());
exports.Dictionary = Dictionary;
});
},{"../utils/util":23}],2:[function(require,module,exports){
(function (factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(["require", "exports"], factory);
}
})(function (require, exports) {
"use strict";
var RuntimeConfigImpl = (function () {
function RuntimeConfigImpl() {
this._headers = null;
this._defaultCachingStore = "session";
this._defaultCachingTimeoutSeconds = 30;
this._globalCacheDisable = false;
this._useSPRequestExecutor = false;
}
RuntimeConfigImpl.prototype.set = function (config) {
if (config.hasOwnProperty("headers")) {
this._headers = config.headers;
}
if (config.hasOwnProperty("globalCacheDisable")) {
this._globalCacheDisable = config.globalCacheDisable;
}
if (config.hasOwnProperty("defaultCachingStore")) {
this._defaultCachingStore = config.defaultCachingStore;
}
if (config.hasOwnProperty("defaultCachingTimeoutSeconds")) {
this._defaultCachingTimeoutSeconds = config.defaultCachingTimeoutSeconds;
}
if (config.hasOwnProperty("useSPRequestExecutor")) {
this._useSPRequestExecutor = config.useSPRequestExecutor;
}
};
Object.defineProperty(RuntimeConfigImpl.prototype, "headers", {
get: function () {
return this._headers;
},
enumerable: true,
configurable: true
});
Object.defineProperty(RuntimeConfigImpl.prototype, "defaultCachingStore", {
get: function () {
return this._defaultCachingStore;
},
enumerable: true,
configurable: true
});
Object.defineProperty(RuntimeConfigImpl.prototype, "defaultCachingTimeoutSeconds", {
get: function () {
return this._defaultCachingTimeoutSeconds;
},
enumerable: true,
configurable: true
});
Object.defineProperty(RuntimeConfigImpl.prototype, "globalCacheDisable", {
get: function () {
return this._globalCacheDisable;
},
enumerable: true,
configurable: true
});
Object.defineProperty(RuntimeConfigImpl.prototype, "useSPRequestExecutor", {
get: function () {
return this._useSPRequestExecutor;
},
enumerable: true,
configurable: true
});
return RuntimeConfigImpl;
}());
exports.RuntimeConfigImpl = RuntimeConfigImpl;
var _runtimeConfig = new RuntimeConfigImpl();
exports.RuntimeConfig = _runtimeConfig;
function setRuntimeConfig(config) {
_runtimeConfig.set(config);
}
exports.setRuntimeConfig = setRuntimeConfig;
});
},{}],3:[function(require,module,exports){
(function (factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(["require", "exports", "./fetchClient", "./digestCache", "../utils/util", "../configuration/pnplibconfig", "./SPRequestExecutorClient"], factory);
}
})(function (require, exports) {
"use strict";
var fetchClient_1 = require("./fetchClient");
var digestCache_1 = require("./digestCache");
var util_1 = require("../utils/util");
var pnplibconfig_1 = require("../configuration/pnplibconfig");
var SPRequestExecutorClient_1 = require("./SPRequestExecutorClient");
var HttpClient = (function () {
function HttpClient() {
if (pnplibconfig_1.RuntimeConfig.useSPRequestExecutor) {
this._impl = new SPRequestExecutorClient_1.SPRequestExecutorClient();
}
else {
this._impl = new fetchClient_1.FetchClient();
}
this._digestCache = new digestCache_1.DigestCache(this);
}
HttpClient.prototype.fetch = function (url, options) {
if (options === void 0) { options = {}; }
var self = this;
var opts = util_1.Util.extend(options, { cache: "no-cache", credentials: "same-origin" }, true);
var headers = new Headers();
this.mergeHeaders(headers, pnplibconfig_1.RuntimeConfig.headers);
this.mergeHeaders(headers, options.headers);
if (!headers.has("Accept")) {
headers.append("Accept", "application/json");
}
if (!headers.has("Content-Type")) {
headers.append("Content-Type", "application/json;odata=verbose;charset=utf-8");
}
if (!headers.has("X-ClientService-ClientTag")) {
headers.append("X-ClientService-ClientTag", "SharePoint.PnP.JavaScriptCore");
}
opts = util_1.Util.extend(opts, { headers: headers });
if (opts.method && opts.method.toUpperCase() !== "GET") {
if (!headers.has("X-RequestDigest")) {
var index = url.indexOf("/_api/");
if (index < 0) {
throw new Error("Unable to determine API url");
}
var webUrl = url.substr(0, index);
return this._digestCache.getDigest(webUrl)
.then(function (digest) {
headers.append("X-RequestDigest", digest);
return self.fetchRaw(url, opts);
});
}
}
return self.fetchRaw(url, opts);
};
HttpClient.prototype.fetchRaw = function (url, options) {
var _this = this;
if (options === void 0) { options = {}; }
var retry = function (ctx) {
_this._impl.fetch(url, options).then(function (response) { return ctx.resolve(response); }).catch(function (response) {
var delay = ctx.delay;
if (response.status !== 429 && response.status !== 503) {
ctx.reject(response);
}
ctx.delay *= 2;
ctx.attempts++;
if (ctx.retryCount <= ctx.attempts) {
ctx.reject(response);
}
setTimeout(util_1.Util.getCtxCallback(_this, retry, ctx), delay);
});
};
return new Promise(function (resolve, reject) {
var retryContext = {
attempts: 0,
delay: 100,
reject: reject,
resolve: resolve,
retryCount: 7,
};
retry.call(_this, retryContext);
});
};
HttpClient.prototype.get = function (url, options) {
if (options === void 0) { options = {}; }
var opts = util_1.Util.extend(options, { method: "GET" });
return this.fetch(url, opts);
};
HttpClient.prototype.post = function (url, options) {
if (options === void 0) { options = {}; }
var opts = util_1.Util.extend(options, { method: "POST" });
return this.fetch(url, opts);
};
HttpClient.prototype.mergeHeaders = function (target, source) {
if (typeof source !== "undefined") {
var temp = new Request("", { headers: source });
temp.headers.forEach(function (value, name) {
target.append(name, value);
});
}
};
return HttpClient;
}());
exports.HttpClient = HttpClient;
});
},{"../configuration/pnplibconfig":2,"../utils/util":23,"./SPRequestExecutorClient":4,"./digestCache":5,"./fetchClient":6}],4:[function(require,module,exports){
(function (factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(["require", "exports"], factory);
}
})(function (require, exports) {
"use strict";
var SPRequestExecutorClient = (function () {
function SPRequestExecutorClient() {
this.convertToResponse = function (spResponse) {
var responseHeaders = new Headers();
for (var h in spResponse.headers) {
if (spResponse.headers[h]) {
responseHeaders.append(h, spResponse.headers[h]);
}
}
return new Response(spResponse.body, {
headers: responseHeaders,
status: spResponse.statusCode,
statusText: spResponse.statusText,
});
};
}
SPRequestExecutorClient.prototype.fetch = function (url, options) {
var _this = this;
if (typeof SP === "undefined" || typeof SP.RequestExecutor === "undefined") {
throw new Error("SP.RequestExecutor is undefined. " +
"Load the SP.RequestExecutor.js library (/_layouts/15/SP.RequestExecutor.js) before loading the PnP JS Core library.");
}
var addinWebUrl = url.substring(0, url.indexOf("/_api")), executor = new SP.RequestExecutor(addinWebUrl), headers = {}, iterator, temp;
if (options.headers && options.headers instanceof Headers) {
iterator = options.headers.entries();
temp = iterator.next();
while (!temp.done) {
headers[temp.value[0]] = temp.value[1];
temp = iterator.next();
}
}
else {
headers = options.headers;
}
return new Promise(function (resolve, reject) {
executor.executeAsync({
body: options.body,
error: function (error) {
reject(_this.convertToResponse(error));
},
headers: headers,
method: options.method,
success: function (response) {
resolve(_this.convertToResponse(response));
},
url: url,
});
});
};
return SPRequestExecutorClient;
}());
exports.SPRequestExecutorClient = SPRequestExecutorClient;
});
},{}],5:[function(require,module,exports){
(function (factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(["require", "exports", "../collections/collections", "../utils/util", "../sharepoint/rest/odata"], factory);
}
})(function (require, exports) {
"use strict";
var collections_1 = require("../collections/collections");
var util_1 = require("../utils/util");
var odata_1 = require("../sharepoint/rest/odata");
var CachedDigest = (function () {
function CachedDigest() {
}
return CachedDigest;
}());
exports.CachedDigest = CachedDigest;
var DigestCache = (function () {
function DigestCache(_httpClient, _digests) {
if (_digests === void 0) { _digests = new collections_1.Dictionary(); }
this._httpClient = _httpClient;
this._digests = _digests;
}
DigestCache.prototype.getDigest = function (webUrl) {
var self = this;
var cachedDigest = this._digests.get(webUrl);
if (cachedDigest !== null) {
var now = new Date();
if (now < cachedDigest.expiration) {
return Promise.resolve(cachedDigest.value);
}
}
var url = util_1.Util.combinePaths(webUrl, "/_api/contextinfo");
return self._httpClient.fetchRaw(url, {
cache: "no-cache",
credentials: "same-origin",
headers: {
"Accept": "application/json;odata=verbose",
"Content-type": "application/json;odata=verbose;charset=utf-8",
},
method: "POST",
}).then(function (response) {
var parser = new odata_1.ODataDefaultParser();
return parser.parse(response).then(function (d) { return d.GetContextWebInformation; });
}).then(function (data) {
var newCachedDigest = new CachedDigest();
newCachedDigest.value = data.FormDigestValue;
var seconds = data.FormDigestTimeoutSeconds;
var expiration = new Date();
expiration.setTime(expiration.getTime() + 1000 * seconds);
newCachedDigest.expiration = expiration;
self._digests.add(webUrl, newCachedDigest);
return newCachedDigest.value;
});
};
DigestCache.prototype.clear = function () {
this._digests.clear();
};
return DigestCache;
}());
exports.DigestCache = DigestCache;
});
},{"../collections/collections":1,"../sharepoint/rest/odata":21,"../utils/util":23}],6:[function(require,module,exports){
(function (global){
(function (factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(["require", "exports"], factory);
}
})(function (require, exports) {
"use strict";
var FetchClient = (function () {
function FetchClient() {
}
FetchClient.prototype.fetch = function (url, options) {
return global.fetch(url, options);
};
return FetchClient;
}());
exports.FetchClient = FetchClient;
});
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],7:[function(require,module,exports){
arguments[4][3][0].apply(exports,arguments)
},{"../configuration/pnplibconfig":2,"../utils/util":23,"./SPRequestExecutorClient":4,"./digestCache":5,"./fetchClient":6,"dup":3}],8:[function(require,module,exports){
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
(function (factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(["require", "exports", "../util", "./ObjectHandlerBase"], factory);
}
})(function (require, exports) {
"use strict";
var util_1 = require("../util");
var ObjectHandlerBase_1 = require("./ObjectHandlerBase");
var ObjectComposedLook = (function (_super) {
__extends(ObjectComposedLook, _super);
function ObjectComposedLook() {
_super.call(this, "ComposedLook");
}
ObjectComposedLook.prototype.ProvisionObjects = function (object) {
var _this = this;
_super.prototype.scope_started.call(this);
return new Promise(function (resolve, reject) {
var clientContext = SP.ClientContext.get_current();
var web = clientContext.get_web();
var colorPaletteUrl = object.ColorPaletteUrl ? util_1.Util.replaceUrlTokens(object.ColorPaletteUrl) : "";
var fontSchemeUrl = object.FontSchemeUrl ? util_1.Util.replaceUrlTokens(object.FontSchemeUrl) : "";
var backgroundImageUrl = object.BackgroundImageUrl ? util_1.Util.replaceUrlTokens(object.BackgroundImageUrl) : null;
web.applyTheme(util_1.Util.getRelativeUrl(colorPaletteUrl), util_1.Util.getRelativeUrl(fontSchemeUrl), backgroundImageUrl, true);
web.update();
clientContext.executeQueryAsync(function () {
_super.prototype.scope_ended.call(_this);
resolve();
}, function () {
_super.prototype.scope_ended.call(_this);
resolve();
});
});
};
return ObjectComposedLook;
}(ObjectHandlerBase_1.ObjectHandlerBase));
exports.ObjectComposedLook = ObjectComposedLook;
});
},{"../util":20,"./ObjectHandlerBase":12}],9:[function(require,module,exports){
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
(function (factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(["require", "exports", "./ObjectHandlerBase"], factory);
}
})(function (require, exports) {
"use strict";
var ObjectHandlerBase_1 = require("./ObjectHandlerBase");
var ObjectCustomActions = (function (_super) {
__extends(ObjectCustomActions, _super);
function ObjectCustomActions() {
_super.call(this, "CustomActions");
}
ObjectCustomActions.prototype.ProvisionObjects = function (customactions) {
var _this = this;
_super.prototype.scope_started.call(this);
return new Promise(function (resolve, reject) {
var clientContext = SP.ClientContext.get_current();
var userCustomActions = clientContext.get_web().get_userCustomActions();
clientContext.load(userCustomActions);
clientContext.executeQueryAsync(function () {
customactions.forEach(function (obj) {
var objExists = userCustomActions.get_data().filter(function (userCustomAction) {
return userCustomAction.get_title() === obj.Title;
}).length > 0;
if (!objExists) {
var objCreationInformation = userCustomActions.add();
if (obj.Description) {
objCreationInformation.set_description(obj.Description);
}
if (obj.CommandUIExtension) {
objCreationInformation.set_commandUIExtension(obj.CommandUIExtension);
}
if (obj.Group) {
objCreationInformation.set_group(obj.Group);
}
if (obj.Title) {
objCreationInformation.set_title(obj.Title);
}
if (obj.Url) {
objCreationInformation.set_url(obj.Url);
}
if (obj.ScriptBlock) {
objCreationInformation.set_scriptBlock(obj.ScriptBlock);
}
if (obj.ScriptSrc) {
objCreationInformation.set_scriptSrc(obj.ScriptSrc);
}
if (obj.Location) {
objCreationInformation.set_location(obj.Location);
}
if (obj.ImageUrl) {
objCreationInformation.set_imageUrl(obj.ImageUrl);
}
if (obj.Name) {
objCreationInformation.set_name(obj.Name);
}
if (obj.RegistrationId) {
objCreationInformation.set_registrationId(obj.RegistrationId);
}
if (obj.RegistrationType) {
objCreationInformation.set_registrationType(obj.RegistrationType);
}
if (obj.Rights) {
objCreationInformation.set_rights(obj.Rights);
}
if (obj.Sequence) {
objCreationInformation.set_sequence(obj.Sequence);
}
objCreationInformation.update();
}
});
clientContext.executeQueryAsync(function () {
_super.prototype.scope_ended.call(_this);
resolve();
}, function () {
_super.prototype.scope_ended.call(_this);
resolve();
});
}, function () {
_super.prototype.scope_ended.call(_this);
resolve();
});
});
};
return ObjectCustomActions;
}(ObjectHandlerBase_1.ObjectHandlerBase));
exports.ObjectCustomActions = ObjectCustomActions;
});
},{"./ObjectHandlerBase":12}],10:[function(require,module,exports){
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
(function (factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(["require", "exports", "./ObjectHandlerBase"], factory);
}
})(function (require, exports) {
"use strict";
var ObjectHandlerBase_1 = require("./ObjectHandlerBase");
var ObjectFeatures = (function (_super) {
__extends(ObjectFeatures, _super);
function ObjectFeatures() {
_super.call(this, "Features");
}
ObjectFeatures.prototype.ProvisionObjects = function (features) {
var _this = this;
_super.prototype.scope_started.call(this);
return new Promise(function (resolve, reject) {
var clientContext = SP.ClientContext.get_current();
var web = clientContext.get_web();
var webFeatures = web.get_features();
features.forEach(function (f) {
if (f.Deactivate === true) {
webFeatures.remove(new SP.Guid(f.ID), true);
}
else {
webFeatures.add(new SP.Guid(f.ID), true, SP.FeatureDefinitionScope.none);
}
});
web.update();
clientContext.load(webFeatures);
clientContext.executeQueryAsync(function () {
_super.prototype.scope_ended.call(_this);
resolve();
}, function () {
_super.prototype.scope_ended.call(_this);
resolve();
});
});
};
return ObjectFeatures;
}(ObjectHandlerBase_1.ObjectHandlerBase));
exports.ObjectFeatures = ObjectFeatures;
});
},{"./ObjectHandlerBase":12}],11:[function(require,module,exports){
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
(function (factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(["require", "exports", "../../../utils/util", "../util", "./ObjectHandlerBase"], factory);
}
})(function (require, exports) {
"use strict";
var CoreUtil = require("../../../utils/util");
var util_1 = require("../util");
var ObjectHandlerBase_1 = require("./ObjectHandlerBase");
var ObjectFiles = (function (_super) {
__extends(ObjectFiles, _super);
function ObjectFiles() {
_super.call(this, "Files");
}
ObjectFiles.prototype.ProvisionObjects = function (objects) {
var _this = this;
_super.prototype.scope_started.call(this);
return new Promise(function (resolve, reject) {
var clientContext = SP.ClientContext.get_current();
var web = clientContext.get_web();
var fileInfos = [];
var promises = [];
objects.forEach(function (obj, index) {
promises.push(_this.httpClient.fetchRaw(util_1.Util.replaceUrlTokens(obj.Src)).then(function (response) {
return response.text();
}));
});
Promise.all(promises).then(function (responses) {
responses.forEach(function (response, index) {
var obj = objects[index];
var filename = _this.GetFilenameFromFilePath(obj.Dest);
var webServerRelativeUrl = _spPageContextInfo.webServerRelativeUrl;
var folder = web.getFolderByServerRelativeUrl(webServerRelativeUrl + "/" + _this.GetFolderFromFilePath(obj.Dest));
var fi = {
Contents: response,
Dest: obj.Dest,
Filename: filename,
Folder: folder,
Instance: null,
Overwrite: false,
Properties: [],
RemoveExistingWebParts: true,
ServerRelativeUrl: obj.Dest,
Src: obj.Src,
Views: [],
WebParts: [],
};
CoreUtil.Util.extend(fi, obj);
if (fi.Filename.indexOf("Form.aspx") !== -1) {
return;
}
var objCreationInformation = new SP.FileCreationInformation();
objCreationInformation.set_overwrite(fi.Overwrite);
objCreationInformation.set_url(fi.Filename);
objCreationInformation.set_content(new SP.Base64EncodedByteArray());
for (var i = 0; i < fi.Contents.length; i++) {
objCreationInformation.get_content().append(fi.Contents.charCodeAt(i));
}
clientContext.load(fi.Folder.get_files().add(objCreationInformation));
fileInfos.push(fi);
});
});
clientContext.executeQueryAsync(function () {
promises = [];
fileInfos.forEach(function (fi) {
if (fi.Properties && Object.keys(fi.Properties).length > 0) {
promises.push(_this.ApplyFileProperties(fi.Dest, fi.Properties));
}
if (fi.WebParts && fi.WebParts.length > 0) {
promises.push(_this.AddWebPartsToWebPartPage(fi.Dest, fi.Src, fi.WebParts, fi.RemoveExistingWebParts));
}
});
Promise.all(promises).then(function () {
_this.ModifyHiddenViews(objects).then(function (value) {
_super.prototype.scope_ended.call(_this);
resolve(value);
}, function (error) {
_super.prototype.scope_ended.call(_this);
reject(error);
});
});
}, function (error) {
_super.prototype.scope_ended.call(_this);
reject(error);
});
});
};
ObjectFiles.prototype.RemoveWebPartsFromFileIfSpecified = function (clientContext, limitedWebPartManager, shouldRemoveExisting) {
return new Promise(function (resolve, reject) {
if (!shouldRemoveExisting) {
resolve();
}
var existingWebParts = limitedWebPartManager.get_webParts();
clientContext.load(existingWebParts);
clientContext.executeQueryAsync(function () {
existingWebParts.get_data().forEach(function (wp) {
wp.deleteWebPart();
});
clientContext.load(existingWebParts);
clientContext.executeQueryAsync(resolve, reject);
}, reject);
});
};
ObjectFiles.prototype.GetWebPartXml = function (webParts) {
var _this = this;
return new Promise(function (resolve, reject) {
var promises = [];
webParts.forEach(function (wp, index) {
if (wp.Contents.FileUrl) {
var fileUrl = util_1.Util.replaceUrlTokens(wp.Contents.FileUrl);
promises.push(_this.httpClient.fetchRaw(fileUrl).then(function (response) {
return response.text();
}));
}
else {
promises.push((function () {
return new Promise(function (res, rej) {
res();
});
})());
}
});
Promise.all(promises).then(function (responses) {
responses.forEach(function (response, index) {
var wp = webParts[index];
if (wp !== null && response && response.length > 0) {
wp.Contents.Xml = response;
}
});
resolve(webParts);
});
});
};
ObjectFiles.prototype.AddWebPartsToWebPartPage = function (dest, src, webParts, shouldRemoveExisting) {
var _this = this;
return new Promise(function (resolve, reject) {
var clientContext = SP.ClientContext.get_current();
var web = clientContext.get_web();
var fileServerRelativeUrl = _spPageContextInfo.webServerRelativeUrl + "/" + dest;
var file = web.getFileByServerRelativeUrl(fileServerRelativeUrl);
clientContext.load(file);
clientContext.executeQueryAsync(function () {
var limitedWebPartManager = file.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
_this.RemoveWebPartsFromFileIfSpecified(clientContext, limitedWebPartManager, shouldRemoveExisting).then(function () {
_this.GetWebPartXml(webParts).then(function (webPartsWithXml) {
webPartsWithXml.forEach(function (wp) {
if (!wp.Contents.Xml) {
return;
}
var oWebPartDefinition = limitedWebPartManager.importWebPart(util_1.Util.replaceUrlTokens(wp.Contents.Xml));
var oWebPart = oWebPartDefinition.get_webPart();
limitedWebPartManager.addWebPart(oWebPart, wp.Zone, wp.Order);
});
clientContext.executeQueryAsync(resolve, resolve);
});
});
}, resolve);
});
};
ObjectFiles.prototype.ApplyFileProperties = function (dest, fileProperties) {
return new Promise(function (resolve, reject) {
var clientContext = SP.ClientContext.get_current();
var web = clientContext.get_web();
var fileServerRelativeUrl = _spPageContextInfo.webServerRelativeUrl + "/" + dest;
var file = web.getFileByServerRelativeUrl(fileServerRelativeUrl);
var listItemAllFields = file.get_listItemAllFields();
Object.keys(fileProperties).forEach(function (key) {
listItemAllFields.set_item(key, fileProperties[key]);
});
listItemAllFields.update();
clientContext.executeQueryAsync(resolve, resolve);
});
};
ObjectFiles.prototype.GetViewFromCollectionByUrl = function (viewCollection, url) {
var serverRelativeUrl = _spPageContextInfo.webServerRelativeUrl + "/" + url;
var viewCollectionEnumerator = viewCollection.getEnumerator();
while (viewCollectionEnumerator.moveNext()) {
var view = viewCollectionEnumerator.get_current();
if (view.get_serverRelativeUrl().toString().toLowerCase() === serverRelativeUrl.toLowerCase()) {
return view;
}
}
return null;
};
ObjectFiles.prototype.ModifyHiddenViews = function (objects) {
var _this = this;
return new Promise(function (resolve, reject) {
var clientContext = SP.ClientContext.get_current();
var web = clientContext.get_web();
var mapping = {};
var lists = [];
var listViewCollections = [];
objects.forEach(function (obj) {
if (!obj.Views) {
return;
}
obj.Views.forEach(function (v) {
mapping[v.List] = mapping[v.List] || [];
mapping[v.List].push(CoreUtil.Util.extend(v, { "Url": obj.Dest }));
});
});
Object.keys(mapping).forEach(function (l, index) {
lists.push(web.get_lists().getByTitle(l));
listViewCollections.push(web.get_lists().getByTitle(l).get_views());
clientContext.load(lists[index]);
clientContext.load(listViewCollections[index]);
});
clientContext.executeQueryAsync(function () {
Object.keys(mapping).forEach(function (l, index) {
var views = mapping[l];
var list = lists[index];
var viewCollection = listViewCollections[index];
views.forEach(function (v) {
var view = _this.GetViewFromCollectionByUrl(viewCollection, v.Url);
if (view == null) {
return;
}
if (v.Paged) {
view.set_paged(v.Paged);
}
if (v.Query) {
view.set_viewQuery(v.Query);
}
if (v.RowLimit) {
view.set_rowLimit(v.RowLimit);
}
if (v.ViewFields && v.ViewFields.length > 0) {
var columns_1 = view.get_viewFields();
columns_1.removeAll();
v.ViewFields.forEach(function (vf) {
columns_1.add(vf);
});
}
view.update();
});
clientContext.load(viewCollection);
list.update();
});
clientContext.executeQueryAsync(resolve, resolve);
}, resolve);
});
};
ObjectFiles.prototype.GetFolderFromFilePath = function (filePath) {
var split = filePath.split("/");
return split.splice(0, split.length - 1).join("/");
};
ObjectFiles.prototype.GetFilenameFromFilePath = function (filePath) {
var split = filePath.split("/");
return split[split.length - 1];
};
return ObjectFiles;
}(ObjectHandlerBase_1.ObjectHandlerBase));
exports.ObjectFiles = ObjectFiles;
;
});
},{"../../../utils/util":23,"../util":20,"./ObjectHandlerBase":12}],12:[function(require,module,exports){
(function (factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(["require", "exports", "../../../net/HttpClient", "../../../utils/logging"], factory);
}
})(function (require, exports) {
"use strict";
var HttpClient_1 = require("../../../net/HttpClient");
var logging_1 = require("../../../utils/logging");
var ObjectHandlerBase = (function () {
function ObjectHandlerBase(name) {
this.name = name;
this.httpClient = new HttpClient_1.HttpClient();
}
ObjectHandlerBase.prototype.ProvisionObjects = function (objects, parameters) {
return new Promise(function (resolve, reject) { resolve("Not implemented."); });
};
ObjectHandlerBase.prototype.scope_started = function () {
logging_1.Logger.write(this.name + ": Code execution scope started");
};
ObjectHandlerBase.prototype.scope_ended = function () {
logging_1.Logger.write(this.name + ": Code execution scope stopped");
};
return ObjectHandlerBase;
}());
exports.ObjectHandlerBase = ObjectHandlerBase;
});
},{"../../../net/HttpClient":3,"../../../utils/logging":22}],13:[function(require,module,exports){
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
(function (factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(["require", "exports", "../Sequencer/Sequencer", "./ObjectHandlerBase"], factory);
}
})(function (require, exports) {
"use strict";
var Sequencer_1 = require("../Sequencer/Sequencer");
var ObjectHandlerBase_1 = require("./ObjectHandlerBase");
var ObjectLists = (function (_super) {
__extends(ObjectLists, _super);
function ObjectLists() {
_super.call(this, "Lists");
}
ObjectLists.prototype.ProvisionObjects = function (objects) {
var _this = this;
_super.prototype.scope_started.call(this);
return new Promise(function (resolve, reject) {
var clientContext = SP.ClientContext.get_current();
var lists = clientContext.get_web().get_lists();
var listInstances = [];
clientContext.load(lists);
clientContext.executeQueryAsync(function () {
objects.forEach(function (obj, index) {
var existingObj = lists.get_data().filter(function (list) {
return list.get_title() === obj.Title;
})[0];
if (existingObj) {
if (obj.Description) {
existingObj.set_description(obj.Description);
}
if (obj.EnableVersioning !== undefined) {
existingObj.set_enableVersioning(obj.EnableVersioning);
}
if (obj.EnableMinorVersions !== undefined) {
existingObj.set_enableMinorVersions(obj.EnableMinorVersions);
}
if (obj.EnableModeration !== undefined) {
existingObj.set_enableModeration(obj.EnableModeration);
}
if (obj.EnableFolderCreation !== undefined) {
existingObj.set_enableFolderCreation(obj.EnableFolderCreation);
}
if (obj.EnableAttachments !== undefined) {
existingObj.set_enableAttachments(obj.EnableAttachments);
}
if (obj.NoCrawl !== undefined) {
existingObj.set_noCrawl(obj.NoCrawl);
}
if (obj.DefaultDisplayFormUrl) {
existingObj.set_defaultDisplayFormUrl(obj.DefaultDisplayFormUrl);
}
if (obj.DefaultEditFormUrl) {
existingObj.set_defaultEditFormUrl(obj.DefaultEditFormUrl);
}
if (obj.DefaultNewFormUrl) {
existingObj.set_defaultNewFormUrl(obj.DefaultNewFormUrl);
}
if (obj.DraftVersionVisibility) {
existingObj.set_draftVersionVisibility(SP.DraftVisibilityType[obj.DraftVersionVisibility]);
}
if (obj.ImageUrl) {
existingObj.set_imageUrl(obj.ImageUrl);
}
if (obj.Hidden !== undefined) {
existingObj.set_hidden(obj.Hidden);
}
if (obj.ForceCheckout !== undefined) {
existingObj.set_forceCheckout(obj.ForceCheckout);
}
existingObj.update();
listInstances.push(existingObj);
clientContext.load(listInstances[index]);
}
else {
var objCreationInformation = new SP.ListCreationInformation();
if (obj.Description) {
objCreationInformation.set_description(obj.Description);
}
if (obj.OnQuickLaunch !== undefined) {
var value = obj.OnQuickLaunch ? SP.QuickLaunchOptions.on : SP.QuickLaunchOptions.off;
objCreationInformation.set_quickLaunchOption(value);
}
if (obj.TemplateType) {
objCreationInformation.set_templateType(obj.TemplateType);
}
if (obj.Title) {
objCreationInformation.set_title(obj.Title);
}
if (obj.Url) {
objCreationInformation.set_url(obj.Url);
}
var createdList = lists.add(objCreationInformation);
if (obj.EnableVersioning !== undefined) {
createdList.set_enableVersioning(obj.EnableVersioning);
}
if (obj.EnableMinorVersions !== undefined) {
createdList.set_enableMinorVersions(obj.EnableMinorVersions);
}
if (obj.EnableModeration !== undefined) {
createdList.set_enableModeration(obj.EnableModeration);
}
if (obj.EnableFolderCreation !== undefined) {
createdList.set_enableFolderCreation(obj.EnableFolderCreation);
}
if (obj.EnableAttachments !== undefined) {
createdList.set_enableAttachments(obj.EnableAttachments);
}
if (obj.NoCrawl !== undefined) {
createdList.set_noCrawl(obj.NoCrawl);
}
if (obj.DefaultDisplayFormUrl) {
createdList.set_defaultDisplayFormUrl(obj.DefaultDisplayFormUrl);
}
if (obj.DefaultEditFormUrl) {
createdList.set_defaultEditFormUrl(obj.DefaultEditFormUrl);
}
if (obj.DefaultNewFormUrl) {
createdList.set_defaultNewFormUrl(obj.DefaultNewFormUrl);
}
if (obj.DraftVersionVisibility) {
var value = SP.DraftVisibilityType[obj.DraftVersionVisibility.toLocaleLowerCase()];
createdList.set_draftVersionVisibility(value);
}
if (obj.ImageUrl) {
createdList.set_imageUrl(obj.ImageUrl);
}
if (obj.Hidden !== undefined) {
createdList.set_hidden(obj.Hidden);
}
if (obj.ForceCheckout !== undefined) {
createdList.set_forceCheckout(obj.ForceCheckout);
}
listInstances.push(createdList);
clientContext.load(listInstances[index]);
}
});
clientContext.executeQueryAsync(function () {
var sequencer = new Sequencer_1.Sequencer([
_this.ApplyContentTypeBindings,
_this.ApplyListInstanceFieldRefs,
_this.ApplyFields,
_this.ApplyLookupFields,
_this.ApplyListSecurity,
_this.CreateViews,
_this.InsertDataRows,
_this.CreateFolders,
], { ClientContext: clientContext, ListInstances: listInstances, Objects: objects }, _this);
sequencer.execute().then(function () {
_super.prototype.scope_ended.call(_this);
resolve();
});
}, function () {
_super.prototype.scope_ended.call(_this);
resolve();
});
}, function () {
_super.prototype.scope_ended.call(_this);
resolve();
});
});
};
ObjectLists.prototype.EnsureLocationBasedMetadataDefaultsReceiver = function (clientContext, list) {
var eventReceivers = list.get_eventReceivers();
var eventRecCreationInfo = new SP.EventReceiverDefinitionCreationInformation();
eventRecCreationInfo.set_receiverName("LocationBasedMetadataDefaultsReceiver ItemAdded");
eventRecCreationInfo.set_synchronization(1);
eventRecCreationInfo.set_sequenceNumber(1000);
eventRecCreationInfo.set_receiverAssembly("Microsoft.Office.DocumentManagement, Version=15.0.0.0, Culture=neutral, " +
"PublicKeyToken=71e9bce111e9429c");
eventRecCreationInfo.set_receiverClass("Microsoft.Office.DocumentManagement.LocationBasedMetadataDefaultsReceiver");
eventRecCreationInfo.set_eventType(SP.EventReceiverType.itemAdded);
eventReceivers.add(eventRecCreationInfo);
list.update();
};
ObjectLists.prototype.CreateFolders = function (params) {
var _this = this;
return new Promise(function (resolve, reject) {
params.ListInstances.forEach(function (l, index) {
var obj = params.Objects[index];
if (!obj.Folders) {
return;
}
var folderServerRelativeUrl = _spPageContextInfo.webServerRelativeUrl + "/" + obj.Url;
var rootFolder = l.get_rootFolder();
var metadataDefaults = "<MetadataDefaults>";
var setMetadataDefaults = false;
obj.Folders.forEach(function (f) {
var folderUrl = folderServerRelativeUrl + "/" + f.Name;
rootFolder.get_folders().add(folderUrl);
if (f.DefaultValues) {
var keys = Object.keys(f.DefaultValues).length;
if (keys > 0) {
metadataDefaults += "<a href='" + folderUrl + "'>";
Object.keys(f.DefaultValues).forEach(function (key) {
metadataDefaults += "<DefaultValue FieldName=\"" + key + "\">" + f.DefaultValues[key] + "</DefaultValue>";
});
metadataDefaults += "</a>";
}
setMetadataDefaults = true;
}
});
metadataDefaults += "</MetadataDefaults>";
if (setMetadataDefaults) {
var metadataDefaultsFileCreateInfo = new SP.FileCreationInformation();
metadataDefaultsFileCreateInfo.set_url(folderServerRelativeUrl + "/Forms/client_LocationBasedDefaults.html");
metadataDefaultsFileCreateInfo.set_content(new SP.Base64EncodedByteArray());
metadataDefaultsFileCreateInfo.set_overwrite(true);
for (var i = 0; i < metadataDefaults.length; i++) {
metadataDefaultsFileCreateInfo.get_content().append(metadataDefaults.charCodeAt(i));
}
rootFolder.get_files().add(metadataDefaultsFileCreateInfo);
_this.EnsureLocationBasedMetadataDefaultsReceiver(params.ClientContext, l);
}
});
params.ClientContext.executeQueryAsync(resolve, resolve);
});
};
ObjectLists.prototype.ApplyContentTypeBindings = function (params) {
return new Promise(function (resolve, reject) {
var webCts = params.ClientContext.get_site().get_rootWeb().get_contentTypes();
var listCts = [];
params.ListInstances.forEach(function (l, index) {
listCts.push(l.get_contentTypes());
params.ClientContext.load(listCts[index], "Include(Name,Id)");
if (params.Objects[index].ContentTypeBindings) {
l.set_contentTypesEnabled(true);
l.update();
}
});
params.ClientContext.load(webCts);
params.ClientContext.executeQueryAsync(function () {
params.ListInstances.forEach(function (list, index) {
var obj = params.Objects[index];
if (!obj.ContentTypeBindings) {
return;
}
var listContentTypes = listCts[index];
var existingContentTypes = new Array();
if (obj.RemoveExistingContentTypes && obj.ContentTypeBindings.length > 0) {
listContentTypes.get_data().forEach(function (ct) {
existingContentTypes.push(ct);
});
}
obj.ContentTypeBindings.forEach(function (ctb) {
listContentTypes.addExistingContentType(webCts.getById(ctb.ContentTypeId));
});
if (obj.RemoveExistingContentTypes && obj.ContentTypeBindings.length > 0) {
for (var j = 0; j < existingContentTypes.length; j++) {
var ect = existingContentTypes[j];
ect.deleteObject();
}
}
list.update();
});
params.ClientContext.executeQueryAsync(resolve, resolve);
}, resolve);
});
};
ObjectLists.prototype.ApplyListInstanceFieldRefs = function (params) {
return new Promise(function (resolve, reject) {
var siteFields = params.ClientContext.get_site().get_rootWeb().get_fields();
params.ListInstances.forEach(function (l, index) {
var obj = params.Objects[index];
if (obj.FieldRefs) {
obj.FieldRefs.forEach(function (fr) {
var field = siteFields.getByInternalNameOrTitle(fr.Name);
l.get_fields().add(field);
});
l.update();
}
});
params.ClientContext.executeQueryAsync(resolve, resolve);
});
};
ObjectLists.prototype.ApplyFields = function (params) {
var _this = this;
return new Promise(function (resolve, reject) {
params.ListInstances.forEach(function (l, index) {
var obj = params.Objects[index];
if (obj.Fields) {
obj.Fields.forEach(function (f) {
var fieldXml = _this.GetFieldXml(f, params.ListInstances, l);
var fieldType = _this.GetFieldXmlAttr(fieldXml, "Type");
if (fieldType !== "Lookup" && fieldType !== "LookupMulti") {
l.get_fields().addFieldAsXml(fieldXml, true, SP.AddFieldOptions.addToAllContentTypes);
}
});
l.update();
}
});
params.ClientContext.executeQueryAsync(resolve, resolve);
});
};
ObjectLists.prototype.ApplyLookupFields = function (params) {
var _this = this;
return new Promise(function (resolve, reject) {
params.ListInstances.forEach(function (l, index) {
var obj = params.Objects[index];
if (obj.Fields) {
obj.Fields.forEach(function (f) {
var fieldXml = _this.GetFieldXml(f, params.ListInstances, l);
if (!fieldXml) {
return;
}
var fieldType = _this.GetFieldXmlAttr(fieldXml, "Type");
if (fieldType === "Lookup" || fieldType === "LookupMulti") {
l.get_fields().addFieldAsXml(fieldXml, true, SP.AddFieldOptions.addToAllContentTypes);
}
});
l.update();
}
});
params.ClientContext.executeQueryAsync(resolve, resolve);
});
};
ObjectLists.prototype.GetFieldXmlAttr = function (fieldXml, attr) {
var regex = new RegExp(attr + '=[\'|\"](?:(.+?))[\'|\"]');
var match = regex.exec(fieldXml);
return match[1];
};
ObjectLists.prototype.GetFieldXml = function (field, lists, list) {
var fieldXml = "";
if (!field.SchemaXml) {
var properties_1 = [];
Object.keys(field).forEach(function (prop) {
var value = field[prop];
if (prop === "List") {
var targetList = lists.filter(function (v) {
return v.get_title() === value;
});
if (targetList.length > 0) {
value = "{" + targetList[0].get_id().toString() + "}";
}
else {
return null;
}
properties_1.push(prop + "=\"" + value + "\"");
}
});
fieldXml = "<Field " + properties_1.join(" ") + ">";
if (field.Type === "Calculated") {
fieldXml += "<Formula>" + field.Formula + "</Formula>";
}
fieldXml += "</Field>";
}
return fieldXml;
};
ObjectLists.prototype.ApplyListSecurity = function (params) {
return new Promise(function (resolve, reject) {
params.ListInstances.forEach(function (l, index) {
var obj = params.Objects[index];
if (!obj.Security) {
return;
}
if (obj.Security.BreakRoleInheritance) {
l.breakRoleInheritance(obj.Security.CopyRoleAssignments, obj.Security.ClearSubscopes);
l.update();
params.ClientContext.load(l.get_roleAssignments());
}
});
var web = params.ClientContext.get_web();
var allProperties = web.get_allProperties();
var siteGroups = web.get_siteGroups();
var roleDefinitions = web.get_roleDefinitions();
params.ClientContext.load(allProperties);
params.ClientContext.load(roleDefinitions);
params.ClientContext.executeQueryAsync(function () {
params.ListInstances.forEach(function (l, index) {
var obj = params.Objects[index];
if (!obj.Security) {
return;
}
obj.Security.RoleAssignments.forEach(function (ra) {
var roleDef = null;
if (typeof ra.RoleDefinition === "number") {
roleDef = roleDefinitions.getById(ra.RoleDefinition);
}
else {
roleDef = roleDefinitions.getByName(ra.RoleDefinition);
}
var roleBindings = SP.RoleDefinitionBindingCollection.newObject(params.ClientContext);
roleBindings.add(roleDef);
var principal = null;
if (ra.Principal.match(/\{[A-Za-z]*\}+/g)) {
var token = ra.Principal.substring(1, ra.Principal.length - 1);
var groupId = allProperties.get_fieldValues()[("vti_" + token)];
principal = siteGroups.getById(groupId);
}
else {
principal = siteGroups.getByName(principal);
}
l.get_roleAssignments().add(principal, roleBindings);
});
l.update();
});
params.ClientContext.executeQueryAsync(resolve, resolve);
}, resolve);
});
};
ObjectLists.prototype.CreateViews = function (params) {
return new Promise(function (resolve, reject) {
var listViewCollections = [];
params.ListInstances.forEach(function (l, index) {
listViewCollections.push(l.get_views());
params.ClientContext.load(listViewCollections[index]);
});
params.ClientContext.executeQueryAsync(function () {
params.ListInstances.forEach(function (l, index) {
var obj = params.Objects[index];
if (!obj.Views) {
return;
}
listViewCollections.push(l.get_views());
params.ClientContext.load(listViewCollections[index]);
obj.Views.forEach(function (v) {
var viewExists = listViewCollections[index].get_data().filter(function (ev) {
if (obj.RemoveExistingViews && obj.Views.length > 0) {
ev.deleteObject();
return false;
}
return ev.get_title() === v.Title;
}).length > 0;
if (viewExists) {
var view = listViewCollections[index].getByTitle(v.Title);
if (v.Paged) {
view.set_paged(v.Paged);
}
if (v.Query) {
view.set_viewQuery(v.Query);
}
if (v.RowLimit) {
view.set_rowLimit(v.RowLimit);
}
if (v.ViewFields && v.ViewFields.length > 0) {
var columns_1 = view.get_viewFields();
columns_1.removeAll();
v.ViewFields.forEach(function (vf) {
columns_1.add(vf);
});
}
if (v.Scope) {
view.set_scope(v.Scope);
}
view.update();
}
else {
var viewCreationInformation = new SP.ViewCreationInformation();
if (v.Title) {
viewCreationInformation.set_title(v.Title);
}
if (v.PersonalView) {
viewCreationInformation.set_personalView(v.PersonalView);
}
if (v.Paged) {
viewCreationInformation.set_paged(v.Paged);
}
if (v.Query) {
viewCreationInformation.set_query(v.Query);
}
if (v.RowLimit) {
viewCreationInformation.set_rowLimit(v.RowLimit);
}
if (v.SetAsDefaultView) {
viewCreationInformation.set_setAsDefaultView(v.SetAsDefaultView);
}
if (v.ViewFields) {
viewCreationInformation.set_viewFields(v.ViewFields);
}
if (v.ViewTypeKind) {
viewCreationInformation.set_viewTypeKind(SP.ViewType.html);
}
var view = l.get_views().add(viewCreationInformation);
if (v.Scope) {
view.set_scope(v.Scope);
view.update();
}
l.update();
}
params.ClientContext.load(l.get_views());
});
});
params.ClientContext.executeQueryAsync(resolve, resolve);
}, resolve);
});
};
ObjectLists.prototype.InsertDataRows = function (params) {
return new Promise(function (resolve, reject) {
params.ListInstances.forEach(function (l, index) {
var obj = params.Objects[index];
if (obj.DataRows) {
obj.DataRows.forEach(function (r) {
var item = l.addItem(new SP.ListItemCreationInformation());
Object.keys(r).forEach(function (key) {
item.set_item(key, r[key]);
});
item.update();
params.ClientContext.load(item);
});
}
});
params.ClientContext.executeQueryAsync(resolve, resolve);
});
};
return ObjectLists;
}(ObjectHandlerBase_1.ObjectHandlerBase));
exports.ObjectLists = ObjectLists;
});
},{"../Sequencer/Sequencer":18,"./ObjectHandlerBase":12}],14:[function(require,module,exports){
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
(function (factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(["require", "exports", "../util", "./ObjectHandlerBase"], factory);
}
})(function (require, exports) {
"use strict";
var util_1 = require("../util");
var ObjectHandlerBase_1 = require("./ObjectHandlerBase");
var ObjectNavigation = (function (_super) {
__extends(ObjectNavigation, _super);
function ObjectNavigation() {
_super.call(this, "Navigation");
}
ObjectNavigation.prototype.ProvisionObjects = function (object) {
var _this = this;
_super.prototype.scope_started.call(this);
var clientContext = SP.ClientContext.get_current();
var navigation = clientContext.get_web().get_navigation();
return new Promise(function (resolve, reject) {
_this.ConfigureQuickLaunch(object.QuickLaunch, clientContext, _this.httpClient, navigation).then(function () {
_super.prototype.scope_ended.call(_this);
resolve();
}, function () {
_super.prototype.scope_ended.call(_this);
reject();
});
});
};
ObjectNavigation.prototype.getNodeFromCollectionByTitle = function (nodeCollection, title) {
var f = nodeCollection.filter(function (val) {
return val.get_title() === title;
});
return f[0] || null;
};
;
ObjectNavigation.prototype.ConfigureQuickLaunch = function (nodes, clientContext, httpClient, navigation) {
var _this = this;
return new Promise(function (resolve, reject) {
if (nodes.length === 0) {
resolve();
}
else {
var quickLaunchNodeCollection_1 = navigation.get_quickLaunch();
clientContext.load(quickLaunchNodeCollection_1);
clientContext.executeQueryAsync(function () {
var temporaryQuickLaunch = [];
var index = quickLaunchNodeCollection_1.get_count() - 1;
while (index >= 0) {
var oldNode = quickLaunchNodeCollection_1.itemAt(index);
temporaryQuickLaunch.push(oldNode);
oldNode.deleteObject();
index--;
}
clientContext.executeQueryAsync(function () {
nodes.forEach(function (n) {
var existingNode = _this.getNodeFromCollectionByTitle(temporaryQuickLaunch, n.Title);
var newNode = new SP.NavigationNodeCreationInformation();
newNode.set_title(n.Title);
newNode.set_url(existingNode ? existingNode.get_url() : util_1.Util.replaceUrlTokens(n.Url));
newNode.set_asLastNode(true);
quickLaunchNodeCollection_1.add(newNode);
});
clientContext.executeQueryAsync(function () {
httpClient.get(_spPageContextInfo.webAbsoluteUrl + "/_api/web/Navigation/QuickLaunch").then(function (response) {
response.json().then(function (json) {
json.value.forEach(function (d) {
var node = navigation.getNodeById(d.Id);
var childrenNodeCollection = node.get_children();
var parentNode = nodes.filter(function (value) { return value.Title === d.Title; })[0];
if (parentNode && parentNode.Children) {
parentNode.Children.forEach(function (n) {
var existingNode = _this.getNodeFromCollectionByTitle(temporaryQuickLaunch, n.Title);
var newNode = new SP.NavigationNodeCreationInformation();
newNode.set_title(n.Title);
newNode.set_url(existingNode
? existingNode.get_url()
: util_1.Util.replaceUrlTokens(n.Url));
newNode.set_asLastNode(true);
childrenNodeCollection.add(newNode);
});
}
});
clientContext.executeQueryAsync(resolve, resolve);
});
});
}, resolve);
});
});
}
});
};
return ObjectNavigation;
}(ObjectHandlerBase_1.ObjectHandlerBase));
exports.ObjectNavigation = ObjectNavigation;
});
},{"../util":20,"./ObjectHandlerBase":12}],15:[function(require,module,exports){
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
(function (factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(["require", "exports", "../util", "./ObjectHandlerBase"], factory);
}
})(function (require, exports) {
"use strict";
var util_1 = require("../util");
var ObjectHandlerBase_1 = require("./ObjectHandlerBase");
var ObjectPropertyBagEntries = (function (_super) {
__extends(ObjectPropertyBagEntries, _super);
function ObjectPropertyBagEntries() {
_super.call(this, "PropertyBagEntries");
}
ObjectPropertyBagEntries.prototype.ProvisionObjects = function (entries) {
var _this = this;
_super.prototype.scope_started.call(this);
return new Promise(function (resolve, reject) {
if (!entries || entries.length === 0) {
resolve();
}
else {
var clientContext_1 = SP.ClientContext.get_current();
var web_1 = clientContext_1.get_web();
var propBag_1 = web_1.get_allProperties();
var indexedProperties_1 = [];
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
propBag_1.set_item(entry.Key, entry.Value);
if (entry.Indexed) {
indexedProperties_1.push(util_1.Util.encodePropertyKey(entry.Key));
}
;
}
;
web_1.update();
clientContext_1.load(propBag_1);
clientContext_1.executeQueryAsync(function () {
if (indexedProperties_1.length > 0) {
propBag_1.set_item("vti_indexedpropertykeys", indexedProperties_1.join("|"));
web_1.update();
clientContext_1.executeQueryAsync(function () {
_super.prototype.scope_ended.call(_this);
resolve();
}, function () {
_super.prototype.scope_ended.call(_this);
resolve();
});
}
else {
_super.prototype.scope_ended.call(_this);
resolve();
}
}, function () {
_super.prototype.scope_ended.call(_this);
resolve();
});
}
});
};
return ObjectPropertyBagEntries;
}(ObjectHandlerBase_1.ObjectHandlerBase));
exports.ObjectPropertyBagEntries = ObjectPropertyBagEntries;
});
},{"../util":20,"./ObjectHandlerBase":12}],16:[function(require,module,exports){
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
(function (factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(["require", "exports", "./ObjectHandlerBase"], factory);
}
})(function (require, exports) {
"use strict";
var ObjectHandlerBase_1 = require("./ObjectHandlerBase");
var ObjectWebSettings = (function (_super) {
__extends(ObjectWebSettings, _super);
function ObjectWebSettings() {
_super.call(this, "WebSettings");
}
ObjectWebSettings.prototype.ProvisionObjects = function (object) {
var _this = this;
_super.prototype.scope_started.call(this);
return new Promise(function (resolve, reject) {
var clientContext = SP.ClientContext.get_current();
var web = clientContext.get_web();
if (object.WelcomePage) {
web.get_rootFolder().set_welcomePage(object.WelcomePage);
web.get_rootFolder().update();
}
if (object.MasterUrl) {
web.set_masterUrl(object.MasterUrl);
}
if (object.CustomMasterUrl) {
web.set_customMasterUrl(object.CustomMasterUrl);
}
if (object.SaveSiteAsTemplateEnabled !== undefined) {
web.set_saveSiteAsTemplateEnabled(object.SaveSiteAsTemplateEnabled);
}
if (object.QuickLaunchEnabled !== undefined) {
web.set_saveSiteAsTemplateEnabled(object.QuickLaunchEnabled);
}
if (object.TreeViewEnabled !== undefined) {
web.set_treeViewEnabled(object.TreeViewEnabled);
}
web.update();
clientContext.load(web);
clientContext.executeQueryAsync(function () {
_super.prototype.scope_ended.call(_this);
resolve();
}, function () {
_super.prototype.scope_ended.call(_this);
resolve();
});
});
};
return ObjectWebSettings;
}(ObjectHandlerBase_1.ObjectHandlerBase));
exports.ObjectWebSettings = ObjectWebSettings;
});
},{"./ObjectHandlerBase":12}],17:[function(require,module,exports){
(function (factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(["require", "exports"], factory);
}
})(function (require, exports) {
"use strict";
var ProvisioningStep = (function () {
function ProvisioningStep(name, index, objects, parameters, handler) {
this.name = name;
this.index = index;
this.objects = objects;
this.parameters = parameters;
this.handler = handler;
}
ProvisioningStep.prototype.execute = function (dependentPromise) {
var _this = this;
var _handler = new this.handler();
if (!dependentPromise) {
return _handler.ProvisionObjects(this.objects, this.parameters);
}
return new Promise(function (resolve, reject) {
dependentPromise.then(function () {
return _handler.ProvisionObjects(_this.objects, _this.parameters).then(resolve, resolve);
});
});
};
return ProvisioningStep;
}());
exports.ProvisioningStep = ProvisioningStep;
});
},{}],18:[function(require,module,exports){
(function (factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(["require", "exports"], factory);
}
})(function (require, exports) {
"use strict";
var Sequencer = (function () {
function Sequencer(functions, parameter, scope) {
this.functions = functions;
this.parameter = parameter;
this.scope = scope;
}
Sequencer.prototype.execute = function (progressFunction) {
var promiseSequence = Promise.resolve();
this.functions.forEach(function (sequenceFunction, functionNr) {
promiseSequence = promiseSequence.then(function () {
return sequenceFunction.call(this.scope, this.parameter);
}).then(function (result) {
if (progressFunction) {
progressFunction.call(this, functionNr, this.functions);
}
});
}, this);
return promiseSequence;
};
return Sequencer;
}());
exports.Sequencer = Sequencer;
});
},{}],19:[function(require,module,exports){
(function (factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(["require", "exports", "./ProvisioningStep", "./ObjectHandlers/ObjectNavigation", "./ObjectHandlers/ObjectPropertyBagEntries", "./ObjectHandlers/ObjectFeatures", "./ObjectHandlers/ObjectWebSettings", "./ObjectHandlers/ObjectComposedLook", "./ObjectHandlers/ObjectCustomActions", "./ObjectHandlers/ObjectFiles", "./ObjectHandlers/ObjectLists", "./util", "../../utils/logging", "../../net/HttpClient"], factory);
}
})(function (require, exports) {
"use strict";
var ProvisioningStep_1 = require("./ProvisioningStep");
var ObjectNavigation_1 = require("./ObjectHandlers/ObjectNavigation");
var ObjectPropertyBagEntries_1 = require("./ObjectHandlers/ObjectPropertyBagEntries");
var ObjectFeatures_1 = require("./ObjectHandlers/ObjectFeatures");
var ObjectWebSettings_1 = require("./ObjectHandlers/ObjectWebSettings");
var ObjectComposedLook_1 = require("./ObjectHandlers/ObjectComposedLook");
var ObjectCustomActions_1 = require("./ObjectHandlers/ObjectCustomActions");
var ObjectFiles_1 = require("./ObjectHandlers/ObjectFiles");
var ObjectLists_1 = require("./ObjectHandlers/ObjectLists");
var util_1 = require("./util");
var logging_1 = require("../../utils/logging");
var HttpClient_1 = require("../../net/HttpClient");
var Provisioning = (function () {
function Provisioning() {
this.handlers = {
"Navigation": ObjectNavigation_1.ObjectNavigation,
"PropertyBagEntries": ObjectPropertyBagEntries_1.ObjectPropertyBagEntries,
"Features": ObjectFeatures_1.ObjectFeatures,
"WebSettings": ObjectWebSettings_1.ObjectWebSettings,
"ComposedLook": ObjectComposedLook_1.ObjectComposedLook,
"CustomActions": ObjectCustomActions_1.ObjectCustomActions,
"Files": ObjectFiles_1.ObjectFiles,
"Lists": ObjectLists_1.ObjectLists,
};
this.httpClient = new HttpClient_1.HttpClient();
}
Provisioning.prototype.applyTemplate = function (path) {
var _this = this;
var url = util_1.Util.replaceUrlTokens(path);
return new Promise(function (resolve, reject) {
_this.httpClient.get(url).then(function (response) {
if (response.ok) {
response.json().then(function (template) {
_this.start(template, Object.keys(template)).then(resolve, reject);
});
}
else {
reject(response.statusText);
}
}, function (error) {
logging_1.Logger.write("Provisioning: The provided template is invalid", logging_1.Logger.LogLevel.Error);
});
});
};
Provisioning.prototype.start = function (json, queue) {
var _this = this;
return new Promise(function (resolve, reject) {
_this.startTime = new Date().getTime();
_this.queueItems = [];
queue.forEach(function (q, index) {
if (!_this.handlers[q]) {
return;
}
_this.queueItems.push(new ProvisioningStep_1.ProvisioningStep(q, index, json[q], json.Parameters, _this.handlers[q]));
});
var promises = [];
promises.push(new Promise(function (res) {
logging_1.Logger.write("Provisioning: Code execution scope started", logging_1.Logger.LogLevel.Info);
res();
}));
var index = 1;
while (_this.queueItems[index - 1] !== undefined) {
var i = promises.length - 1;
promises.push(_this.queueItems[index - 1].execute(promises[i]));
index++;
}
;
Promise.all(promises).then(function (value) {
logging_1.Logger.write("Provisioning: Code execution scope ended", logging_1.Logger.LogLevel.Info);
resolve(value);
}, function (error) {
logging_1.Logger.write("Provisioning: Code execution scope ended" + JSON.stringify(error), logging_1.Logger.LogLevel.Error);
reject(error);
});
});
};
return Provisioning;
}());
exports.Provisioning = Provisioning;
});
},{"../../net/HttpClient":3,"../../utils/logging":22,"./ObjectHandlers/ObjectComposedLook":8,"./ObjectHandlers/ObjectCustomActions":9,"./ObjectHandlers/ObjectFeatures":10,"./ObjectHandlers/ObjectFiles":11,"./ObjectHandlers/ObjectLists":13,"./ObjectHandlers/ObjectNavigation":14,"./ObjectHandlers/ObjectPropertyBagEntries":15,"./ObjectHandlers/ObjectWebSettings":16,"./ProvisioningStep":17,"./util":20}],20:[function(require,module,exports){
(function (factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(["require", "exports"], factory);
}
})(function (require, exports) {
"use strict";
var Util = (function () {
function Util() {
}
Util.getRelativeUrl = function (url) {
return url.replace(document.location.protocol + "//" + document.location.hostname, "");
};
Util.replaceUrlTokens = function (url) {
return url.replace(/{site}/g, _spPageContextInfo.webAbsoluteUrl)
.replace(/{sitecollection}/g, _spPageContextInfo.siteAbsoluteUrl)
.replace(/{themegallery}/g, _spPageContextInfo.siteAbsoluteUrl + "/_catalogs/theme/15");
};
;
Util.encodePropertyKey = function (propKey) {
var bytes = [];
for (var i = 0; i < propKey.length; ++i) {
bytes.push(propKey.charCodeAt(i));
bytes.push(0);
}
var b64encoded = window.btoa(String.fromCharCode.apply(null, bytes));
return b64encoded;
};
return Util;
}());
exports.Util = Util;
});
},{}],21:[function(require,module,exports){
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
(function (factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(["require", "exports", "../../utils/util", "../../utils/logging", "../../net/httpclient", "../../configuration/pnplibconfig"], factory);
}
})(function (require, exports) {
"use strict";
var util_1 = require("../../utils/util");
var logging_1 = require("../../utils/logging");
var httpclient_1 = require("../../net/httpclient");
var pnplibconfig_1 = require("../../configuration/pnplibconfig");
var ODataParserBase = (function () {
function ODataParserBase() {
}
ODataParserBase.prototype.parse = function (r) {
return r.json().then(function (json) {
if (json.hasOwnProperty("d")) {
if (json.d.hasOwnProperty("results")) {
return json.d.results;
}
return json.d;
}
else if (json.hasOwnProperty("value")) {
return json.value;
}
return json;
});
};
return ODataParserBase;
}());
exports.ODataParserBase = ODataParserBase;
var ODataDefaultParser = (function (_super) {
__extends(ODataDefaultParser, _super);
function ODataDefaultParser() {
_super.apply(this, arguments);
}
return ODataDefaultParser;
}(ODataParserBase));
exports.ODataDefaultParser = ODataDefaultParser;
var ODataRawParserImpl = (function () {
function ODataRawParserImpl() {
}
ODataRawParserImpl.prototype.parse = function (r) {
return r.json();
};
return ODataRawParserImpl;
}());
exports.ODataRawParserImpl = ODataRawParserImpl;
var ODataValueParserImpl = (function (_super) {
__extends(ODataValueParserImpl, _super);
function ODataValueParserImpl() {
_super.apply(this, arguments);
}
ODataValueParserImpl.prototype.parse = function (r) {
return _super.prototype.parse.call(this, r).then(function (d) { return d; });
};
return ODataValueParserImpl;
}(ODataParserBase));
var ODataEntityParserImpl = (function (_super) {
__extends(ODataEntityParserImpl, _super);
function ODataEntityParserImpl(factory) {
_super.call(this);
this.factory = factory;
}
ODataEntityParserImpl.prototype.parse = function (r) {
var _this = this;
return _super.prototype.parse.call(this, r).then(function (d) {
var o = new _this.factory(getEntityUrl(d), null);
return util_1.Util.extend(o, d);
});
};
return ODataEntityParserImpl;
}(ODataParserBase));
var ODataEntityArrayParserImpl = (function (_super) {
__extends(ODataEntityArrayParserImpl, _super);
function ODataEntityArrayParserImpl(factory) {
_super.call(this);
this.factory = factory;
}
ODataEntityArrayParserImpl.prototype.parse = function (r) {
var _this = this;
return _super.prototype.parse.call(this, r).then(function (d) {
return d.map(function (v) {
var o = new _this.factory(getEntityUrl(v), null);
return util_1.Util.extend(o, v);
});
});
};
return ODataEntityArrayParserImpl;
}(ODataParserBase));
function getEntityUrl(entity) {
if (entity.hasOwnProperty("__metadata")) {
return entity.__metadata.uri;
}
else if (entity.hasOwnProperty("odata.editLink")) {
return util_1.Util.combinePaths("_api", entity["odata.editLink"]);
}
else {
logging_1.Logger.write("No uri information found in ODataEntity parsing, chaining will fail for this object.", logging_1.Logger.LogLevel.Warning);
return "";
}
}
exports.ODataRaw = new ODataRawParserImpl();
function ODataValue() {
return new ODataValueParserImpl();
}
exports.ODataValue = ODataValue;
function ODataEntity(factory) {
return new ODataEntityParserImpl(factory);
}
exports.ODataEntity = ODataEntity;
function ODataEntityArray(factory) {
return new ODataEntityArrayParserImpl(factory);
}
exports.ODataEntityArray = ODataEntityArray;
var ODataBatch = (function () {
function ODataBatch(_batchId) {
if (_batchId === void 0) { _batchId = util_1.Util.getGUID(); }
this._batchId = _batchId;
this._requests = [];
this._batchDepCount = 0;
}
ODataBatch.prototype.add = function (url, method, options, parser) {
var info = {
method: method.toUpperCase(),
options: options,
parser: parser,
reject: null,
resolve: null,
url: url,
};
var p = new Promise(function (resolve, reject) {
info.resolve = resolve;
info.reject = reject;
});
this._requests.push(info);
return p;
};
ODataBatch.prototype.incrementBatchDep = function () {
this._batchDepCount++;
};
ODataBatch.prototype.decrementBatchDep = function () {
this._batchDepCount--;
};
ODataBatch.prototype.execute = function () {
var _this = this;
if (this._batchDepCount > 0) {
setTimeout(function () { return _this.execute(); }, 100);
}
else {
this.executeImpl();
}
};
ODataBatch.prototype.executeImpl = function () {
var _this = this;
if (this._requests.length < 1) {
return;
}
var batchBody = [];
var currentChangeSetId = "";
this._requests.forEach(function (reqInfo, index) {
if (reqInfo.method === "GET") {
if (currentChangeSetId.length > 0) {
batchBody.push("--changeset_" + currentChangeSetId + "--\n\n");
currentChangeSetId = "";
}
batchBody.push("--batch_" + _this._batchId + "\n");
}
else {
if (currentChangeSetId.length < 1) {
currentChangeSetId = util_1.Util.getGUID();
batchBody.push("--batch_" + _this._batchId + "\n");
batchBody.push("Content-Type: multipart/mixed; boundary=\"changeset_" + currentChangeSetId + "\"\n\n");
}
batchBody.push("--changeset_" + currentChangeSetId + "\n");
}
batchBody.push("Content-Type: application/http\n");
batchBody.push("Content-Transfer-Encoding: binary\n\n");
var headers = {
"Accept": "application/json;",
};
if (reqInfo.method !== "GET") {
var method = reqInfo.method;
if (reqInfo.options && reqInfo.options.headers && reqInfo.options.headers["X-HTTP-Method"] !== typeof undefined) {
method = reqInfo.options.headers["X-HTTP-Method"];
delete reqInfo.options.headers["X-HTTP-Method"];
}
batchBody.push(method + " " + reqInfo.url + " HTTP/1.1\n");
headers = util_1.Util.extend(headers, { "Content-Type": "application/json;odata=verbose;charset=utf-8" });
}
else {
batchBody.push(reqInfo.method + " " + reqInfo.url + " HTTP/1.1\n");
}
if (typeof pnplibconfig_1.RuntimeConfig.headers !== "undefined") {
headers = util_1.Util.extend(headers, pnplibconfig_1.RuntimeConfig.headers);
}
if (reqInfo.options && reqInfo.options.headers) {
headers = util_1.Util.extend(headers, reqInfo.options.headers);
}
for (var name_1 in headers) {
if (headers.hasOwnProperty(name_1)) {
batchBody.push(name_1 + ": " + headers[name_1] + "\n");
}
}
batchBody.push("\n");
if (reqInfo.options.body) {
batchBody.push(reqInfo.options.body + "\n\n");
}
});
if (currentChangeSetId.length > 0) {
batchBody.push("--changeset_" + currentChangeSetId + "--\n\n");
currentChangeSetId = "";
}
batchBody.push("--batch_" + this._batchId + "--\n");
var batchHeaders = new Headers();
batchHeaders.append("Content-Type", "multipart/mixed; boundary=batch_" + this._batchId);
var batchOptions = {
"body": batchBody.join(""),
"headers": batchHeaders,
};
var client = new httpclient_1.HttpClient();
client.post(util_1.Util.makeUrlAbsolute("/_api/$batch"), batchOptions)
.then(function (r) { return r.text(); })
.then(this._parseResponse)
.then(function (responses) {
if (responses.length !== _this._requests.length) {
throw new Error("Could not properly parse responses to match requests in batch.");
}
for (var i = 0; i < responses.length; i++) {
var request = _this._requests[i];
var response = responses[i];
if (!response.ok) {
request.reject(new Error(response.statusText));
}
request.parser.parse(response).then(request.resolve).catch(request.reject);
}
});
};
ODataBatch.prototype._parseResponse = function (body) {
return new Promise(function (resolve, reject) {
var responses = [];
var header = "--batchresponse_";
var statusRegExp = new RegExp("^HTTP/[0-9.]+ +([0-9]+) +(.*)", "i");
var lines = body.split("\n");
var state = "batch";
var status;
var statusText;
for (var i = 0; i < lines.length; ++i) {
var line = lines[i];
switch (state) {
case "batch":
if (line.substr(0, header.length) === header) {
state = "batchHeaders";
}
else {
if (line.trim() !== "") {
throw new Error("Invalid response, line " + i);
}
}
break;
case "batchHeaders":
if (line.trim() === "") {
state = "status";
}
break;
case "status":
var parts = statusRegExp.exec(line);
if (parts.length !== 3) {
throw new Error("Invalid status, line " + i);
}
status = parseInt(parts[1], 10);
statusText = parts[2];
state = "statusHeaders";
break;
case "statusHeaders":
if (line.trim() === "") {
state = "body";
}
break;
case "body":
var response = void 0;
if (status === 204) {
response = new Response();
}
else {
response = new Response(line, { status: status, statusText: statusText });
}
responses.push(response);
state = "batch";
break;
}
}
if (state !== "status") {
reject(new Error("Unexpected end of input"));
}
resolve(responses);
});
};
return ODataBatch;
}());
exports.ODataBatch = ODataBatch;
});
},{"../../configuration/pnplibconfig":2,"../../net/httpclient":7,"../../utils/logging":22,"../../utils/util":23}],22:[function(require,module,exports){
(function (factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(["require", "exports"], factory);
}
})(function (require, exports) {
"use strict";
var Logger = (function () {
function Logger() {
}
Object.defineProperty(Logger, "activeLogLevel", {
get: function () {
return Logger.instance.activeLogLevel;
},
set: function (value) {
Logger.instance.activeLogLevel = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Logger, "instance", {
get: function () {
if (typeof Logger._instance === "undefined" || Logger._instance === null) {
Logger._instance = new LoggerImpl();
}
return Logger._instance;
},
enumerable: true,
configurable: true
});
Logger.subscribe = function () {
var listeners = [];
for (var _i = 0; _i < arguments.length; _i++) {
listeners[_i - 0] = arguments[_i];
}
for (var i = 0; i < listeners.length; i++) {
Logger.instance.subscribe(listeners[i]);
}
};
Logger.clearSubscribers = function () {
return Logger.instance.clearSubscribers();
};
Object.defineProperty(Logger, "count", {
get: function () {
return Logger.instance.count;
},
enumerable: true,
configurable: true
});
Logger.write = function (message, level) {
if (level === void 0) { level = Logger.LogLevel.Verbose; }
Logger.instance.log({ level: level, message: message });
};
Logger.log = function (entry) {
Logger.instance.log(entry);
};
Logger.measure = function (name, f) {
return Logger.instance.measure(name, f);
};
return Logger;
}());
exports.Logger = Logger;
var LoggerImpl = (function () {
function LoggerImpl(activeLogLevel, subscribers) {
if (activeLogLevel === void 0) { activeLogLevel = Logger.LogLevel.Warning; }
if (subscribers === void 0) { subscribers = []; }
this.activeLogLevel = activeLogLevel;
this.subscribers = subscribers;
}
LoggerImpl.prototype.subscribe = function (listener) {
this.subscribers.push(listener);
};
LoggerImpl.prototype.clearSubscribers = function () {
var s = this.subscribers.slice(0);
this.subscribers.length = 0;
return s;
};
Object.defineProperty(LoggerImpl.prototype, "count", {
get: function () {
return this.subscribers.length;
},
enumerable: true,
configurable: true
});
LoggerImpl.prototype.write = function (message, level) {
if (level === void 0) { level = Logger.LogLevel.Verbose; }
this.log({ level: level, message: message });
};
LoggerImpl.prototype.log = function (entry) {
if (typeof entry === "undefined" || entry.level < this.activeLogLevel) {
return;
}
for (var i = 0; i < this.subscribers.length; i++) {
this.subscribers[i].log(entry);
}
};
LoggerImpl.prototype.measure = function (name, f) {
console.profile(name);
try {
return f();
}
finally {
console.profileEnd();
}
};
return LoggerImpl;
}());
var Logger;
(function (Logger) {
(function (LogLevel) {
LogLevel[LogLevel["Verbose"] = 0] = "Verbose";
LogLevel[LogLevel["Info"] = 1] = "Info";
LogLevel[LogLevel["Warning"] = 2] = "Warning";
LogLevel[LogLevel["Error"] = 3] = "Error";
LogLevel[LogLevel["Off"] = 99] = "Off";
})(Logger.LogLevel || (Logger.LogLevel = {}));
var LogLevel = Logger.LogLevel;
var ConsoleListener = (function () {
function ConsoleListener() {
}
ConsoleListener.prototype.log = function (entry) {
var msg = this.format(entry);
switch (entry.level) {
case LogLevel.Verbose:
case LogLevel.Info:
console.log(msg);
break;
case LogLevel.Warning:
console.warn(msg);
break;
case LogLevel.Error:
console.error(msg);
break;
}
};
ConsoleListener.prototype.format = function (entry) {
return "Message: " + entry.message + ". Data: " + JSON.stringify(entry.data);
};
return ConsoleListener;
}());
Logger.ConsoleListener = ConsoleListener;
var AzureInsightsListener = (function () {
function AzureInsightsListener(azureInsightsInstrumentationKey) {
this.azureInsightsInstrumentationKey = azureInsightsInstrumentationKey;
var appInsights = window["appInsights"] || function (config) {
function r(config) {
t[config] = function () {
var i = arguments;
t.queue.push(function () { t[config].apply(t, i); });
};
}
var t = { config: config }, u = document, e = window, o = "script", s = u.createElement(o), i, f;
for (s.src = config.url || "//az416426.vo.msecnd.net/scripts/a/ai.0.js", u.getElementsByTagName(o)[0].parentNode.appendChild(s), t.cookie = u.cookie, t.queue = [], i = ["Event", "Exception", "Metric", "PageView", "Trace"]; i.length;) {
r("track" + i.pop());
}
return r("setAuthenticatedUserContext"), r("clearAuthenticatedUserContext"), config.disableExceptionTracking || (i = "onerror", r("_" + i), f = e[i], e[i] = function (config, r, u, e, o) {
var s = f && f(config, r, u, e, o);
return s !== !0 && t["_" + i](config, r, u, e, o), s;
}), t;
}({
instrumentationKey: this.azureInsightsInstrumentationKey
});
window["appInsights"] = appInsights;
}
AzureInsightsListener.prototype.log = function (entry) {
var ai = window["appInsights"];
var msg = this.format(entry);
if (entry.level === LogLevel.Error) {
ai.trackException(msg);
}
else {
ai.trackEvent(msg);
}
};
AzureInsightsListener.prototype.format = function (entry) {
return "Message: " + entry.message + ". Data: " + JSON.stringify(entry.data);
};
return AzureInsightsListener;
}());
Logger.AzureInsightsListener = AzureInsightsListener;
var FunctionListener = (function () {
function FunctionListener(method) {
this.method = method;
}
FunctionListener.prototype.log = function (entry) {
this.method(entry);
};
return FunctionListener;
}());
Logger.FunctionListener = FunctionListener;
})(Logger = exports.Logger || (exports.Logger = {}));
});
},{}],23:[function(require,module,exports){
(function (factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(["require", "exports"], factory);
}
})(function (require, exports) {
"use strict";
var Util = (function () {
function Util() {
}
Util.getCtxCallback = function (context, method) {
var params = [];
for (var _i = 2; _i < arguments.length; _i++) {
params[_i - 2] = arguments[_i];
}
return function () {
method.apply(context, params);
};
};
Util.urlParamExists = function (name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
return regex.test(location.search);
};
Util.getUrlParamByName = function (name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
var results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
};
Util.getUrlParamBoolByName = function (name) {
var p = this.getUrlParamByName(name);
var isFalse = (p === "" || /false|0/i.test(p));
return !isFalse;
};
Util.stringInsert = function (target, index, s) {
if (index > 0) {
return target.substring(0, index) + s + target.substring(index, target.length);
}
return s + target;
};
Util.dateAdd = function (date, interval, units) {
var ret = new Date(date.toLocaleString());
switch (interval.toLowerCase()) {
case "year":
ret.setFullYear(ret.getFullYear() + units);
break;
case "quarter":
ret.setMonth(ret.getMonth() + 3 * units);
break;
case "month":
ret.setMonth(ret.getMonth() + units);
break;
case "week":
ret.setDate(ret.getDate() + 7 * units);
break;
case "day":
ret.setDate(ret.getDate() + units);
break;
case "hour":
ret.setTime(ret.getTime() + units * 3600000);
break;
case "minute":
ret.setTime(ret.getTime() + units * 60000);
break;
case "second":
ret.setTime(ret.getTime() + units * 1000);
break;
default:
ret = undefined;
break;
}
return ret;
};
Util.loadStylesheet = function (path, avoidCache) {
if (avoidCache) {
path += "?" + encodeURIComponent((new Date()).getTime().toString());
}
var head = document.getElementsByTagName("head");
if (head.length > 0) {
var e = document.createElement("link");
head[0].appendChild(e);
e.setAttribute("type", "text/css");
e.setAttribute("rel", "stylesheet");
e.setAttribute("href", path);
}
};
Util.combinePaths = function () {
var paths = [];
for (var _i = 0; _i < arguments.length; _i++) {
paths[_i - 0] = arguments[_i];
}
var parts = [];
for (var i = 0; i < paths.length; i++) {
if (typeof paths[i] !== "undefined" && paths[i] !== null) {
parts.push(paths[i].replace(/^[\\|\/]/, "").replace(/[\\|\/]$/, ""));
}
}
return parts.join("/").replace(/\\/, "/");
};
Util.getRandomString = function (chars) {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < chars; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
};
Util.getGUID = function () {
var d = new Date().getTime();
var guid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === "x" ? r : (r & 0x3 | 0x8)).toString(16);
});
return guid;
};
Util.isFunction = function (candidateFunction) {
return typeof candidateFunction === "function";
};
Util.isArray = function (array) {
if (Array.isArray) {
return Array.isArray(array);
}
return array && typeof array.length === "number" && array.constructor === Array;
};
Util.stringIsNullOrEmpty = function (s) {
return typeof s === "undefined" || s === null || s === "";
};
Util.extend = function (target, source, noOverwrite) {
if (noOverwrite === void 0) { noOverwrite = false; }
var result = {};
for (var id in target) {
result[id] = target[id];
}
var check = noOverwrite ? function (o, i) { return !o.hasOwnProperty(i); } : function (o, i) { return true; };
for (var id in source) {
if (check(result, id)) {
result[id] = source[id];
}
}
return result;
};
Util.applyMixins = function (derivedCtor) {
var baseCtors = [];
for (var _i = 1; _i < arguments.length; _i++) {
baseCtors[_i - 1] = arguments[_i];
}
baseCtors.forEach(function (baseCtor) {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(function (name) {
derivedCtor.prototype[name] = baseCtor.prototype[name];
});
});
};
Util.isUrlAbsolute = function (url) {
return /^https?:\/\/|^\/\//i.test(url);
};
Util.makeUrlAbsolute = function (url) {
if (Util.isUrlAbsolute(url)) {
return url;
}
if (typeof _spPageContextInfo !== "undefined") {
if (_spPageContextInfo.hasOwnProperty("webAbsoluteUrl")) {
return Util.combinePaths(_spPageContextInfo.webAbsoluteUrl, url);
}
else if (_spPageContextInfo.hasOwnProperty("webServerRelativeUrl")) {
return Util.combinePaths(_spPageContextInfo.webServerRelativeUrl, url);
}
}
else {
return url;
}
};
return Util;
}());
exports.Util = Util;
});
},{}]},{},[19])(19)
});
|
/*!
* OOjs UI v0.9.2
* https://www.mediawiki.org/wiki/OOjs_UI
*
* Copyright 2011–2015 OOjs Team and other contributors.
* Released under the MIT license
* http://oojs.mit-license.org
*
* Date: 2015-03-12T23:43:45Z
*/
/**
* @class
* @extends OO.ui.Theme
*
* @constructor
*/
OO.ui.ApexTheme = function OoUiApexTheme() {
// Parent constructor
OO.ui.ApexTheme.super.call( this );
};
/* Setup */
OO.inheritClass( OO.ui.ApexTheme, OO.ui.Theme );
/* Instantiation */
OO.ui.theme = new OO.ui.ApexTheme();
|
var demand = require('must');
var SelectType = require('../SelectType');
exports.initList = function (List) {
List.add({
select: { type: SelectType, options: 'one, two, three' },
nested: {
select: { type: SelectType, options: 'one, two, three' },
},
extraProps: { type: SelectType, options: [
{ value: 'one', label: 'One', custom: '1' },
{ value: 'two', label: 'Two', custom: '2' },
] },
numeric: { type: SelectType, numeric: true, options: [
{ value: 1, label: 'one' },
{ value: 2, label: 'two' },
{ value: 3, label: 'three' },
] },
emptyStringSelect: { type: SelectType, options: [
{ value: '', label: '' },
{ value: 'two', label: 'Two' },
] },
});
};
exports.testFieldType = function (List) {
describe('invalid options', function () {
it('should throw when no options are passed', function (done) {
try {
List.add({
noOptions: { type: SelectType },
});
} catch (err) {
demand(err.message).eql('Select fields require an options array.');
done();
}
});
});
describe('validateInput', function () {
it('should validate top level selects', function (done) {
List.fields.select.validateInput({
select: 'one',
}, function (result) {
demand(result).be.true();
done();
});
});
it('should validate nested selects', function (done) {
List.fields['nested.select'].validateInput({
nested: {
select: 'one',
},
}, function (result) {
demand(result).be.true();
done();
});
});
it('should validate undefined input', function (done) {
List.fields.select.validateInput({
select: undefined,
}, function (result) {
demand(result).be.true();
done();
});
});
it('should validate null input', function (done) {
List.fields.select.validateInput({
select: null,
}, function (result) {
demand(result).be.true();
done();
});
});
it('should validate an empty string', function (done) {
List.fields.select.validateInput({
select: '',
}, function (result) {
demand(result).be.true();
done();
});
});
it('should validate an empty string if specified as an option', function (done) {
List.fields.emptyStringSelect.validateInput({
emptyStringSelect: '',
}, function (result) {
demand(result).be.true();
done();
});
});
it('should invalidate numbers', function (done) {
List.fields.select.validateInput({
select: 1,
}, function (result) {
demand(result).be.false();
done();
});
});
it('should validate numbers when numeric is set to true', function (done) {
List.fields.numeric.validateInput({
numeric: 1,
}, function (result) {
demand(result).be.true();
done();
});
});
it('should validate number strings when numeric is set to true', function (done) {
List.fields.numeric.validateInput({
numeric: '1',
}, function (result) {
demand(result).be.true();
done();
});
});
it('should invalidate non existing options', function (done) {
List.fields.select.validateInput({
select: 'four',
}, function (result) {
demand(result).be.false();
done();
});
});
it('should invalidate two selected options', function (done) {
List.fields.select.validateInput({
select: 'one, two',
}, function (result) {
demand(result).be.false();
done();
});
});
it('should invalidate true', function (done) {
List.fields.select.validateInput({
select: true,
}, function (result) {
demand(result).be.false();
done();
});
});
it('should invalidate false', function (done) {
List.fields.select.validateInput({
select: false,
}, function (result) {
demand(result).be.false();
done();
});
});
});
describe('validateRequiredInput', function () {
it('should validate a selected option', function (done) {
var testItem = new List.model();
List.fields.select.validateRequiredInput(testItem, {
select: 'one',
}, function (result) {
demand(result).be.true();
done();
});
});
it('should validate a nested select', function (done) {
var testItem = new List.model();
List.fields['nested.select'].validateRequiredInput(testItem, {
nested: {
select: 'one',
},
}, function (result) {
demand(result).be.true();
done();
});
});
it('should validate a nested select with a flat path', function (done) {
List.fields.select.validateInput({
'nested.select': ['a', 'b'],
}, function (result) {
demand(result).be.true();
done();
});
});
it('should invalidate an empty string', function (done) {
var testItem = new List.model();
List.fields.select.validateRequiredInput(testItem, {
select: '',
}, function (result) {
demand(result).be.false();
done();
});
});
it('should invalidate undefined', function (done) {
var testItem = new List.model();
List.fields.select.validateRequiredInput(testItem, {
select: undefined,
}, function (result) {
demand(result).be.false();
done();
});
});
it('should validate undefined if a value exists', function (done) {
var testItem = new List.model({
select: 'one',
});
List.fields.select.validateRequiredInput(testItem, {
select: undefined,
}, function (result) {
demand(result).be.true();
done();
});
});
it('should invalidate null', function (done) {
var testItem = new List.model();
List.fields.select.validateRequiredInput(testItem, {
select: null,
}, function (result) {
demand(result).be.false();
done();
});
});
it('should invalidate an empty string even if specified as an option', function (done) {
var testItem = new List.model();
List.fields.emptyStringSelect.validateRequiredInput(testItem, {
emptyStringSelect: '',
}, function (result) {
demand(result).be.false();
done();
});
});
});
describe('updateItem', function () {
it('should update top level fields', function (done) {
var testItem = new List.model();
List.fields.select.updateItem(testItem, {
select: 'one',
}, function () {
demand(testItem.select).be('one');
done();
});
});
it('should update nested fields', function (done) {
var testItem = new List.model();
List.fields['nested.select'].updateItem(testItem, {
nested: {
select: 'one',
},
}, function () {
demand(testItem.nested.select).be('one');
done();
});
});
it('should update nested fields with flat paths', function (done) {
var testItem = new List.model();
List.fields['nested.select'].updateItem(testItem, {
'nested.select': 'one',
}, function () {
demand(testItem.nested.select).be('one');
done();
});
});
});
describe('addFilterToQuery', function () {
it('should filter by an array', function () {
var result = List.fields.select.addFilterToQuery({
value: ['Some', 'strings'],
});
demand(result.select).eql({
$in: ['Some', 'strings'],
});
});
it('should support inverted mode for an array', function () {
var result = List.fields.select.addFilterToQuery({
value: ['Some', 'strings'],
inverted: true,
});
demand(result.select).eql({
$nin: ['Some', 'strings'],
});
});
it('should filter by a string', function () {
var result = List.fields.select.addFilterToQuery({
value: 'a string',
});
demand(result.select).eql('a string');
});
it('should support inverted mode for a string', function () {
var result = List.fields.select.addFilterToQuery({
value: 'a string',
inverted: true,
});
demand(result.select).eql({
$ne: 'a string',
});
});
it('should filter by existance if no value exists', function () {
var result = List.fields.select.addFilterToQuery({});
demand(result.select).eql({
$in: ['', null],
});
});
it('should filter by non-existance if no value exists', function () {
var result = List.fields.select.addFilterToQuery({
inverted: true,
});
demand(result.select).eql({
$nin: ['', null],
});
});
});
it('should format values with the label of the option', function () {
var testItem = new List.model({
select: 'one',
});
demand(List.fields.select.format(testItem)).be('One');
});
it('should pluck custom properties from the selected option', function () {
var testItem = new List.model({
extraProps: 'two',
});
demand(testItem._.extraProps.pluck('custom')).be('2');
});
it('should have the label in nameLabel', function () {
var testItem = new List.model({
extraProps: 'two',
});
demand(testItem.extraPropsLabel).be('Two');
});
it('should have the current data in nameData', function () {
var testItem = new List.model({
extraProps: 'two',
});
demand(testItem.extraPropsData).eql({
value: 'two', label: 'Two', custom: '2',
});
});
it('should have the options in nameOption', function () {
var testItem = new List.model({
extraProps: 'two',
});
demand(testItem.extraPropsOptions).eql([
{ value: 'one', label: 'One', custom: '1' },
{ value: 'two', label: 'Two', custom: '2' },
]);
});
it('should have the options map in nameOptionsMap', function () {
var testItem = new List.model({
extraProps: 'two',
});
demand(testItem.extraPropsOptionsMap).eql({
one: {
value: 'one', label: 'One', custom: '1',
},
two: {
value: 'two', label: 'Two', custom: '2',
},
});
});
it('should return a blank string when formatting an undefined value', function () {
var testItem = new List.model();
demand(List.fields.select.format(testItem)).be('');
});
it('should return a shallow clone of the options', function () {
var clonedOps = List.fields.select.cloneOps();
demand(clonedOps).eql(List.fields.select.ops);
demand(clonedOps).not.equal(List.fields.select.ops);
});
};
|
module.exports={title:"Shotcut",slug:"shotcut",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Shotcut</title><path d="M0 0h6.667v24H0v-.889h5.778V.889H0V0zm7.556 0v24H24v-.889H8.444V.889H24V0H7.556zm1.388 22.611H24V1.389H8.944v21.222zM5.278 1.389H0v21.222h5.278V1.389z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://shotcut.com/media/",hex:"115C77",guidelines:void 0,license:void 0};
|
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { Component } from 'react'; // eslint-disable-line no-unused-vars
import EventEmitter from 'eventemitter3';
import { canUseDOM } from '../../node_modules/react/lib/ExecutionEnvironment';
let EE;
let viewport = {width: 1366, height: 768}; // Default size for server-side rendering
const RESIZE_EVENT = 'resize';
function handleWindowResize() {
if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) {
viewport = {width: window.innerWidth, height: window.innerHeight};
EE.emit(RESIZE_EVENT, viewport);
}
}
function withViewport(ComposedComponent) {
return class WithViewport extends Component {
constructor() {
super();
this.state = {
viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : viewport
};
}
componentDidMount() {
if (!EE) {
EE = new EventEmitter();
window.addEventListener('resize', handleWindowResize);
window.addEventListener('orientationchange', handleWindowResize);
}
EE.on('resize', this.handleResize, this);
}
componentWillUnmount() {
EE.removeListener(RESIZE_EVENT, this.handleResize, this);
if (!EE.listeners(RESIZE_EVENT, true)) {
window.removeEventListener('resize', handleWindowResize);
window.removeEventListener('orientationchange', handleWindowResize);
EE = null;
}
}
render() {
return <ComposedComponent {...this.props} viewport={this.state.viewport}/>;
}
handleResize(value) {
this.setState({viewport: value});
}
};
}
export default withViewport;
|
'use strict';
exports.__esModule = true;
/**
* Safe chained function
*
* Will only create a new function if needed,
* otherwise will pass back existing functions or null.
*
* @param {function} functions to chain
* @returns {function|null}
*/
function createChainedFunction() {
for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) {
funcs[_key] = arguments[_key];
}
return funcs.filter(function (f) {
return f != null;
}).reduce(function (acc, f) {
if (typeof f !== 'function') {
throw new Error('Invalid Argument Type, must only provide functions, undefined, or null.');
}
if (acc === null) {
return f;
}
return function chainedFunction() {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
acc.apply(this, args);
f.apply(this, args);
};
}, null);
}
exports['default'] = createChainedFunction;
module.exports = exports['default'];
|
/*
* Translated default messages for the jQuery validation plugin.
* Locale: UK (Ukrainian; українська мова)
*/
$.extend($.validator.messages, {
required: "Це поле необхідно заповнити.",
remote: "Будь ласка, введіть правильне значення.",
email: "Будь ласка, введіть коректну адресу електронної пошти.",
url: "Будь ласка, введіть коректний URL.",
date: "Будь ласка, введіть коректну дату.",
dateISO: "Будь ласка, введіть коректну дату у форматі ISO.",
number: "Будь ласка, введіть число.",
digits: "Вводите потрібно лише цифри.",
creditcard: "Будь ласка, введіть правильний номер кредитної карти.",
equalTo: "Будь ласка, введіть таке ж значення ще раз.",
extension: "Будь ласка, виберіть файл з правильним розширенням.",
maxlength: $.validator.format("Будь ласка, введіть не більше {0} символів."),
minlength: $.validator.format("Будь ласка, введіть не менше {0} символів."),
rangelength: $.validator.format("Будь ласка, введіть значення довжиною від {0} до {1} символів."),
range: $.validator.format("Будь ласка, введіть число від {0} до {1}."),
max: $.validator.format("Будь ласка, введіть число, менше або рівно {0}."),
min: $.validator.format("Будь ласка, введіть число, більше або рівно {0}.")
});
|
/**
* Requires commas as last token on a line in lists.
*
* Type: `Boolean`
*
* Value: `true`
*
* JSHint: [`laxcomma`](http://www.jshint.com/docs/options/#laxcomma)
*
* #### Example
*
* ```js
* "requireCommaBeforeLineBreak": true
* ```
*
* ##### Valid
*
* ```js
* var x = {
* one: 1,
* two: 2
* };
* var y = { three: 3, four: 4};
* ```
*
* ##### Invalid
*
* ```js
* var x = {
* one: 1
* , two: 2
* };
* ```
*/
var assert = require('assert');
module.exports = function() {};
module.exports.prototype = {
configure: function(options) {
assert(
options === true,
this.getOptionName() + ' option requires a true value or should be removed'
);
},
getOptionName: function() {
return 'requireCommaBeforeLineBreak';
},
check: function(file, errors) {
file.iterateTokensByTypeAndValue('Punctuator', ',', function(token) {
var prevToken = token.getPreviousCodeToken();
if (prevToken.value === ',') {
return;
}
errors.assert.sameLine({
token: prevToken,
nextToken: token,
message: 'Commas should not be placed on new line'
});
});
}
};
|
//>>built
define("dojox/mobile/ValuePickerDatePicker",["dojo/_base/declare","dojo/dom-class","dojo/dom-attr","./_DatePickerMixin","./ValuePicker","./ValuePickerSlot"],function(_1,_2,_3,_4,_5,_6){
return _1("dojox.mobile.ValuePickerDatePicker",[_5,_4],{readOnly:false,yearPlusBtnLabel:"",yearPlusBtnLabelRef:"",yearMinusBtnLabel:"",yearMinusBtnLabelRef:"",monthPlusBtnLabel:"",monthPlusBtnLabelRef:"",monthMinusBtnLabel:"",monthMinusBtnLabelRef:"",dayPlusBtnLabel:"",dayPlusBtnLabelRef:"",dayMinusBtnLabel:"",dayMinusBtnLabelRef:"",slotClasses:[_6,_6,_6],slotProps:[{labelFrom:1970,labelTo:2038,style:{width:"87px"}},{style:{width:"72px"}},{style:{width:"72px"}}],buildRendering:function(){
var p=this.slotProps;
p[0].readOnly=p[1].readOnly=p[2].readOnly=this.readOnly;
this._setBtnLabels(p);
this.initSlots();
this.inherited(arguments);
_2.add(this.domNode,"mblValuePickerDatePicker");
this._conn=[this.connect(this.slots[0],"_spinToValue","_onYearSet"),this.connect(this.slots[1],"_spinToValue","_onMonthSet"),this.connect(this.slots[2],"_spinToValue","_onDaySet")];
},disableValues:function(_7){
var _8=this.slots[2].items;
if(this._tail){
this.slots[2].items=_8=_8.concat(this._tail);
}
this._tail=_8.slice(_7);
_8.splice(_7);
},_setBtnLabels:function(_9){
_9[0].plusBtnLabel=this.yearPlusBtnLabel;
_9[0].plusBtnLabelRef=this.yearPlusBtnLabelRef;
_9[0].minusBtnLabel=this.yearMinusBtnLabel;
_9[0].minusBtnLabelRef=this.yearMinusBtnLabelRef;
_9[1].plusBtnLabel=this.monthPlusBtnLabel;
_9[1].plusBtnLabelRef=this.monthPlusBtnLabelRef;
_9[1].minusBtnLabel=this.monthMinusBtnLabel;
_9[1].minusBtnLabelRef=this.monthMinusBtnLabelRef;
_9[2].plusBtnLabel=this.dayPlusBtnLabel;
_9[2].plusBtnLabelRef=this.dayPlusBtnLabelRef;
_9[2].minusBtnLabel=this.dayMinusBtnLabel;
_9[2].minusBtnLabelRef=this.dayMinusBtnLabelRef;
}});
});
|
/**
* An Angular module that gives you access to the browsers local storage
* @version v0.2.7 - 2016-03-16
* @link https://github.com/grevory/angular-local-storage
* @author grevory <greg@gregpike.ca>
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
(function (window, angular) {
var isDefined = angular.isDefined,
isUndefined = angular.isUndefined,
isNumber = angular.isNumber,
isObject = angular.isObject,
isArray = angular.isArray,
extend = angular.extend,
toJson = angular.toJson;
angular
.module('LocalStorageModule', [])
.provider('localStorageService', function() {
// You should set a prefix to avoid overwriting any local storage variables from the rest of your app
// e.g. localStorageServiceProvider.setPrefix('yourAppName');
// With provider you can use config as this:
// myApp.config(function (localStorageServiceProvider) {
// localStorageServiceProvider.prefix = 'yourAppName';
// });
this.prefix = 'ls';
// You could change web storage type localstorage or sessionStorage
this.storageType = 'localStorage';
// Cookie options (usually in case of fallback)
// expiry = Number of days before cookies expire // 0 = Does not expire
// path = The web path the cookie represents
this.cookie = {
expiry: 30,
path: '/'
};
// Send signals for each of the following actions?
this.notify = {
setItem: true,
removeItem: false
};
// Setter for the prefix
this.setPrefix = function(prefix) {
this.prefix = prefix;
return this;
};
// Setter for the storageType
this.setStorageType = function(storageType) {
this.storageType = storageType;
return this;
};
// Setter for cookie config
this.setStorageCookie = function(exp, path) {
this.cookie.expiry = exp;
this.cookie.path = path;
return this;
};
// Setter for cookie domain
this.setStorageCookieDomain = function(domain) {
this.cookie.domain = domain;
return this;
};
// Setter for notification config
// itemSet & itemRemove should be booleans
this.setNotify = function(itemSet, itemRemove) {
this.notify = {
setItem: itemSet,
removeItem: itemRemove
};
return this;
};
this.$get = ['$rootScope', '$window', '$document', '$parse', function($rootScope, $window, $document, $parse) {
var self = this;
var prefix = self.prefix;
var cookie = self.cookie;
var notify = self.notify;
var storageType = self.storageType;
var webStorage;
// When Angular's $document is not available
if (!$document) {
$document = document;
} else if ($document[0]) {
$document = $document[0];
}
// If there is a prefix set in the config lets use that with an appended period for readability
if (prefix.substr(-1) !== '.') {
prefix = !!prefix ? prefix + '.' : '';
}
var deriveQualifiedKey = function(key) {
return prefix + key;
};
// Checks the browser to see if local storage is supported
var browserSupportsLocalStorage = (function () {
try {
var supported = (storageType in $window && $window[storageType] !== null);
// When Safari (OS X or iOS) is in private browsing mode, it appears as though localStorage
// is available, but trying to call .setItem throws an exception.
//
// "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage
// that exceeded the quota."
var key = deriveQualifiedKey('__' + Math.round(Math.random() * 1e7));
if (supported) {
webStorage = $window[storageType];
webStorage.setItem(key, '');
webStorage.removeItem(key);
}
return supported;
} catch (e) {
storageType = 'cookie';
$rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
return false;
}
}());
// Directly adds a value to local storage
// If local storage is not available in the browser use cookies
// Example use: localStorageService.add('library','angular');
var addToLocalStorage = function (key, value) {
// Let's convert undefined values to null to get the value consistent
if (isUndefined(value)) {
value = null;
} else {
value = toJson(value);
}
// If this browser does not support local storage use cookies
if (!browserSupportsLocalStorage || self.storageType === 'cookie') {
if (!browserSupportsLocalStorage) {
$rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
}
if (notify.setItem) {
$rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: 'cookie'});
}
return addToCookies(key, value);
}
try {
if (webStorage) {
webStorage.setItem(deriveQualifiedKey(key), value);
}
if (notify.setItem) {
$rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: self.storageType});
}
} catch (e) {
$rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
return addToCookies(key, value);
}
return true;
};
// Directly get a value from local storage
// Example use: localStorageService.get('library'); // returns 'angular'
var getFromLocalStorage = function (key) {
if (!browserSupportsLocalStorage || self.storageType === 'cookie') {
if (!browserSupportsLocalStorage) {
$rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
}
return getFromCookies(key);
}
var item = webStorage ? webStorage.getItem(deriveQualifiedKey(key)) : null;
// angular.toJson will convert null to 'null', so a proper conversion is needed
// FIXME not a perfect solution, since a valid 'null' string can't be stored
if (!item || item === 'null') {
return null;
}
try {
return JSON.parse(item);
} catch (e) {
return item;
}
};
// Remove an item from local storage
// Example use: localStorageService.remove('library'); // removes the key/value pair of library='angular'
var removeFromLocalStorage = function () {
var i, key;
for (i=0; i<arguments.length; i++) {
key = arguments[i];
if (!browserSupportsLocalStorage || self.storageType === 'cookie') {
if (!browserSupportsLocalStorage) {
$rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
}
if (notify.removeItem) {
$rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: 'cookie'});
}
removeFromCookies(key);
}
else {
try {
webStorage.removeItem(deriveQualifiedKey(key));
if (notify.removeItem) {
$rootScope.$broadcast('LocalStorageModule.notification.removeitem', {
key: key,
storageType: self.storageType
});
}
} catch (e) {
$rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
removeFromCookies(key);
}
}
}
};
// Return array of keys for local storage
// Example use: var keys = localStorageService.keys()
var getKeysForLocalStorage = function () {
if (!browserSupportsLocalStorage) {
$rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
return [];
}
var prefixLength = prefix.length;
var keys = [];
for (var key in webStorage) {
// Only return keys that are for this app
if (key.substr(0, prefixLength) === prefix) {
try {
keys.push(key.substr(prefixLength));
} catch (e) {
$rootScope.$broadcast('LocalStorageModule.notification.error', e.Description);
return [];
}
}
}
return keys;
};
// Remove all data for this app from local storage
// Also optionally takes a regular expression string and removes the matching key-value pairs
// Example use: localStorageService.clearAll();
// Should be used mostly for development purposes
var clearAllFromLocalStorage = function (regularExpression) {
// Setting both regular expressions independently
// Empty strings result in catchall RegExp
var prefixRegex = !!prefix ? new RegExp('^' + prefix) : new RegExp();
var testRegex = !!regularExpression ? new RegExp(regularExpression) : new RegExp();
if (!browserSupportsLocalStorage || self.storageType === 'cookie') {
if (!browserSupportsLocalStorage) {
$rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
}
return clearAllFromCookies();
}
var prefixLength = prefix.length;
for (var key in webStorage) {
// Only remove items that are for this app and match the regular expression
if (prefixRegex.test(key) && testRegex.test(key.substr(prefixLength))) {
try {
removeFromLocalStorage(key.substr(prefixLength));
} catch (e) {
$rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
return clearAllFromCookies();
}
}
}
return true;
};
// Checks the browser to see if cookies are supported
var browserSupportsCookies = (function() {
try {
return $window.navigator.cookieEnabled ||
("cookie" in $document && ($document.cookie.length > 0 ||
($document.cookie = "test").indexOf.call($document.cookie, "test") > -1));
} catch (e) {
$rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
return false;
}
}());
// Directly adds a value to cookies
// Typically used as a fallback is local storage is not available in the browser
// Example use: localStorageService.cookie.add('library','angular');
var addToCookies = function (key, value, daysToExpiry) {
if (isUndefined(value)) {
return false;
} else if(isArray(value) || isObject(value)) {
value = toJson(value);
}
if (!browserSupportsCookies) {
$rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED');
return false;
}
try {
var expiry = '',
expiryDate = new Date(),
cookieDomain = '';
if (value === null) {
// Mark that the cookie has expired one day ago
expiryDate.setTime(expiryDate.getTime() + (-1 * 24 * 60 * 60 * 1000));
expiry = "; expires=" + expiryDate.toGMTString();
value = '';
} else if (isNumber(daysToExpiry) && daysToExpiry !== 0) {
expiryDate.setTime(expiryDate.getTime() + (daysToExpiry * 24 * 60 * 60 * 1000));
expiry = "; expires=" + expiryDate.toGMTString();
} else if (cookie.expiry !== 0) {
expiryDate.setTime(expiryDate.getTime() + (cookie.expiry * 24 * 60 * 60 * 1000));
expiry = "; expires=" + expiryDate.toGMTString();
}
if (!!key) {
var cookiePath = "; path=" + cookie.path;
if(cookie.domain){
cookieDomain = "; domain=" + cookie.domain;
}
$document.cookie = deriveQualifiedKey(key) + "=" + encodeURIComponent(value) + expiry + cookiePath + cookieDomain;
}
} catch (e) {
$rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
return false;
}
return true;
};
// Directly get a value from a cookie
// Example use: localStorageService.cookie.get('library'); // returns 'angular'
var getFromCookies = function (key) {
if (!browserSupportsCookies) {
$rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED');
return false;
}
var cookies = $document.cookie && $document.cookie.split(';') || [];
for(var i=0; i < cookies.length; i++) {
var thisCookie = cookies[i];
while (thisCookie.charAt(0) === ' ') {
thisCookie = thisCookie.substring(1,thisCookie.length);
}
if (thisCookie.indexOf(deriveQualifiedKey(key) + '=') === 0) {
var storedValues = decodeURIComponent(thisCookie.substring(prefix.length + key.length + 1, thisCookie.length));
try {
return JSON.parse(storedValues);
} catch(e) {
return storedValues;
}
}
}
return null;
};
var removeFromCookies = function (key) {
addToCookies(key,null);
};
var clearAllFromCookies = function () {
var thisCookie = null, thisKey = null;
var prefixLength = prefix.length;
var cookies = $document.cookie.split(';');
for(var i = 0; i < cookies.length; i++) {
thisCookie = cookies[i];
while (thisCookie.charAt(0) === ' ') {
thisCookie = thisCookie.substring(1, thisCookie.length);
}
var key = thisCookie.substring(prefixLength, thisCookie.indexOf('='));
removeFromCookies(key);
}
};
var getStorageType = function() {
return storageType;
};
// Add a listener on scope variable to save its changes to local storage
// Return a function which when called cancels binding
var bindToScope = function(scope, key, def, lsKey) {
lsKey = lsKey || key;
var value = getFromLocalStorage(lsKey);
if (value === null && isDefined(def)) {
value = def;
} else if (isObject(value) && isObject(def)) {
value = extend(value, def);
}
$parse(key).assign(scope, value);
return scope.$watch(key, function(newVal) {
addToLocalStorage(lsKey, newVal);
}, isObject(scope[key]));
};
// Return localStorageService.length
// ignore keys that not owned
var lengthOfLocalStorage = function() {
var count = 0;
var storage = $window[storageType];
for(var i = 0; i < storage.length; i++) {
if(storage.key(i).indexOf(prefix) === 0 ) {
count++;
}
}
return count;
};
return {
isSupported: browserSupportsLocalStorage,
getStorageType: getStorageType,
set: addToLocalStorage,
add: addToLocalStorage, //DEPRECATED
get: getFromLocalStorage,
keys: getKeysForLocalStorage,
remove: removeFromLocalStorage,
clearAll: clearAllFromLocalStorage,
bind: bindToScope,
deriveKey: deriveQualifiedKey,
length: lengthOfLocalStorage,
cookie: {
isSupported: browserSupportsCookies,
set: addToCookies,
add: addToCookies, //DEPRECATED
get: getFromCookies,
remove: removeFromCookies,
clearAll: clearAllFromCookies
}
};
}];
});
})(window, window.angular);
|
/*!
* inferno-hyperscript v1.0.0-beta8
* (c) 2016 undefined
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.h = factory());
}(this, (function () { 'use strict';
var ERROR_MSG = 'a runtime error occured! Use Inferno in development environment to find the error.';
function isArray(obj) {
return obj instanceof Array;
}
function isStatefulComponent(o) {
return !isUndefined(o.prototype) && !isUndefined(o.prototype.render);
}
function isStringOrNumber(obj) {
return isString(obj) || isNumber(obj);
}
function isNullOrUndef(obj) {
return isUndefined(obj) || isNull(obj);
}
function isInvalid(obj) {
return isNull(obj) || obj === false || isTrue(obj) || isUndefined(obj);
}
function isString(obj) {
return typeof obj === 'string';
}
function isNumber(obj) {
return typeof obj === 'number';
}
function isNull(obj) {
return obj === null;
}
function isTrue(obj) {
return obj === true;
}
function isUndefined(obj) {
return obj === undefined;
}
function cloneVNode(vNodeToClone, props) {
var _children = [], len = arguments.length - 2;
while ( len-- > 0 ) _children[ len ] = arguments[ len + 2 ];
var children = _children;
if (_children.length > 0 && !isNull(_children[0])) {
if (!props) {
props = {};
}
if (_children.length === 1) {
children = _children[0];
}
if (isUndefined(props.children)) {
props.children = children;
}
else {
if (isArray(children)) {
if (isArray(props.children)) {
props.children = props.children.concat(children);
}
else {
props.children = [props.children].concat(children);
}
}
else {
if (isArray(props.children)) {
props.children.push(children);
}
else {
props.children = [props.children];
props.children.push(children);
}
}
}
}
children = null;
var newVNode;
if (isArray(vNodeToClone)) {
newVNode = vNodeToClone.map(function (vNode) { return cloneVNode(vNode); });
}
else if (isNullOrUndef(props) && isNullOrUndef(children)) {
newVNode = Object.assign({}, vNodeToClone);
}
else {
var flags = vNodeToClone.flags;
if (flags & 28 /* Component */) {
newVNode = createVNode(flags, vNodeToClone.type, Object.assign({}, vNodeToClone.props, props), null, vNodeToClone.key, vNodeToClone.ref, true);
}
else if (flags & 3970 /* Element */) {
children = (props && props.children) || vNodeToClone.children;
newVNode = createVNode(flags, vNodeToClone.type, Object.assign({}, vNodeToClone.props, props), children, vNodeToClone.key, vNodeToClone.ref, !children);
}
}
newVNode.dom = null;
return newVNode;
}
function _normalizeVNodes(nodes, result, i) {
for (; i < nodes.length; i++) {
var n = nodes[i];
if (!isInvalid(n)) {
if (Array.isArray(n)) {
_normalizeVNodes(n, result, 0);
}
else {
if (isStringOrNumber(n)) {
n = createTextVNode(n);
}
else if (isVNode(n) && n.dom) {
n = cloneVNode(n);
}
result.push(n);
}
}
}
}
function normalizeVNodes(nodes) {
var newNodes;
for (var i = 0; i < nodes.length; i++) {
var n = nodes[i];
if (isInvalid(n) || Array.isArray(n)) {
var result = (newNodes || nodes).slice(0, i);
_normalizeVNodes(nodes, result, i);
return result;
}
else if (isStringOrNumber(n)) {
if (!newNodes) {
newNodes = nodes.slice(0, i);
}
newNodes.push(createTextVNode(n));
}
else if (isVNode(n) && n.dom) {
if (!newNodes) {
newNodes = nodes.slice(0, i);
}
newNodes.push(cloneVNode(n));
}
else if (newNodes) {
newNodes.push(cloneVNode(n));
}
}
return newNodes || nodes;
}
function normalize(vNode) {
var props = vNode.props;
var children = vNode.children;
if (props) {
if (isNullOrUndef(children) && !isNullOrUndef(props.children)) {
vNode.children = props.children;
}
if (props.ref) {
vNode.ref = props.ref;
}
if (!isNullOrUndef(props.key)) {
vNode.key = props.key;
}
}
if (isArray(children)) {
vNode.children = normalizeVNodes(children);
}
}
function createVNode(flags, type, props, children, key, ref, noNormalise) {
if (flags & 16 /* ComponentUnknown */) {
flags = isStatefulComponent(type) ? 4 /* ComponentClass */ : 8 /* ComponentFunction */;
}
var vNode = {
children: isUndefined(children) ? null : children,
dom: null,
flags: flags || 0,
key: key === undefined ? null : key,
props: props || null,
ref: ref || null,
type: type
};
if (!noNormalise) {
normalize(vNode);
}
return vNode;
}
function createTextVNode(text) {
return createVNode(1 /* Text */, null, null, text);
}
function isVNode(o) {
return !!o.flags;
}
var classIdSplit = /([.#]?[a-zA-Z0-9_:-]+)/;
var notClassId = /^\.|#/;
function parseTag(tag, props) {
if (!tag) {
return 'div';
}
var noId = props && isUndefined(props.id);
var tagParts = tag.split(classIdSplit);
var tagName = null;
if (notClassId.test(tagParts[1])) {
tagName = "div";
}
var classes;
for (var i = 0; i < tagParts.length; i++) {
var part = tagParts[i];
if (!part) {
continue;
}
var type = part.charAt(0);
if (!tagName) {
tagName = part;
}
else if (type === '.') {
classes = classes || [];
classes.push(part.substring(1, part.length));
}
else if (type === '#' && noId) {
props.id = part.substring(1, part.length);
}
}
if (classes) {
if (props.className) {
classes.push(props.className);
}
props.className = classes.join(' ');
}
return tagName ? tagName.toLowerCase() : "div";
}
function isChildren(x) {
return isStringOrNumber(x) || (x && isArray(x));
}
function extractProps(_props, _tag) {
_props = _props || {};
var tag = isString(_tag) ? parseTag(_tag, _props) : _tag;
var props = {};
var key = null;
var ref = null;
var children = null;
for (var prop in _props) {
if (prop === 'key') {
key = _props[prop];
}
else if (prop === 'ref') {
ref = _props[prop];
}
else if (prop.substr(0, 11) === 'onComponent') {
if (!ref) {
ref = {};
}
ref[prop] = _props[prop];
}
else if (prop === 'hooks') {
ref = _props[prop];
}
else if (prop === 'children') {
children = _props[prop];
}
else {
props[prop] = _props[prop];
}
}
return { tag: tag, props: props, key: key, ref: ref, children: children };
}
function hyperscript$1(_tag, _props, _children, _childrenType) {
// If a child array or text node are passed as the second argument, shift them
if (!_children && isChildren(_props)) {
_children = _props;
_props = {};
}
var ref$1 = extractProps(_props, _tag);
var tag = ref$1.tag;
var props = ref$1.props;
var key = ref$1.key;
var ref = ref$1.ref;
var children = ref$1.children;
if (isString(tag)) {
var flags = 2;
switch (tag) {
case 'svg':
flags = 128 /* SvgElement */;
break;
case 'input':
flags = 512 /* InputElement */;
break;
case 'textarea':
flags = 1024 /* TextareaElement */;
break;
case 'select':
flags = 2048 /* SelectElement */;
break;
default:
}
return createVNode(flags, tag, props, _children || children, key, ref);
}
else {
var flags$1 = isStatefulComponent(tag) ? 4 /* ComponentClass */ : 8;
if (children) {
props.children = children;
}
return createVNode(flags$1, tag, props, null, key, ref);
}
}
return hyperscript$1;
})));
|
/*! jQuery-ui-Slider-Pips - v1.8.3 - 2015-04-06
* Copyright (c) 2015 Simon Goellner <simey.me@gmail.com>; Licensed MIT */
// PIPS
(function($) {
"use strict";
var extensionMethods = {
pips: function( settings ) {
var i,
p,
slider = this,
collection = "",
pips = ( slider.options.max - slider.options.min ) / slider.options.step,
$handles = slider.element.find(".ui-slider-handle"),
$pips;
var options = {
first: "label",
// "label", "pip", false
last: "label",
// "label", "pip", false
rest: "pip",
// "label", "pip", false
labels: false,
// [array], { first: "string", rest: [array], last: "string" }, false
prefix: "",
// "", string
suffix: "",
// "", string
step: ( pips > 100 ) ? Math.floor( pips * 0.05 ) : 1,
// number
formatLabel: function(value) {
return this.prefix + value + this.suffix;
}
// function
// must return a value to display in the pip labels
};
$.extend( options, settings );
slider.options.pipStep = options.step;
// get rid of all pips that might already exist.
slider.element
.addClass("ui-slider-pips")
.find(".ui-slider-pip")
.remove();
// small object with functions for marking pips as selected.
var selectPip = {
single: function(value) {
this.resetClasses();
$pips
.filter(".ui-slider-pip-" + value )
.addClass("ui-slider-pip-selected");
},
range: function(values) {
this.resetClasses();
for( i = 0; i < values.length; i++ ) {
$pips
.filter(".ui-slider-pip-" + values[i] )
.addClass("ui-slider-pip-selected-" + (i+1) );
}
},
resetClasses: function() {
$pips.removeClass( function (index, css) {
return ( css.match(/(^|\s)ui-slider-pip-selected(\S+|\s|$)/g) || [] ).join(" ");
});
}
};
// when we click on a label, we want to make sure the
// slider's handle actually goes to that label!
// so we check all the handles and see which one is closest
// to the label we clicked. If 2 handles are equidistant then
// we move both of them. We also want to trigger focus on the
// handle.
// without this method the label is just treated like a part
// of the slider and there's no accuracy in the selected value
function labelClick( label ) {
if (slider.option("disabled")) {
return;
}
var h,
val = $(label).data("value"),
$thisSlider = slider.element,
sliderVals,
comparedVals,
finalVals,
closestVal;
if ( slider.options.values && slider.options.values.length ) {
finalVals = sliderVals = $thisSlider.slider("values");
comparedVals = sliderVals.map(function(v) {
return Math.abs( v - val );
});
closestVal = Math.min.apply( Math, comparedVals );
for( h = 0; h < comparedVals.length; h++ ) {
if( comparedVals[h] === closestVal ) {
finalVals[h] = val;
$handles.eq(h).trigger("focus.selectPip");
}
}
$thisSlider.slider("values", finalVals);
selectPip.range( finalVals );
} else {
$handles.trigger("focus.selectPip");
$thisSlider.slider("value", val );
selectPip.single( val );
}
}
// method for creating a pip. We loop this for creating all
// the pips.
function createPip( which ) {
var label,
percent,
number = which,
classes = "ui-slider-pip",
css = "";
if ( "first" === which ) { number = 0; }
else if ( "last" === which ) { number = pips; }
// labelValue is the actual value of the pip based on the min/step
var labelValue = slider.options.min + ( slider.options.step * number );
// classLabel replaces any decimals with hyphens
var classLabel = labelValue.toString().replace(".","-");
// We need to set the human-readable label to either the
// corresponding element in the array, or the appropriate
// item in the object... or an empty string.
if( $.type(options.labels) === "array" ) {
label = options.labels[number] || "";
}
else if( $.type( options.labels ) === "object" ) {
// set first label
if( "first" === which ) {
label = options.labels.first || "";
}
// set last label
else if( "last" === which ) {
label = options.labels.last || "";
}
// set other labels, but our index should start at -1
// because of the first pip.
else if( $.type( options.labels.rest ) === "array" ) {
label = options.labels.rest[ number - 1 ] || "";
}
// urrggh, the options must be f**ked, just show nothing.
else {
label = labelValue;
}
}
else {
label = labelValue;
}
// First Pip on the Slider
if ( "first" === which ) {
percent = "0%";
classes += " ui-slider-pip-first";
classes += ( "label" === options.first ) ? " ui-slider-pip-label" : "";
classes += ( false === options.first ) ? " ui-slider-pip-hide" : "";
// Last Pip on the Slider
} else if ( "last" === which ) {
percent = "100%";
classes += " ui-slider-pip-last";
classes += ( "label" === options.last ) ? " ui-slider-pip-label" : "";
classes += ( false === options.last ) ? " ui-slider-pip-hide" : "";
// All other Pips
} else {
percent = ((100/pips) * which).toFixed(4) + "%";
classes += ( "label" === options.rest ) ? " ui-slider-pip-label" : "";
classes += ( false === options.rest ) ? " ui-slider-pip-hide" : "";
}
classes += " ui-slider-pip-" + classLabel;
// add classes for the initial-selected values.
if ( slider.options.values && slider.options.values.length ) {
for( i = 0; i < slider.options.values.length; i++ ) {
if ( labelValue === slider.options.values[i] ) {
classes += " ui-slider-pip-initial-" + (i+1);
classes += " ui-slider-pip-selected-" + (i+1);
}
}
} else {
if ( labelValue === slider.options.value ) {
classes += " ui-slider-pip-initial";
classes += " ui-slider-pip-selected";
}
}
css = ( slider.options.orientation === "horizontal" ) ?
"left: "+ percent :
"bottom: "+ percent;
// add this current pip to the collection
return "<span class=\""+classes+"\" style=\""+css+"\">"+
"<span class=\"ui-slider-line\"></span>"+
"<span class=\"ui-slider-label\" data-value=\""+labelValue+"\">"+ options.formatLabel(label) +"</span>"+
"</span>";
}
// we don't want the step ever to be a floating point.
slider.options.pipStep = Math.round( slider.options.pipStep );
// create our first pip
collection += createPip("first");
// for every stop in the slider; we create a pip.
for( p = 1; p < pips; p++ ) {
if( p % slider.options.pipStep === 0 ) {
collection += createPip( p );
}
}
// create our last pip
collection += createPip("last");
// append the collection of pips.
slider.element.append( collection );
// store the pips for setting classes later.
$pips = slider.element.find(".ui-slider-pip");
slider.element.on( "mousedown.selectPip mouseup.selectPip", ".ui-slider-label", function(e) {
e.stopPropagation();
labelClick( this );
});
slider.element.on( "slide.selectPip slidechange.selectPip", function(e,ui) {
var value, values,
$slider = $(this);
if ( !ui ) {
value = $slider.slider("value");
values = $slider.slider("values");
if ( values.length ) {
selectPip.range( values );
} else {
selectPip.single( value );
}
} else {
if ( ui.values ) {
selectPip.range( ui.values );
} else {
selectPip.single( ui.value );
}
}
});
}
};
$.extend(true, $.ui.slider.prototype, extensionMethods);
})(jQuery);
// FLOATS
(function($) {
"use strict";
var extensionMethods = {
float: function( settings ) {
var i,
slider = this,
tipValues = [],
$handles = slider.element.find(".ui-slider-handle");
var options = {
handle: true,
// false
pips: false,
// true
labels: false,
// [array], { first: "string", rest: [array], last: "string" }, false
prefix: "",
// "", string
suffix: "",
// "", string
event: "slidechange slide",
// "slidechange", "slide", "slidechange slide"
formatLabel: function(value) {
return this.prefix + value + this.suffix;
}
// function
// must return a value to display in the floats
};
$.extend( options, settings );
if ( slider.options.value < slider.options.min ) {
slider.options.value = slider.options.min;
}
if ( slider.options.value > slider.options.max ) {
slider.options.value = slider.options.max;
}
if ( slider.options.values && slider.options.values.length ) {
for( i = 0; i < slider.options.values.length; i++ ) {
if ( slider.options.values[i] < slider.options.min ) {
slider.options.values[i] = slider.options.min;
}
if ( slider.options.values[i] > slider.options.max ) {
slider.options.values[i] = slider.options.max;
}
}
}
// add a class for the CSS
slider.element
.addClass("ui-slider-float")
.find(".ui-slider-tip, .ui-slider-tip-label")
.remove();
function getPipLabels( values ) {
// when checking the array we need to divide
// by the step option, so we store those values here.
var vals = [],
steppedVals = values.map(function(v) {
return Math.ceil(( v - slider.options.min ) / slider.options.step);
});
// now we just get the values we need to return
// by looping through the values array and assigning the
// label if it exists.
if( $.type( options.labels ) === "array" ) {
for( i = 0; i < values.length; i++ ) {
vals[i] = options.labels[ steppedVals[i] ] || values[i];
}
}
else if( $.type( options.labels ) === "object" ) {
for( i = 0; i < values.length; i++ ) {
if( values[i] === slider.options.min ) {
vals[i] = options.labels.first || slider.options.min;
}
else if( values[i] === slider.options.max ) {
vals[i] = options.labels.last || slider.options.max;
}
else if( $.type( options.labels.rest ) === "array" ) {
vals[i] = options.labels.rest[ steppedVals[i] - 1 ] || values[i];
}
else {
vals[i] = values[i];
}
}
}
else {
for( i = 0; i < values.length; i++ ) {
vals[i] = values[i];
}
}
return vals;
}
// apply handle tip if settings allows.
if ( options.handle ) {
// We need to set the human-readable label to either the
// corresponding element in the array, or the appropriate
// item in the object... or an empty string.
tipValues = ( slider.options.values && slider.options.values.length ) ?
getPipLabels( slider.options.values ) :
getPipLabels( [ slider.options.value ] );
for( i = 0; i < tipValues.length; i++ ) {
$handles
.eq( i )
.append( $("<span class=\"ui-slider-tip\">"+ options.formatLabel(tipValues[i]) +"</span>") );
}
}
if ( options.pips ) {
// if this slider also has pip-labels, we make those into tips, too.
slider.element.find(".ui-slider-label").each(function(k,v) {
var $this = $(v),
val = [ $this.data("value") ],
label,
$tip;
label = options.formatLabel( getPipLabels( val )[0] );
// create a tip element
$tip =
$("<span class=\"ui-slider-tip-label\">" + label + "</span>")
.insertAfter( $this );
});
}
// check that the event option is actually valid against our
// own list of the slider's events.
if ( options.event !== "slide" &&
options.event !== "slidechange" &&
options.event !== "slide slidechange" &&
options.event !== "slidechange slide" ) {
options.event = "slidechange slide";
}
// when slider changes, update handle tip label.
slider.element.on( options.event , function( e, ui ) {
var uiValue = ( $.type( ui.value ) === "array" ) ? ui.value : [ ui.value ],
val = options.formatLabel( getPipLabels( uiValue )[0] );
$(ui.handle)
.find(".ui-slider-tip")
.html( val );
});
}
};
$.extend(true, $.ui.slider.prototype, extensionMethods);
})(jQuery);
|
var _ = require('../util')
var templateParser = require('../parsers/template')
var textParser = require('../parsers/text')
var compiler = require('../compiler')
var Cache = require('../cache')
var cache = new Cache(1000)
// v-partial reuses logic from v-if
var vIf = require('../directives/if')
module.exports = {
link: vIf.link,
teardown: vIf.teardown,
getContainedComponents: vIf.getContainedComponents,
bind: function () {
var el = this.el
this.start = _.createAnchor('v-partial-start')
this.end = _.createAnchor('v-partial-end')
_.replace(el, this.end)
_.before(this.start, this.end)
var id = el.getAttribute('name')
var tokens = textParser.parse(id)
if (tokens) {
// dynamic partial
this.setupDynamic(tokens)
} else {
// static partial
this.insert(id)
}
},
setupDynamic: function (tokens) {
var self = this
var exp = textParser.tokensToExp(tokens)
this.unwatch = this.vm.$watch(exp, function (value) {
self.teardown()
self.insert(value)
}, {
immediate: true,
user: false
})
},
insert: function (id) {
var partial = _.resolveAsset(this.vm.$options, 'partials', id)
if (process.env.NODE_ENV !== 'production') {
_.assertAsset(partial, 'partial', id)
}
if (partial) {
var frag = templateParser.parse(partial, true)
// cache partials based on constructor id.
var cacheId = (this.vm.constructor.cid || '') + partial
var linker = this.compile(frag, cacheId)
// this is provided by v-if
this.link(frag, linker)
}
},
compile: function (frag, cacheId) {
var hit = cache.get(cacheId)
if (hit) return hit
var linker = compiler.compile(frag, this.vm.$options, true)
cache.put(cacheId, linker)
return linker
},
unbind: function () {
if (this.unlink) this.unlink()
if (this.unwatch) this.unwatch()
}
}
|
require('babel-polyfill');
// Webpack config for creating the production bundle.
var path = require('path');
var webpack = require('webpack');
var CleanPlugin = require('clean-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var strip = require('strip-loader');
var projectRootPath = path.resolve(__dirname, '../');
var assetsPath = path.resolve(projectRootPath, './static/dist');
// https://github.com/halt-hammerzeit/webpack-isomorphic-tools
var WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');
var webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(require('./webpack-isomorphic-tools'));
module.exports = {
devtool: 'source-map',
context: path.resolve(__dirname, '..'),
entry: {
'main': [
'bootstrap-sass!./src/theme/bootstrap.config.prod.js',
'font-awesome-webpack!./src/theme/font-awesome.config.prod.js',
'./src/client.js'
]
},
output: {
path: assetsPath,
filename: '[name]-[chunkhash].js',
chunkFilename: '[name]-[chunkhash].js',
publicPath: '/dist/'
},
module: {
loaders: [
{ test: /\.jsx?$/, exclude: /node_modules/, loaders: [strip.loader('debug'), 'babel']},
{ test: /\.json$/, loader: 'json-loader' },
{ test: /\.less$/, loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=2&sourceMap!autoprefixer?browsers=last 2 version!less?outputStyle=expanded&sourceMap=true&sourceMapContents=true') },
{ test: /\.scss$/, loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=2&sourceMap!autoprefixer?browsers=last 2 version!sass?outputStyle=expanded&sourceMap=true&sourceMapContents=true') },
{ test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" },
{ test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream" },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file" },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml" },
{ test: webpackIsomorphicToolsPlugin.regular_expression('images'), loader: 'url-loader?limit=10240' }
]
},
progress: true,
resolve: {
modulesDirectories: [
'src',
'node_modules'
],
extensions: ['', '.json', '.js', '.jsx']
},
plugins: [
new CleanPlugin([assetsPath], { root: projectRootPath }),
// css files from the extract-text-plugin loader
new ExtractTextPlugin('[name]-[chunkhash].css', {allChunks: true}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
},
__CLIENT__: true,
__SERVER__: false,
__DEVELOPMENT__: false,
__DEVTOOLS__: false
}),
// ignore dev config
new webpack.IgnorePlugin(/\.\/dev/, /\/config$/),
// optimizations
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
webpackIsomorphicToolsPlugin
]
};
|
//! moment.js locale configuration
//! locale : Esperanto [eo]
//! author : Colin Dean : https://github.com/colindean
//! author : Mia Nordentoft Imperatori : https://github.com/miestasmia
//! comment : miestasmia corrected the translation by colindean
//! comment : Vivakvo corrected the translation by colindean and miestasmia
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['../moment'], factory) :
factory(global.moment)
}(this, (function (moment) { 'use strict';
//! moment.js locale configuration
var eo = moment.defineLocale('eo', {
months: 'januaro_februaro_marto_aprilo_majo_junio_julio_aŭgusto_septembro_oktobro_novembro_decembro'.split(
'_'
),
monthsShort: 'jan_feb_mart_apr_maj_jun_jul_aŭg_sept_okt_nov_dec'.split('_'),
weekdays: 'dimanĉo_lundo_mardo_merkredo_ĵaŭdo_vendredo_sabato'.split('_'),
weekdaysShort: 'dim_lun_mard_merk_ĵaŭ_ven_sab'.split('_'),
weekdaysMin: 'di_lu_ma_me_ĵa_ve_sa'.split('_'),
longDateFormat: {
LT: 'HH:mm',
LTS: 'HH:mm:ss',
L: 'YYYY-MM-DD',
LL: '[la] D[-an de] MMMM, YYYY',
LLL: '[la] D[-an de] MMMM, YYYY HH:mm',
LLLL: 'dddd[n], [la] D[-an de] MMMM, YYYY HH:mm',
llll: 'ddd, [la] D[-an de] MMM, YYYY HH:mm',
},
meridiemParse: /[ap]\.t\.m/i,
isPM: function (input) {
return input.charAt(0).toLowerCase() === 'p';
},
meridiem: function (hours, minutes, isLower) {
if (hours > 11) {
return isLower ? 'p.t.m.' : 'P.T.M.';
} else {
return isLower ? 'a.t.m.' : 'A.T.M.';
}
},
calendar: {
sameDay: '[Hodiaŭ je] LT',
nextDay: '[Morgaŭ je] LT',
nextWeek: 'dddd[n je] LT',
lastDay: '[Hieraŭ je] LT',
lastWeek: '[pasintan] dddd[n je] LT',
sameElse: 'L',
},
relativeTime: {
future: 'post %s',
past: 'antaŭ %s',
s: 'kelkaj sekundoj',
ss: '%d sekundoj',
m: 'unu minuto',
mm: '%d minutoj',
h: 'unu horo',
hh: '%d horoj',
d: 'unu tago', //ne 'diurno', ĉar estas uzita por proksimumo
dd: '%d tagoj',
M: 'unu monato',
MM: '%d monatoj',
y: 'unu jaro',
yy: '%d jaroj',
},
dayOfMonthOrdinalParse: /\d{1,2}a/,
ordinal: '%da',
week: {
dow: 1, // Monday is the first day of the week.
doy: 7, // The week that contains Jan 7th is the first week of the year.
},
});
return eo;
})));
|
module.exports = {
"name": "de_CH",
"day": {
"abbrev": [
"Son",
"Mon",
"Die",
"Mit",
"Don",
"Fre",
"Sam"
],
"full": [
"Sonntag",
"Montag",
"Dienstag",
"Mittwoch",
"Donnerstag",
"Freitag",
"Samstag"
]
},
"month": {
"abbrev": [
"Jan",
"Feb",
"Mär",
"Apr",
"Mai",
"Jun",
"Jul",
"Aug",
"Sep",
"Okt",
"Nov",
"Dez"
],
"full": [
"Januar",
"Februar",
"März",
"April",
"Mai",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"Dezember"
]
},
"meridiem": [
"",
""
],
"date": "%d.%m.%Y",
"time24": "%T",
"dateTime": "%a %d %b %Y %T %Z",
"time12": "",
"full": "%a %b %e %H:%M:%S %Z %Y"
}
|
import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
const Label = React.createClass({
mixins: [BootstrapMixin],
getDefaultProps() {
return {
bsClass: 'label',
bsStyle: 'default'
};
},
render() {
let classes = this.getBsClassSet();
return (
<span {...this.props} className={classNames(this.props.className, classes)}>
{this.props.children}
</span>
);
}
});
export default Label;
|
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
(function(){function b(a,b,c){var h=n[this.id];if(h)for(var f=this instanceof CKEDITOR.ui.dialog.checkbox,e=0;e<h.length;e++){var d=h[e];switch(d.type){case 1:if(!a)continue;if(null!==a.getAttribute(d.name)){a=a.getAttribute(d.name);f?this.setValue("true"==a.toLowerCase()):this.setValue(a);return}f&&this.setValue(!!d["default"]);break;case 2:if(!a)continue;if(d.name in c){a=c[d.name];f?this.setValue("true"==a.toLowerCase()):this.setValue(a);return}f&&this.setValue(!!d["default"]);break;case 4:if(!b)continue;
if(b.getAttribute(d.name)){a=b.getAttribute(d.name);f?this.setValue("true"==a.toLowerCase()):this.setValue(a);return}f&&this.setValue(!!d["default"])}}}function c(a,b,c){var h=n[this.id];if(h)for(var f=""===this.getValue(),e=this instanceof CKEDITOR.ui.dialog.checkbox,d=0;d<h.length;d++){var g=h[d];switch(g.type){case 1:if(!a||"data"==g.name&&b&&!a.hasAttribute("data"))continue;var m=this.getValue();f||e&&m===g["default"]?a.removeAttribute(g.name):a.setAttribute(g.name,m);break;case 2:if(!a)continue;
m=this.getValue();if(f||e&&m===g["default"])g.name in c&&c[g.name].remove();else if(g.name in c)c[g.name].setAttribute("value",m);else{var p=CKEDITOR.dom.element.createFromHtml("\x3ccke:param\x3e\x3c/cke:param\x3e",a.getDocument());p.setAttributes({name:g.name,value:m});1>a.getChildCount()?p.appendTo(a):p.insertBefore(a.getFirst())}break;case 4:if(!b)continue;m=this.getValue();f||e&&m===g["default"]?b.removeAttribute(g.name):b.setAttribute(g.name,m)}}}for(var n={id:[{type:1,name:"id"}],classid:[{type:1,
name:"classid"}],codebase:[{type:1,name:"codebase"}],pluginspage:[{type:4,name:"pluginspage"}],src:[{type:2,name:"movie"},{type:4,name:"src"},{type:1,name:"data"}],name:[{type:4,name:"name"}],align:[{type:1,name:"align"}],"class":[{type:1,name:"class"},{type:4,name:"class"}],width:[{type:1,name:"width"},{type:4,name:"width"}],height:[{type:1,name:"height"},{type:4,name:"height"}],hSpace:[{type:1,name:"hSpace"},{type:4,name:"hSpace"}],vSpace:[{type:1,name:"vSpace"},{type:4,name:"vSpace"}],style:[{type:1,
name:"style"},{type:4,name:"style"}],type:[{type:4,name:"type"}]},k="play loop menu quality scale salign wmode bgcolor base flashvars allowScriptAccess allowFullScreen".split(" "),l=0;l<k.length;l++)n[k[l]]=[{type:4,name:k[l]},{type:2,name:k[l]}];k=["play","loop","menu"];for(l=0;l<k.length;l++)n[k[l]][0]["default"]=n[k[l]][1]["default"]=!0;CKEDITOR.dialog.add("flash",function(a){var l=!a.config.flashEmbedTagOnly,k=a.config.flashAddEmbedTag||a.config.flashEmbedTagOnly,h,f="\x3cdiv\x3e"+CKEDITOR.tools.htmlEncode(a.lang.common.preview)+
'\x3cbr\x3e\x3cdiv id\x3d"cke_FlashPreviewLoader'+CKEDITOR.tools.getNextNumber()+'" style\x3d"display:none"\x3e\x3cdiv class\x3d"loading"\x3e\x26nbsp;\x3c/div\x3e\x3c/div\x3e\x3cdiv id\x3d"cke_FlashPreviewBox'+CKEDITOR.tools.getNextNumber()+'" class\x3d"FlashPreviewBox"\x3e\x3c/div\x3e\x3c/div\x3e';return{title:a.lang.flash.title,minWidth:420,minHeight:310,onShow:function(){this.fakeImage=this.objectNode=this.embedNode=null;h=new CKEDITOR.dom.element("embed",a.document);var e=this.getSelectedElement();
if(e&&e.data("cke-real-element-type")&&"flash"==e.data("cke-real-element-type")){this.fakeImage=e;var d=a.restoreRealElement(e),g=null,b=null,c={};if("cke:object"==d.getName()){g=d;d=g.getElementsByTag("embed","cke");0<d.count()&&(b=d.getItem(0));for(var d=g.getElementsByTag("param","cke"),f=0,l=d.count();f<l;f++){var k=d.getItem(f),n=k.getAttribute("name"),k=k.getAttribute("value");c[n]=k}}else"cke:embed"==d.getName()&&(b=d);this.objectNode=g;this.embedNode=b;this.setupContent(g,b,c,e)}},onOk:function(){var e=
null,d=null,b=null;this.fakeImage?(e=this.objectNode,d=this.embedNode):(l&&(e=CKEDITOR.dom.element.createFromHtml("\x3ccke:object\x3e\x3c/cke:object\x3e",a.document),e.setAttributes({classid:"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000",codebase:"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version\x3d6,0,40,0"})),k&&(d=CKEDITOR.dom.element.createFromHtml("\x3ccke:embed\x3e\x3c/cke:embed\x3e",a.document),d.setAttributes({type:"application/x-shockwave-flash",pluginspage:"http://www.macromedia.com/go/getflashplayer"}),
e&&d.appendTo(e)));if(e)for(var b={},c=e.getElementsByTag("param","cke"),f=0,h=c.count();f<h;f++)b[c.getItem(f).getAttribute("name")]=c.getItem(f);c={};f={};this.commitContent(e,d,b,c,f);e=a.createFakeElement(e||d,"cke_flash","flash",!0);e.setAttributes(f);e.setStyles(c);this.fakeImage?(e.replace(this.fakeImage),a.getSelection().selectElement(e)):a.insertElement(e)},onHide:function(){this.preview&&this.preview.setHtml("")},contents:[{id:"info",label:a.lang.common.generalTab,accessKey:"I",elements:[{type:"vbox",
padding:0,children:[{type:"hbox",widths:["280px","110px"],align:"right",children:[{id:"src",type:"text",label:a.lang.common.url,required:!0,validate:CKEDITOR.dialog.validate.notEmpty(a.lang.flash.validateSrc),setup:b,commit:c,onLoad:function(){var a=this.getDialog(),b=function(b){h.setAttribute("src",b);a.preview.setHtml('\x3cembed height\x3d"100%" width\x3d"100%" src\x3d"'+CKEDITOR.tools.htmlEncode(h.getAttribute("src"))+'" type\x3d"application/x-shockwave-flash"\x3e\x3c/embed\x3e')};a.preview=a.getContentElement("info",
"preview").getElement().getChild(3);this.on("change",function(a){a.data&&a.data.value&&b(a.data.value)});this.getInputElement().on("change",function(){b(this.getValue())},this)}},{type:"button",id:"browse",filebrowser:"info:src",hidden:!0,style:"display:inline-block;margin-top:14px;",label:a.lang.common.browseServer}]}]},{type:"hbox",widths:["25%","25%","25%","25%","25%"],children:[{type:"text",id:"width",requiredContent:"embed[width]",style:"width:95px",label:a.lang.common.width,validate:CKEDITOR.dialog.validate.htmlLength(a.lang.common.invalidHtmlLength.replace("%1",
a.lang.common.width)),setup:b,commit:c},{type:"text",id:"height",requiredContent:"embed[height]",style:"width:95px",label:a.lang.common.height,validate:CKEDITOR.dialog.validate.htmlLength(a.lang.common.invalidHtmlLength.replace("%1",a.lang.common.height)),setup:b,commit:c},{type:"text",id:"hSpace",requiredContent:"embed[hspace]",style:"width:95px",label:a.lang.flash.hSpace,validate:CKEDITOR.dialog.validate.integer(a.lang.flash.validateHSpace),setup:b,commit:c},{type:"text",id:"vSpace",requiredContent:"embed[vspace]",
style:"width:95px",label:a.lang.flash.vSpace,validate:CKEDITOR.dialog.validate.integer(a.lang.flash.validateVSpace),setup:b,commit:c}]},{type:"vbox",children:[{type:"html",id:"preview",style:"width:95%;",html:f}]}]},{id:"Upload",hidden:!0,filebrowser:"uploadButton",label:a.lang.common.upload,elements:[{type:"file",id:"upload",label:a.lang.common.upload,size:38},{type:"fileButton",id:"uploadButton",label:a.lang.common.uploadSubmit,filebrowser:"info:src","for":["Upload","upload"]}]},{id:"properties",
label:a.lang.flash.propertiesTab,elements:[{type:"hbox",widths:["50%","50%"],children:[{id:"scale",type:"select",requiredContent:"embed[scale]",label:a.lang.flash.scale,"default":"",style:"width : 100%;",items:[[a.lang.common.notSet,""],[a.lang.flash.scaleAll,"showall"],[a.lang.flash.scaleNoBorder,"noborder"],[a.lang.flash.scaleFit,"exactfit"]],setup:b,commit:c},{id:"allowScriptAccess",type:"select",requiredContent:"embed[allowscriptaccess]",label:a.lang.flash.access,"default":"",style:"width : 100%;",
items:[[a.lang.common.notSet,""],[a.lang.flash.accessAlways,"always"],[a.lang.flash.accessSameDomain,"samedomain"],[a.lang.flash.accessNever,"never"]],setup:b,commit:c}]},{type:"hbox",widths:["50%","50%"],children:[{id:"wmode",type:"select",requiredContent:"embed[wmode]",label:a.lang.flash.windowMode,"default":"",style:"width : 100%;",items:[[a.lang.common.notSet,""],[a.lang.flash.windowModeWindow,"window"],[a.lang.flash.windowModeOpaque,"opaque"],[a.lang.flash.windowModeTransparent,"transparent"]],
setup:b,commit:c},{id:"quality",type:"select",requiredContent:"embed[quality]",label:a.lang.flash.quality,"default":"high",style:"width : 100%;",items:[[a.lang.common.notSet,""],[a.lang.flash.qualityBest,"best"],[a.lang.flash.qualityHigh,"high"],[a.lang.flash.qualityAutoHigh,"autohigh"],[a.lang.flash.qualityMedium,"medium"],[a.lang.flash.qualityAutoLow,"autolow"],[a.lang.flash.qualityLow,"low"]],setup:b,commit:c}]},{type:"hbox",widths:["50%","50%"],children:[{id:"align",type:"select",requiredContent:"object[align]",
label:a.lang.common.align,"default":"",style:"width : 100%;",items:[[a.lang.common.notSet,""],[a.lang.common.alignLeft,"left"],[a.lang.flash.alignAbsBottom,"absBottom"],[a.lang.flash.alignAbsMiddle,"absMiddle"],[a.lang.flash.alignBaseline,"baseline"],[a.lang.common.alignBottom,"bottom"],[a.lang.common.alignMiddle,"middle"],[a.lang.common.alignRight,"right"],[a.lang.flash.alignTextTop,"textTop"],[a.lang.common.alignTop,"top"]],setup:b,commit:function(a,b,f,k,l){var h=this.getValue();c.apply(this,arguments);
h&&(l.align=h)}},{type:"html",html:"\x3cdiv\x3e\x3c/div\x3e"}]},{type:"fieldset",label:CKEDITOR.tools.htmlEncode(a.lang.flash.flashvars),children:[{type:"vbox",padding:0,children:[{type:"checkbox",id:"menu",label:a.lang.flash.chkMenu,"default":!0,setup:b,commit:c},{type:"checkbox",id:"play",label:a.lang.flash.chkPlay,"default":!0,setup:b,commit:c},{type:"checkbox",id:"loop",label:a.lang.flash.chkLoop,"default":!0,setup:b,commit:c},{type:"checkbox",id:"allowFullScreen",label:a.lang.flash.chkFull,"default":!0,
setup:b,commit:c}]}]}]},{id:"advanced",label:a.lang.common.advancedTab,elements:[{type:"hbox",children:[{type:"text",id:"id",requiredContent:"object[id]",label:a.lang.common.id,setup:b,commit:c}]},{type:"hbox",widths:["45%","55%"],children:[{type:"text",id:"bgcolor",requiredContent:"embed[bgcolor]",label:a.lang.flash.bgcolor,setup:b,commit:c},{type:"text",id:"class",requiredContent:"embed(cke-xyz)",label:a.lang.common.cssClass,setup:b,commit:c}]},{type:"text",id:"style",requiredContent:"embed{cke-xyz}",
validate:CKEDITOR.dialog.validate.inlineStyle(a.lang.common.invalidInlineStyle),label:a.lang.common.cssStyle,setup:b,commit:c}]}]}})})();
|
/*
* /MathJax/jax/output/HTML-CSS/fonts/TeX/AMS/Regular/MiscSymbols.js
*
* Copyright (c) 2009-2014 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.Hub.Insert(MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS.MathJax_AMS,{9733:[694,111,944,49,895]});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir+"/AMS/Regular/MiscSymbols.js");
|
describe('alert:', function() {
beforeEach(function() {
this.addMatchers({
// Place alert-specific matchers here...
});
var origFunc = $.fn.foundation;
spyOn($.fn, 'foundation').andCallFake(function() {
var result = origFunc.apply(this, arguments);
jasmine.Clock.tick(1000); // Let things settle...
return result;
});
});
describe('basic alert', function() {
beforeEach(function() {
document.body.innerHTML = __html__['spec/alert/basic.html'];
});
it('should be visible by default', function() {
$(document).foundation();
expect($('#myAlert')).toBeVisible();
});
it('should be hidden when close is clicked', function() {
$(document).foundation();
// TODO: Figure out how to get this working... more difficult than it seems. :)
// $('a.close').click();
// jasmine.Clock.tick(1000);
//expect($('#alertClose')).not.toBeVisible();
});
});
});
|
CKEDITOR.plugins.setLang("templates","bg",{button:"Шаблони",emptyListMsg:"(Няма дефинирани шаблони)",insertOption:"Замяна на актуалното съдържание",options:"Опции за шаблона",selectPromptMsg:"Моля изберете шаблон за отваряне в редактора",title:"Шаблони"});
|
module.exports={title:"C++",slug:"cplusplus",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>C++ icon</title><path d="M22.393 6c-.167-.29-.398-.543-.652-.69L12.925.22c-.508-.293-1.339-.293-1.847 0L2.26 5.31c-.508.293-.923 1.013-.923 1.6v10.18c0 .294.104.62.271.91.167.29.398.543.652.689l8.816 5.091c.508.293 1.339.293 1.847 0l8.816-5.091c.254-.146.485-.399.652-.689s.271-.616.271-.91V6.91c.002-.294-.102-.62-.269-.91zM12 19.109c-3.92 0-7.109-3.189-7.109-7.109S8.08 4.891 12 4.891a7.133 7.133 0 0 1 6.156 3.552l-3.076 1.781A3.567 3.567 0 0 0 12 8.445c-1.96 0-3.554 1.595-3.554 3.555S10.04 15.555 12 15.555a3.57 3.57 0 0 0 3.08-1.778l3.077 1.78A7.135 7.135 0 0 1 12 19.109zm7.109-6.714h-.79v.79h-.79v-.79h-.79v-.79h.79v-.79h.79v.79h.79v.79zm2.962 0h-.79v.79h-.79v-.79h-.789v-.79h.789v-.79h.79v.79h.79v.79z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://github.com/isocpp/logos",hex:"00599C"};
|
for (var i = (1 in []) in []);
for (var i = 1 in ([] in []));
for (var i = (10 * 10 in []) in []);
for (var i = (10 + 10 in []) in []);
for (var i = 10 + (10 in []) in []);
for (var i = 10 + 10 in ([] in []));
for (var i = (1 in []);;);
for ((1 in []);;);
for (1 * (1 in []);;);
for (1 * (1 + 1 in []);;);
for (1 * (1 + 1 in []);;);
for (1 * (1 + (1 in []));;);
|
/* Copyright (c) 2006-2012 by OpenLayers Contributors (see authors.txt for
* full list of contributors). Published under the 2-clause BSD license.
* See license.txt in the OpenLayers distribution or repository for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
*/
/**
* Class: OpenLayers.Control.ZoomIn
* The ZoomIn control is a button to increase the zoom level of a map.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.ZoomIn = OpenLayers.Class(OpenLayers.Control, {
/**
* Property: type
* {String} The type of <OpenLayers.Control> -- When added to a
* <Control.Panel>, 'type' is used by the panel to determine how to
* handle our events.
*/
type: OpenLayers.Control.TYPE_BUTTON,
/**
* Method: trigger
*/
trigger: function(){
this.map.zoomIn();
},
CLASS_NAME: "OpenLayers.Control.ZoomIn"
});
|
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var ReplaceSource = require("webpack-core/lib/ReplaceSource");
var RawSource = require("webpack-core/lib/RawSource");
function DependenciesBlockVariable(name, expression, dependencies) {
this.name = name;
this.expression = expression;
this.dependencies = dependencies || [];
}
module.exports = DependenciesBlockVariable;
DependenciesBlockVariable.prototype.updateHash = function(hash) {
hash.update(this.name);
hash.update(this.expression);
this.dependencies.forEach(function(d) {
d.updateHash(hash);
});
};
DependenciesBlockVariable.prototype.expressionSource = function(dependencyTemplates, outputOptions, requestShortener) {
var source = new ReplaceSource(new RawSource(this.expression));
this.dependencies.forEach(function(dep) {
var template = dependencyTemplates.get(dep.constructor);
if(!template) throw new Error("No template for dependency: " + dep.constructor.name);
template.apply(dep, source, outputOptions, requestShortener, dependencyTemplates);
});
return source;
};
DependenciesBlockVariable.prototype.disconnect = function() {
this.dependencies.forEach(function(d) {
d.disconnect();
});
};
DependenciesBlockVariable.prototype.hasDependencies = function() {
return this.dependencies.length > 0;
};
|
YUI.add('editor-base', function(Y) {
/**
* Base class for Editor. Handles the business logic of Editor, no GUI involved only utility methods and events.
* @module editor
* @submodule editor-base
*/
/**
* Base class for Editor. Handles the business logic of Editor, no GUI involved only utility methods and events.
* @class EditorBase
* @for EditorBase
* @extends Base
* @constructor
*/
var EditorBase = function() {
EditorBase.superclass.constructor.apply(this, arguments);
}, LAST_CHILD = ':last-child', BODY = 'body';
Y.extend(EditorBase, Y.Base, {
/**
* Internal reference to the Y.Frame instance
* @property frame
*/
frame: null,
initializer: function() {
var frame = new Y.Frame({
designMode: true,
title: EditorBase.STRINGS.title,
use: EditorBase.USE,
dir: this.get('dir'),
extracss: this.get('extracss'),
linkedcss: this.get('linkedcss'),
defaultblock: this.get('defaultblock'),
host: this
}).plug(Y.Plugin.ExecCommand);
frame.after('ready', Y.bind(this._afterFrameReady, this));
frame.addTarget(this);
this.frame = frame;
this.publish('nodeChange', {
emitFacade: true,
bubbles: true,
defaultFn: this._defNodeChangeFn
});
this.plug(Y.Plugin.EditorPara);
},
destructor: function() {
this.frame.destroy();
this.detachAll();
},
/**
* Copy certain styles from one node instance to another (used for new paragraph creation mainly)
* @method copyStyles
* @param {Node} from The Node instance to copy the styles from
* @param {Node} to The Node instance to copy the styles to
*/
copyStyles: function(from, to) {
if (from.test('a')) {
//Don't carry the A styles
return;
}
var styles = ['color', 'fontSize', 'fontFamily', 'backgroundColor', 'fontStyle' ],
newStyles = {};
Y.each(styles, function(v) {
newStyles[v] = from.getStyle(v);
});
if (from.ancestor('b,strong')) {
newStyles.fontWeight = 'bold';
}
if (from.ancestor('u')) {
if (!newStyles.textDecoration) {
newStyles.textDecoration = 'underline';
}
}
to.setStyles(newStyles);
},
/**
* Holder for the selection bookmark in IE.
* @property _lastBookmark
* @private
*/
_lastBookmark: null,
/**
* Resolves the e.changedNode in the nodeChange event if it comes from the document. If
* the event came from the document, it will get the last child of the last child of the document
* and return that instead.
* @method _resolveChangedNode
* @param {Node} n The node to resolve
* @private
*/
_resolveChangedNode: function(n) {
var inst = this.getInstance(), lc, lc2, found;
if (inst && n && n.test('html')) {
lc = inst.one(BODY).one(LAST_CHILD);
while (!found) {
if (lc) {
lc2 = lc.one(LAST_CHILD);
if (lc2) {
lc = lc2;
} else {
found = true;
}
} else {
found = true;
}
}
if (lc) {
if (lc.test('br')) {
if (lc.previous()) {
lc = lc.previous();
} else {
lc = lc.get('parentNode');
}
}
if (lc) {
n = lc;
}
}
}
return n;
},
/**
* The default handler for the nodeChange event.
* @method _defNodeChangeFn
* @param {Event} e The event
* @private
*/
_defNodeChangeFn: function(e) {
var startTime = (new Date()).getTime();
var inst = this.getInstance(), sel, cur,
btag = inst.Selection.DEFAULT_BLOCK_TAG;
if (Y.UA.ie) {
try {
sel = inst.config.doc.selection.createRange();
if (sel.getBookmark) {
this._lastBookmark = sel.getBookmark();
}
} catch (ie) {}
}
e.changedNode = this._resolveChangedNode(e.changedNode);
/*
* @TODO
* This whole method needs to be fixed and made more dynamic.
* Maybe static functions for the e.changeType and an object bag
* to walk through and filter to pass off the event to before firing..
*/
switch (e.changedType) {
case 'keydown':
//inst.later(100, inst, inst.Selection.cleanCursor);
inst.Selection.cleanCursor();
break;
case 'tab':
if (!e.changedNode.test('li, li *') && !e.changedEvent.shiftKey) {
e.changedEvent.frameEvent.preventDefault();
if (Y.UA.webkit) {
this.execCommand('inserttext', '\t');
} else {
sel = new inst.Selection();
sel.setCursor();
cur = sel.getCursor();
cur.insert(EditorBase.TABKEY, 'before');
sel.focusCursor();
inst.Selection.cleanCursor();
}
}
break;
case 'enter-up':
var para = ((this._lastPara) ? this._lastPara : e.changedNode),
b = para.one('br.yui-cursor');
if (this._lastPara) {
delete this._lastPara;
}
if (b) {
if (b.previous() || b.next()) {
b.remove();
}
}
if (!para.test(btag)) {
var para2 = para.ancestor(btag);
if (para2) {
para = para2;
para2 = null;
}
}
if (para.test(btag)) {
var prev = para.previous(), lc, lc2, found = false;
if (prev) {
lc = prev.one(LAST_CHILD);
while (!found) {
if (lc) {
lc2 = lc.one(LAST_CHILD);
if (lc2) {
lc = lc2;
} else {
found = true;
}
} else {
found = true;
}
}
if (lc) {
this.copyStyles(lc, para);
}
}
}
break;
}
if (Y.UA.webkit && (e.commands.indent || e.commands.outdent)) {
/**
* When executing execCommand 'indent or 'outdent' Webkit applies
* a class to the BLOCKQUOTE that adds left/right margin to it
* This strips that style so it is just a normal BLOCKQUOTE
*/
var bq = inst.all('.webkit-indent-blockquote');
if (bq.size()) {
bq.setStyle('margin', '');
}
}
if (Y.UA.gecko) {
if (e.changedNode && !e.changedNode.test(btag)) {
var p = e.changedNode.ancestor(btag);
if (p) {
this._lastPara = p;
}
}
}
var changed = this.getDomPath(e.changedNode, false),
cmds = {}, family, fsize, classes = [],
fColor = '', bColor = '';
if (e.commands) {
cmds = e.commands;
}
Y.each(changed, function(el) {
var tag = el.tagName.toLowerCase(),
cmd = EditorBase.TAG2CMD[tag];
if (cmd) {
cmds[cmd] = 1;
}
//Bold and Italic styles
var s = el.currentStyle || el.style;
if ((''+s.fontWeight) == 'bold') { //Cast this to a string
cmds.bold = 1;
}
if (s.fontStyle == 'italic') {
cmds.italic = 1;
}
if (s.textDecoration == 'underline') {
cmds.underline = 1;
}
if (s.textDecoration == 'line-through') {
cmds.strikethrough = 1;
}
var n = inst.one(el);
if (n.getStyle('fontFamily')) {
var family2 = n.getStyle('fontFamily').split(',')[0].toLowerCase();
if (family2) {
family = family2;
}
if (family) {
family = family.replace(/'/g, '').replace(/"/g, '');
}
}
fsize = EditorBase.NORMALIZE_FONTSIZE(n);
var cls = el.className.split(' ');
Y.each(cls, function(v) {
if (v !== '' && (v.substr(0, 4) !== 'yui_')) {
classes.push(v);
}
});
fColor = EditorBase.FILTER_RGB(n.getStyle('color'));
var bColor2 = EditorBase.FILTER_RGB(s.backgroundColor);
if (bColor2 !== 'transparent') {
if (bColor2 !== '') {
bColor = bColor2;
}
}
});
e.dompath = inst.all(changed);
e.classNames = classes;
e.commands = cmds;
//TODO Dont' like this, not dynamic enough..
if (!e.fontFamily) {
e.fontFamily = family;
}
if (!e.fontSize) {
e.fontSize = fsize;
}
if (!e.fontColor) {
e.fontColor = fColor;
}
if (!e.backgroundColor) {
e.backgroundColor = bColor;
}
var endTime = (new Date()).getTime();
},
/**
* Walk the dom tree from this node up to body, returning a reversed array of parents.
* @method getDomPath
* @param {Node} node The Node to start from
*/
getDomPath: function(node, nodeList) {
var domPath = [], domNode,
inst = this.frame.getInstance();
domNode = inst.Node.getDOMNode(node);
//return inst.all(domNode);
while (domNode !== null) {
if ((domNode === inst.config.doc.documentElement) || (domNode === inst.config.doc) || !domNode.tagName) {
domNode = null;
break;
}
if (!inst.DOM.inDoc(domNode)) {
domNode = null;
break;
}
//Check to see if we get el.nodeName and nodeType
if (domNode.nodeName && domNode.nodeType && (domNode.nodeType == 1)) {
domPath.push(domNode);
}
if (domNode == inst.config.doc.body) {
domNode = null;
break;
}
domNode = domNode.parentNode;
}
/*{{{ Using Node
while (node !== null) {
if (node.test('html') || node.test('doc') || !node.get('tagName')) {
node = null;
break;
}
if (!node.inDoc()) {
node = null;
break;
}
//Check to see if we get el.nodeName and nodeType
if (node.get('nodeName') && node.get('nodeType') && (node.get('nodeType') == 1)) {
domPath.push(inst.Node.getDOMNode(node));
}
if (node.test('body')) {
node = null;
break;
}
node = node.get('parentNode');
}
}}}*/
if (domPath.length === 0) {
domPath[0] = inst.config.doc.body;
}
if (nodeList) {
return inst.all(domPath.reverse());
} else {
return domPath.reverse();
}
},
/**
* After frame ready, bind mousedown & keyup listeners
* @method _afterFrameReady
* @private
*/
_afterFrameReady: function() {
var inst = this.frame.getInstance();
this.frame.on('dom:mouseup', Y.bind(this._onFrameMouseUp, this));
this.frame.on('dom:mousedown', Y.bind(this._onFrameMouseDown, this));
this.frame.on('dom:keydown', Y.bind(this._onFrameKeyDown, this));
if (Y.UA.ie) {
this.frame.on('dom:activate', Y.bind(this._onFrameActivate, this));
this.frame.on('dom:keyup', Y.throttle(Y.bind(this._onFrameKeyUp, this), 800));
this.frame.on('dom:keypress', Y.throttle(Y.bind(this._onFrameKeyPress, this), 800));
} else {
this.frame.on('dom:keyup', Y.bind(this._onFrameKeyUp, this));
this.frame.on('dom:keypress', Y.bind(this._onFrameKeyPress, this));
}
inst.Selection.filter();
this.fire('ready');
},
/**
* Moves the cached selection bookmark back so IE can place the cursor in the right place.
* @method _onFrameActivate
* @private
*/
_onFrameActivate: function() {
if (this._lastBookmark) {
try {
var inst = this.getInstance(),
sel = inst.config.doc.selection.createRange(),
bk = sel.moveToBookmark(this._lastBookmark);
sel.select();
this._lastBookmark = null;
} catch (e) {
}
}
},
/**
* Fires nodeChange event
* @method _onFrameMouseUp
* @private
*/
_onFrameMouseUp: function(e) {
this.fire('nodeChange', { changedNode: e.frameTarget, changedType: 'mouseup', changedEvent: e.frameEvent });
},
/**
* Fires nodeChange event
* @method _onFrameMouseDown
* @private
*/
_onFrameMouseDown: function(e) {
this.fire('nodeChange', { changedNode: e.frameTarget, changedType: 'mousedown', changedEvent: e.frameEvent });
},
/**
* Caches a copy of the selection for key events. Only creating the selection on keydown
* @property _currentSelection
* @private
*/
_currentSelection: null,
/**
* Holds the timer for selection clearing
* @property _currentSelectionTimer
* @private
*/
_currentSelectionTimer: null,
/**
* Flag to determine if we can clear the selection or not.
* @property _currentSelectionClear
* @private
*/
_currentSelectionClear: null,
/**
* Fires nodeChange event
* @method _onFrameKeyDown
* @private
*/
_onFrameKeyDown: function(e) {
var inst, sel;
if (!this._currentSelection) {
if (this._currentSelectionTimer) {
this._currentSelectionTimer.cancel();
}
this._currentSelectionTimer = Y.later(850, this, function() {
this._currentSelectionClear = true;
});
inst = this.frame.getInstance();
sel = new inst.Selection(e);
this._currentSelection = sel;
} else {
sel = this._currentSelection;
}
inst = this.frame.getInstance();
sel = new inst.Selection();
this._currentSelection = sel;
if (sel && sel.anchorNode) {
this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: 'keydown', changedEvent: e.frameEvent });
if (EditorBase.NC_KEYS[e.keyCode]) {
this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: EditorBase.NC_KEYS[e.keyCode], changedEvent: e.frameEvent });
this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: EditorBase.NC_KEYS[e.keyCode] + '-down', changedEvent: e.frameEvent });
}
}
},
/**
* Fires nodeChange event
* @method _onFrameKeyPress
* @private
*/
_onFrameKeyPress: function(e) {
var sel = this._currentSelection;
if (sel && sel.anchorNode) {
this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: 'keypress', changedEvent: e.frameEvent });
if (EditorBase.NC_KEYS[e.keyCode]) {
this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: EditorBase.NC_KEYS[e.keyCode] + '-press', changedEvent: e.frameEvent });
}
}
},
/**
* Fires nodeChange event for keyup on specific keys
* @method _onFrameKeyUp
* @private
*/
_onFrameKeyUp: function(e) {
var sel = this._currentSelection;
if (sel && sel.anchorNode) {
this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: 'keyup', selection: sel, changedEvent: e.frameEvent });
if (EditorBase.NC_KEYS[e.keyCode]) {
this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: EditorBase.NC_KEYS[e.keyCode] + '-up', selection: sel, changedEvent: e.frameEvent });
}
}
if (this._currentSelectionClear) {
this._currentSelectionClear = this._currentSelection = null;
}
},
/**
* Pass through to the frame.execCommand method
* @method execCommand
* @param {String} cmd The command to pass: inserthtml, insertimage, bold
* @param {String} val The optional value of the command: Helvetica
* @return {Node/NodeList} The Node or Nodelist affected by the command. Only returns on override commands, not browser defined commands.
*/
execCommand: function(cmd, val) {
var ret = this.frame.execCommand(cmd, val),
inst = this.frame.getInstance(),
sel = new inst.Selection(), cmds = {},
e = { changedNode: sel.anchorNode, changedType: 'execcommand', nodes: ret };
switch (cmd) {
case 'forecolor':
e.fontColor = val;
break;
case 'backcolor':
e.backgroundColor = val;
break;
case 'fontsize':
e.fontSize = val;
break;
case 'fontname':
e.fontFamily = val;
break;
}
cmds[cmd] = 1;
e.commands = cmds;
this.fire('nodeChange', e);
return ret;
},
/**
* Get the YUI instance of the frame
* @method getInstance
* @return {YUI} The YUI instance bound to the frame.
*/
getInstance: function() {
return this.frame.getInstance();
},
/**
* Renders the Y.Frame to the passed node.
* @method render
* @param {Selector/HTMLElement/Node} node The node to append the Editor to
* @return {EditorBase}
* @chainable
*/
render: function(node) {
this.frame.set('content', this.get('content'));
this.frame.render(node);
return this;
},
/**
* Focus the contentWindow of the iframe
* @method focus
* @param {Function} fn Callback function to execute after focus happens
* @return {EditorBase}
* @chainable
*/
focus: function(fn) {
this.frame.focus(fn);
return this;
},
/**
* Handles the showing of the Editor instance. Currently only handles the iframe
* @method show
* @return {EditorBase}
* @chainable
*/
show: function() {
this.frame.show();
return this;
},
/**
* Handles the hiding of the Editor instance. Currently only handles the iframe
* @method hide
* @return {EditorBase}
* @chainable
*/
hide: function() {
this.frame.hide();
return this;
},
/**
* (Un)Filters the content of the Editor, cleaning YUI related code. //TODO better filtering
* @method getContent
* @return {String} The filtered content of the Editor
*/
getContent: function() {
var html = '', inst = this.getInstance();
if (inst && inst.Selection) {
html = inst.Selection.unfilter();
}
//Removing the _yuid from the objects in IE
html = html.replace(/ _yuid="([^>]*)"/g, '');
return html;
}
}, {
/**
* @static
* @method NORMALIZE_FONTSIZE
* @description Pulls the fontSize from a node, then checks for string values (x-large, x-small)
* and converts them to pixel sizes. If the parsed size is different from the original, it calls
* node.setStyle to update the node with a pixel size for normalization.
*/
NORMALIZE_FONTSIZE: function(n) {
var size = n.getStyle('fontSize'), oSize = size;
switch (size) {
case '-webkit-xxx-large':
size = '48px';
break;
case 'xx-large':
size = '32px';
break;
case 'x-large':
size = '24px';
break;
case 'large':
size = '18px';
break;
case 'medium':
size = '16px';
break;
case 'small':
size = '13px';
break;
case 'x-small':
size = '10px';
break;
}
if (oSize !== size) {
n.setStyle('fontSize', size);
}
return size;
},
/**
* @static
* @property TABKEY
* @description The HTML markup to use for the tabkey
*/
TABKEY: '<span class="tab"> </span>',
/**
* @static
* @method FILTER_RGB
* @param String css The CSS string containing rgb(#,#,#);
* @description Converts an RGB color string to a hex color, example: rgb(0, 255, 0) converts to #00ff00
* @return String
*/
FILTER_RGB: function(css) {
if (css.toLowerCase().indexOf('rgb') != -1) {
var exp = new RegExp("(.*?)rgb\\s*?\\(\\s*?([0-9]+).*?,\\s*?([0-9]+).*?,\\s*?([0-9]+).*?\\)(.*?)", "gi");
var rgb = css.replace(exp, "$1,$2,$3,$4,$5").split(',');
if (rgb.length == 5) {
var r = parseInt(rgb[1], 10).toString(16);
var g = parseInt(rgb[2], 10).toString(16);
var b = parseInt(rgb[3], 10).toString(16);
r = r.length == 1 ? '0' + r : r;
g = g.length == 1 ? '0' + g : g;
b = b.length == 1 ? '0' + b : b;
css = "#" + r + g + b;
}
}
return css;
},
/**
* @static
* @property TAG2CMD
* @description A hash table of tags to their execcomand's
*/
TAG2CMD: {
'b': 'bold',
'strong': 'bold',
'i': 'italic',
'em': 'italic',
'u': 'underline',
'sup': 'superscript',
'sub': 'subscript',
'img': 'insertimage',
'a' : 'createlink',
'ul' : 'insertunorderedlist',
'ol' : 'insertorderedlist'
},
/**
* Hash table of keys to fire a nodeChange event for.
* @static
* @property NC_KEYS
* @type Object
*/
NC_KEYS: {
8: 'backspace',
9: 'tab',
13: 'enter',
32: 'space',
33: 'pageup',
34: 'pagedown',
35: 'end',
36: 'home',
37: 'left',
38: 'up',
39: 'right',
40: 'down',
46: 'delete'
},
/**
* The default modules to use inside the Frame
* @static
* @property USE
* @type Array
*/
USE: ['substitute', 'node', 'selector-css3', 'selection', 'stylesheet'],
/**
* The Class Name: editorBase
* @static
* @property NAME
*/
NAME: 'editorBase',
/**
* Editor Strings
* @static
* @property STRINGS
*/
STRINGS: {
/**
* Title of frame document: Rich Text Editor
* @static
* @property STRINGS.title
*/
title: 'Rich Text Editor'
},
ATTRS: {
/**
* The content to load into the Editor Frame
* @attribute content
*/
content: {
value: '<br>',
setter: function(str) {
if (str.substr(0, 1) === "\n") {
str = str.substr(1);
}
if (str === '') {
str = '<br>';
}
return this.frame.set('content', str);
},
getter: function() {
return this.frame.get('content');
}
},
/**
* The value of the dir attribute on the HTML element of the frame. Default: ltr
* @attribute dir
*/
dir: {
writeOnce: true,
value: 'ltr'
},
/**
* @attribute linkedcss
* @description An array of url's to external linked style sheets
* @type String
*/
linkedcss: {
value: '',
setter: function(css) {
if (this.frame) {
this.frame.set('linkedcss', css);
}
return css;
}
},
/**
* @attribute extracss
* @description A string of CSS to add to the Head of the Editor
* @type String
*/
extracss: {
value: false,
setter: function(css) {
if (this.frame) {
this.frame.set('extracss', css);
}
return css;
}
},
/**
* @attribute defaultblock
* @description The default tag to use for block level items, defaults to: p
* @type String
*/
defaultblock: {
value: 'p'
}
}
});
Y.EditorBase = EditorBase;
/**
* @event nodeChange
* @description Fired from mouseup & keyup.
* @param {Event.Facade} event An Event Facade object with the following specific properties added:
* <dl>
* <dt>changedEvent</dt><dd>The event that caused the nodeChange</dd>
* <dt>changedNode</dt><dd>The node that was interacted with</dd>
* <dt>changedType</dt><dd>The type of change: mousedown, mouseup, right, left, backspace, tab, enter, etc..</dd>
* <dt>commands</dt><dd>The list of execCommands that belong to this change and the dompath that's associated with the changedNode</dd>
* <dt>classNames</dt><dd>An array of classNames that are applied to the changedNode and all of it's parents</dd>
* <dt>dompath</dt><dd>A sorted array of node instances that make up the DOM path from the changedNode to body.</dd>
* <dt>backgroundColor</dt><dd>The cascaded backgroundColor of the changedNode</dd>
* <dt>fontColor</dt><dd>The cascaded fontColor of the changedNode</dd>
* <dt>fontFamily</dt><dd>The cascaded fontFamily of the changedNode</dd>
* <dt>fontSize</dt><dd>The cascaded fontSize of the changedNode</dd>
* </dl>
* @type {Event.Custom}
*/
/**
* @event ready
* @description Fired after the frame is ready.
* @param {Event.Facade} event An Event Facade object.
* @type {Event.Custom}
*/
}, '@VERSION@' ,{requires:['base', 'frame', 'node', 'exec-command', 'selection', 'editor-para'], skinnable:false});
|
hljs.registerLanguage("go",function(a){var b={keyword:"break default func interface select case map struct chan else goto package switch const fallthrough if range type continue for import return var go defer",constant:"true false iota nil",typename:"bool byte complex64 complex128 float32 float64 int8 int16 int32 int64 string uint8 uint16 uint32 uint64 int uint uintptr rune",built_in:"append cap close complex copy imag len make new panic print println real recover delete"};return{aliases:["golang"],k:b,i:"</",c:[a.CLCM,a.CBCM,a.QSM,{cN:"string",b:"'",e:"[^\\\\]'"},{cN:"string",b:"`",e:"`"},{cN:"number",b:"[^a-zA-Z_0-9](\\-|\\+)?\\d+(\\.\\d+|\\/\\d+)?((d|e|f|l|s)(\\+|\\-)?\\d+)?",r:0},a.CNM]}});
|
/*!
* Qoopido.js library v3.3.7, 2014-5-26
* https://github.com/dlueth/qoopido.js
* (c) 2014 Dirk Lueth
* Dual licensed under MIT and GPL
*/
!function(o){window.qoopido.register("pool/dom",o,["../pool"])}(function(o,t,e,r,n,i){"use strict";var p=o.pool.extend({_initPool:function(){return{}},_getPool:function(o){var t=this;return"string"!=typeof o&&(o=o.tagName.toLowerCase()),t._pool[o]=t._pool[o]||[]},_dispose:function(o){var t;o.parentNode&&o.parentNode.removeChild(o);for(t in o)if(Object.prototype.hasOwnProperty.call(o,t))try{o.removeAttribute(t)}catch(e){o.property=null}return o},_obtain:function(o){return i.createElement(o)}});return t.pool=t.pool||{},t.pool.dom=p.create(),p});
|
/**
* Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
* Build: `lodash modularize underscore exports="node" -o ./underscore/`
* Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <http://lodash.com/license>
*/
/** Used to determine if values are of the language type Object */
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
module.exports = objectTypes;
|
/*!
Plottable v0.3.0 (https://github.com/palantir/plottable)
Copyright 2014 Palantir Technologies
Licensed under MIT (https://github.com/palantir/plottable/blob/master/LICENSE)
*/
///<reference path="reference.ts" />
var Plottable;
(function (Plottable) {
(function (Utils) {
/**
* Checks if x is between a and b.
*/
function inRange(x, a, b) {
return (Math.min(a, b) <= x && x <= Math.max(a, b));
}
Utils.inRange = inRange;
/**
* Gets the bounding box of an element.
* @param {D3.Selection} element
* @returns {SVGRed} The bounding box.
*/
function getBBox(element) {
return element.node().getBBox();
}
Utils.getBBox = getBBox;
/**
* Truncates a text string to a max length, given the element in which to draw the text
*
* @param {string} text: The string to put in the text element, and truncate
* @param {D3.Selection} element: The element in which to measure and place the text
* @param {number} length: How much space to truncate text into
* @returns {string} text - the shortened text
*/
function truncateTextToLength(text, length, element) {
var originalText = element.text();
element.text(text);
var bbox = Utils.getBBox(element);
var textLength = bbox.width;
if (textLength < length) {
element.text(originalText);
return text;
}
element.text(text + "...");
var textNode = element.node();
var dotLength = textNode.getSubStringLength(textNode.textContent.length - 3, 3);
if (dotLength > length) {
element.text(originalText);
return "";
}
var numChars = text.length;
for (var i = 1; i < numChars; i++) {
var testLength = textNode.getSubStringLength(0, i);
if (testLength + dotLength > length) {
element.text(originalText);
return text.substr(0, i - 1).trim() + "...";
}
}
}
Utils.truncateTextToLength = truncateTextToLength;
/**
* Gets the height of a text element, as rendered.
*
* @param {D3.Selection} textElement
* @return {number} The height of the text element, in pixels.
*/
function getTextHeight(textElement) {
var originalText = textElement.text();
textElement.text("bqpdl");
var height = Utils.getBBox(textElement).height;
textElement.text(originalText);
return height;
}
Utils.getTextHeight = getTextHeight;
})(Plottable.Utils || (Plottable.Utils = {}));
var Utils = Plottable.Utils;
})(Plottable || (Plottable = {}));
///<reference path="reference.ts" />
// This file contains open source utilities, along with their copyright notices
var Plottable;
(function (Plottable) {
(function (OSUtils) {
function sortedIndex(val, arr, accessor) {
var low = 0;
var high = arr.length;
while (low < high) {
/* tslint:disable:no-bitwise */
var mid = (low + high) >>> 1;
/* tslint:enable:no-bitwise */
var x = accessor == null ? arr[mid] : accessor(arr[mid]);
if (x < val) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
OSUtils.sortedIndex = sortedIndex;
;
})(Plottable.OSUtils || (Plottable.OSUtils = {}));
var OSUtils = Plottable.OSUtils;
})(Plottable || (Plottable = {}));
///<reference path="reference.ts" />
var Plottable;
(function (Plottable) {
var Component = (function () {
function Component() {
this.interactionsToRegister = [];
this.boxes = [];
this.clipPathEnabled = false;
this.fixedWidthVal = true;
this.fixedHeightVal = true;
this.rowMinimumVal = 0;
this.colMinimumVal = 0;
this.isTopLevelComponent = false;
this.xOffsetVal = 0;
this.yOffsetVal = 0;
this.xAlignProportion = 0;
this.yAlignProportion = 0;
this.cssClasses = ["component"];
}
/**
* Attaches the Component to a DOM element. Usually only directly invoked on root-level Components.
*
* @param {D3.Selection} element A D3 selection consisting of the element to anchor to.
* @returns {Component} The calling component.
*/
Component.prototype.anchor = function (element) {
var _this = this;
if (element.node().childNodes.length > 0) {
throw new Error("Can't anchor to a non-empty element");
}
if (element.node().nodeName === "svg") {
// svg node gets the "plottable" CSS class
element.classed("plottable", true);
this.element = element.append("g");
this.element.attr("width", element.attr("width"));
this.element.attr("height", element.attr("height"));
this.isTopLevelComponent = true;
} else {
this.element = element;
}
this.cssClasses.forEach(function (cssClass) {
_this.element.classed(cssClass, true);
});
this.cssClasses = null;
this.backgroundContainer = this.element.append("g").classed("background-container", true);
this.content = this.element.append("g").classed("content", true);
this.foregroundContainer = this.element.append("g").classed("foreground-container", true);
this.boxContainer = this.element.append("g").classed("box-container", true);
if (this.clipPathEnabled) {
this.generateClipPath();
}
;
this.addBox("bounding-box");
this.interactionsToRegister.forEach(function (r) {
return _this.registerInteraction(r);
});
this.interactionsToRegister = null;
return this;
};
/**
* Computes the size, position, and alignment from the specified values.
* If no parameters are supplied and the component is a root node,
* they are inferred from the size of the component's element.
*
* @param {number} xOrigin
* @param {number} yOrigin
* @param {number} availableWidth
* @param {number} availableHeight
* @returns {Component} The calling Component.
*/
Component.prototype.computeLayout = function (xOrigin, yOrigin, availableWidth, availableHeight) {
var _this = this;
if (xOrigin == null || yOrigin == null || availableWidth == null || availableHeight == null) {
if (this.element == null) {
throw new Error("anchor must be called before computeLayout");
} else if (this.isTopLevelComponent) {
// we are the root node, height and width have already been set
xOrigin = 0;
yOrigin = 0;
availableWidth = parseFloat(this.element.attr("width"));
availableHeight = parseFloat(this.element.attr("height"));
} else {
throw new Error("null arguments cannot be passed to computeLayout() on a non-root node");
}
}
this.xOrigin = xOrigin;
this.yOrigin = yOrigin;
var xPosition = this.xOrigin;
var yPosition = this.yOrigin;
if (this.colMinimum() !== 0 && this.isFixedWidth()) {
// The component has free space, so it makes sense to think about how to position or offset it
xPosition += (availableWidth - this.colMinimum()) * this.xAlignProportion;
xPosition += this.xOffsetVal;
// Decrease size so hitbox / bounding box and children are sized correctly
availableWidth = availableWidth > this.colMinimum() ? this.colMinimum() : availableWidth;
}
if (this.rowMinimum() !== 0 && this.isFixedHeight()) {
yPosition += (availableHeight - this.rowMinimum()) * this.yAlignProportion;
yPosition += this.yOffsetVal;
availableHeight = availableHeight > this.rowMinimum() ? this.rowMinimum() : availableHeight;
}
this.availableWidth = availableWidth;
this.availableHeight = availableHeight;
this.element.attr("transform", "translate(" + xPosition + "," + yPosition + ")");
this.boxes.forEach(function (b) {
return b.attr("width", _this.availableWidth).attr("height", _this.availableHeight);
});
return this;
};
/**
* Renders the component.
*
* @returns {Component} The calling Component.
*/
Component.prototype.render = function () {
return this;
};
Component.prototype.renderTo = function (element) {
// When called on top-level-component, a shortcut for component.anchor(svg).computeLayout().render()
if (this.element == null) {
this.anchor(element);
}
this.computeLayout().render();
return this;
};
/**
* Sets the x alignment of the Component.
*
* @param {string} alignment The x alignment of the Component (one of LEFT/CENTER/RIGHT).
* @returns {Component} The calling Component.
*/
Component.prototype.xAlign = function (alignment) {
if (alignment === "LEFT") {
this.xAlignProportion = 0;
} else if (alignment === "CENTER") {
this.xAlignProportion = 0.5;
} else if (alignment === "RIGHT") {
this.xAlignProportion = 1;
} else {
throw new Error("Unsupported alignment");
}
return this;
};
/**
* Sets the y alignment of the Component.
*
* @param {string} alignment The y alignment of the Component (one of TOP/CENTER/BOTTOM).
* @returns {Component} The calling Component.
*/
Component.prototype.yAlign = function (alignment) {
if (alignment === "TOP") {
this.yAlignProportion = 0;
} else if (alignment === "CENTER") {
this.yAlignProportion = 0.5;
} else if (alignment === "BOTTOM") {
this.yAlignProportion = 1;
} else {
throw new Error("Unsupported alignment");
}
return this;
};
/**
* Sets the x offset of the Component.
*
* @param {number} offset The desired x offset, in pixels.
* @returns {Component} The calling Component.
*/
Component.prototype.xOffset = function (offset) {
this.xOffsetVal = offset;
return this;
};
/**
* Sets the y offset of the Component.
*
* @param {number} offset The desired y offset, in pixels.
* @returns {Component} The calling Component.
*/
Component.prototype.yOffset = function (offset) {
this.yOffsetVal = offset;
return this;
};
Component.prototype.addBox = function (className, parentElement) {
if (this.element == null) {
throw new Error("Adding boxes before anchoring is currently disallowed");
}
var parentElement = parentElement == null ? this.boxContainer : parentElement;
var box = parentElement.append("rect");
if (className != null) {
box.classed(className, true);
}
;
this.boxes.push(box);
if (this.availableWidth != null && this.availableHeight != null) {
box.attr("width", this.availableWidth).attr("height", this.availableHeight);
}
return box;
};
Component.prototype.generateClipPath = function () {
// The clip path will prevent content from overflowing its component space.
var clipPathId = Component.clipPathId++;
this.element.attr("clip-path", "url(#clipPath" + clipPathId + ")");
var clipPathParent = this.boxContainer.append("clipPath").attr("id", "clipPath" + clipPathId);
this.addBox("clip-rect", clipPathParent);
};
/**
* Attaches an Interaction to the Component, so that the Interaction will listen for events on the Component.
*
* @param {Interaction} interaction The Interaction to attach to the Component.
* @return {Component} The calling Component.
*/
Component.prototype.registerInteraction = function (interaction) {
// Interactions can be registered before or after anchoring. If registered before, they are
// pushed to this.interactionsToRegister and registered during anchoring. If after, they are
// registered immediately
if (this.element != null) {
if (this.hitBox == null) {
this.hitBox = this.addBox("hit-box");
this.hitBox.style("fill", "#ffffff").style("opacity", 0); // We need to set these so Chrome will register events
}
interaction.anchor(this.hitBox);
} else {
this.interactionsToRegister.push(interaction);
}
return this;
};
Component.prototype.classed = function (cssClass, addClass) {
if (addClass == null) {
if (this.element == null) {
return (this.cssClasses.indexOf(cssClass) !== -1);
} else {
return this.element.classed(cssClass);
}
} else {
if (this.element == null) {
var classIndex = this.cssClasses.indexOf(cssClass);
if (addClass && classIndex === -1) {
this.cssClasses.push(cssClass);
} else if (!addClass && classIndex !== -1) {
this.cssClasses.splice(classIndex, 1);
}
} else {
this.element.classed(cssClass, addClass);
}
return this;
}
};
Component.prototype.rowMinimum = function (newVal) {
if (newVal != null) {
this.rowMinimumVal = newVal;
return this;
} else {
return this.rowMinimumVal;
}
};
Component.prototype.colMinimum = function (newVal) {
if (newVal != null) {
this.colMinimumVal = newVal;
return this;
} else {
return this.colMinimumVal;
}
};
/**
* Checks if the Component has a fixed width or scales to fill available space.
* Returns true by default on the base Component class.
*
* @return {boolean} Whether the component has a fixed width.
*/
Component.prototype.isFixedWidth = function () {
return this.fixedWidthVal;
};
/**
* Checks if the Component has a fixed height or scales to fill available space.
* Returns true by default on the base Component class.
*
* @return {boolean} Whether the component has a fixed height.
*/
Component.prototype.isFixedHeight = function () {
return this.fixedHeightVal;
};
Component.clipPathId = 0;
return Component;
})();
Plottable.Component = Component;
})(Plottable || (Plottable = {}));
///<reference path="reference.ts" />
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var Plottable;
(function (Plottable) {
var Scale = (function () {
/**
* Creates a new Scale.
* @constructor
* @param {D3.Scale.Scale} scale The D3 scale backing the Scale.
*/
function Scale(scale) {
this.broadcasterCallbacks = [];
this._d3Scale = scale;
}
/**
* Returns the range value corresponding to a given domain value.
*
* @param value {any} A domain value to be scaled.
* @returns {any} The range value corresponding to the supplied domain value.
*/
Scale.prototype.scale = function (value) {
return this._d3Scale(value);
};
Scale.prototype.domain = function (values) {
var _this = this;
if (values == null) {
return this._d3Scale.domain();
} else {
this._d3Scale.domain(values);
this.broadcasterCallbacks.forEach(function (b) {
return b(_this);
});
return this;
}
};
Scale.prototype.range = function (values) {
if (values == null) {
return this._d3Scale.range();
} else {
this._d3Scale.range(values);
return this;
}
};
/**
* Creates a copy of the Scale with the same domain and range but without any registered listeners.
* @returns {Scale} A copy of the calling Scale.
*/
Scale.prototype.copy = function () {
return new Scale(this._d3Scale.copy());
};
/**
* Registers a callback to be called when the scale's domain is changed.
* @param {IBroadcasterCallback} callback A callback to be called when the Scale's domain changes.
* @returns {Scale} The Calling Scale.
*/
Scale.prototype.registerListener = function (callback) {
this.broadcasterCallbacks.push(callback);
return this;
};
return Scale;
})();
Plottable.Scale = Scale;
var QuantitiveScale = (function (_super) {
__extends(QuantitiveScale, _super);
/**
* Creates a new QuantitiveScale.
* @constructor
* @param {D3.Scale.QuantitiveScale} scale The D3 QuantitiveScale backing the QuantitiveScale.
*/
function QuantitiveScale(scale) {
_super.call(this, scale);
}
/**
* Retrieves the domain value corresponding to a supplied range value.
* @param {number} value: A value from the Scale's range.
* @returns {number} The domain value corresponding to the supplied range value.
*/
QuantitiveScale.prototype.invert = function (value) {
return this._d3Scale.invert(value);
};
/**
* Creates a copy of the QuantitiveScale with the same domain and range but without any registered listeners.
* @returns {QuantitiveScale} A copy of the calling QuantitiveScale.
*/
QuantitiveScale.prototype.copy = function () {
return new QuantitiveScale(this._d3Scale.copy());
};
/**
* Expands the QuantitiveScale's domain to cover the new region.
* @param {number} newDomain The additional domain to be covered by the QuantitiveScale.
* @returns {QuantitiveScale} The scale.
*/
QuantitiveScale.prototype.widenDomain = function (newDomain) {
var currentDomain = this.domain();
var wideDomain = [Math.min(newDomain[0], currentDomain[0]), Math.max(newDomain[1], currentDomain[1])];
this.domain(wideDomain);
return this;
};
QuantitiveScale.prototype.interpolate = function (factory) {
if (factory == null) {
return this._d3Scale.interpolate();
}
this._d3Scale.interpolate(factory);
return this;
};
/**
* Sets the range of the QuantitiveScale and sets the interpolator to d3.interpolateRound.
*
* @param {number[]} values The new range value for the range.
*/
QuantitiveScale.prototype.rangeRound = function (values) {
this._d3Scale.rangeRound(values);
return this;
};
QuantitiveScale.prototype.clamp = function (clamp) {
if (clamp == null) {
return this._d3Scale.clamp();
}
this._d3Scale.clamp(clamp);
return this;
};
/**
* Extends the scale's domain so it starts and ends with "nice" values.
*
* @param {number} [count] The number of ticks that should fit inside the new domain.
*/
QuantitiveScale.prototype.nice = function (count) {
this._d3Scale.nice(count);
this.domain(this._d3Scale.domain()); // nice() can change the domain, so update all listeners
return this;
};
/**
* Generates tick values.
* @param {number} [count] The number of ticks to generate.
* @returns {any[]} The generated ticks.
*/
QuantitiveScale.prototype.ticks = function (count) {
return this._d3Scale.ticks(count);
};
/**
* Gets a tick formatting function for displaying tick values.
*
* @param {number} count The number of ticks to be displayed
* @param {string} [format] A format specifier string.
* @returns {(n: number) => string} A formatting function.
*/
QuantitiveScale.prototype.tickFormat = function (count, format) {
return this._d3Scale.tickFormat(count, format);
};
return QuantitiveScale;
})(Scale);
Plottable.QuantitiveScale = QuantitiveScale;
var LinearScale = (function (_super) {
__extends(LinearScale, _super);
function LinearScale(scale) {
_super.call(this, scale == null ? d3.scale.linear() : scale);
this.domain([Infinity, -Infinity]);
}
/**
* Creates a copy of the LinearScale with the same domain and range but without any registered listeners.
* @returns {LinearScale} A copy of the calling LinearScale.
*/
LinearScale.prototype.copy = function () {
return new LinearScale(this._d3Scale.copy());
};
return LinearScale;
})(QuantitiveScale);
Plottable.LinearScale = LinearScale;
var ColorScale = (function (_super) {
__extends(ColorScale, _super);
/**
* Creates a ColorScale.
* @constructor
* @param {string} [scaleType] the type of color scale to create (Category10/Category20/Category20b/Category20c)
*/
function ColorScale(scaleType) {
var scale;
switch (scaleType) {
case "Category10":
case "category10":
case "10":
scale = d3.scale.category10();
break;
case "Category20":
case "category20":
case "20":
scale = d3.scale.category20();
break;
case "Category20b":
case "category20b":
case "20b":
scale = d3.scale.category20b();
break;
case "Category20c":
case "category20c":
case "20c":
scale = d3.scale.category20c();
break;
case null:
case undefined:
scale = d3.scale.ordinal();
default:
throw new Error("Unsupported ColorScale type");
}
_super.call(this, scale);
}
return ColorScale;
})(Scale);
Plottable.ColorScale = ColorScale;
})(Plottable || (Plottable = {}));
///<reference path="reference.ts" />
var Plottable;
(function (Plottable) {
var Interaction = (function () {
/**
* Creates an Interaction.
*
* @constructor
* @param {Component} componentToListenTo The component to listen for interactions on.
*/
function Interaction(componentToListenTo) {
this.componentToListenTo = componentToListenTo;
}
Interaction.prototype.anchor = function (hitBox) {
this.hitBox = hitBox;
};
/**
* Registers the Interaction on the Component it's listening to.
* This needs to be called to activate the interaction.
*/
Interaction.prototype.registerWithComponent = function () {
this.componentToListenTo.registerInteraction(this);
return this;
};
return Interaction;
})();
Plottable.Interaction = Interaction;
var PanZoomInteraction = (function (_super) {
__extends(PanZoomInteraction, _super);
/**
* Creates a PanZoomInteraction.
*
* @constructor
* @param {Component} componentToListenTo The component to listen for interactions on.
* @param {QuantitiveScale} xScale The X scale to update on panning/zooming.
* @param {QuantitiveScale} yScale The Y scale to update on panning/zooming.
*/
function PanZoomInteraction(componentToListenTo, xScale, yScale) {
var _this = this;
_super.call(this, componentToListenTo);
this.xScale = xScale;
this.yScale = yScale;
this.zoom = d3.behavior.zoom();
this.zoom.x(this.xScale._d3Scale);
this.zoom.y(this.yScale._d3Scale);
this.zoom.on("zoom", function () {
return _this.rerenderZoomed();
});
}
PanZoomInteraction.prototype.anchor = function (hitBox) {
_super.prototype.anchor.call(this, hitBox);
this.zoom(hitBox);
};
PanZoomInteraction.prototype.rerenderZoomed = function () {
// HACKHACK since the d3.zoom.x modifies d3 scales and not our TS scales, and the TS scales have the
// event listener machinery, let's grab the domain out of the d3 scale and pipe it back into the TS scale
var xDomain = this.xScale._d3Scale.domain();
var yDomain = this.yScale._d3Scale.domain();
this.xScale.domain(xDomain);
this.yScale.domain(yDomain);
};
return PanZoomInteraction;
})(Interaction);
Plottable.PanZoomInteraction = PanZoomInteraction;
var AreaInteraction = (function (_super) {
__extends(AreaInteraction, _super);
/**
* Creates an AreaInteraction.
*
* @param {Component} componentToListenTo The component to listen for interactions on.
*/
function AreaInteraction(componentToListenTo) {
var _this = this;
_super.call(this, componentToListenTo);
this.dragInitialized = false;
this.origin = [0, 0];
this.location = [0, 0];
this.dragBehavior = d3.behavior.drag();
this.dragBehavior.on("dragstart", function () {
return _this.dragstart();
});
this.dragBehavior.on("drag", function () {
return _this.drag();
});
this.dragBehavior.on("dragend", function () {
return _this.dragend();
});
}
/**
* Adds a callback to be called when the AreaInteraction triggers.
*
* @param {(a: SelectionArea) => any} cb The function to be called. Takes in a SelectionArea in pixels.
* @returns {AreaInteraction} The calling AreaInteraction.
*/
AreaInteraction.prototype.callback = function (cb) {
this.callbackToCall = cb;
return this;
};
AreaInteraction.prototype.dragstart = function () {
this.clearBox();
var availableWidth = parseFloat(this.hitBox.attr("width"));
var availableHeight = parseFloat(this.hitBox.attr("height"));
// the constraint functions ensure that the selection rectangle will not exceed the hit box
var constraintFunction = function (min, max) {
return function (x) {
return Math.min(Math.max(x, min), max);
};
};
this.constrainX = constraintFunction(0, availableWidth);
this.constrainY = constraintFunction(0, availableHeight);
};
AreaInteraction.prototype.drag = function () {
if (!this.dragInitialized) {
this.origin = [d3.event.x, d3.event.y];
this.dragInitialized = true;
}
this.location = [this.constrainX(d3.event.x), this.constrainY(d3.event.y)];
var width = Math.abs(this.origin[0] - this.location[0]);
var height = Math.abs(this.origin[1] - this.location[1]);
var x = Math.min(this.origin[0], this.location[0]);
var y = Math.min(this.origin[1], this.location[1]);
this.dragBox.attr("x", x).attr("y", y).attr("height", height).attr("width", width);
};
AreaInteraction.prototype.dragend = function () {
if (!this.dragInitialized) {
return;
}
this.dragInitialized = false;
if (this.callbackToCall == null) {
return;
}
var xMin = Math.min(this.origin[0], this.location[0]);
var xMax = Math.max(this.origin[0], this.location[0]);
var yMin = Math.min(this.origin[1], this.location[1]);
var yMax = Math.max(this.origin[1], this.location[1]);
var pixelArea = { xMin: xMin, xMax: xMax, yMin: yMin, yMax: yMax };
this.callbackToCall(pixelArea);
};
/**
* Clears the highlighted drag-selection box drawn by the AreaInteraction.
*
* @returns {AreaInteraction} The calling AreaInteraction.
*/
AreaInteraction.prototype.clearBox = function () {
this.dragBox.attr("height", 0).attr("width", 0);
return this;
};
AreaInteraction.prototype.anchor = function (hitBox) {
_super.prototype.anchor.call(this, hitBox);
var cname = AreaInteraction.CLASS_DRAG_BOX;
var background = this.componentToListenTo.backgroundContainer;
this.dragBox = background.append("rect").classed(cname, true).attr("x", 0).attr("y", 0);
hitBox.call(this.dragBehavior);
return this;
};
AreaInteraction.CLASS_DRAG_BOX = "drag-box";
return AreaInteraction;
})(Interaction);
Plottable.AreaInteraction = AreaInteraction;
var ZoomCallbackGenerator = (function () {
function ZoomCallbackGenerator() {
this.xScaleMappings = [];
this.yScaleMappings = [];
}
/**
* Adds listen-update pair of X scales.
*
* @param {QuantitiveScale} listenerScale An X scale to listen for events on.
* @param {QuantitiveScale} [targetScale] An X scale to update when events occur.
* If not supplied, listenerScale will be updated when an event occurs.
* @returns {ZoomCallbackGenerator} The calling ZoomCallbackGenerator.
*/
ZoomCallbackGenerator.prototype.addXScale = function (listenerScale, targetScale) {
if (targetScale == null) {
targetScale = listenerScale;
}
this.xScaleMappings.push([listenerScale, targetScale]);
return this;
};
/**
* Adds listen-update pair of Y scales.
*
* @param {QuantitiveScale} listenerScale A Y scale to listen for events on.
* @param {QuantitiveScale} [targetScale] A Y scale to update when events occur.
* If not supplied, listenerScale will be updated when an event occurs.
* @returns {ZoomCallbackGenerator} The calling ZoomCallbackGenerator.
*/
ZoomCallbackGenerator.prototype.addYScale = function (listenerScale, targetScale) {
if (targetScale == null) {
targetScale = listenerScale;
}
this.yScaleMappings.push([listenerScale, targetScale]);
return this;
};
ZoomCallbackGenerator.prototype.updateScale = function (referenceScale, targetScale, pixelMin, pixelMax) {
var originalDomain = referenceScale.domain();
var newDomain = [referenceScale.invert(pixelMin), referenceScale.invert(pixelMax)];
var sameDirection = (newDomain[0] < newDomain[1]) === (originalDomain[0] < originalDomain[1]);
if (!sameDirection) {
newDomain.reverse();
}
targetScale.domain(newDomain);
};
/**
* Generates a callback that can be passed to Interactions.
*
* @returns {(area: SelectionArea) => void} A callback that updates the scales previously specified.
*/
ZoomCallbackGenerator.prototype.getCallback = function () {
var _this = this;
return function (area) {
_this.xScaleMappings.forEach(function (sm) {
_this.updateScale(sm[0], sm[1], area.xMin, area.xMax);
});
_this.yScaleMappings.forEach(function (sm) {
_this.updateScale(sm[0], sm[1], area.yMin, area.yMax);
});
};
};
return ZoomCallbackGenerator;
})();
Plottable.ZoomCallbackGenerator = ZoomCallbackGenerator;
var MousemoveInteraction = (function (_super) {
__extends(MousemoveInteraction, _super);
function MousemoveInteraction(componentToListenTo) {
_super.call(this, componentToListenTo);
}
MousemoveInteraction.prototype.anchor = function (hitBox) {
var _this = this;
_super.prototype.anchor.call(this, hitBox);
hitBox.on("mousemove", function () {
var xy = d3.mouse(hitBox.node());
var x = xy[0];
var y = xy[1];
_this.mousemove(x, y);
});
};
MousemoveInteraction.prototype.mousemove = function (x, y) {
return;
};
return MousemoveInteraction;
})(Interaction);
Plottable.MousemoveInteraction = MousemoveInteraction;
var CrosshairsInteraction = (function (_super) {
__extends(CrosshairsInteraction, _super);
function CrosshairsInteraction(renderer) {
_super.call(this, renderer);
this.renderer = renderer;
}
CrosshairsInteraction.prototype.anchor = function (hitBox) {
_super.prototype.anchor.call(this, hitBox);
var container = this.renderer.foregroundContainer.append("g").classed("crosshairs", true);
this.circle = container.append("circle").classed("centerpoint", true);
this.xLine = container.append("path").classed("x-line", true);
this.yLine = container.append("path").classed("y-line", true);
this.circle.attr("r", 5);
};
CrosshairsInteraction.prototype.mousemove = function (x, y) {
var domainX = this.renderer.xScale.invert(x);
var data = this.renderer.dataset.data;
var dataIndex = Plottable.OSUtils.sortedIndex(domainX, data, this.renderer.xAccessor);
dataIndex = dataIndex > 0 ? dataIndex - 1 : 0;
var dataPoint = data[dataIndex];
var dataX = this.renderer.xAccessor(dataPoint);
var dataY = this.renderer.yAccessor(dataPoint);
var pixelX = this.renderer.xScale.scale(dataX);
var pixelY = this.renderer.yScale.scale(dataY);
this.circle.attr("cx", pixelX).attr("cy", pixelY);
var width = this.renderer.availableWidth;
var height = this.renderer.availableHeight;
this.xLine.attr("d", "M 0 " + pixelY + " L " + width + " " + pixelY);
this.yLine.attr("d", "M " + pixelX + " 0 L " + pixelX + " " + height);
};
return CrosshairsInteraction;
})(MousemoveInteraction);
Plottable.CrosshairsInteraction = CrosshairsInteraction;
})(Plottable || (Plottable = {}));
///<reference path="reference.ts" />
var Plottable;
(function (Plottable) {
var Label = (function (_super) {
__extends(Label, _super);
/**
* Creates a Label.
*
* @constructor
* @param {string} [text] The text of the Label.
* @param {string} [orientation] The orientation of the Label (horizontal/vertical-left/vertical-right).
*/
function Label(text, orientation) {
if (typeof text === "undefined") { text = ""; }
if (typeof orientation === "undefined") { orientation = "horizontal"; }
_super.call(this);
this.classed(Label.CSS_CLASS, true);
this.setText(text);
if (orientation === "horizontal" || orientation === "vertical-left" || orientation === "vertical-right") {
this.orientation = orientation;
if (orientation === "horizontal") {
this.fixedWidthVal = false;
} else {
this.fixedHeightVal = false;
}
} else {
throw new Error(orientation + " is not a valid orientation for LabelComponent");
}
this.xAlign("CENTER").yAlign("CENTER"); // the defaults
}
Label.prototype.anchor = function (element) {
_super.prototype.anchor.call(this, element);
this.textElement = this.content.append("text");
this.setText(this.text);
return this;
};
/**
* Sets the text on the Label.
*
* @param {string} text The new text for the Label.
* @returns {Label} The calling Label.
*/
Label.prototype.setText = function (text) {
this.text = text;
if (this.element != null) {
this.textElement.text(text);
this.measureAndSetTextSize();
}
return this;
};
Label.prototype.measureAndSetTextSize = function () {
var bbox = Plottable.Utils.getBBox(this.textElement);
this.textHeight = bbox.height;
this.textLength = bbox.width;
if (this.orientation === "horizontal") {
this.rowMinimum(this.textHeight);
} else {
this.colMinimum(this.textHeight);
}
};
Label.prototype.truncateTextAndRemeasure = function (availableLength) {
var shortText = Plottable.Utils.truncateTextToLength(this.text, availableLength, this.textElement);
this.textElement.text(shortText);
this.measureAndSetTextSize();
};
Label.prototype.computeLayout = function (xOffset, yOffset, availableWidth, availableHeight) {
_super.prototype.computeLayout.call(this, xOffset, yOffset, availableWidth, availableHeight);
this.textElement.attr("dy", 0); // Reset this so we maintain idempotence
var bbox = Plottable.Utils.getBBox(this.textElement);
this.textElement.attr("dy", -bbox.y);
var xShift = 0;
var yShift = 0;
if (this.orientation === "horizontal") {
this.truncateTextAndRemeasure(this.availableWidth);
xShift = (this.availableWidth - this.textLength) * this.xAlignProportion;
} else {
this.truncateTextAndRemeasure(this.availableHeight);
xShift = (this.availableHeight - this.textLength) * this.yAlignProportion;
if (this.orientation === "vertical-right") {
this.textElement.attr("transform", "rotate(90)");
yShift = -this.textHeight;
} else {
this.textElement.attr("transform", "rotate(-90)");
xShift = -xShift - this.textLength; // flip xShift
}
}
this.textElement.attr("x", xShift);
this.textElement.attr("y", yShift);
return this;
};
Label.CSS_CLASS = "label";
return Label;
})(Plottable.Component);
Plottable.Label = Label;
var TitleLabel = (function (_super) {
__extends(TitleLabel, _super);
function TitleLabel(text, orientation) {
_super.call(this, text, orientation);
this.classed(TitleLabel.CSS_CLASS, true);
}
TitleLabel.CSS_CLASS = "title-label";
return TitleLabel;
})(Label);
Plottable.TitleLabel = TitleLabel;
var AxisLabel = (function (_super) {
__extends(AxisLabel, _super);
function AxisLabel(text, orientation) {
_super.call(this, text, orientation);
this.classed(AxisLabel.CSS_CLASS, true);
}
AxisLabel.CSS_CLASS = "axis-label";
return AxisLabel;
})(Label);
Plottable.AxisLabel = AxisLabel;
})(Plottable || (Plottable = {}));
///<reference path="reference.ts" />
var Plottable;
(function (Plottable) {
var Renderer = (function (_super) {
__extends(Renderer, _super);
/**
* Creates a Renderer.
*
* @constructor
* @param {IDataset} [dataset] The dataset associated with the Renderer.
*/
function Renderer(dataset) {
if (typeof dataset === "undefined") { dataset = { seriesName: "", data: [] }; }
_super.call(this);
this.clipPathEnabled = true;
this.fixedWidthVal = false;
this.fixedHeightVal = false;
this.dataset = dataset;
this.classed(Renderer.CSS_CLASS, true);
}
/**
* Sets a new dataset on the Renderer.
*
* @param {IDataset} dataset The new dataset to be associated with the Renderer.
* @returns {Renderer} The calling Renderer.
*/
Renderer.prototype.data = function (dataset) {
this.renderArea.classed(this.dataset.seriesName, false);
this.dataset = dataset;
this.renderArea.classed(dataset.seriesName, true);
return this;
};
Renderer.prototype.anchor = function (element) {
_super.prototype.anchor.call(this, element);
this.renderArea = this.content.append("g").classed("render-area", true).classed(this.dataset.seriesName, true);
return this;
};
Renderer.CSS_CLASS = "renderer";
return Renderer;
})(Plottable.Component);
Plottable.Renderer = Renderer;
;
var XYRenderer = (function (_super) {
__extends(XYRenderer, _super);
/**
* Creates an XYRenderer.
*
* @constructor
* @param {IDataset} dataset The dataset to render.
* @param {QuantitiveScale} xScale The x scale to use.
* @param {QuantitiveScale} yScale The y scale to use.
* @param {IAccessor} [xAccessor] A function for extracting x values from the data.
* @param {IAccessor} [yAccessor] A function for extracting y values from the data.
*/
function XYRenderer(dataset, xScale, yScale, xAccessor, yAccessor) {
var _this = this;
_super.call(this, dataset);
this.classed(XYRenderer.CSS_CLASS);
this.xAccessor = (xAccessor != null) ? xAccessor : XYRenderer.defaultXAccessor;
this.yAccessor = (yAccessor != null) ? yAccessor : XYRenderer.defaultYAccessor;
this.xScale = xScale;
this.yScale = yScale;
var data = dataset.data;
var xDomain = d3.extent(data, this.xAccessor);
this.xScale.widenDomain(xDomain);
var yDomain = d3.extent(data, this.yAccessor);
this.yScale.widenDomain(yDomain);
this.xScale.registerListener(function () {
return _this.rescale();
});
this.yScale.registerListener(function () {
return _this.rescale();
});
}
XYRenderer.prototype.computeLayout = function (xOffset, yOffset, availableWidth, availableHeight) {
_super.prototype.computeLayout.call(this, xOffset, yOffset, availableWidth, availableHeight);
this.xScale.range([0, this.availableWidth]);
this.yScale.range([this.availableHeight, 0]);
return this;
};
/**
* Converts a SelectionArea with pixel ranges to one with data ranges.
*
* @param {SelectionArea} pixelArea The selected area, in pixels.
* @returns {SelectionArea} The corresponding selected area in the domains of the scales.
*/
XYRenderer.prototype.invertXYSelectionArea = function (pixelArea) {
var xMin = this.xScale.invert(pixelArea.xMin);
var xMax = this.xScale.invert(pixelArea.xMax);
var yMin = this.yScale.invert(pixelArea.yMin);
var yMax = this.yScale.invert(pixelArea.yMax);
var dataArea = { xMin: xMin, xMax: xMax, yMin: yMin, yMax: yMax };
return dataArea;
};
/**
* Gets the data in a selected area.
*
* @param {SelectionArea} dataArea The selected area.
* @returns {D3.UpdateSelection} The data in the selected area.
*/
XYRenderer.prototype.getSelectionFromArea = function (dataArea) {
var _this = this;
var filterFunction = function (d) {
var x = _this.xAccessor(d);
var y = _this.yAccessor(d);
return Plottable.Utils.inRange(x, dataArea.xMin, dataArea.xMax) && Plottable.Utils.inRange(y, dataArea.yMin, dataArea.yMax);
};
return this.dataSelection.filter(filterFunction);
};
/**
* Gets the indices of data in a selected area
*
* @param {SelectionArea} dataArea The selected area.
* @returns {number[]} An array of the indices of datapoints in the selected area.
*/
XYRenderer.prototype.getDataIndicesFromArea = function (dataArea) {
var _this = this;
var filterFunction = function (d) {
var x = _this.xAccessor(d);
var y = _this.yAccessor(d);
return Plottable.Utils.inRange(x, dataArea.xMin, dataArea.xMax) && Plottable.Utils.inRange(y, dataArea.yMin, dataArea.yMax);
};
var results = [];
this.dataset.data.forEach(function (d, i) {
if (filterFunction(d)) {
results.push(i);
}
});
return results;
};
XYRenderer.prototype.rescale = function () {
if (this.element != null) {
this.render();
}
};
XYRenderer.CSS_CLASS = "xy-renderer";
XYRenderer.defaultXAccessor = function (d) {
return d.x;
};
XYRenderer.defaultYAccessor = function (d) {
return d.y;
};
return XYRenderer;
})(Renderer);
Plottable.XYRenderer = XYRenderer;
var LineRenderer = (function (_super) {
__extends(LineRenderer, _super);
/**
* Creates a LineRenderer.
*
* @constructor
* @param {IDataset} dataset The dataset to render.
* @param {QuantitiveScale} xScale The x scale to use.
* @param {QuantitiveScale} yScale The y scale to use.
* @param {IAccessor} [xAccessor] A function for extracting x values from the data.
* @param {IAccessor} [yAccessor] A function for extracting y values from the data.
*/
function LineRenderer(dataset, xScale, yScale, xAccessor, yAccessor) {
_super.call(this, dataset, xScale, yScale, xAccessor, yAccessor);
this.classed(LineRenderer.CSS_CLASS, true);
}
LineRenderer.prototype.anchor = function (element) {
_super.prototype.anchor.call(this, element);
this.path = this.renderArea.append("path");
return this;
};
LineRenderer.prototype.render = function () {
var _this = this;
_super.prototype.render.call(this);
this.line = d3.svg.line().x(function (datum) {
return _this.xScale.scale(_this.xAccessor(datum));
}).y(function (datum) {
return _this.yScale.scale(_this.yAccessor(datum));
});
this.dataSelection = this.path.classed("line", true).classed(this.dataset.seriesName, true).datum(this.dataset.data);
this.path.attr("d", this.line);
return this;
};
LineRenderer.CSS_CLASS = "line-renderer";
return LineRenderer;
})(XYRenderer);
Plottable.LineRenderer = LineRenderer;
var CircleRenderer = (function (_super) {
__extends(CircleRenderer, _super);
/**
* Creates a CircleRenderer.
*
* @constructor
* @param {IDataset} dataset The dataset to render.
* @param {QuantitiveScale} xScale The x scale to use.
* @param {QuantitiveScale} yScale The y scale to use.
* @param {IAccessor} [xAccessor] A function for extracting x values from the data.
* @param {IAccessor} [yAccessor] A function for extracting y values from the data.
* @param {number} [size] The radius of the circles, in pixels.
*/
function CircleRenderer(dataset, xScale, yScale, xAccessor, yAccessor, size) {
if (typeof size === "undefined") { size = 3; }
_super.call(this, dataset, xScale, yScale, xAccessor, yAccessor);
this.classed(CircleRenderer.CSS_CLASS, true);
this.size = size;
}
CircleRenderer.prototype.render = function () {
var _this = this;
_super.prototype.render.call(this);
this.dataSelection = this.renderArea.selectAll("circle").data(this.dataset.data);
this.dataSelection.enter().append("circle");
this.dataSelection.attr("cx", function (datum) {
return _this.xScale.scale(_this.xAccessor(datum));
}).attr("cy", function (datum) {
return _this.yScale.scale(_this.yAccessor(datum));
}).attr("r", this.size);
this.dataSelection.exit().remove();
return this;
};
CircleRenderer.CSS_CLASS = "circle-renderer";
return CircleRenderer;
})(XYRenderer);
Plottable.CircleRenderer = CircleRenderer;
var BarRenderer = (function (_super) {
__extends(BarRenderer, _super);
/**
* Creates a BarRenderer.
*
* @constructor
* @param {IDataset} dataset The dataset to render.
* @param {QuantitiveScale} xScale The x scale to use.
* @param {QuantitiveScale} yScale The y scale to use.
* @param {IAccessor} [xAccessor] A function for extracting the start position of each bar from the data.
* @param {IAccessor} [dxAccessor] A function for extracting the width of each bar from the data.
* @param {IAccessor} [yAccessor] A function for extracting height of each bar from the data.
*/
function BarRenderer(dataset, xScale, yScale, xAccessor, dxAccessor, yAccessor) {
var _this = this;
_super.call(this, dataset, xScale, yScale, xAccessor, yAccessor);
this.barPaddingPx = 1;
this.classed(BarRenderer.CSS_CLASS, true);
var yDomain = this.yScale.domain();
if (!Plottable.Utils.inRange(0, yDomain[0], yDomain[1])) {
var newMin = 0;
var newMax = yDomain[1];
this.yScale.widenDomain([newMin, newMax]); // TODO: make this handle reversed scales
}
this.dxAccessor = (dxAccessor != null) ? dxAccessor : BarRenderer.defaultDxAccessor;
var x2Extent = d3.extent(dataset.data, function (d) {
return _this.xAccessor(d) + _this.dxAccessor(d);
});
this.xScale.widenDomain(x2Extent);
}
BarRenderer.prototype.render = function () {
var _this = this;
_super.prototype.render.call(this);
var yRange = this.yScale.range();
var maxScaledY = Math.max(yRange[0], yRange[1]);
this.dataSelection = this.renderArea.selectAll("rect").data(this.dataset.data);
var xdr = this.xScale.domain()[1] - this.xScale.domain()[0];
var xrr = this.xScale.range()[1] - this.xScale.range()[0];
this.dataSelection.enter().append("rect");
this.dataSelection.attr("x", function (d) {
return _this.xScale.scale(_this.xAccessor(d)) + _this.barPaddingPx;
}).attr("y", function (d) {
return _this.yScale.scale(_this.yAccessor(d));
}).attr("width", function (d) {
return _this.xScale.scale(_this.dxAccessor(d)) - _this.xScale.scale(0) - 2 * _this.barPaddingPx;
}).attr("height", function (d) {
return maxScaledY - _this.yScale.scale(_this.yAccessor(d));
});
this.dataSelection.exit().remove();
return this;
};
BarRenderer.CSS_CLASS = "bar-renderer";
BarRenderer.defaultDxAccessor = function (d) {
return d.dx;
};
return BarRenderer;
})(XYRenderer);
Plottable.BarRenderer = BarRenderer;
})(Plottable || (Plottable = {}));
///<reference path="reference.ts" />
var Plottable;
(function (Plottable) {
var Table = (function (_super) {
__extends(Table, _super);
/**
* Creates a Table.
*
* @constructor
* @param {Component[][]} [rows] A 2-D array of the Components to place in the table.
* null can be used if a cell is empty.
*/
function Table(rows) {
if (typeof rows === "undefined") { rows = []; }
_super.call(this);
this.rowPadding = 0;
this.colPadding = 0;
this.classed(Table.CSS_CLASS, true);
var cleanOutNulls = function (c) {
return c == null ? new Plottable.Component() : c;
};
rows = rows.map(function (row) {
return row.map(cleanOutNulls);
});
this.rows = rows;
this.rowWeights = this.rows.map(function () {
return null;
});
this.colWeights = d3.transpose(this.rows).map(function () {
return null;
});
}
/**
* Adds a Component in the specified cell.
*
* @param {number} row The row in which to add the Component.
* @param {number} col The column in which to add the Component.
* @param {Component} component The Component to be added.
*/
Table.prototype.addComponent = function (row, col, component) {
if (this.element != null) {
throw new Error("addComponent cannot be called after anchoring (for the moment)");
}
this.padTableToSize(row + 1, col + 1);
var currentComponent = this.rows[row][col];
if (currentComponent.constructor.name !== "Component") {
throw new Error("addComponent cannot be called on a cell where a component already exists (for the moment)");
}
this.rows[row][col] = component;
return this;
};
Table.prototype.anchor = function (element) {
var _this = this;
_super.prototype.anchor.call(this, element);
// recursively anchor children
this.rows.forEach(function (row, rowIndex) {
row.forEach(function (component, colIndex) {
component.anchor(_this.content.append("g"));
});
});
return this;
};
Table.prototype.computeLayout = function (xOffset, yOffset, availableWidth, availableHeight) {
var _this = this;
_super.prototype.computeLayout.call(this, xOffset, yOffset, availableWidth, availableHeight);
// calculate the amount of free space by recursive col-/row- Minimum() calls
var freeWidth = this.availableWidth - this.colMinimum();
var freeHeight = this.availableHeight - this.rowMinimum();
if (freeWidth < 0 || freeHeight < 0) {
throw new Error("Insufficient Space");
}
var cols = d3.transpose(this.rows);
var rowWeights = Table.calcComponentWeights(this.rowWeights, this.rows, function (c) {
return c.isFixedHeight();
});
var colWeights = Table.calcComponentWeights(this.colWeights, cols, function (c) {
return c.isFixedWidth();
});
// distribute remaining height to rows
var rowProportionalSpace = Table.calcProportionalSpace(rowWeights, freeHeight);
var colProportionalSpace = Table.calcProportionalSpace(colWeights, freeWidth);
var sumPair = function (p) {
return p[0] + p[1];
};
var rowHeights = d3.zip(rowProportionalSpace, this.rowMinimums).map(sumPair);
var colWidths = d3.zip(colProportionalSpace, this.colMinimums).map(sumPair);
var childYOffset = 0;
this.rows.forEach(function (row, rowIndex) {
var childXOffset = 0;
row.forEach(function (component, colIndex) {
// recursively compute layout
component.computeLayout(childXOffset, childYOffset, colWidths[colIndex], rowHeights[rowIndex]);
childXOffset += colWidths[colIndex] + _this.colPadding;
});
childYOffset += rowHeights[rowIndex] + _this.rowPadding;
});
return this;
};
Table.prototype.render = function () {
// recursively render children
this.rows.forEach(function (row, rowIndex) {
row.forEach(function (component, colIndex) {
component.render();
});
});
return this;
};
/**
* Sets the row and column padding on the Table.
*
* @param {number} rowPadding The padding above and below each row, in pixels.
* @param {number} colPadding the padding to the left and right of each column, in pixels.
* @returns {Table} The calling Table.
*/
Table.prototype.padding = function (rowPadding, colPadding) {
this.rowPadding = rowPadding;
this.colPadding = colPadding;
return this;
};
/**
* Sets the layout weight of a particular row.
* Space is allocated to rows based on their weight. Rows with higher weights receive proportionally more space.
*
* @param {number} index The index of the row.
* @param {number} weight The weight to be set on the row.
* @returns {Table} The calling Table.
*/
Table.prototype.rowWeight = function (index, weight) {
this.rowWeights[index] = weight;
return this;
};
/**
* Sets the layout weight of a particular column.
* Space is allocated to columns based on their weight. Columns with higher weights receive proportionally more space.
*
* @param {number} index The index of the column.
* @param {number} weight The weight to be set on the column.
* @returns {Table} The calling Table.
*/
Table.prototype.colWeight = function (index, weight) {
this.colWeights[index] = weight;
return this;
};
Table.prototype.rowMinimum = function (newVal) {
if (newVal != null) {
throw new Error("Row minimum cannot be directly set on Table");
} else {
this.rowMinimums = this.rows.map(function (row) {
return d3.max(row, function (r) {
return r.rowMinimum();
});
});
return d3.sum(this.rowMinimums) + this.rowPadding * (this.rows.length - 1);
}
};
Table.prototype.colMinimum = function (newVal) {
if (newVal != null) {
throw new Error("Col minimum cannot be directly set on Table");
} else {
var cols = d3.transpose(this.rows);
this.colMinimums = cols.map(function (col) {
return d3.max(col, function (r) {
return r.colMinimum();
});
});
return d3.sum(this.colMinimums) + this.colPadding * (cols.length - 1);
}
};
Table.prototype.isFixedWidth = function () {
var cols = d3.transpose(this.rows);
return Table.fixedSpace(cols, function (c) {
return c.isFixedWidth();
});
};
Table.prototype.isFixedHeight = function () {
return Table.fixedSpace(this.rows, function (c) {
return c.isFixedHeight();
});
};
Table.prototype.padTableToSize = function (nRows, nCols) {
for (var i = 0; i < nRows; i++) {
if (this.rows[i] === undefined) {
this.rows[i] = [];
this.rowWeights[i] = null;
}
for (var j = 0; j < nCols; j++) {
if (this.rows[i][j] === undefined) {
this.rows[i][j] = new Plottable.Component();
}
}
}
for (j = 0; j < nCols; j++) {
if (this.colWeights[j] === undefined) {
this.colWeights[j] = null;
}
}
};
Table.calcComponentWeights = function (setWeights, componentGroups, fixityAccessor) {
// If the row/col weight was explicitly set, then return it outright
// If the weight was not explicitly set, then guess it using the heuristic that if all components are fixed-space
// then weight is 0, otherwise weight is 1
return setWeights.map(function (w, i) {
if (w != null) {
return w;
}
var fixities = componentGroups[i].map(fixityAccessor);
var allFixed = fixities.reduce(function (a, b) {
return a && b;
});
return allFixed ? 0 : 1;
});
};
Table.calcProportionalSpace = function (weights, freeSpace) {
var weightSum = d3.sum(weights);
if (weightSum === 0) {
var numGroups = weights.length;
return weights.map(function (w) {
return freeSpace / numGroups;
});
} else {
return weights.map(function (w) {
return freeSpace * w / weightSum;
});
}
};
Table.fixedSpace = function (componentGroup, fixityAccessor) {
var all = function (bools) {
return bools.reduce(function (a, b) {
return a && b;
});
};
var groupIsFixed = function (components) {
return all(components.map(fixityAccessor));
};
return all(componentGroup.map(groupIsFixed));
};
Table.CSS_CLASS = "table";
return Table;
})(Plottable.Component);
Plottable.Table = Table;
})(Plottable || (Plottable = {}));
///<reference path="reference.ts" />
var Plottable;
(function (Plottable) {
var ScaleDomainCoordinator = (function () {
/**
* Creates a ScaleDomainCoordinator.
*
* @constructor
* @param {Scale[]} scales A list of scales whose domains should be linked.
*/
function ScaleDomainCoordinator(scales) {
var _this = this;
/* This class is responsible for maintaining coordination between linked scales.
It registers event listeners for when one of its scales changes its domain. When the scale
does change its domain, it re-propogates the change to every linked scale.
*/
this.rescaleInProgress = false;
this.scales = scales;
this.scales.forEach(function (s) {
return s.registerListener(function (sx) {
return _this.rescale(sx);
});
});
}
ScaleDomainCoordinator.prototype.rescale = function (scale) {
if (this.rescaleInProgress) {
return;
}
this.rescaleInProgress = true;
var newDomain = scale.domain();
this.scales.forEach(function (s) {
return s.domain(newDomain);
});
this.rescaleInProgress = false;
};
return ScaleDomainCoordinator;
})();
Plottable.ScaleDomainCoordinator = ScaleDomainCoordinator;
})(Plottable || (Plottable = {}));
///<reference path="reference.ts" />
var Plottable;
(function (Plottable) {
var Legend = (function (_super) {
__extends(Legend, _super);
/**
* Creates a Legend.
*
* @constructor
* @param {ColorScale} colorScale
*/
function Legend(colorScale) {
_super.call(this);
this.classed(Legend.CSS_CLASS, true);
this.colMinimum(120); // the default width
this.colorScale = colorScale;
this.xAlign("RIGHT").yAlign("TOP");
this.xOffset(5).yOffset(5);
}
/**
* Assigns a new ColorScale to the Legend.
*
* @param {ColorScale} scale
* @returns {Legend} The calling Legend.
*/
Legend.prototype.scale = function (scale) {
this.colorScale = scale;
return this;
};
Legend.prototype.rowMinimum = function (newVal) {
if (newVal != null) {
throw new Error("Row minimum cannot be directly set on Legend");
} else {
var textHeight = this.measureTextHeight();
return this.colorScale.domain().length * textHeight;
}
};
Legend.prototype.measureTextHeight = function () {
// note: can't be called before anchoring atm
var fakeLegendEl = this.content.append("g").classed(Legend.SUBELEMENT_CLASS, true);
var textHeight = Plottable.Utils.getTextHeight(fakeLegendEl.append("text"));
fakeLegendEl.remove();
return textHeight;
};
Legend.prototype.render = function () {
_super.prototype.render.call(this);
var domain = this.colorScale.domain();
var textHeight = this.measureTextHeight();
var availableWidth = this.colMinimum() - textHeight - Legend.MARGIN;
this.content.selectAll("." + Legend.SUBELEMENT_CLASS).remove(); // hackhack to ensure it always rerenders properly
var legend = this.content.selectAll("." + Legend.SUBELEMENT_CLASS).data(domain);
var legendEnter = legend.enter().append("g").classed(Legend.SUBELEMENT_CLASS, true).attr("transform", function (d, i) {
return "translate(0," + i * textHeight + ")";
});
legendEnter.append("rect").attr("x", Legend.MARGIN).attr("y", Legend.MARGIN).attr("width", textHeight - Legend.MARGIN * 2).attr("height", textHeight - Legend.MARGIN * 2);
legendEnter.append("text").attr("x", textHeight).attr("y", Legend.MARGIN + textHeight / 2);
legend.selectAll("rect").attr("fill", this.colorScale._d3Scale);
legend.selectAll("text").text(function (d, i) {
return Plottable.Utils.truncateTextToLength(d, availableWidth, d3.select(this));
});
return this;
};
Legend.CSS_CLASS = "legend";
Legend.SUBELEMENT_CLASS = "legend-row";
Legend.MARGIN = 5;
return Legend;
})(Plottable.Component);
Plottable.Legend = Legend;
})(Plottable || (Plottable = {}));
///<reference path="reference.ts" />
var Plottable;
(function (Plottable) {
var Axis = (function (_super) {
__extends(Axis, _super);
/**
* Creates an Axis.
*
* @constructor
* @param {Scale} scale The Scale to base the Axis on.
* @param {string} orientation The orientation of the Axis (top/bottom/left/right)
* @param {any} [formatter] a D3 formatter
*/
function Axis(axisScale, orientation, formatter) {
var _this = this;
_super.call(this);
this.axisScale = axisScale;
this.d3Axis = d3.svg.axis().scale(axisScale._d3Scale).orient(orientation);
this.classed(Axis.CSS_CLASS, true);
this.clipPathEnabled = true;
this.isXAligned = this.orient() === "bottom" || this.orient() === "top";
if (formatter == null) {
formatter = d3.format(".3s");
}
this.d3Axis.tickFormat(formatter);
this.axisScale.registerListener(function () {
return _this.rescale();
});
}
Axis.prototype.anchor = function (element) {
_super.prototype.anchor.call(this, element);
this.axisElement = this.content.append("g").classed("axis", true); // TODO: remove extraneous sub-element
return this;
};
Axis.prototype.render = function () {
if (this.orient() === "left") {
this.axisElement.attr("transform", "translate(" + Axis.yWidth + ", 0)");
}
;
if (this.orient() === "top") {
this.axisElement.attr("transform", "translate(0," + Axis.xHeight + ")");
}
;
var domain = this.d3Axis.scale().domain();
var extent = Math.abs(domain[1] - domain[0]);
var min = +d3.min(domain);
var max = +d3.max(domain);
var newDomain;
var standardOrder = domain[0] < domain[1];
if (typeof (domain[0]) === "number") {
newDomain = standardOrder ? [min - extent, max + extent] : [max + extent, min - extent];
} else {
newDomain = standardOrder ? [new Date(min - extent), new Date(max + extent)] : [new Date(max + extent), new Date(min - extent)];
}
// hackhack Make tiny-zero representations not look terrible, by rounding them to 0
if (this.axisScale.ticks != null) {
var scale = this.axisScale;
var nTicks = 10;
var ticks = scale.ticks(nTicks);
var numericDomain = scale.domain();
var interval = numericDomain[1] - numericDomain[0];
var cleanTick = function (n) {
return Math.abs(n / interval / nTicks) < 0.0001 ? 0 : n;
};
ticks = ticks.map(cleanTick);
this.d3Axis.tickValues(ticks);
}
this.axisElement.call(this.d3Axis);
var bbox = this.axisElement.node().getBBox();
if (bbox.height > this.availableHeight || bbox.width > this.availableWidth) {
this.axisElement.classed("error", true);
}
return this;
};
Axis.prototype.rescale = function () {
return (this.element != null) ? this.render() : null;
// short circuit, we don't care about perf.
};
Axis.prototype.scale = function (newScale) {
if (newScale == null) {
return this.axisScale;
} else {
this.axisScale = newScale;
this.d3Axis.scale(newScale._d3Scale);
return this;
}
};
Axis.prototype.orient = function (newOrient) {
if (newOrient == null) {
return this.d3Axis.orient();
} else {
this.d3Axis.orient(newOrient);
return this;
}
};
Axis.prototype.ticks = function () {
var args = [];
for (var _i = 0; _i < (arguments.length - 0); _i++) {
args[_i] = arguments[_i + 0];
}
if (args == null || args.length === 0) {
return this.d3Axis.ticks();
} else {
this.d3Axis.ticks(args);
return this;
}
};
Axis.prototype.tickValues = function () {
var args = [];
for (var _i = 0; _i < (arguments.length - 0); _i++) {
args[_i] = arguments[_i + 0];
}
if (args == null) {
return this.d3Axis.tickValues();
} else {
this.d3Axis.tickValues(args);
return this;
}
};
Axis.prototype.tickSize = function (inner, outer) {
if (inner != null && outer != null) {
this.d3Axis.tickSize(inner, outer);
return this;
} else if (inner != null) {
this.d3Axis.tickSize(inner);
return this;
} else {
return this.d3Axis.tickSize();
}
};
Axis.prototype.innerTickSize = function (val) {
if (val == null) {
return this.d3Axis.innerTickSize();
} else {
this.d3Axis.innerTickSize(val);
return this;
}
};
Axis.prototype.outerTickSize = function (val) {
if (val == null) {
return this.d3Axis.outerTickSize();
} else {
this.d3Axis.outerTickSize(val);
return this;
}
};
Axis.prototype.tickPadding = function (val) {
if (val == null) {
return this.d3Axis.tickPadding();
} else {
this.d3Axis.tickPadding(val);
return this;
}
};
Axis.prototype.tickFormat = function (formatter) {
if (formatter == null) {
return this.d3Axis.tickFormat();
} else {
this.d3Axis.tickFormat(formatter);
return this;
}
};
Axis.CSS_CLASS = "axis";
Axis.yWidth = 50;
Axis.xHeight = 30;
return Axis;
})(Plottable.Component);
Plottable.Axis = Axis;
var XAxis = (function (_super) {
__extends(XAxis, _super);
/**
* Creates an XAxis (a horizontal Axis).
*
* @constructor
* @param {Scale} scale The Scale to base the Axis on.
* @param {string} orientation The orientation of the Axis (top/bottom/left/right)
* @param {any} [formatter] a D3 formatter
*/
function XAxis(scale, orientation, formatter) {
if (typeof formatter === "undefined") { formatter = null; }
_super.call(this, scale, orientation, formatter);
_super.prototype.rowMinimum.call(this, Axis.xHeight);
this.fixedWidthVal = false;
}
return XAxis;
})(Axis);
Plottable.XAxis = XAxis;
var YAxis = (function (_super) {
__extends(YAxis, _super);
/**
* Creates a YAxis (a vertical Axis).
*
* @constructor
* @param {Scale} scale The Scale to base the Axis on.
* @param {string} orientation The orientation of the Axis (top/bottom/left/right)
* @param {any} [formatter] a D3 formatter
*/
function YAxis(scale, orientation, formatter) {
if (typeof formatter === "undefined") { formatter = null; }
_super.call(this, scale, orientation, formatter);
_super.prototype.colMinimum.call(this, Axis.yWidth);
this.fixedHeightVal = false;
}
return YAxis;
})(Axis);
Plottable.YAxis = YAxis;
})(Plottable || (Plottable = {}));
///<reference path="reference.ts" />
var Plottable;
(function (Plottable) {
var ComponentGroup = (function (_super) {
__extends(ComponentGroup, _super);
/**
* Creates a ComponentGroup.
*
* @constructor
* @param {Component[]} [components] The Components in the ComponentGroup.
*/
function ComponentGroup(components) {
if (typeof components === "undefined") { components = []; }
_super.call(this);
this.classed(ComponentGroup.CSS_CLASS, true);
this.components = components;
}
/**
* Adds a Component to the ComponentGroup.
*
* @param {Component} c The Component to add.
* @returns {ComponentGroup} The calling ComponentGroup.
*/
ComponentGroup.prototype.addComponent = function (c) {
this.components.push(c);
if (this.element != null) {
c.anchor(this.content.append("g"));
}
return this;
};
ComponentGroup.prototype.anchor = function (element) {
var _this = this;
_super.prototype.anchor.call(this, element);
this.components.forEach(function (c) {
return c.anchor(_this.content.append("g"));
});
return this;
};
ComponentGroup.prototype.computeLayout = function (xOrigin, yOrigin, availableWidth, availableHeight) {
var _this = this;
_super.prototype.computeLayout.call(this, xOrigin, yOrigin, availableWidth, availableHeight);
this.components.forEach(function (c) {
c.computeLayout(0, 0, _this.availableWidth, _this.availableHeight);
});
return this;
};
ComponentGroup.prototype.render = function () {
_super.prototype.render.call(this);
this.components.forEach(function (c) {
return c.render();
});
return this;
};
ComponentGroup.prototype.isFixedWidth = function () {
return this.components.every(function (c) {
return c.isFixedWidth();
});
};
ComponentGroup.prototype.isFixedHeight = function () {
return this.components.every(function (c) {
return c.isFixedHeight();
});
};
ComponentGroup.CSS_CLASS = "component-group";
return ComponentGroup;
})(Plottable.Component);
Plottable.ComponentGroup = ComponentGroup;
})(Plottable || (Plottable = {}));
|
// Browser specific code for the OAuth package.
// Open a popup window, centered on the screen, and call a callback when it
// closes.
//
// @param url {String} url to show
// @param callback {Function} Callback function to call on completion. Takes no
// arguments.
// @param dimensions {optional Object(width, height)} The dimensions of
// the popup. If not passed defaults to something sane.
OAuth.showPopup = function (url, callback, dimensions) {
// default dimensions that worked well for facebook and google
var popup = openCenteredPopup(
url,
(dimensions && dimensions.width) || 650,
(dimensions && dimensions.height) || 331
);
var checkPopupOpen = setInterval(function() {
try {
// Fix for #328 - added a second test criteria (popup.closed === undefined)
// to humour this Android quirk:
// http://code.google.com/p/android/issues/detail?id=21061
var popupClosed = popup.closed || popup.closed === undefined;
} catch (e) {
// For some unknown reason, IE9 (and others?) sometimes (when
// the popup closes too quickly?) throws "SCRIPT16386: No such
// interface supported" when trying to read 'popup.closed'. Try
// again in 100ms.
return;
}
if (popupClosed) {
clearInterval(checkPopupOpen);
callback();
}
}, 100);
};
var openCenteredPopup = function(url, width, height) {
var screenX = typeof window.screenX !== 'undefined'
? window.screenX : window.screenLeft;
var screenY = typeof window.screenY !== 'undefined'
? window.screenY : window.screenTop;
var outerWidth = typeof window.outerWidth !== 'undefined'
? window.outerWidth : document.body.clientWidth;
var outerHeight = typeof window.outerHeight !== 'undefined'
? window.outerHeight : (document.body.clientHeight - 22);
// XXX what is the 22?
// Use `outerWidth - width` and `outerHeight - height` for help in
// positioning the popup centered relative to the current window
var left = screenX + (outerWidth - width) / 2;
var top = screenY + (outerHeight - height) / 2;
var features = ('width=' + width + ',height=' + height +
',left=' + left + ',top=' + top + ',scrollbars=yes');
var newwindow = window.open(url, 'Login', features);
if (typeof newwindow === 'undefined') {
// blocked by a popup blocker maybe?
var err = new Error("The login popup was blocked by the browser");
err.attemptedUrl = url;
throw err;
}
if (newwindow.focus)
newwindow.focus();
return newwindow;
};
|
require('./angular-locale_bg');
module.exports = 'ngLocale';
|
var baseSlice = require('../internal/baseSlice'),
createWrapper = require('../internal/createWrapper'),
replaceHolders = require('../internal/replaceHolders');
/** Used to compose bitmasks for wrapper metadata. */
var PARTIAL_RIGHT_FLAG = 64;
/**
* This method is like `_.partial` except that partially applied arguments
* are appended to those provided to the new function.
*
* The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method does not set the `length` property of partially
* applied functions.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [args] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* var greet = function(greeting, name) {
* return greeting + ' ' + name;
* };
*
* var greetFred = _.partialRight(greet, 'fred');
* greetFred('hi');
* // => 'hi fred'
*
* // using placeholders
* var sayHelloTo = _.partialRight(greet, 'hello', _);
* sayHelloTo('fred');
* // => 'hello fred'
*/
function partialRight(func) {
var partials = baseSlice(arguments, 1),
holders = replaceHolders(partials, partialRight.placeholder);
return createWrapper(func, PARTIAL_RIGHT_FLAG, null, partials, holders);
}
// Assign default placeholders.
partialRight.placeholder = {};
module.exports = partialRight;
|
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v14.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
|
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-core
*/
/*jslint evil: true */
'use strict';
var React;
var ReactInstanceMap;
var ReactMount;
var getTestDocument;
var testDocument;
var UNMOUNT_INVARIANT_MESSAGE =
'Invariant Violation: ReactFullPageComponenthtml tried to unmount. ' +
'Because of cross-browser quirks it is impossible to unmount some ' +
'top-level components (eg <html>, <head>, and <body>) reliably and ' +
'efficiently. To fix this, have a single top-level component that ' +
'never unmounts render these elements.';
describe('rendering React components at document', function() {
beforeEach(function() {
require('mock-modules').dumpCache();
React = require('React');
ReactInstanceMap = require('ReactInstanceMap');
ReactMount = require('ReactMount');
getTestDocument = require('getTestDocument');
testDocument = getTestDocument();
});
it('should be able to get root component id for document node', function() {
expect(testDocument).not.toBeUndefined();
var Root = React.createClass({
render: function() {
return (
<html>
<head>
<title>Hello World</title>
</head>
<body>
Hello world
</body>
</html>
);
}
});
var markup = React.renderToString(<Root />);
testDocument = getTestDocument(markup);
var component = React.render(<Root />, testDocument);
expect(testDocument.body.innerHTML).toBe('Hello world');
// TODO: This is a bad test. I have no idea what this is testing.
// Node IDs is an implementation detail and not part of the public API.
var componentID = ReactMount.getReactRootID(testDocument);
expect(componentID).toBe(ReactInstanceMap.get(component)._rootNodeID);
});
it('should not be able to unmount component from document node', function() {
expect(testDocument).not.toBeUndefined();
var Root = React.createClass({
render: function() {
return (
<html>
<head>
<title>Hello World</title>
</head>
<body>
Hello world
</body>
</html>
);
}
});
var markup = React.renderToString(<Root />);
testDocument = getTestDocument(markup);
React.render(<Root />, testDocument);
expect(testDocument.body.innerHTML).toBe('Hello world');
expect(function() {
React.unmountComponentAtNode(testDocument);
}).toThrow(UNMOUNT_INVARIANT_MESSAGE);
expect(testDocument.body.innerHTML).toBe('Hello world');
});
it('should not be able to switch root constructors', function() {
expect(testDocument).not.toBeUndefined();
var Component = React.createClass({
render: function() {
return (
<html>
<head>
<title>Hello World</title>
</head>
<body>
Hello world
</body>
</html>
);
}
});
var Component2 = React.createClass({
render: function() {
return (
<html>
<head>
<title>Hello World</title>
</head>
<body>
Goodbye world
</body>
</html>
);
}
});
var markup = React.renderToString(<Component />);
testDocument = getTestDocument(markup);
React.render(<Component />, testDocument);
expect(testDocument.body.innerHTML).toBe('Hello world');
// Reactive update
expect(function() {
React.render(<Component2 />, testDocument);
}).toThrow(UNMOUNT_INVARIANT_MESSAGE);
expect(testDocument.body.innerHTML).toBe('Hello world');
});
it('should be able to mount into document', function() {
expect(testDocument).not.toBeUndefined();
var Component = React.createClass({
render: function() {
return (
<html>
<head>
<title>Hello World</title>
</head>
<body>
{this.props.text}
</body>
</html>
);
}
});
var markup = React.renderToString(
<Component text="Hello world" />
);
testDocument = getTestDocument(markup);
React.render(<Component text="Hello world" />, testDocument);
expect(testDocument.body.innerHTML).toBe('Hello world');
});
it('should give helpful errors on state desync', function() {
expect(testDocument).not.toBeUndefined();
var Component = React.createClass({
render: function() {
return (
<html>
<head>
<title>Hello World</title>
</head>
<body>
{this.props.text}
</body>
</html>
);
}
});
var markup = React.renderToString(
<Component text="Goodbye world" />
);
testDocument = getTestDocument(markup);
expect(function() {
// Notice the text is different!
React.render(<Component text="Hello world" />, testDocument);
}).toThrow(
'Invariant Violation: ' +
'You\'re trying to render a component to the document using ' +
'server rendering but the checksum was invalid. This usually ' +
'means you rendered a different component type or props on ' +
'the client from the one on the server, or your render() methods ' +
'are impure. React cannot handle this case due to cross-browser ' +
'quirks by rendering at the document root. You should look for ' +
'environment dependent code in your components and ensure ' +
'the props are the same client and server side:\n' +
' (client) data-reactid=".0.1">Hello world</body></\n' +
' (server) data-reactid=".0.1">Goodbye world</body>'
);
});
it('should throw on full document render w/ no markup', function() {
expect(testDocument).not.toBeUndefined();
var container = testDocument;
var Component = React.createClass({
render: function() {
return (
<html>
<head>
<title>Hello World</title>
</head>
<body>
{this.props.text}
</body>
</html>
);
}
});
expect(function() {
React.render(<Component />, container);
}).toThrow(
'Invariant Violation: You\'re trying to render a component to the ' +
'document but you didn\'t use server rendering. We can\'t do this ' +
'without using server rendering due to cross-browser quirks. See ' +
'React.renderToString() for server rendering.'
);
});
it('supports getDOMNode on full-page components', function() {
var tree =
<html>
<head>
<title>Hello World</title>
</head>
<body>
Hello world
</body>
</html>;
var markup = React.renderToString(tree);
testDocument = getTestDocument(markup);
var component = React.render(tree, testDocument);
expect(testDocument.body.innerHTML).toBe('Hello world');
expect(component.getDOMNode().tagName).toBe('HTML');
});
});
|
/*
* NotFoundPage Messages
*
* This contains all the text for the NotFoundPage component.
*/
import { defineMessages } from 'react-intl';
export default defineMessages({
header: {
id: 'app.components.NotFoundPage.header',
defaultMessage: 'This is NotFoundPage component!',
},
});
|
/*
AngularJS v1.4.3
(c) 2010-2015 Google, Inc. http://angularjs.org
License: MIT
*/
(function(A,h,B){'use strict';function v(h){return["$animate",function(q){return{restrict:"AE",transclude:"element",terminal:!0,require:"^^ngMessages",link:function(m,e,a,g,k){var c=e[0],n,l=a.ngMessage||a.when;a=a.ngMessageExp||a.whenExp;var p=function(d){n=d?w(d)?d:d.split(/[\s,]+/):null;g.reRender()};a?(p(m.$eval(a)),m.$watchCollection(a,p)):p(l);var f,r;g.register(c,r={test:function(d){var b=n;d=b?w(b)?0<=b.indexOf(d):b.hasOwnProperty(d):void 0;return d},attach:function(){f||k(m,function(d){q.enter(d,
null,e);f=d;f.on("$destroy",function(){f&&(g.deregister(c),r.detach())})})},detach:function(){if(f){var d=f;f=null;q.leave(d)}}})}}}]}var w=h.isArray,x=h.forEach,y=h.isString,z=h.element;h.module("ngMessages",[]).directive("ngMessages",["$animate",function(h){function q(e,a){return y(a)&&0===a.length||m(e.$eval(a))}function m(e){return y(e)?e.length:!!e}return{require:"ngMessages",restrict:"AE",controller:["$element","$scope","$attrs",function(e,a,g){function k(a,d){for(var b=d,e=[];b&&b!==a;){var c=
b.$$ngMessageNode;if(c&&c.length)return l[c];b.childNodes.length&&-1==e.indexOf(b)?(e.push(b),b=b.childNodes[b.childNodes.length-1]):b=b.previousSibling||b.parentNode}}var c=this,n=0,l=this.messages={},p,f;this.render=function(r){r=r||{};p=!1;f=r;for(var d=q(a,g.ngMessagesMultiple)||q(a,g.multiple),b=[],n={},s=c.head,k=!1,l=0;null!=s;){l++;var t=s.message,u=!1;k||x(r,function(b,a){!u&&m(b)&&t.test(a)&&!n[a]&&(u=n[a]=!0,t.attach())});u?k=!d:b.push(t);s=s.next}x(b,function(b){b.detach()});b.length!==
l?h.setClass(e,"ng-active","ng-inactive"):h.setClass(e,"ng-inactive","ng-active")};a.$watchCollection(g.ngMessages||g["for"],c.render);this.reRender=function(){p||(p=!0,a.$evalAsync(function(){p&&f&&c.render(f)}))};this.register=function(a,d){var b=n.toString();l[b]={message:d};var g=e[0],f=l[b];c.head?(g=k(g,a))?(f.next=g.next,g.next=f):(f.next=c.head,c.head=f):c.head=f;a.$$ngMessageNode=b;n++;c.reRender()};this.deregister=function(a){var d=a.$$ngMessageNode;delete a.$$ngMessageNode;var b=l[d];(a=
k(e[0],a))?a.next=b.next:c.head=b.next;delete l[d];c.reRender()}}]}}]).directive("ngMessagesInclude",["$templateRequest","$document","$compile",function(h,q,m){return{restrict:"AE",require:"^^ngMessages",link:function(e,a,g){var k=g.ngMessagesInclude||g.src;h(k).then(function(c){m(c)(e,function(c){a.after(c);c=z(q[0].createComment(" ngMessagesInclude: "+k+" "));a.after(c);a.remove()})})}}}]).directive("ngMessage",v("AE")).directive("ngMessageExp",v("A"))})(window,window.angular);
//# sourceMappingURL=angular-messages.min.js.map
|
/*
* /MathJax/localization/ia/HTML-CSS.js
*
* Copyright (c) 2009-2013 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.Localization.addTranslation("ia","HTML-CSS",{version:"2.3",isLoaded:true,strings:{}});MathJax.Ajax.loadComplete("[MathJax]/localization/ia/HTML-CSS.js");
|
(function() {
var Bacon, Bus, CompositeUnsubscribe, Dispatcher, End, Error, Event, EventStream, Initial, Next, None, Observable, Property, PropertyDispatcher, PropertyTransaction, Some, addPropertyInitValueToStream, assert, assertArray, assertEvent, assertEventStream, assertFunction, assertNoArguments, assertString, cloneArray, compositeUnsubscribe, convertArgsToFunction, end, former, indexOf, initial, isFieldKey, isFunction, latter, liftCallback, makeFunction, makeSpawner, methodCall, next, nop, partiallyApplied, sendWrapped, toCombinator, toEvent, toFieldExtractor, toFieldKey, toOption, toSimpleExtractor, _, _ref, _ref1, _ref2,
__slice = [].slice,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
if (typeof module !== "undefined" && module !== null) {
module.exports = Bacon = {};
Bacon.Bacon = Bacon;
} else {
if (typeof require === 'function' && (require.amd != null)) {
define('bacon', [], function() {
return Bacon;
});
}
this.Bacon = Bacon = {};
}
Bacon.fromBinder = function(binder, eventTransformer) {
if (eventTransformer == null) {
eventTransformer = _.id;
}
return new EventStream(function(sink) {
var unbinder;
return unbinder = binder(function() {
var args, event, reply, value, _i, _len, _results;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
value = eventTransformer.apply(null, args);
if (!(value instanceof Array && _.last(value) instanceof Event)) {
value = [value];
}
_results = [];
for (_i = 0, _len = value.length; _i < _len; _i++) {
event = value[_i];
reply = sink(event = toEvent(event));
if (reply === Bacon.noMore || event.isEnd()) {
if (unbinder != null) {
_results.push(unbinder());
} else {
_results.push(Bacon.scheduler.setTimeout((function() {
return unbinder();
}), 0));
}
} else {
_results.push(void 0);
}
}
return _results;
});
});
};
Bacon.$ = {
asEventStream: function(eventName, selector, eventTransformer) {
var _ref,
_this = this;
if (isFunction(selector)) {
_ref = [selector, null], eventTransformer = _ref[0], selector = _ref[1];
}
return Bacon.fromBinder(function(handler) {
_this.on(eventName, selector, handler);
return function() {
return _this.off(eventName, selector, handler);
};
}, eventTransformer);
}
};
if ((_ref = typeof jQuery !== "undefined" && jQuery !== null ? jQuery : typeof Zepto !== "undefined" && Zepto !== null ? Zepto : null) != null) {
_ref.fn.asEventStream = Bacon.$.asEventStream;
}
Bacon.fromEventTarget = function(target, eventName, eventTransformer) {
var sub, unsub, _ref1, _ref2, _ref3, _ref4;
sub = (_ref1 = target.addEventListener) != null ? _ref1 : (_ref2 = target.addListener) != null ? _ref2 : target.bind;
unsub = (_ref3 = target.removeEventListener) != null ? _ref3 : (_ref4 = target.removeListener) != null ? _ref4 : target.unbind;
return Bacon.fromBinder(function(handler) {
sub.call(target, eventName, handler);
return function() {
return unsub.call(target, eventName, handler);
};
}, eventTransformer);
};
Bacon.fromPromise = function(promise, abort) {
return Bacon.fromBinder(function(handler) {
promise.then(handler, function(e) {
return handler(new Error(e));
});
return function() {
if (abort) {
return typeof promise.abort === "function" ? promise.abort() : void 0;
}
};
}, function(value) {
return [value, end()];
});
};
Bacon.noMore = ["<no-more>"];
Bacon.more = ["<more>"];
Bacon.later = function(delay, value) {
return Bacon.sequentially(delay, [value]);
};
Bacon.sequentially = function(delay, values) {
var index;
index = 0;
return Bacon.fromPoll(delay, function() {
var value;
value = values[index++];
if (index < values.length) {
return value;
} else if (index === values.length) {
return [value, end()];
} else {
return end();
}
});
};
Bacon.repeatedly = function(delay, values) {
var index;
index = 0;
return Bacon.fromPoll(delay, function() {
return values[index++ % values.length];
});
};
liftCallback = function(wrapped) {
return function() {
var args, f, stream;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
stream = partiallyApplied(wrapped, [
function(values, callback) {
return f.apply(null, __slice.call(values).concat([callback]));
}
]);
return Bacon.combineAsArray(args).flatMap(stream);
};
};
Bacon.fromCallback = liftCallback(function() {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return Bacon.fromBinder(function(handler) {
makeFunction(f, args)(handler);
return nop;
}, function(value) {
return [value, end()];
});
});
Bacon.fromNodeCallback = liftCallback(function() {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return Bacon.fromBinder(function(handler) {
makeFunction(f, args)(handler);
return nop;
}, function(error, value) {
if (error) {
return [new Error(error), end()];
}
return [value, end()];
});
});
Bacon.fromPoll = function(delay, poll) {
return Bacon.fromBinder(function(handler) {
var id;
id = Bacon.scheduler.setInterval(handler, delay);
return function() {
return Bacon.scheduler.clearInterval(id);
};
}, poll);
};
Bacon.interval = function(delay, value) {
if (value == null) {
value = {};
}
return Bacon.fromPoll(delay, function() {
return next(value);
});
};
Bacon.constant = function(value) {
return new Property(sendWrapped([value], initial), true);
};
Bacon.never = function() {
return Bacon.fromArray([]);
};
Bacon.once = function(value) {
return Bacon.fromArray([value]);
};
Bacon.fromArray = function(values) {
return new EventStream(sendWrapped(values, toEvent));
};
sendWrapped = function(values, wrapper) {
return function(sink) {
var value, _i, _len;
for (_i = 0, _len = values.length; _i < _len; _i++) {
value = values[_i];
sink(wrapper(value));
}
sink(end());
return nop;
};
};
Bacon.mergeAll = function() {
var more, streams;
streams = arguments[0], more = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
if (!(streams instanceof Array)) {
streams = [streams].concat(more);
}
return _.fold(streams, Bacon.never(), (function(a, b) {
return a.merge(b);
}));
};
Bacon.zipAsArray = function() {
var more, streams;
streams = arguments[0], more = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
if (!(streams instanceof Array)) {
streams = [streams].concat(more);
}
return Bacon.zipWith(streams, Array);
};
Bacon.zipWith = function() {
var f, more, streams, _ref1;
streams = arguments[0], f = arguments[1], more = 3 <= arguments.length ? __slice.call(arguments, 2) : [];
if (isFunction(streams)) {
_ref1 = [[f].concat(more), streams], streams = _ref1[0], f = _ref1[1];
}
return Bacon.when(streams, f);
};
Bacon.combineAsArray = function() {
var more, s, streams, values,
_this = this;
streams = arguments[0], more = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
if (!(streams instanceof Array)) {
streams = [streams].concat(more);
}
if (streams.length) {
values = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = streams.length; _i < _len; _i++) {
s = streams[_i];
_results.push(None);
}
return _results;
})();
return new Property(function(sink) {
var checkEnd, combiningSink, ends, index, initialSent, sinkFor, stream, unsubAll, unsubs, unsubscribed, _i, _len;
unsubscribed = false;
unsubs = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = streams.length; _i < _len; _i++) {
s = streams[_i];
_results.push(nop);
}
return _results;
})();
unsubAll = (function() {
var f, _i, _len;
for (_i = 0, _len = unsubs.length; _i < _len; _i++) {
f = unsubs[_i];
f();
}
return unsubscribed = true;
});
ends = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = streams.length; _i < _len; _i++) {
s = streams[_i];
_results.push(false);
}
return _results;
})();
checkEnd = function() {
var reply;
if (_.all(ends)) {
reply = sink(end());
if (reply === Bacon.noMore) {
unsubAll();
}
return reply;
}
};
initialSent = false;
combiningSink = function(markEnd, setValue) {
return function(event) {
var reply, valueArrayF;
if (event.isEnd()) {
markEnd();
checkEnd();
return Bacon.noMore;
} else if (event.isError()) {
reply = sink(event);
if (reply === Bacon.noMore) {
unsubAll();
}
return reply;
} else {
setValue(event.value);
if (_.all(_.map((function(x) {
return x.isDefined;
}), values))) {
if (initialSent && event.isInitial()) {
return Bacon.more;
} else {
initialSent = true;
valueArrayF = function() {
var x, _i, _len, _results;
_results = [];
for (_i = 0, _len = values.length; _i < _len; _i++) {
x = values[_i];
_results.push(x.get()());
}
return _results;
};
reply = sink(event.apply(valueArrayF));
if (reply === Bacon.noMore) {
unsubAll();
}
return reply;
}
} else {
return Bacon.more;
}
}
};
};
sinkFor = function(index) {
return combiningSink((function() {
return ends[index] = true;
}), (function(x) {
return values[index] = new Some(x);
}));
};
for (index = _i = 0, _len = streams.length; _i < _len; index = ++_i) {
stream = streams[index];
if (!(stream instanceof Observable)) {
stream = Bacon.constant(stream);
}
if (!unsubscribed) {
unsubs[index] = stream.subscribeInternal(sinkFor(index));
}
}
return unsubAll;
});
} else {
return Bacon.constant([]);
}
};
Bacon.onValues = function() {
var f, streams, _i;
streams = 2 <= arguments.length ? __slice.call(arguments, 0, _i = arguments.length - 1) : (_i = 0, []), f = arguments[_i++];
return Bacon.combineAsArray(streams).onValues(f);
};
Bacon.combineWith = function() {
var f, streams;
f = arguments[0], streams = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return Bacon.combineAsArray(streams).map(function(values) {
return f.apply(null, values);
});
};
Bacon.combineTemplate = function(template) {
var applyStreamValue, combinator, compile, compileTemplate, constantValue, current, funcs, mkContext, setValue, streams;
funcs = [];
streams = [];
current = function(ctxStack) {
return ctxStack[ctxStack.length - 1];
};
setValue = function(ctxStack, key, value) {
return current(ctxStack)[key] = value;
};
applyStreamValue = function(key, index) {
return function(ctxStack, values) {
return setValue(ctxStack, key, values[index]);
};
};
constantValue = function(key, value) {
return function(ctxStack, values) {
return setValue(ctxStack, key, value);
};
};
mkContext = function(template) {
if (template instanceof Array) {
return [];
} else {
return {};
}
};
compile = function(key, value) {
var popContext, pushContext;
if (value instanceof Observable) {
streams.push(value);
return funcs.push(applyStreamValue(key, streams.length - 1));
} else if (value === Object(value) && typeof value !== "function") {
pushContext = function(key) {
return function(ctxStack, values) {
var newContext;
newContext = mkContext(value);
setValue(ctxStack, key, newContext);
return ctxStack.push(newContext);
};
};
popContext = function(ctxStack, values) {
return ctxStack.pop();
};
funcs.push(pushContext(key));
compileTemplate(value);
return funcs.push(popContext);
} else {
return funcs.push(constantValue(key, value));
}
};
compileTemplate = function(template) {
return _.each(template, compile);
};
compileTemplate(template);
combinator = function(values) {
var ctxStack, f, rootContext, _i, _len;
rootContext = mkContext(template);
ctxStack = [rootContext];
for (_i = 0, _len = funcs.length; _i < _len; _i++) {
f = funcs[_i];
f(ctxStack, values);
}
return rootContext;
};
return Bacon.combineAsArray(streams).map(combinator);
};
Event = (function() {
function Event() {}
Event.prototype.isEvent = function() {
return true;
};
Event.prototype.isEnd = function() {
return false;
};
Event.prototype.isInitial = function() {
return false;
};
Event.prototype.isNext = function() {
return false;
};
Event.prototype.isError = function() {
return false;
};
Event.prototype.hasValue = function() {
return false;
};
Event.prototype.filter = function(f) {
return true;
};
return Event;
})();
Next = (function(_super) {
__extends(Next, _super);
function Next(valueF, sourceEvent) {
var _this = this;
if (isFunction(valueF)) {
this.value = function() {
var v;
v = valueF();
_this.value = _.always(v);
return v;
};
} else {
this.value = _.always(valueF);
}
}
Next.prototype.isNext = function() {
return true;
};
Next.prototype.hasValue = function() {
return true;
};
Next.prototype.fmap = function(f) {
var _this = this;
return this.apply(function() {
return f(_this.value());
});
};
Next.prototype.apply = function(value) {
return new Next(value);
};
Next.prototype.filter = function(f) {
return f(this.value());
};
Next.prototype.describe = function() {
return this.value();
};
return Next;
})(Event);
Initial = (function(_super) {
__extends(Initial, _super);
function Initial() {
_ref1 = Initial.__super__.constructor.apply(this, arguments);
return _ref1;
}
Initial.prototype.isInitial = function() {
return true;
};
Initial.prototype.isNext = function() {
return false;
};
Initial.prototype.apply = function(value) {
return new Initial(value);
};
Initial.prototype.toNext = function() {
return new Next(this.value);
};
return Initial;
})(Next);
End = (function(_super) {
__extends(End, _super);
function End() {
_ref2 = End.__super__.constructor.apply(this, arguments);
return _ref2;
}
End.prototype.isEnd = function() {
return true;
};
End.prototype.fmap = function() {
return this;
};
End.prototype.apply = function() {
return this;
};
End.prototype.describe = function() {
return "<end>";
};
return End;
})(Event);
Error = (function(_super) {
__extends(Error, _super);
function Error(error) {
this.error = error;
}
Error.prototype.isError = function() {
return true;
};
Error.prototype.fmap = function() {
return this;
};
Error.prototype.apply = function() {
return this;
};
Error.prototype.describe = function() {
return "<error> " + this.error;
};
return Error;
})(Event);
Observable = (function() {
function Observable() {
this.combine = __bind(this.combine, this);
this.flatMapLatest = __bind(this.flatMapLatest, this);
this.fold = __bind(this.fold, this);
this.scan = __bind(this.scan, this);
this.assign = this.onValue;
}
Observable.prototype.onValue = function() {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
f = makeFunction(f, args);
return this.subscribe(function(event) {
if (event.hasValue()) {
return f(event.value());
}
});
};
Observable.prototype.onValues = function(f) {
return this.onValue(function(args) {
return f.apply(null, args);
});
};
Observable.prototype.onError = function() {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
f = makeFunction(f, args);
return this.subscribe(function(event) {
if (event.isError()) {
return f(event.error);
}
});
};
Observable.prototype.onEnd = function() {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
f = makeFunction(f, args);
return this.subscribe(function(event) {
if (event.isEnd()) {
return f();
}
});
};
Observable.prototype.errors = function() {
return this.filter(function() {
return false;
});
};
Observable.prototype.filter = function() {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return convertArgsToFunction(this, f, args, function(f) {
return this.withHandler(function(event) {
if (event.filter(f)) {
return this.push(event);
} else {
return Bacon.more;
}
});
});
};
Observable.prototype.takeWhile = function() {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return convertArgsToFunction(this, f, args, function(f) {
return this.withHandler(function(event) {
if (event.filter(f)) {
return this.push(event);
} else {
this.push(end());
return Bacon.noMore;
}
});
});
};
Observable.prototype.endOnError = function() {
return this.withHandler(function(event) {
if (event.isError()) {
this.push(event);
return this.push(end());
} else {
return this.push(event);
}
});
};
Observable.prototype.take = function(count) {
if (count <= 0) {
return Bacon.never();
}
return this.withHandler(function(event) {
if (!event.hasValue()) {
return this.push(event);
} else {
count--;
if (count > 0) {
return this.push(event);
} else {
if (count === 0) {
this.push(event);
}
this.push(end());
return Bacon.noMore;
}
}
});
};
Observable.prototype.map = function() {
var args, p;
p = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
if (p instanceof Property) {
return p.sampledBy(this, former);
} else {
return convertArgsToFunction(this, p, args, function(f) {
return this.withHandler(function(event) {
return this.push(event.fmap(f));
});
});
}
};
Observable.prototype.mapError = function() {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
f = makeFunction(f, args);
return this.withHandler(function(event) {
if (event.isError()) {
return this.push(next(f(event.error)));
} else {
return this.push(event);
}
});
};
Observable.prototype.mapEnd = function() {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
f = makeFunction(f, args);
return this.withHandler(function(event) {
if (event.isEnd()) {
this.push(next(f(event)));
this.push(end());
return Bacon.noMore;
} else {
return this.push(event);
}
});
};
Observable.prototype.doAction = function() {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
f = makeFunction(f, args);
return this.withHandler(function(event) {
if (event.hasValue()) {
f(event.value());
}
return this.push(event);
});
};
Observable.prototype.skip = function(count) {
return this.withHandler(function(event) {
if (!event.hasValue()) {
return this.push(event);
} else if (count > 0) {
count--;
return Bacon.more;
} else {
return this.push(event);
}
});
};
Observable.prototype.skipDuplicates = function(isEqual) {
if (isEqual == null) {
isEqual = function(a, b) {
return a === b;
};
}
return this.withStateMachine(None, function(prev, event) {
if (!event.hasValue()) {
return [prev, [event]];
} else if (event.isInitial() || prev === None || !isEqual(prev.get(), event.value())) {
return [new Some(event.value()), [event]];
} else {
return [prev, []];
}
});
};
Observable.prototype.skipErrors = function() {
return this.withHandler(function(event) {
if (event.isError()) {
return Bacon.more;
} else {
return this.push(event);
}
});
};
Observable.prototype.withStateMachine = function(initState, f) {
var state;
state = initState;
return this.withHandler(function(event) {
var fromF, newState, output, outputs, reply, _i, _len;
fromF = f(state, event);
newState = fromF[0], outputs = fromF[1];
state = newState;
reply = Bacon.more;
for (_i = 0, _len = outputs.length; _i < _len; _i++) {
output = outputs[_i];
reply = this.push(output);
if (reply === Bacon.noMore) {
return reply;
}
}
return reply;
});
};
Observable.prototype.scan = function(seed, f) {
var acc, subscribe,
_this = this;
f = toCombinator(f);
acc = toOption(seed);
subscribe = function(sink) {
var initSent, reply, sendInit, unsub;
initSent = false;
unsub = nop;
reply = Bacon.more;
sendInit = function() {
if (!initSent) {
initSent = true;
return acc.forEach(function(value) {
reply = sink(initial(value));
if (reply === Bacon.noMore) {
unsub();
return unsub = nop;
}
});
}
};
unsub = _this.subscribe(function(event) {
if (event.hasValue()) {
if (initSent && event.isInitial()) {
return Bacon.more;
} else {
if (!event.isInitial()) {
sendInit();
}
initSent = true;
acc = new Some(f(acc.getOrElse(void 0), event.value()));
return sink(event.apply(_.always(acc.get())));
}
} else {
if (event.isEnd()) {
reply = sendInit();
}
if (reply !== Bacon.noMore) {
return sink(event);
}
}
});
sendInit();
return unsub;
};
return new Property(subscribe);
};
Observable.prototype.fold = function(seed, f) {
return this.scan(seed, f).sampledBy(this.filter(false).mapEnd().toProperty());
};
Observable.prototype.zip = function(other, f) {
if (f == null) {
f = Array;
}
return Bacon.zipWith([this, other], f);
};
Observable.prototype.diff = function(start, f) {
f = toCombinator(f);
return this.scan([start], function(prevTuple, next) {
return [next, f(prevTuple[0], next)];
}).filter(function(tuple) {
return tuple.length === 2;
}).map(function(tuple) {
return tuple[1];
});
};
Observable.prototype.flatMap = function(f, firstOnly) {
var root;
f = makeSpawner(f);
root = this;
return new EventStream(function(sink) {
var checkEnd, children, rootEnd, spawner, unbind, unsubRoot;
children = [];
rootEnd = false;
unsubRoot = function() {};
unbind = function() {
var unsubChild, _i, _len;
unsubRoot();
for (_i = 0, _len = children.length; _i < _len; _i++) {
unsubChild = children[_i];
unsubChild();
}
return children = [];
};
checkEnd = function() {
if (rootEnd && (children.length === 0)) {
return sink(end());
}
};
spawner = function(event) {
var child, childEnded, handler, removeChild, unsubChild;
if (event.isEnd()) {
rootEnd = true;
return checkEnd();
} else if (event.isError()) {
return sink(event);
} else if (firstOnly && children.length) {
return Bacon.more;
} else {
child = f(event.value());
if (!(child instanceof Observable)) {
child = Bacon.once(child);
}
unsubChild = void 0;
childEnded = false;
removeChild = function() {
if (unsubChild != null) {
_.remove(unsubChild, children);
}
return checkEnd();
};
handler = function(event) {
var reply;
if (event.isEnd()) {
removeChild();
childEnded = true;
return Bacon.noMore;
} else {
if (event instanceof Initial) {
event = event.toNext();
}
reply = sink(event);
if (reply === Bacon.noMore) {
unbind();
}
return reply;
}
};
unsubChild = child.subscribe(handler);
if (!childEnded) {
return children.push(unsubChild);
}
}
};
unsubRoot = root.subscribe(spawner);
return unbind;
});
};
Observable.prototype.flatMapFirst = function(f) {
return this.flatMap(f, true);
};
Observable.prototype.flatMapLatest = function(f) {
var stream,
_this = this;
f = makeSpawner(f);
stream = this.toEventStream();
return stream.flatMap(function(value) {
return f(value).takeUntil(stream);
});
};
Observable.prototype.not = function() {
return this.map(function(x) {
return !x;
});
};
Observable.prototype.log = function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
this.subscribe(function(event) {
return typeof console !== "undefined" && console !== null ? typeof console.log === "function" ? console.log.apply(console, __slice.call(args).concat([event.describe()])) : void 0 : void 0;
});
return this;
};
Observable.prototype.slidingWindow = function(n, minValues) {
if (minValues == null) {
minValues = 0;
}
return this.scan([], (function(window, value) {
return window.concat([value]).slice(-n);
})).filter((function(values) {
return values.length >= minValues;
}));
};
Observable.prototype.combine = function(other, f) {
var combinator;
combinator = toCombinator(f);
return Bacon.combineAsArray(this, other).map(function(values) {
return combinator(values[0], values[1]);
});
};
Observable.prototype.decode = function(cases) {
return this.combine(Bacon.combineTemplate(cases), function(key, values) {
return values[key];
});
};
Observable.prototype.awaiting = function(other) {
return this.toEventStream().map(true).merge(other.toEventStream().map(false)).toProperty(false);
};
return Observable;
})();
Observable.prototype.reduce = Observable.prototype.fold;
EventStream = (function(_super) {
__extends(EventStream, _super);
function EventStream(subscribe) {
this.takeUntil = __bind(this.takeUntil, this);
var dispatcher;
EventStream.__super__.constructor.call(this);
assertFunction(subscribe);
dispatcher = new Dispatcher(subscribe);
this.subscribe = dispatcher.subscribe;
this.subscribeInternal = this.subscribe;
this.hasSubscribers = dispatcher.hasSubscribers;
}
EventStream.prototype.delay = function(delay) {
return this.flatMap(function(value) {
return Bacon.later(delay, value);
});
};
EventStream.prototype.debounce = function(delay) {
return this.flatMapLatest(function(value) {
return Bacon.later(delay, value);
});
};
EventStream.prototype.debounceImmediate = function(delay) {
return this.flatMapFirst(function(value) {
return Bacon.once(value).concat(Bacon.later(delay).filter(false));
});
};
EventStream.prototype.throttle = function(delay) {
return this.bufferWithTime(delay).map(function(values) {
return values[values.length - 1];
});
};
EventStream.prototype.bufferWithTime = function(delay) {
return this.bufferWithTimeOrCount(delay, Number.MAX_VALUE);
};
EventStream.prototype.bufferWithCount = function(count) {
return this.bufferWithTimeOrCount(void 0, count);
};
EventStream.prototype.bufferWithTimeOrCount = function(delay, count) {
var flushOrSchedule;
flushOrSchedule = function(buffer) {
if (buffer.values.length === count) {
return buffer.flush();
} else if (delay !== void 0) {
return buffer.schedule();
}
};
return this.buffer(delay, flushOrSchedule, flushOrSchedule);
};
EventStream.prototype.buffer = function(delay, onInput, onFlush) {
var buffer, delayMs, reply;
if (onInput == null) {
onInput = (function() {});
}
if (onFlush == null) {
onFlush = (function() {});
}
buffer = {
scheduled: false,
end: null,
values: [],
flush: function() {
var reply;
this.scheduled = false;
if (this.values.length > 0) {
reply = this.push(next(this.values));
this.values = [];
if (this.end != null) {
return this.push(this.end);
} else if (reply !== Bacon.noMore) {
return onFlush(this);
}
} else {
if (this.end != null) {
return this.push(this.end);
}
}
},
schedule: function() {
var _this = this;
if (!this.scheduled) {
this.scheduled = true;
return delay(function() {
return _this.flush();
});
}
}
};
reply = Bacon.more;
if (!isFunction(delay)) {
delayMs = delay;
delay = function(f) {
return Bacon.scheduler.setTimeout(f, delayMs);
};
}
return this.withHandler(function(event) {
buffer.push = this.push;
if (event.isError()) {
reply = this.push(event);
} else if (event.isEnd()) {
buffer.end = event;
if (!buffer.scheduled) {
buffer.flush();
}
} else {
buffer.values.push(event.value());
onInput(buffer);
}
return reply;
});
};
EventStream.prototype.merge = function(right) {
var left;
assertEventStream(right);
left = this;
return new EventStream(function(sink) {
var ends, smartSink, unsubBoth, unsubLeft, unsubRight, unsubscribed;
unsubLeft = nop;
unsubRight = nop;
unsubscribed = false;
unsubBoth = function() {
unsubLeft();
unsubRight();
return unsubscribed = true;
};
ends = 0;
smartSink = function(event) {
var reply;
if (event.isEnd()) {
ends++;
if (ends === 2) {
return sink(end());
} else {
return Bacon.more;
}
} else {
reply = sink(event);
if (reply === Bacon.noMore) {
unsubBoth();
}
return reply;
}
};
unsubLeft = left.subscribe(smartSink);
if (!unsubscribed) {
unsubRight = right.subscribe(smartSink);
}
return unsubBoth;
});
};
EventStream.prototype.toProperty = function(initValue) {
if (arguments.length === 0) {
initValue = None;
}
return this.scan(initValue, latter);
};
EventStream.prototype.toEventStream = function() {
return this;
};
EventStream.prototype.concat = function(right) {
var left;
left = this;
return new EventStream(function(sink) {
var unsub;
unsub = left.subscribe(function(e) {
if (e.isEnd()) {
return unsub = right.subscribe(sink);
} else {
return sink(e);
}
});
return function() {
return unsub();
};
});
};
EventStream.prototype.takeUntil = function(stopper) {
var self;
self = this;
return new EventStream(function(sink) {
var produce, stop;
stop = function(unsubAll) {
return stopper.onValue(function() {
sink(end());
unsubAll();
return Bacon.noMore;
});
};
produce = function(unsubAll) {
return self.subscribe(function(x) {
var reply;
reply = sink(x);
if (x.isEnd() || reply === Bacon.noMore) {
unsubAll();
}
return reply;
});
};
return compositeUnsubscribe(stop, produce);
});
};
EventStream.prototype.skipUntil = function(starter) {
var started;
started = starter.take(1).map(true).toProperty(false);
return this.filter(started);
};
EventStream.prototype.skipWhile = function() {
var args, f, ok;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
ok = false;
return convertArgsToFunction(this, f, args, function(f) {
return this.withHandler(function(event) {
if (ok || !event.hasValue() || !f(event.value())) {
ok = true;
return this.push(event);
} else {
return Bacon.more;
}
});
});
};
EventStream.prototype.startWith = function(seed) {
return Bacon.once(seed).concat(this);
};
EventStream.prototype.withHandler = function(handler) {
var dispatcher;
dispatcher = new Dispatcher(this.subscribe, handler);
return new EventStream(dispatcher.subscribe);
};
EventStream.prototype.withSubscribe = function(subscribe) {
return new EventStream(subscribe);
};
return EventStream;
})(Observable);
Property = (function(_super) {
__extends(Property, _super);
function Property(subscribe, handler) {
this.toEventStream = __bind(this.toEventStream, this);
this.toProperty = __bind(this.toProperty, this);
this.changes = __bind(this.changes, this);
this.sample = __bind(this.sample, this);
var _this = this;
Property.__super__.constructor.call(this);
if (handler === true) {
this.subscribeInternal = subscribe;
} else {
this.subscribeInternal = new PropertyDispatcher(subscribe, handler).subscribe;
}
this.sampledBy = function(sampler, combinator) {
var lazyCombinator, myVal;
lazyCombinator = (combinator != null) ? (combinator = toCombinator(combinator), function(myVal, otherVal) {
return combinator(myVal.value(), otherVal.value());
}) : function(myVal, otherVal) {
return myVal.value();
};
myVal = None;
subscribe = function(sink) {
var unsubBoth, unsubMe, unsubOther, unsubscribed;
unsubscribed = false;
unsubMe = nop;
unsubOther = nop;
unsubBoth = function() {
unsubMe();
unsubOther();
return unsubscribed = true;
};
unsubMe = _this.subscribeInternal(function(event) {
if (event.hasValue()) {
return myVal = new Some(event);
} else if (event.isError()) {
return sink(event);
}
});
unsubOther = sampler.subscribe(function(event) {
if (event.hasValue()) {
return myVal.forEach(function(myVal) {
return sink(event.apply(function() {
return lazyCombinator(myVal, event);
}));
});
} else {
if (event.isEnd()) {
unsubMe();
}
return sink(event);
}
});
return unsubBoth;
};
if (sampler instanceof Property) {
return new Property(subscribe);
} else {
return new EventStream(subscribe);
}
};
this.subscribe = function(sink) {
var LatestEvent, end, reply, unsub, value;
reply = Bacon.more;
LatestEvent = (function() {
function LatestEvent() {}
LatestEvent.prototype.set = function(event) {
return this.event = event;
};
LatestEvent.prototype.send = function() {
var event;
event = this.event;
this.event = null;
if ((event != null) && reply !== Bacon.noMore) {
reply = sink(event);
if (reply === Bacon.noMore) {
return unsub();
}
}
};
return LatestEvent;
})();
value = new LatestEvent();
end = new LatestEvent();
unsub = nop;
unsub = _this.subscribeInternal(function(event) {
if (event.isError()) {
if (reply !== Bacon.noMore) {
reply = sink(event);
}
} else {
if (event.hasValue()) {
value.set(event);
} else if (event.isEnd()) {
end.set(event);
}
PropertyTransaction.onDone(function() {
value.send();
return end.send();
});
}
return reply;
});
return function() {
reply = Bacon.noMore;
return unsub();
};
};
}
Property.prototype.sample = function(interval) {
return this.sampledBy(Bacon.interval(interval, {}));
};
Property.prototype.changes = function() {
var _this = this;
return new EventStream(function(sink) {
return _this.subscribe(function(event) {
if (!event.isInitial()) {
return sink(event);
}
});
});
};
Property.prototype.withHandler = function(handler) {
return new Property(this.subscribeInternal, handler);
};
Property.prototype.withSubscribe = function(subscribe) {
return new Property(subscribe);
};
Property.prototype.toProperty = function() {
assertNoArguments(arguments);
return this;
};
Property.prototype.toEventStream = function() {
var _this = this;
return new EventStream(function(sink) {
return _this.subscribe(function(event) {
if (event.isInitial()) {
event = event.toNext();
}
return sink(event);
});
});
};
Property.prototype.and = function(other) {
return this.combine(other, function(x, y) {
return x && y;
});
};
Property.prototype.or = function(other) {
return this.combine(other, function(x, y) {
return x || y;
});
};
Property.prototype.delay = function(delay) {
return this.delayChanges(function(changes) {
return changes.delay(delay);
});
};
Property.prototype.debounce = function(delay) {
return this.delayChanges(function(changes) {
return changes.debounce(delay);
});
};
Property.prototype.throttle = function(delay) {
return this.delayChanges(function(changes) {
return changes.throttle(delay);
});
};
Property.prototype.delayChanges = function(f) {
return addPropertyInitValueToStream(this, f(this.changes()));
};
Property.prototype.takeUntil = function(stopper) {
var changes;
changes = this.changes().takeUntil(stopper);
return addPropertyInitValueToStream(this, changes);
};
return Property;
})(Observable);
convertArgsToFunction = function(obs, f, args, method) {
var sampled;
if (f instanceof Property) {
sampled = f.sampledBy(obs, function(p, s) {
return [p, s];
});
return method.apply(sampled, [
function(_arg) {
var p, s;
p = _arg[0], s = _arg[1];
return p;
}
]).map(function(_arg) {
var p, s;
p = _arg[0], s = _arg[1];
return s;
});
} else {
f = makeFunction(f, args);
return method.apply(obs, [f]);
}
};
addPropertyInitValueToStream = function(property, stream) {
var getInitValue;
getInitValue = function(property) {
var value;
value = None;
property.subscribe(function(event) {
if (event.hasValue()) {
value = new Some(event.value());
}
return Bacon.noMore;
});
return value;
};
return stream.toProperty(getInitValue(property));
};
Dispatcher = (function() {
function Dispatcher(subscribe, handleEvent) {
var done, ended, prevError, pushing, queue, removeSub, subscriptions, unsubscribeFromSource, waiters,
_this = this;
if (subscribe == null) {
subscribe = function() {
return nop;
};
}
subscriptions = [];
queue = null;
pushing = false;
ended = false;
this.hasSubscribers = function() {
return subscriptions.length > 0;
};
prevError = null;
unsubscribeFromSource = nop;
removeSub = function(subscription) {
return subscriptions = _.without(subscription, subscriptions);
};
waiters = null;
done = function(event) {
var w, ws, _i, _len, _results;
if (waiters != null) {
ws = waiters;
waiters = null;
_results = [];
for (_i = 0, _len = ws.length; _i < _len; _i++) {
w = ws[_i];
_results.push(w());
}
return _results;
}
};
this.push = function(event) {
var reply, sub, success, tmp, _i, _len;
if (!pushing) {
if (event === prevError) {
return;
}
if (event.isError()) {
prevError = event;
}
success = false;
try {
pushing = true;
tmp = subscriptions;
for (_i = 0, _len = tmp.length; _i < _len; _i++) {
sub = tmp[_i];
reply = sub.sink(event);
if (reply === Bacon.noMore || event.isEnd()) {
removeSub(sub);
}
}
success = true;
} finally {
pushing = false;
if (!success) {
queue = null;
}
}
success = true;
while (queue != null ? queue.length : void 0) {
event = _.head(queue);
queue = _.tail(queue);
_this.push(event);
}
done(event);
if (_this.hasSubscribers()) {
return Bacon.more;
} else {
return Bacon.noMore;
}
} else {
queue = (queue || []).concat([event]);
return Bacon.more;
}
};
if (handleEvent == null) {
handleEvent = function(event) {
return this.push(event);
};
}
this.handleEvent = function(event) {
if (event.isEnd()) {
ended = true;
}
return handleEvent.apply(_this, [event]);
};
this.subscribe = function(sink) {
var subscription;
if (ended) {
sink(end());
return nop;
} else {
assertFunction(sink);
subscription = {
sink: sink
};
subscriptions = subscriptions.concat(subscription);
if (subscriptions.length === 1) {
unsubscribeFromSource = subscribe(_this.handleEvent);
}
assertFunction(unsubscribeFromSource);
return function() {
removeSub(subscription);
if (!_this.hasSubscribers()) {
return unsubscribeFromSource();
}
};
}
};
}
return Dispatcher;
})();
PropertyDispatcher = (function(_super) {
__extends(PropertyDispatcher, _super);
function PropertyDispatcher(subscribe, handleEvent) {
var current, ended, push,
_this = this;
PropertyDispatcher.__super__.constructor.call(this, subscribe, handleEvent);
current = None;
push = this.push;
subscribe = this.subscribe;
ended = false;
this.push = function(event) {
if (event.isEnd()) {
ended = true;
}
if (event.hasValue()) {
current = new Some(event.value());
}
return PropertyTransaction.inTransaction(function() {
return push.apply(_this, [event]);
});
};
this.subscribe = function(sink) {
var initSent, reply, shouldBounceInitialValue;
initSent = false;
shouldBounceInitialValue = function() {
return _this.hasSubscribers() || ended;
};
reply = current.filter(shouldBounceInitialValue).map(function(val) {
return sink(initial(val));
});
if (reply.getOrElse(Bacon.more) === Bacon.noMore) {
return nop;
} else if (ended) {
sink(end());
return nop;
} else {
return subscribe.apply(_this, [sink]);
}
};
}
return PropertyDispatcher;
})(Dispatcher);
PropertyTransaction = (function() {
var inTransaction, onDone, tx, txListeners;
txListeners = [];
tx = false;
onDone = function(f) {
if (tx) {
return txListeners.push(f);
} else {
return f();
}
};
inTransaction = function(f) {
var g, gs, result, _i, _len;
if (tx) {
return f();
} else {
tx = true;
try {
result = f();
} finally {
tx = false;
}
gs = txListeners;
txListeners = [];
for (_i = 0, _len = gs.length; _i < _len; _i++) {
g = gs[_i];
g();
}
return result;
}
};
return {
onDone: onDone,
inTransaction: inTransaction
};
})();
Bus = (function(_super) {
__extends(Bus, _super);
function Bus() {
var ended, guardedSink, sink, subscribeAll, subscribeInput, subscriptions, unsubAll, unsubscribeInput,
_this = this;
sink = void 0;
subscriptions = [];
ended = false;
guardedSink = function(input) {
return function(event) {
if (event.isEnd()) {
unsubscribeInput(input);
return Bacon.noMore;
} else {
return sink(event);
}
};
};
unsubAll = function() {
var sub, _i, _len, _results;
_results = [];
for (_i = 0, _len = subscriptions.length; _i < _len; _i++) {
sub = subscriptions[_i];
_results.push(typeof sub.unsub === "function" ? sub.unsub() : void 0);
}
return _results;
};
subscribeInput = function(subscription) {
return subscription.unsub = subscription.input.subscribe(guardedSink(subscription.input));
};
unsubscribeInput = function(input) {
var i, sub, _i, _len;
for (i = _i = 0, _len = subscriptions.length; _i < _len; i = ++_i) {
sub = subscriptions[i];
if (sub.input === input) {
if (typeof sub.unsub === "function") {
sub.unsub();
}
subscriptions.splice(i, 1);
return;
}
}
};
subscribeAll = function(newSink) {
var subscription, unsubFuncs, _i, _len, _ref3;
sink = newSink;
unsubFuncs = [];
_ref3 = cloneArray(subscriptions);
for (_i = 0, _len = _ref3.length; _i < _len; _i++) {
subscription = _ref3[_i];
subscribeInput(subscription);
}
return unsubAll;
};
Bus.__super__.constructor.call(this, subscribeAll);
this.plug = function(input) {
var sub;
if (ended) {
return;
}
sub = {
input: input
};
subscriptions.push(sub);
if ((sink != null)) {
subscribeInput(sub);
}
return function() {
return unsubscribeInput(input);
};
};
this.push = function(value) {
return typeof sink === "function" ? sink(next(value)) : void 0;
};
this.error = function(error) {
return typeof sink === "function" ? sink(new Error(error)) : void 0;
};
this.end = function() {
ended = true;
unsubAll();
return typeof sink === "function" ? sink(end()) : void 0;
};
}
return Bus;
})(EventStream);
Bacon.when = function() {
var Source, f, i, index, ix, len, pat, patSources, pats, patterns, s, sources, usage, _i, _j, _len, _len1, _ref3;
patterns = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
if (patterns.length === 0) {
return Bacon.never();
}
len = patterns.length;
usage = "when: expecting arguments in the form (Observable+,function)+";
assert(usage, len % 2 === 0);
sources = [];
pats = [];
i = 0;
while (i < len) {
patSources = _.toArray(patterns[i]);
f = patterns[i + 1];
pat = {
f: (isFunction(f) ? f : (function() {
return f;
})),
ixs: []
};
for (_i = 0, _len = patSources.length; _i < _len; _i++) {
s = patSources[_i];
assert(s instanceof Observable, usage);
index = sources.indexOf(s);
if (index < 0) {
sources.push(s);
index = sources.length - 1;
}
_ref3 = pat.ixs;
for (_j = 0, _len1 = _ref3.length; _j < _len1; _j++) {
ix = _ref3[_j];
if (ix.index === index) {
ix.count++;
}
}
pat.ixs.push({
index: index,
count: 1
});
}
pats.push(pat);
i = i + 2;
}
Source = (function() {
function Source(s) {
var isEnded, queue;
queue = [];
isEnded = false;
this.subscribe = s.subscribe;
this.markEnded = function() {
return isEnded = true;
};
if (s instanceof Property) {
this.consume = function() {
return queue[0];
};
this.push = function(x) {
return queue = [x];
};
this.mayHave = function() {
return true;
};
this.hasAtLeast = function(c) {
return queue.length;
};
} else {
this.consume = function() {
return queue.shift();
};
this.push = function(x) {
return queue.push(x);
};
this.mayHave = function(c) {
return !isEnded || queue.length >= c;
};
this.hasAtLeast = function(c) {
return queue.length >= c;
};
}
}
return Source;
})();
sources = _.map((function(s) {
return new Source(s);
}), sources);
return new EventStream(function(sink) {
var cannotMatch, match, part;
match = function(p) {
return _.all(p.ixs, function(i) {
return sources[i.index].hasAtLeast(i.count);
});
};
cannotMatch = function(p) {
return _.any(p.ixs, function(i) {
return !sources[i.index].mayHave(i.count);
});
};
part = function(source, sourceIndex) {
return function(unsubAll) {
return source.subscribe(function(e) {
var p, reply, val, _k, _len2;
if (e.isEnd()) {
sources[sourceIndex].markEnded();
if (_.all(pats, cannotMatch)) {
reply = Bacon.noMore;
sink(end());
}
} else if (e.isError()) {
reply = sink(e);
} else {
sources[sourceIndex].push(e.value());
for (_k = 0, _len2 = pats.length; _k < _len2; _k++) {
p = pats[_k];
if (match(p)) {
val = p.f.apply(p, (function() {
var _l, _len3, _ref4, _results;
_ref4 = p.ixs;
_results = [];
for (_l = 0, _len3 = _ref4.length; _l < _len3; _l++) {
i = _ref4[_l];
_results.push(sources[i.index].consume());
}
return _results;
})());
reply = sink(next(val));
break;
}
}
}
if (reply === Bacon.noMore) {
unsubAll();
}
return reply || Bacon.more;
});
};
};
return compositeUnsubscribe.apply(null, (function() {
var _k, _len2, _results;
_results = [];
for (i = _k = 0, _len2 = sources.length; _k < _len2; i = ++_k) {
s = sources[i];
_results.push(part(s, i));
}
return _results;
})());
});
};
Bacon.update = function() {
var i, initial, lateBindFirst, patterns;
initial = arguments[0], patterns = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
lateBindFirst = function(f) {
return function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return function(i) {
return f.apply(null, [i].concat(args));
};
};
};
i = patterns.length - 1;
while (i > 0) {
if (!(patterns[i] instanceof Function)) {
patterns[i] = (function(x) {
return function() {
return x;
};
})(patterns[i]);
}
patterns[i] = lateBindFirst(patterns[i]);
i = i - 2;
}
return Bacon.when.apply(Bacon, patterns).scan(initial, (function(x, f) {
return f(x);
}));
};
compositeUnsubscribe = function() {
var ss;
ss = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return new CompositeUnsubscribe(ss).unsubscribe;
};
CompositeUnsubscribe = (function() {
function CompositeUnsubscribe(ss) {
var s, _i, _len;
if (ss == null) {
ss = [];
}
this.empty = __bind(this.empty, this);
this.unsubscribe = __bind(this.unsubscribe, this);
this.add = __bind(this.add, this);
this.unsubscribed = false;
this.subscriptions = [];
this.starting = [];
for (_i = 0, _len = ss.length; _i < _len; _i++) {
s = ss[_i];
this.add(s);
}
}
CompositeUnsubscribe.prototype.add = function(subscription) {
var ended, unsub, unsubMe,
_this = this;
if (this.unsubscribed) {
return;
}
ended = false;
unsub = nop;
this.starting.push(subscription);
unsubMe = function() {
unsub();
ended = true;
_this.remove(unsub);
return _.remove(subscription, _this.starting);
};
unsub = subscription(this.unsubscribe, unsubMe);
if (!(this.unsubscribed || ended)) {
this.subscriptions.push(unsub);
}
_.remove(subscription, this.starting);
return unsub;
};
CompositeUnsubscribe.prototype.remove = function(subscription) {
if (this.unsubscribed) {
return;
}
return _.remove(subscription, this.subscriptions);
};
CompositeUnsubscribe.prototype.unsubscribe = function() {
var s, _i, _len, _ref3;
if (this.unsubscribed) {
return;
}
this.unsubscribed = true;
_ref3 = this.subscriptions;
for (_i = 0, _len = _ref3.length; _i < _len; _i++) {
s = _ref3[_i];
s();
}
this.subscriptions = [];
return this.starting = [];
};
CompositeUnsubscribe.prototype.empty = function() {
return !this.subscriptions.length && !this.starting.length;
};
return CompositeUnsubscribe;
})();
Some = (function() {
function Some(value) {
this.value = value;
}
Some.prototype.getOrElse = function() {
return this.value;
};
Some.prototype.get = function() {
return this.value;
};
Some.prototype.filter = function(f) {
if (f(this.value)) {
return new Some(this.value);
} else {
return None;
}
};
Some.prototype.map = function(f) {
return new Some(f(this.value));
};
Some.prototype.forEach = function(f) {
return f(this.value);
};
Some.prototype.isDefined = true;
Some.prototype.toArray = function() {
return [this.value];
};
return Some;
})();
None = {
getOrElse: function(value) {
return value;
},
filter: function() {
return None;
},
map: function() {
return None;
},
forEach: function() {},
isDefined: false,
toArray: function() {
return [];
}
};
Bacon.EventStream = EventStream;
Bacon.Property = Property;
Bacon.Observable = Observable;
Bacon.Bus = Bus;
Bacon.Initial = Initial;
Bacon.Next = Next;
Bacon.End = End;
Bacon.Error = Error;
nop = function() {};
latter = function(_, x) {
return x;
};
former = function(x, _) {
return x;
};
initial = function(value) {
return new Initial(_.always(value));
};
next = function(value) {
return new Next(_.always(value));
};
end = function() {
return new End();
};
toEvent = function(x) {
if (x instanceof Event) {
return x;
} else {
return next(x);
}
};
cloneArray = function(xs) {
return xs.slice(0);
};
indexOf = Array.prototype.indexOf ? function(xs, x) {
return xs.indexOf(x);
} : function(xs, x) {
var i, y, _i, _len;
for (i = _i = 0, _len = xs.length; _i < _len; i = ++_i) {
y = xs[i];
if (x === y) {
return i;
}
}
return -1;
};
assert = function(message, condition) {
if (!condition) {
throw message;
}
};
assertEvent = function(event) {
return assert("not an event : " + event, event instanceof Event && event.isEvent());
};
assertEventStream = function(event) {
return assert("not an EventStream : " + event, event instanceof EventStream);
};
assertFunction = function(f) {
return assert("not a function : " + f, isFunction(f));
};
isFunction = function(f) {
return typeof f === "function";
};
assertArray = function(xs) {
return assert("not an array : " + xs, xs instanceof Array);
};
assertNoArguments = function(args) {
return assert("no arguments supported", args.length === 0);
};
assertString = function(x) {
return assert("not a string : " + x, typeof x === "string");
};
methodCall = function(obj, method, args) {
assertString(method);
if (args === void 0) {
args = [];
}
return function(value) {
return obj[method].apply(obj, args.concat([value]));
};
};
partiallyApplied = function(f, applied) {
return function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return f.apply(null, applied.concat(args));
};
};
makeSpawner = function(f) {
if (f instanceof Observable) {
f = _.always(f);
}
assertFunction(f);
return f;
};
makeFunction = function(f, args) {
if (isFunction(f)) {
if (args.length) {
return partiallyApplied(f, args);
} else {
return f;
}
} else if (isFieldKey(f)) {
return toFieldExtractor(f, args);
} else if (typeof f === "object" && args.length) {
return methodCall(f, _.head(args), _.tail(args));
} else {
return _.always(f);
}
};
isFieldKey = function(f) {
return (typeof f === "string") && f.length > 1 && f.charAt(0) === ".";
};
Bacon.isFieldKey = isFieldKey;
toFieldExtractor = function(f, args) {
var partFuncs, parts;
parts = f.slice(1).split(".");
partFuncs = _.map(toSimpleExtractor(args), parts);
return function(value) {
var _i, _len;
for (_i = 0, _len = partFuncs.length; _i < _len; _i++) {
f = partFuncs[_i];
value = f(value);
}
return value;
};
};
toSimpleExtractor = function(args) {
return function(key) {
return function(value) {
var fieldValue;
if (value == null) {
return void 0;
} else {
fieldValue = value[key];
if (isFunction(fieldValue)) {
return fieldValue.apply(value, args);
} else {
return fieldValue;
}
}
};
};
};
toFieldKey = function(f) {
return f.slice(1);
};
toCombinator = function(f) {
var key;
if (isFunction(f)) {
return f;
} else if (isFieldKey(f)) {
key = toFieldKey(f);
return function(left, right) {
return left[key](right);
};
} else {
return assert("not a function or a field key: " + f, false);
}
};
toOption = function(v) {
if (v instanceof Some || v === None) {
return v;
} else {
return new Some(v);
}
};
if ((typeof define !== "undefined" && define !== null) && (define.amd != null)) {
if (typeof define === "function") {
define(function() {
return Bacon;
});
}
}
_ = {
head: function(xs) {
return xs[0];
},
always: function(x) {
return function() {
return x;
};
},
negate: function(f) {
return function(x) {
return !f(x);
};
},
empty: function(xs) {
return xs.length === 0;
},
tail: function(xs) {
return xs.slice(1, xs.length);
},
filter: function(f, xs) {
var filtered, x, _i, _len;
filtered = [];
for (_i = 0, _len = xs.length; _i < _len; _i++) {
x = xs[_i];
if (f(x)) {
filtered.push(x);
}
}
return filtered;
},
map: function(f, xs) {
var x, _i, _len, _results;
_results = [];
for (_i = 0, _len = xs.length; _i < _len; _i++) {
x = xs[_i];
_results.push(f(x));
}
return _results;
},
each: function(xs, f) {
var key, value, _results;
_results = [];
for (key in xs) {
value = xs[key];
_results.push(f(key, value));
}
return _results;
},
toArray: function(xs) {
if (xs instanceof Array) {
return xs;
} else {
return [xs];
}
},
contains: function(xs, x) {
return indexOf(xs, x) !== -1;
},
id: function(x) {
return x;
},
last: function(xs) {
return xs[xs.length - 1];
},
all: function(xs, f) {
var x, _i, _len;
if (f == null) {
f = _.id;
}
for (_i = 0, _len = xs.length; _i < _len; _i++) {
x = xs[_i];
if (!f(x)) {
return false;
}
}
return true;
},
any: function(xs, f) {
var x, _i, _len;
if (f == null) {
f = _.id;
}
for (_i = 0, _len = xs.length; _i < _len; _i++) {
x = xs[_i];
if (f(x)) {
return true;
}
}
return false;
},
without: function(x, xs) {
return _.filter((function(y) {
return y !== x;
}), xs);
},
remove: function(x, xs) {
var i;
i = indexOf(xs, x);
if (i >= 0) {
return xs.splice(i, 1);
}
},
fold: function(xs, seed, f) {
var x, _i, _len;
for (_i = 0, _len = xs.length; _i < _len; _i++) {
x = xs[_i];
seed = f(seed, x);
}
return seed;
}
};
Bacon._ = _;
Bacon.scheduler = {
setTimeout: function(f, d) {
return setTimeout(f, d);
},
setInterval: function(f, i) {
return setInterval(f, i);
},
clearInterval: function(id) {
return clearInterval(id);
},
now: function() {
return new Date().getTime();
}
};
}).call(this);
|
/*jslint browser: true*/
/*globals window, define, Class*/
define('yaga-dummy', ['yaga'], function (Yaga) {
'use strict';
var Dummy;
Dummy = new Class({
Extends: Yaga,
initialize: function (opts) {
Dummy.init.call(this, opts);
},
functions: function (value) {
this.emt('functions', value);
// to something...
return this;
},
obj: null
});
Dummy.init = function YagaDummy(opts) {
var privates;
opts = opts || {};
Yaga.init.call(this, opts);
if (opts.obj) {
this.functions(opts.obj);
}
};
Dummy.assume = function () {
throw new Error('not implemented');
};
Dummy.create = function (opts) {
opts = opts || {};
return new Dummy(opts);
};
return Dummy;
});
|
#!/usr/bin/env node
"use strict";
const Consolist = require("../consolist");
const fs = require("fs");
const path = require("path");
const imagePath = path.join(__dirname, "dman.raw");
const data = fs.readFileSync(imagePath);
console.log("24-bit mode:");
Consolist.log({
width: 48,
height: 92,
data: data
});
console.log("8-bit mode:");
Consolist.log({
width: 48,
height: 92,
data: data
}, {
terminal: "ansi8"
});
|
import * as ReactLinkStateVM from 'react-link-state-vm';
import React from 'react';
// For LiveEditor
global.require = dependency =>
({
react: React,
'react-link-state-vm': ReactLinkStateVM
}[dependency]);
|
'use strict'
var Base = require('../base')
/**
* @namespace Emitter
* @class
* @augments base
* @param {*} val
* difference with base -- sets listeners for each key
* if there is a function will set a listener on fn val
* @return {base}
*/
module.exports = new Base({
inject: [
require('./storage'),
require('./trigger'),
require('./off'),
require('./on'),
require('./once'),
require('./emit'),
require('./dataStorage'),
require('./condition')
],
properties: {
onRemoveProperty: true, // this is a dirty hack still.... remove it later
emitInstances: { val: true }, // hmm maybe just dont even address this dont use it now
emitContexts: { val: true } // now we need to check what about making a non context trigger only? that way you keep it save and sound
// yes saves a check -- we can make a non context emitter or something
},
// define: {
// remove () {
// console.error('remove emitter!@#?', this.path)
// return Base.prototype.remove.apply(this, arguments)
// }
// },
// define: {
// generateConstructor () {
// return function GodammnEmitter () {
// // console.log('wtf wtf wtf!', this.fn && this.fn.adapter, this, this.path)
// return Base.apply(this, arguments)
// }
// }
// },
useVal: true
}).Constructor
|
describe("Internal values are not exposed: ", function() {
const GLOBAL = (typeof global == "object") ? global : window;
const PRIVATE_KEYS =
[
// source/moduleUtilities.js
"valueType",
"ShadowKeyMap",
"makeShadowTarget",
"getRealTarget",
"inGraphHandler",
"NOT_YET_DETERMINED",
"OverriddenProxyParts",
"makeRevokeDeleteRefs",
"MembraneMayLog",
"AssertIsPropertyKey",
"Constants",
// source/ProxyMapping.js
"ProxyMapping",
// source/Membrane.js
"MembraneInternal",
// source/ObjectGraphHandler.js
"ObjectGraphHandler",
// source/ProxyNotify.js
"ProxyNotify",
// source/ModifyRulesAPI.js
"ChainHandlers",
"ChainHandlerProtection",
"ModifyRulesAPI",
// source/dogfood.js
"DogfoodMembrane",
];
PRIVATE_KEYS.forEach(function(name) {
it(name, function() {
expect(name in GLOBAL).toBe(false);
});
});
});
|
var util = require('util'),
Tab = require('../client/tab').Tab;
var GoldTab = function ()
{
Tab.call(this);
};
util.inherits(GoldTab, Tab);
GoldTab.prototype.tabName = 'gold';
GoldTab.prototype.mainMenu = 'fund';
GoldTab.prototype.angularDeps = Tab.prototype.angularDeps.concat(['qr']);
GoldTab.prototype.generateHtml = function ()
{
return require('../../jade/tabs/gold.jade')();
};
GoldTab.prototype.angular = function (module)
{
module.controller('GoldCtrl', ['$scope', 'rpId', 'rpAppManager', 'rpTracker', '$routeParams', 'rpKeychain', 'rpNetwork', '$timeout',
function ($scope, $id, appManager, rpTracker, $routeParams, keychain, $network, $timeout) {
$scope.toggle_instructions = function () {
$scope.showInstructions = !$scope.showInstructions;
};
$scope.save_account = function () {
$scope.loading = true;
var amount = ripple.Amount.from_human(
Options.gateway_max_limit + ' ' + '0158415500000000C1F76FF6ECB0BAC600000000',
{reference_date: new Date(+new Date() + 5*60000)}
);
amount.set_issuer("rrh7rf1gV2pXAoqA8oYbpHd8TKv5ZQeo67");
if (!amount.is_valid()) {
// Invalid amount. Indicates a bug in one of the validators.
console.log('Invalid amount');
return;
}
var tx = $network.remote.transaction();
// Add memo to tx
tx.addMemo('client', 'rt' + $scope.version);
// Flags
tx
.rippleLineSet($id.account, amount)
.setFlags('NoRipple')
.on('proposed', function(res){
$scope.$apply(function () {
setEngineStatus(res, false);
});
})
.on('success', function (res) {
$scope.$apply(function () {
setEngineStatus(res, true);
$scope.loading = false;
$scope.editing = false;
});
})
.on('error', function (res) {
setEngineStatus(res, false);
console.log('error', res);
setImmediate(function () {
$scope.$apply(function () {
$scope.mode = 'error';
$scope.loading = false;
$scope.editing = false;
});
});
});
function setEngineStatus(res, accepted) {
$scope.engine_result = res.engine_result;
$scope.engine_result_message = res.engine_result_message;
$scope.engine_status_accepted = accepted;
switch (res.engine_result.slice(0, 3)) {
case 'tes':
$scope.tx_result = accepted ? 'cleared' : 'pending';
break;
case 'tem':
$scope.tx_result = 'malformed';
break;
case 'ter':
$scope.tx_result = 'failed';
break;
case 'tec':
$scope.tx_result = 'failed';
break;
case 'tel':
$scope.tx_result = "local";
break;
case 'tep':
console.warn('Unhandled engine status encountered!');
}
if ($scope.tx_result=="cleared"){
$scope.gbiConnected = true;
$scope.showInstructions = true;
}
console.log($scope.tx_result);
}
keychain.requestSecret($id.account, $id.username, function (err, secret) {
// XXX Error handling
if (err) {
$scope.loading = false;
console.log(err);
return;
}
$scope.mode = 'granting';
tx.secret(secret);
tx.submit();
});
};
$scope.$watch('lines', function () {
if($scope.lines['rrh7rf1gV2pXAoqA8oYbpHd8TKv5ZQeo670158415500000000C1F76FF6ECB0BAC600000000']){
$scope.gbiConnected = true;
}
else {
$scope.gbiConnected = false;
}
}, true);
// User should be notified if the reserve is insufficient to add a gateway
$scope.$watch('account', function() {
$scope.can_add_trust = false;
if ($scope.account.Balance && $scope.account.reserve_to_add_trust) {
if (!$scope.account.reserve_to_add_trust.subtract($scope.account.Balance).is_positive()
|| $.isEmptyObject($scope.lines))
{
$scope.can_add_trust = true;
}
}
}, true);
}]);
};
module.exports = GoldTab;
|
"use strict";
const resolve = require("./resolve");
const { promise } = require("@xmpp/events");
async function fetchURIs(domain) {
const result = await resolve(domain, {
srv: [
{
service: "xmpps-client",
protocol: "tcp",
},
{
service: "xmpp-client",
protocol: "tcp",
},
],
});
return [
// Remove duplicates
...new Set(result.map((record) => record.uri)),
];
}
function filterSupportedURIs(entity, uris) {
return uris.filter((uri) => entity._findTransport(uri));
}
async function fallbackConnect(entity, uris) {
if (uris.length === 0) {
throw new Error("Couldn't connect");
}
const uri = uris.shift();
const Transport = entity._findTransport(uri);
if (!Transport) {
return fallbackConnect(entity, uris);
}
entity._status("connecting", uri);
const params = Transport.prototype.socketParameters(uri);
const socket = new Transport.prototype.Socket();
try {
socket.connect(params);
await promise(socket, "connect");
} catch {
return fallbackConnect(entity, uris);
}
entity._attachSocket(socket);
socket.emit("connect");
entity.Transport = Transport;
entity.Socket = Transport.prototype.Socket;
entity.Parser = Transport.prototype.Parser;
}
module.exports = function resolve({ entity }) {
const _connect = entity.connect;
entity.connect = async function connect(service) {
if (!service || /:\/\//.test(service)) {
return _connect.call(this, service);
}
const uris = filterSupportedURIs(entity, await fetchURIs(service));
if (uris.length === 0) {
throw new Error("No compatible transport found.");
}
try {
await fallbackConnect(entity, uris);
} catch (err) {
entity._reset();
entity._status("disconnect");
throw err;
}
};
};
|
var title = require('./lib/title');
var TennuTitle = {
configDefaults: {
"title": {
"liveTitle": false
}
},
requiresRoles: ['dblogger', 'dbcore'],
init: function(client, imports) {
const helps = {
"title": [
"{{!}}title",
"Shows the title of the last URL sent to the channel."
]
};
var titleConfig = client.config("title");
title = title(imports.dbcore.knex);
return {
handlers: {
"privmsg": function(message) {
if (titleConfig.liveTitle) {
return title.handleLiveTitle(message.message);
}
},
"!title": function(command) {
return title.searchTitle(command.channel, client.nickname());
}
},
help: {
"title": helps.title
},
commands: ["title"]
}
}
};
module.exports = TennuTitle;
|
import React, { Component } from "react";
import { Text, View, ViewPagerAndroid } from "react-native";
import { connect } from "react-redux";
import LinkButton from "../components/LinkButton";
import PopUp from "../components/PopUp";
import PopUpLink from "../components/PopUpLink";
import { MediaQueryStyleSheet } from "react-native-responsive";
//Interfaces. For elements that bridge to native
import GraphView from "../interface/GraphView";
import FilterGraphView from "../interface/FilterGraphView";
import config from "../redux/config";
import I18n from "../i18n/i18n";
import * as colors from "../styles/colors";
// Sets isVisible prop by comparing state.scene.key (active scene) to the key of the wrapped scene
function mapStateToProps(state) {
return {
connectionStatus: state.connectionStatus,
dimensions: state.graphviewDimensions,
notchFrequency: state.notchFrequency
};
}
class SlideFour extends Component {
constructor(props) {
super(props);
// Initialize States
this.state = {
popUpVisible: false
};
}
render() {
return (
<View style={styles.container}>
<View style={styles.halfGraphContainer}>
<GraphView notchFrequency={this.props.notchFrequency} style={styles.graphView} />
<Text style={styles.halfGraphLabelText}>
{I18n.t("raw")}
</Text>
</View>
<View style={styles.halfGraphContainer}>
<FilterGraphView
notchFrequency={this.props.notchFrequency}
style={styles.graphView}
filterType={config.filterType.BANDPASS}
/>
<Text style={styles.halfGraphLabelText}>
{I18n.t("bandPassFilter")}
</Text>
</View>
<Text style={styles.currentTitle}>
{I18n.t("filteringSlideTitle")}
</Text>
<ViewPagerAndroid //Allows us to swipe between blocks
style={styles.viewPager}
initialPage={0}
>
<View style={styles.pageStyle}>
<Text style={styles.header}>
{I18n.t("meaningfulData")}
</Text>
<Text style={styles.body}>
{I18n.t("firstEEGMust")}{' '}
<PopUpLink onPress={() => this.setState({ popUpVisible: true })}>
{I18n.t("filteredLink")}
</PopUpLink>{' '}
{I18n.t("toReduceSignals")}
</Text>
<LinkButton path="./slideFive">
{I18n.t("nextLink")}
</LinkButton>
</View>
</ViewPagerAndroid>
<PopUp
onClose={() => this.setState({ popUpVisible: false })}
visible={this.state.popUpVisible}
title={I18n.t("filtersTitle")}
>
{I18n.t("filtersDescription")}
</PopUp>
<PopUp
onClose={() => this.props.history.push("/connectorOne")}
visible={
this.props.connectionStatus === config.connectionStatus.DISCONNECTED
}
title={I18n.t("museDisconnectedTitle")}
>
{I18n.t("museDisconnectedDescription")}
</PopUp>
</View>
);
}
}
const styles = MediaQueryStyleSheet.create(
// Base styles
{
pageStyle: {
padding: 20,
alignItems: "stretch",
justifyContent: "space-around"
},
body: {
fontFamily: "Roboto-Light",
color: colors.black,
fontSize: 19
},
currentTitle: {
marginLeft: 20,
marginTop: 10,
fontSize: 13,
fontFamily: "Roboto-Medium",
color: colors.skyBlue
},
container: {
backgroundColor: colors.white,
flex: 1,
justifyContent: "space-around",
alignItems: "stretch"
},
header: {
fontFamily: "Roboto-Bold",
color: colors.black,
fontSize: 20
},
viewPager: {
flex: 4
},
graphView: {
flex: 1
},
halfGraphContainer: {
flex: 2,
justifyContent: "center",
alignItems: "stretch"
},
halfGraphLabelText: {
position: "absolute",
top: 5,
left: 5,
fontSize: 13,
fontFamily: "Roboto-Medium",
color: colors.white
}
},
// Responsive styles
{
"@media (min-device-height: 700)": {
viewPager: {
flex: 3
},
header: {
fontSize: 30
},
currentTitle: {
fontSize: 20
},
body: {
fontSize: 25
}
}
}
);
export default connect(mapStateToProps)(SlideFour);
|
require.config({
baseUrl: '/base', //karma servers files from base
paths: {
knockout: 'bower_components/knockout.js/knockout'
}
});
require(['spec/<%=name%>'], window.__karma__.start);
|
import func from '../../../../src/evaluate-by-operator/operator/minus';
describe('minus operator', () => {
it('should set SYMBOL const', () => {
expect(func.SYMBOL).to.eq('-');
});
it('should correctly process values', () => {
expect(func(2, 8.8)).to.eq(-6.8);
expect(func('2', 8.8)).to.eq(-6.8);
expect(func('2', '8.8')).to.eq(-6.8);
expect(func('2', '-8.8', 6, 0.4)).to.eq(4.4);
expect(() => func('foo', ' ', 'bar', ' baz')).to.throw('VALUE');
expect(() => func('foo', 2)).to.throw('VALUE');
});
});
|
/**
* NodeJs Server-Side Example for Fine Uploader (traditional endpoints).
* Maintained by Widen Enterprises.
*
* This example:
* - handles non-CORS environments
* - handles delete file requests assuming the method is DELETE
* - Ensures the file size does not exceed the max
* - Handles chunked upload requests
* - Returns a public URL to allow Fine Uploader to display the image
* in the browser if the browser is not capable of generating previews
* pre-upload client-side.
*
* Requirements:
* - express (for handling requests)
* - rimraf (for "rm -rf" support)
* - mkdirp (for "mkdir -p" support)
*/
var PORT = 8000,
//dependencies
express = require("express"),
fs = require("fs"),
rimraf = require("rimraf"),
mkdirp = require("mkdirp"),
app = express(),
// paths/constants
fileInputName = "qqfile",
uploadedFilesPath = __dirname + "/assets/uploadedFiles/",
chunkDirName = "chunks";
app.use(express.bodyParser());
app.listen(PORT);
console.log("Express server started on port %s", PORT);
// routes
app.use(express.static(__dirname));
app.use("/fineuploader", express.static(__dirname + "/node_modules/fine-uploader/jquery.fine-uploader/"));
app.use("/uploads", express.static(uploadedFilesPath));
app.post("/uploads", onUpload);
app.delete("/uploads/:uuid", onDeleteFile);
function onUpload(req, res) {
var partIndex = req.body.qqpartindex;
// text/plain is required to ensure support for IE9 and older
res.set("Content-Type", "text/plain");
if (partIndex == null) {
onSimpleUpload(req, res);
}
else {
onChunkedUpload(req, res);
}
}
function onSimpleUpload(req, res) {
var file = req.files[fileInputName],
uuid = req.body.qquuid,
sendThumbnailUrl = req.body.sendThumbnailUrl == "true",
responseData = {
success: false
};
file.name = req.body.qqfilename;
moveUploadedFile(file, uuid, function() {
responseData.success = true;
if (sendThumbnailUrl) {
responseData.thumbnailUrl = "/uploads/" + uuid + "/" + file.name;
}
res.send(responseData);
},
function() {
responseData.error = "Problem copying the file!";
res.send(responseData);
});
}
function onChunkedUpload(req, res) {
var file = req.files[fileInputName],
size = parseInt(req.body.qqtotalfilesize),
uuid = req.body.qquuid,
index = req.body.qqpartindex,
totalParts = parseInt(req.body.qqtotalparts),
sendThumbnailUrl = req.body.sendThumbnailUrl == "true",
responseData = {
success: false
};
file.name = req.body.qqfilename;
storeChunk(file, uuid, index, totalParts, function() {
if (index < totalParts-1) {
responseData.success = true;
res.send(responseData);
}
else {
combineChunks(file, uuid, function() {
responseData.success = true;
if (sendThumbnailUrl) {
responseData.thumbnailUrl = "/uploads/" + uuid + "/" + file.name;
}
res.send(responseData);
},
function() {
responseData.error = "Problem conbining the chunks!";
res.send(responseData);
});
}
},
function(reset) {
responseData.error = "Problem storing the chunk!";
res.send(responseData);
});
}
function onDeleteFile(req, res) {
var uuid = req.params.uuid,
dirToDelete = uploadedFilesPath + uuid;
rimraf(dirToDelete, function(error) {
if (error) {
console.error("Problem deleting file! " + error);
res.status(500);
}
res.send();
});
}
function moveFile(destinationDir, sourceFile, destinationFile, success, failure) {
mkdirp(destinationDir, function(error) {
var sourceStream, destStream;
if (error) {
console.error("Problem creating directory " + destinationDir + ": " + error);
failure();
}
else {
sourceStream = fs.createReadStream(sourceFile);
destStream = fs.createWriteStream(destinationFile);
sourceStream
.on("error", function(error) {
console.error("Problem copying file: " + error.stack);
failure();
})
.on("end", success)
.pipe(destStream);
}
});
}
function moveUploadedFile(file, uuid, success, failure) {
var destinationDir = uploadedFilesPath + uuid + "/",
fileDestination = destinationDir + file.name;
moveFile(destinationDir, file.path, fileDestination, success, failure);
}
function storeChunk(file, uuid, index, numChunks, success, failure) {
var destinationDir = uploadedFilesPath + uuid + "/" + chunkDirName + "/",
chunkFilename = getChunkFilename(index, numChunks),
fileDestination = destinationDir + chunkFilename;
moveFile(destinationDir, file.path, fileDestination, success, failure);
}
function combineChunks(file, uuid, success, failure) {
var chunksDir = uploadedFilesPath + uuid + "/" + chunkDirName + "/",
destinationDir = uploadedFilesPath + uuid + "/",
fileDestination = destinationDir + file.name;
fs.readdir(chunksDir, function(err, fileNames) {
var destFileStream;
if (err) {
console.error("Problem listing chunks! " + err);
failure();
}
else {
fileNames.sort();
destFileStream = fs.createWriteStream(fileDestination, {flags: "a"});
appendToStream(destFileStream, chunksDir, fileNames, 0, function() {
rimraf(chunksDir, function(rimrafError) {
if (rimrafError) {
console.log("Problem deleting chunks dir! " + rimrafError);
}
});
success();
},
failure);
}
});
}
function appendToStream(destStream, srcDir, srcFilesnames, index, success, failure) {
if (index < srcFilesnames.length) {
fs.createReadStream(srcDir + srcFilesnames[index])
.on("end", function() {
appendToStream(destStream, srcDir, srcFilesnames, index+1, success, failure);
})
.on("error", function(error) {
console.error("Problem appending chunk! " + error);
failure();
})
.pipe(destStream, {end: false});
}
else {
success();
}
}
function getChunkFilename(index, count) {
var digits = new String(count).length,
zeros = new Array(digits + 1).join("0");
return (zeros + index).slice(-digits);
}
|
import {merge} from 'lodash';
const DeviceCollection = {
devices: {},
get(deviceId) {
return this.devices[deviceId];
},
set(device) {
const deviceId = device.id || device.identity && device.identity.id;
// check if the device is already existing, if so then merge else add
const existingDevice = this.devices[deviceId];
if (existingDevice) {
// already existing, merge for any new binding information
merge(existingDevice, device);
}
else {
this.devices[deviceId] = device;
}
},
reset() {
this.devices = {};
},
getAll() {
return Object.values(this.devices);
}
};
export default DeviceCollection;
|
'use strict';
module.exports = {
BLANK: '_blank',
SELF: '_self',
PARENT: '_parent',
TOP: '_top'
};
|
/**
* Created by markus.candido on 19/07/15.
* public/js/controllers/grupos-controller.js
*/
angular.module('alurapic')
.controller('GruposController', function($scope, $http){
$http.get('/v1/grupos')
.success(function(grupos) {
console.log(grupos);
$scope.grupos = grupos;
console.log($scope.grupos);
})
.error(function(error){
console.log(error);
});
});
|
/**
* Created by moses on 12/6/14.
*/
'use strict';
var Config = {};
Config.yearDirBase = '/Volumes/MoBucket/Users/Dean\ Moses/Pictures/raw';
Config.jsonDirBase = '/Users/moses/devgit/tacocat-gallery-data';
Config.targetDirBase = '/Users/moses/devgit/albums';
module.exports = Config;
|
export const boldUp = {"viewBox":"0 0 20 20","children":[{"name":"path","attribs":{"d":"M10,2.5l7.5,7.5H14v7H6v-7H2.5L10,2.5z"}}]};
|
// xStrRepeat r1, Copyright 2010 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL
function xStrRepeat(s, n)
{
for (var r = s, i = 1; i < n; ++i) r += s;
return r;
}
|
var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config.js');
var app = express();
var compiler = webpack(config);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
app.use(require('webpack-hot-middleware')(compiler));
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.listen(1337, '0.0.0.0', function(err) {
if (err) {
console.log(err);
return;
}
console.log('Listening at http://0.0.0.0:1337');
});
|
const imager = require('../src/imager');
const readPath = '../resources/snail.bmp';
imager.binaryScale(readPath, './output/_binary_pic.bmp');
imager.grayScale(readPath, './output/_gray_pic.bmp');
imager.negative(readPath, './output/_negative_pic.bmp');
imager.captureScreen('./output/_captureScreen.bmp');
|
var settings = {
API: 'http://176.58.113.253:8090/api/'
}
|
/**
* MULTIPLAYER ASTEROIDS GAME CLIENT
*/
/**
* Game variables
*/
var canvas, // Canvas DOM element
ctx, // Canvas rendering context
keys, // Keyboard input
localPlayer, // Local player
remotePlayers, // Remote players
asteroids, // Asteroids
smoke, // Smoke effects
socket, // Socket for communication with Socket.IO server
animationId, // Animation frame id
fps, // Animation frames per second
ping, // Ping (ms)
pingStart, // Start time of ping measurement
startTime, // Start time of current round
lastGameTick, // Time when the animation frame was updated last time
lastBulletsShot; // Number of bullets local player had shot in total last time checked
/**
* Game constants
*/
var host = "http://localhost", // Socket.io server host
port = 8021, // Socket.io server port
countDown = 3000, // Count down time to each round (ms)
roundTime = 2*60*1000 + countDown, // Time one round lasts (ms)
area = { // The game area
width: 3000,
height: 2250
};
/**
* Game initialization
*/
function init(alias) {
// Define the canvas and rendering context
canvas = document.getElementById("game-canvas");
ctx = canvas.getContext("2d");
// Maximise the canvas
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Initialize essential modules
sound.init(); // sounds (see sound.js)
texture.init(); // textures (see texture.js)
log.init(); // log (see log.js)
stats.init(); // modal window for statistics (see stats.js)
// Keep all asteroids in an array
asteroids = [];
// Keep all running smoke effects in an array
smoke = [];
// Initialize keyboard controls
keys = new Keys();
// Initialize the local player and set start values
localPlayer = new SpaceShip();
localPlayer.alias = alias;
localPlayer.hue = random(0, 255);
setLocalPlayerStartProperties();
// Set last time a bullet was shot by local player to zero
lastBulletsShot = 0;
// Set canvas background and define canvas offsets
canvas.offset = {
x: 0,
y: 0
};
// Connect to Socket.io server
socket = io.connect(host, {port: port, transports: ["websocket"]});
// Keep all remote players in an array
remotePlayers = [];
// Start listening for events
setEventHandlers();
};
/**
* Game event handlers
*/
function setEventHandlers() {
// Keyboard
window.addEventListener("keydown", onKeydown, false);
window.addEventListener("keyup", onKeyup, false);
// Mouse move
window.addEventListener("mousemove", onMousemove, false);
// Window resize
window.addEventListener("resize", onResize, false);
// Socket.IO server events
socket.on("connect", onSocketConnected);
socket.on("disconnect", onSocketDisconnect);
socket.on("ping", onPing);
socket.on("pong", onPong);
socket.on("new round", onNewRound);
socket.on("new asteroid", onNewAsteroid);
socket.on("new player", onNewPlayer);
socket.on("move player", onMovePlayer);
socket.on("respawn player", onRespawnPlayer);
socket.on("players collide", onPlayersCollide);
socket.on("player message", onPlayerMessage);
socket.on("remove player", onRemovePlayer);
socket.on("new bullet", onNewBullet);
socket.on("remove bullet", onRemoveBullet);
socket.on("bullet hit player", onBulletHitPlayer);
socket.on("bullet hit asteroid", onBulletHitAsteroid);
socket.on("asteroid hit player", onAsteroidHitPlayer);
}
// Keyboard key down
function onKeydown(e) {
// Only respond as usual to key press if message container is invisible
if (!log.msgVisible) {
/**
* On press TAB
*/
if (e.keyCode === keys.TAB) {
// Prevent from flipping between focused elements on press TAB
e.preventDefault();
// Make stats visible if it isn't already
if (!keys.isKeydown(keys.TAB)) {
stats.show();
}
}
/**
* On press MESSAGE
*/
else if (e.keyCode === keys.MESSAGE) {
log.showMsg();
}
/**
* On press MUTE
*/
else if (e.keyCode === keys.MUTE && !keys.isKeydown(keys.MUTE)) {
sound.muteToggle();
}
// Provide keys object with the event
keys.onKeydown(e);
}
// Else, if message container is visible
else {
/**
* On press MESSAGE
*/
if (e.keyCode === keys.MESSAGE && !keys.isKeydown(keys.MESSAGE)) {
var message = log.msgVal();
// Only post message if not empty
if (message !== "") {
socket.emit("player message", {message: message});
}
// Hide message container
log.hideMsg();
}
}
}
// Keyboard key up
function onKeyup(e) {
/**
* On release TAB
*/
if (e.keyCode === keys.TAB) {
stats.hide();
}
// Provide keys object with the event
keys.onKeyup(e);
}
// Mouse move
var hideMouseId;
function onMousemove(e) {
var timeout = 2000, // Time until cursor gets hided
target = document.body;
// Set cursor to default
target.style.cursor = "default";
// Clear ongoing timeout if any
if (hideMouseId) clearTimeout(hideMouseId);
// Start timeout for hiding cursor
hideMouseId = setTimeout(function () {
target.style.cursor = "none";
}, timeout);
}
// Browser window resize
function onResize(e) {
// Maximize the canvas
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Resize log
log.resize();
// Resize modal window for statistics
stats.resize();
}
// Socket connected
function onSocketConnected() {
console.log("Connected to socket server");
// Hide loader
$("#loader").fadeOut(100);
// Start the animation
animate();
// Emit ping
pingStart = Date.now();
socket.emit("ping");
// Emit new player
socket.emit("new player", localPlayer.getNewPlayerData());
// Set local player id to socket session id
localPlayer.id = socket.socket.sessionid;
console.log("localPlayer.id: " + localPlayer.id);
// Create DOM-element for the local player's stats
stats.addPlayer(localPlayer, "local-player");
// Print message in log
log.print("You are now connected!");
}
// Socket disconnect
function onSocketDisconnect() {
// Print message in log
log.print("<span style='color:#f00'>You got disconnected from the server.</span>");
// Stop the animation
cancelAnimationFrame(animationId);
// Empty remote players array
remotePlayers = [];
// Remove all players from statistics table
stats.removeAll();
// Reset local player stats
localPlayer.resetStats();
}
// New round
function onNewRound(data) {
var i, remotePlayer, winner, score;
// Set start time of round
startTime = Date.now() - (roundTime - data.timeLeft);
// Do not reset round if player connected to already ongoing round
if (data.reset) {
// Empty asteroids array
asteroids = [];
// Make local player immune
localPlayer.makeImmune();
// Store winner data
winner = data.winner.playerId === localPlayer.id ? localPlayer : playerById(data.winner.playerId);
score = data.winner.score;
// Reset remote players statistics and bullets
for (i = 0; i < remotePlayers.length; i++) {
remotePlayer = remotePlayers[i];
remotePlayer.resetStats();
remotePlayer.bullets = [];
}
// Reset local player statistics and bullets, and set start properties
localPlayer.resetStats();
localPlayer.bullets = [];
setLocalPlayerStartProperties();
// Show new round modal
stats.showNewRoundModal(winner, score);
// Reset statistics table
stats.reset();
// Print last rounds winner in log
log.print(aliasTag(winner) + " won last round with a score of " + score + "!");
}
}
// On ping
function onPing(data) {
socket.emit("pong");
ping = data.ping;
if (ping) {
// Print the ping (and fps at the same time)
printPingFps();
}
}
// On pong (ping is sent by client ONLY on connection, the rest of the time it is calculated by the server)
function onPong() {
ping = Date.now() - pingStart;
// Print the ping (and fps at the same time)
printPingFps();
}
// New asteroid was generated by server
function onNewAsteroid(data) {
var x, y, position, rotation, velocity, timeExisted, latency;
// Calculate for how long the asteroid has already existed
latency = ping / 2;
timeExisted = (data.timeExisted + latency) / 1000;
// Convert data.velocity to a vector
velocity = new Vector(data.velocity.x, data.velocity.y);
// Calculate the current position of asteroid
position = new Vector(data.spawnX, data.spawnY);
position.iAddVector(velocity.mulScalar(timeExisted));
// Calculate current rotation of asteroid
rotation = data.rotation + data.rotationSpeed * timeExisted;
// Instantiate new Asteroid object
newAsteroid = new Asteroid(position.x, position.y, rotation, velocity, data.diameter, data.rotationSpeed);
// Add new asteroid to asteroids array
asteroids[data.index] = newAsteroid;
asteroids[data.index].index = data.index;
}
// New player connected
function onNewPlayer(data) {
// Create new SpaceShip instance
var newPlayer = new SpaceShip(data.x, data.y, data.rotation, data.health, data.kills, data.deaths, data.asteroidsShot, data.hue);
// Set player identifiers
newPlayer.id = data.id;
newPlayer.alias = data.alias;
// Add new player to remotePlayers
remotePlayers.push(newPlayer);
// Add new player to stats modal
stats.addPlayer(newPlayer);
// Print message in log
if (!data.wasAlreadyPlaying) {
log.print(aliasTag(newPlayer) + " joined the game!");
}
}
// Remote player moved
function onMovePlayer(data) {
var movePlayer = playerById(data.id);
// Don't do anything if player can't be found or is in limbo state
if (!movePlayer || movePlayer.limbo) return;
// Update moved player's properties
movePlayer.position.x = data.x;
movePlayer.position.y = data.y;
movePlayer.rotation = data.rotation;
movePlayer.isAccelerating = data.isAccelerating;
}
// Killed player re-spawn
function onRespawnPlayer(data) {
var respawnPlayer = playerById(data.playerId);
// Make sure re-spawned player isn't in limbo state
respawnPlayer.limbo = false;
}
// Two players collide
function onPlayersCollide(data) {
var i, playerId, player, collidedPlayers;
collidedPlayers = [];
for (i = 1; i <= 2; i++) {
playerId = data["playerId"+i];
if (playerId === localPlayer.id) {
player = localPlayer;
} else {
player = playerById(playerId);
}
collidedPlayers.push(player);
// Do nothing if anyone of the players is immune
if (player.isImmune) return;
}
for (i = 0; i <= 1; i++) {
player = collidedPlayers[i];
updateAfterKill(player);
if (player.id === localPlayer.id) {
setLocalPlayerStartProperties();
// Let server know local player died on collision
socket.emit("players collide", {playerId: localPlayer.id});
}
}
// Print to log that the players collided
log.print(aliasTag(collidedPlayers[0]) + " and " + aliasTag(collidedPlayers[1]) + " collided!");
}
// Player message
function onPlayerMessage(data) {
var player = data.playerId === localPlayer.id ? localPlayer : playerById(data.playerId);
// Print message in log
log.print(aliasTag(player) + " says: " + data.message);
}
// Remote player is removed
function onRemovePlayer(data) {
var removePlayer = playerById(data.id);
// Don't do anything if player can't be found
if (!removePlayer) return;
// Remove player from remote players array
remotePlayers.splice(remotePlayers.indexOf(removePlayer), 1);
// Remove player from stats modal
stats.removePlayer(removePlayer);
// Print message in log
log.print(aliasTag(removePlayer) + " left the game.");
}
// Bullet hit player
function onBulletHitPlayer(data) {
var hitPlayer, // Player who got hit by a bullet
playerWhoShot; // Player who shot the bullet
playerWhoShot = playerById(data.playerWhoShot);
// If local player was hit
if (data.hitPlayer == localPlayer.id) {
hitPlayer = localPlayer;
}
// Else if another player was hit (and local player was not the one who shot)
else {
hitPlayer = playerById(data.hitPlayer);
}
// Decrement hit player health
hitPlayer.health -= Bullet.prototype.damage;
// If player died
if (hitPlayer.health <= 0) {
updateAfterKill(hitPlayer, playerWhoShot);
// If local player died, set start properties
if (hitPlayer.id == localPlayer.id) {
setLocalPlayerStartProperties();
}
}
// Else, play hit sound
else {
sound.hit.play(getVolume(hitPlayer.position));
}
}
// Remote player shot a bullet
function onNewBullet(data) {
var timeExisted, latency, position, velocity, newBullet, playerWhoShot;
// Get remote player who shot the bullet
playerWhoShot = playerById(data.playerId);
// Don't do anything if player can't be found
if (!playerWhoShot) return;
// Calculate how long ago bullet was fired
latency = ping / 2;
timeExisted = (data.timeExisted + latency) / 1000;
// Create velocity vector
velocity = new Vector(data.velocity.x, data.velocity.y);
// Calculate bullet's current position based on time existed and velocity
position = new Vector(data.spawnX, data.spawnY);
position.iAddVector(velocity.mulScalar(timeExisted));
// Create new Bullet instance
newBullet = new Bullet(position.x, position.y, velocity);
// Play shoot sound
sound.shoot.play(getVolume(newBullet.position));
// Add bullet to remote player's bullet array
playerWhoShot.bullets[data.index] = newBullet;
}
// Remove bullet shot by remote player
function onRemoveBullet(data) {
var playerWhoShot = playerById(data.playerId);
// Do nothing if player can't be found
if (!playerWhoShot) return;
// Remove bullet from bullet array of player who shot
playerWhoShot.bullets.splice(data.index, 1);
}
// Remote player's bullet hit asteroid
function onBulletHitAsteroid(data) {
var playerWhoShot = playerById(data.playerId),
asteroid = asteroids[data.asteroidIndex];
// Do nothing if player or asteroid can't be found
if (!playerWhoShot || !asteroid) return;
// Update stats
playerWhoShot.asteroidsShot++;
stats.update(playerWhoShot, "asteroidsShot");
// Add explosion effects
smoke = effect.addExplosion(asteroid.position, smoke);
sound.hit.play(getVolume(asteroid.position));
}
// Asteroid hit player
function onAsteroidHitPlayer(data) {
var hitPlayer = playerById(data.playerId);
// Do nothing if player can't be found
if (!hitPlayer) return;
// Print in log
log.print(aliasTag(hitPlayer) + " collided with an asteroid!");
// Update hit player
updateAfterKill(hitPlayer);
}
/**
* Game animation loop
*/
function animate() {
var now = Date.now(),
td = (now - (lastGameTick || now)) / 1000; // Time difference since last frame (seconds)
// Set last game tick to now
lastGameTick = now;
// Update properties of all game objects
update(td);
// Draw all game objects on canvas
draw();
// Request a new animation frame
animationId = requestAnimationFrame(animate);
}
/**
* Game update
*/
function update(td) {
var i, j, newSmoke, asteroid, bulletsShot, index, newBullet, bullet, hitPlayer, hitAsteroid, remotePlayer;
// Set value of frames per second
fps = parseInt(1 / td, 10);
// Update local player's properties
localPlayer.update(td, keys);
// Add smoke effect if local player is accelerating
if (localPlayer.isAccelerating) {
// Add smoke to global smoke array
newSmoke = effect.getSmokeBehindSpaceShip(localPlayer);
smoke.push(newSmoke);
}
// Check if local player collided with asteroid
if (asteroid = asteroidHasHitLocalPlayer()) {
// Emit that local player was hit by asteroid to server
socket.emit("asteroid hit player", {asteroidIndex: asteroid.index});
// Update local player properties
updateAfterKill(localPlayer);
setLocalPlayerStartProperties();
}
// Send updated properties to server
socket.emit("move player", localPlayer.getMovePlayerData());
// If bullet has been shot, emit new bullet to server
bulletsShot = localPlayer.bulletsShot;
if (bulletsShot > lastBulletsShot) {
index = localPlayer.bullets.length - 1;
newBullet = localPlayer.bullets[index];
// Play shoot sound
sound.shoot.play();
// Emit new bullet to server
socket.emit("new bullet", {
index: index,
spawnX: newBullet.spawnX,
spawnY: newBullet.spawnY,
velocity: {x: newBullet.velocity.x, y: newBullet.velocity.y},
timeExisted: (Date.now() - newBullet.spawnTime)
});
}
lastBulletsShot = bulletsShot;
// Update local player's bullets' positions
for (i = 0; i < localPlayer.bullets.length ; i++) {
bullet = localPlayer.bullets[i];
bullet.update(td);
// Check if bullet hit remote player
if (hitPlayer = bulletHasHitRemotePlayer(bullet.position)) {
// Play hit sound
sound.hit.play(getVolume(hitPlayer.position));
// Emit to server that local player hit someone
socket.emit("bullet hit player", {id: hitPlayer.id});
// Remove local bullet and emit to server that bullet has been removed
removeLocalBulletAndEmitToServer(i);
}
// Check if bullet hit asteroid
else if (hitAsteroid = bulletHasHitAsteroid(bullet.position)) {
// Add explosion effects
smoke = effect.addExplosion(hitAsteroid.position, smoke);
sound.hit.play(getVolume(hitAsteroid.position));
// Set asteroid in "limbo" state
hitAsteroid.limbo = true;
hitAsteroid.position = new Vector(-hitAsteroid.diameter, -hitAsteroid.diameter);
// Update stats
localPlayer.asteroidsShot++;
stats.update(localPlayer, "asteroidsShot");
// Emit to server that local player hit asteroid
socket.emit("bullet hit asteroid", {index: hitAsteroid.index});
// Remove local bullet and emit to server that bullet has been removed
removeLocalBulletAndEmitToServer(i);
}
// Check if bullet is outside of game area
else if (bullet.isOutsideGameArea(area.width, area.height)) {
// Remove bullet and emit to server that bullet has been removed
removeLocalBulletAndEmitToServer(i);
}
}
// Update remote players' properties
for (i = 0; i < remotePlayers.length; i++) {
remotePlayer = remotePlayers[i];
// Add smoke if remote player is accelerating
if (remotePlayer.isAccelerating) {
newSmoke = effect.getSmokeBehindSpaceShip(remotePlayer);
smoke.push(newSmoke);
}
// Update remote player's bullet's positions
for (j = 0; j < remotePlayer.bullets.length; j++) {
bullet = remotePlayer.bullets[j];
if (bullet) {
bullet.update(td);
}
}
}
// Update positions of asteroids
for (i = 0; i < asteroids.length; i++) {
asteroid = asteroids[i];
// Skip this iteration if asteroid was removed during the loop (there may be a lag between server and client)
if (!asteroid) continue;
asteroid.update(td);
}
// Update smoke
smoke = effect.updateSmoke(td, smoke);
// Update canvas offsets to local players new position
updateCanvasOffsets();
}
// Update statistics after kill
function updateAfterKill(killedPlayer, playerWhoShot) {
// Increment death stats by 1 on killed player
killedPlayer.deaths++;
// Add explosion effects
smoke = effect.addExplosion(killedPlayer.position, smoke);
sound.explode.play(getVolume(killedPlayer.position));
// Make player disappear from screen
killedPlayer.limbo = true;
killedPlayer.position = new Vector(-killedPlayer.height, -killedPlayer.height);
// Update stats modal
stats.update(killedPlayer, "deaths");
// Increment kill stats by 1 on player who shot (if killed player didn't die on collision for example)
if (playerWhoShot) {
playerWhoShot.kills++;
stats.update(playerWhoShot, "kills");
log.print(aliasTag(playerWhoShot) + " killed " + aliasTag(killedPlayer) + "!");
}
// Reset killed player health
killedPlayer.health = 100;
// Make killed player immune for set immuneTime
killedPlayer.makeImmune();
}
// Adjust canvas offsets to local player's position
function updateCanvasOffsets() {
var x = localPlayer.position.x,
y = localPlayer.position.y,
// Spaces between canvas borders and local player's position when moving towards game area border
paddingX = canvas.width*0.45,
paddingY = canvas.height*0.45;
// Adjust x offset if the position out of bounds
if (x > canvas.offset.x + canvas.width - paddingX) {
canvas.offset.x += x - (canvas.offset.x + canvas.width - paddingX);
}
else if (x < canvas.offset.x + paddingX) {
canvas.offset.x -= canvas.offset.x + paddingX - x;
}
// Adjust y offset if the position out of bounds
if (y > canvas.height + canvas.offset.y - paddingY) {
canvas.offset.y += y - (canvas.height + canvas.offset.y - paddingY);
}
else if (y < canvas.offset.y + paddingY) {
canvas.offset.y -= canvas.offset.y + paddingY - y;
}
// Keep "camera" inside game area
if (canvas.offset.x < 0) canvas.offset.x = 0;
else if (canvas.offset.x > area.width - canvas.width) canvas.offset.x = area.width - canvas.width;
if (canvas.offset.y < 0) canvas.offset.y = 0;
else if (canvas.offset.y > area.height - canvas.height) canvas.offset.y = area.height - canvas.height;
// Update offsets on game background
canvas.style.backgroundPosition = -canvas.offset.x + "px " + -canvas.offset.y + "px";
}
// Set space ship start properties (on initialization and re-spawn)
function setLocalPlayerStartProperties() {
var startX = random(canvas.width*0.1, area.width - canvas.width*0.1),
startY = random(canvas.width*0.1, area.height - canvas.width*0.1),
startVelocity = new Vector(0, 0);
startRotation = random(0, 360)*(Math.PI/180);
localPlayer.position = new Vector(startX, startY);
localPlayer.velocity = startVelocity;
localPlayer.rotation = startRotation;
localPlayer.limbo = false;
if (socket) {
// Emit to server that local player has re-spawned
socket.emit("respawn player");
}
}
/**
* Game draw
*/
function draw() {
var i, j, remotePlayer, bullet, asteroid;
// Wipe the canvas clean
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw smoke effects
effect.drawSmoke(ctx, smoke, canvas.offset);
// Draw the local player's bullets and the local player
for (i = 0; i < localPlayer.bullets.length; i++) {
bullet = localPlayer.bullets[i];
// Only draw bullet if it is in view
if (bullet && !bullet.isOutsideGameArea(canvas.width, canvas.height, canvas.offset.x, canvas.offset.y))
bullet.draw(ctx, canvas.offset);
}
localPlayer.draw(ctx, canvas.offset);
// Draw arrows indicating local players position if outside of game area
if (localPlayer.isOutsideGameArea(area.width, area.height)) {
drawLocalPlayerPositionIndicators();
}
// Draw remote players' bullets and the remote players
for (i = 0; i < remotePlayers.length; i++) {
remotePlayer = remotePlayers[i];
// Draw bullets (if they are inside canvas)
for (j = 0; j < remotePlayer.bullets.length; j++) {
bullet = remotePlayer.bullets[j];
if (bullet && !bullet.isOutsideGameArea(canvas.width, canvas.height, canvas.offset.x, canvas.offset.y))
bullet.draw(ctx, canvas.offset);
}
// Draw player (if it is inside canvas)
if (remotePlayer && !remotePlayer.isOutsideGameArea(canvas.width, canvas.height, canvas.offset.x, canvas.offset.y))
remotePlayer.draw(ctx, canvas.offset);
}
// Draw asteroids (if they are inside canvas)
for (i = 0; i < asteroids.length; i++) {
asteroid = asteroids[i];
if (asteroid && !asteroid.isOutsideGameArea(canvas.width, canvas.height, canvas.offset.x, canvas.offset.y))
asteroid.draw(ctx, canvas.offset);
}
// Draw clock showing time left of current round
drawClock();
// Draw map
drawMap();
}
// Draw clock showing time left of current round
function drawClock() {
var clockFontSize, margin, timeLeft;
margin = Math.min(canvas.width, canvas.height) * 0.05;
clockFontSize = canvas.height * 0.2;
timeLeft = roundTime - (Date.now() - startTime) + 1000;
ctx.save();
ctx.font = clockFontSize + "px verdana";
ctx.strokeStyle = timeLeft > 5000 ? "rgba(255, 255, 255, 0.8)" : "rgba(255, 0, 0, 0.8)";
ctx.fillStyle = timeLeft > 5000 ? "rgba(255, 255, 255, 0.1)" : "rgba(255, 0, 0, 0.1)";
ctx.fillText(msToMMSS(timeLeft), margin, canvas.height - margin);
ctx.strokeText(msToMMSS(timeLeft), margin, canvas.height - margin);
ctx.restore();
}
// Draw game area map
function drawMap() {
var mapWidth, mapHeight, mapRatio, margin, x, y, mapAreaRatioX, mapAreaRatioY,
viewWidth, viewHeight, viewOffsetX, viewOffsetY, viewLineLength,
localPlayerX, localPlayerY, remotePlayerX, remotePlayerY, i;
// The ratio of game area dimensions
mapRatio = area.width / area.height;
// Set map dimensions depending on canvas dimensions
if (canvas.width > canvas.height) {
mapHeight = canvas.height * 0.35;
mapWidth = mapHeight * mapRatio;
margin = canvas.height * 0.05;
} else {
mapWidth = canvas.width * 0.35;
mapHeight = mapWidth / mapRatio;
margin = canvas.width * 0.05;
}
// Ratio between map and area
mapAreaRatioX = mapWidth / area.width;
mapAreaRatioY = mapHeight / area.height;
// Set dimensions and offsets for the current view
viewWidth = canvas.width * mapAreaRatioX;
viewHeight = canvas.height * mapAreaRatioY;
viewOffsetX = canvas.offset.x * mapAreaRatioX;
viewOffsetY = canvas.offset.y * mapAreaRatioY;
viewLineLength = Math.min(viewWidth, viewHeight)*0.25;
// Set dimensions for local player position indicator
localPlayerX = localPlayer.position.x * mapAreaRatioX;
localPlayerY = localPlayer.position.y * mapAreaRatioY;
// Set the coordinates for where to start drawing the map
x = canvas.width - margin - mapWidth;
y = canvas.height - margin - mapHeight;
// Draw the map
ctx.save();
ctx.translate(x, y);
// Map border and fill
ctx.fillStyle = "rgba(0, 0, 0, 0.2)";
ctx.fillRect(0, 0, mapWidth, mapHeight);
ctx.strokeStyle = "rgba(255, 255, 255, 0.8)";
ctx.strokeRect(0, 0, mapWidth, mapHeight);
// Map grid
ctx.beginPath();
ctx.strokeStyle = "rgba(255, 255, 255, 0.2)";
for (i = 1; i < 8; i++) { // Vertical lines
ctx.moveTo(i * mapWidth / 8, 0);
ctx.lineTo(i * mapWidth / 8, mapHeight);
}
for (i = 1; i < 6; i++) { // Horizontal lines
ctx.moveTo(0, i * mapHeight / 6);
ctx.lineTo(mapWidth, i * mapHeight / 6);
}
ctx.closePath();
ctx.stroke();
// Map view
ctx.strokeStyle = "hsla(90, 100%, 50%, 0.8)";
ctx.beginPath();
// Top left
ctx.moveTo(viewOffsetX, viewOffsetY);
ctx.lineTo(viewOffsetX + viewLineLength, viewOffsetY);
ctx.moveTo(viewOffsetX, viewOffsetY);
ctx.lineTo(viewOffsetX, viewOffsetY + viewLineLength);
// Bottom left
ctx.moveTo(viewOffsetX, viewOffsetY + viewHeight);
ctx.lineTo(viewOffsetX + viewLineLength, viewOffsetY + viewHeight);
ctx.moveTo(viewOffsetX, viewOffsetY + viewHeight);
ctx.lineTo(viewOffsetX, viewOffsetY + viewHeight - viewLineLength);
// Top right
ctx.moveTo(viewOffsetX + viewWidth, viewOffsetY);
ctx.lineTo(viewOffsetX + viewWidth - viewLineLength, viewOffsetY);
ctx.moveTo(viewOffsetX + viewWidth, viewOffsetY);
ctx.lineTo(viewOffsetX + viewWidth, viewOffsetY + viewLineLength);
// Bottom right
ctx.moveTo(viewOffsetX + viewWidth, viewOffsetY + viewHeight);
ctx.lineTo(viewOffsetX + viewWidth - viewLineLength, viewOffsetY + viewHeight);
ctx.moveTo(viewOffsetX + viewWidth, viewOffsetY + viewHeight);
ctx.lineTo(viewOffsetX + viewWidth, viewOffsetY + viewHeight - viewLineLength);
ctx.closePath();
ctx.stroke();
// Local player position indicator
ctx.fillStyle = "hsla(90, 100%, 50%, 0.8)";
ctx.beginPath();
ctx.arc(localPlayerX, localPlayerY, 2, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
ctx.strokeStyle = "hsla(90, 100%, 50%, 0.2)";
ctx.beginPath();
ctx.arc(localPlayerX, localPlayerY, 8, 0, Math.PI*2, true);
ctx.closePath();
ctx.stroke();
// Remote player position indicators
ctx.fillStyle = "hsla(0, 100%, 50%, 0.8)";
for (i = 0; i < remotePlayers.length; i++) {
ctx.beginPath();
remotePlayerX = remotePlayers[i].position.x * mapAreaRatioX;
remotePlayerY = remotePlayers[i].position.y * mapAreaRatioY;
ctx.arc(remotePlayerX, remotePlayerY, 2, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
}
ctx.restore();
}
// Draw local player position indicators (for when player is outside of arena)
function drawLocalPlayerPositionIndicators() {
var margin = 20, // The distance between edge of canvas and arrow
length = 12, // Length of arrow
x, // Arrow x position
y; // Arrow y position
// Save canvas context
ctx.save();
// Position the arrow depending on players position
if (localPlayer.position.x < 0) {
x = margin;
y = localPlayer.position.y - canvas.offset.y;
}
else if (localPlayer.position.x > area.width) {
x = canvas.width - margin;
y = localPlayer.position.y - canvas.offset.y;
}
if (localPlayer.position.y < 0) {
x = localPlayer.position.x - canvas.offset.x;
y = margin;
}
else if (localPlayer.position.y > area.height) {
x = localPlayer.position.x - canvas.offset.x;
y = canvas.height - margin;
}
ctx.translate(x, y);
// Rotate the arrow according to local player's rotation
ctx.rotate(localPlayer.rotation);
// Draw the arrow
ctx.strokeStyle = "#fff";
ctx.moveTo(-length/2, 0);
ctx.lineTo(length/2, 0);
ctx.lineTo(length/4, length/4);
ctx.moveTo(length/2, 0);
ctx.lineTo(length/4, -length/4);
ctx.stroke();
// Restore canvas context
ctx.restore();
}
// Print ping and fps
function printPingFps() {
var pingHTML = ping < 200 ? "Ping: " + ping : "<span style='color:#f00'>Ping: " + ping + "</span>";
fpsHTML = fps >= 30 ? "Fps: " + fps : "<span style='color:#f00'>Fps: " + fps + "</span>";
$("#ping").html(pingHTML);
$("#fps").html(fpsHTML);
}
/**
* Objects collision check functions
*/
// Check if local bullet hit remote player
function bulletHasHitRemotePlayer(bulletPosition) {
var i, remotePlayer, radius;
for (i = 0; i < remotePlayers.length; i++) {
remotePlayer = remotePlayers[i];
radius = Math.max(remotePlayer.width/2 + Bullet.prototype.width, remotePlayer.height/2 + Bullet.prototype.width);
// If player was actually hit
if (remotePlayer.position.distanceTo(bulletPosition) < radius && !remotePlayer.isImmune) {
remotePlayer.health -= Bullet.prototype.damage;
// If player died
if (remotePlayer.health <= 0) {
updateAfterKill(remotePlayer, localPlayer);
}
return remotePlayer;
}
}
return false;
}
// Check if local bullet hit asteroid
function bulletHasHitAsteroid(bulletPosition) {
var i, asteroid, radius;
for (i = 0; i < asteroids.length; i++) {
asteroid = asteroids[i];
radius = asteroid.diameter/2 + Bullet.prototype.width;
// If asteroid was actually hit
if (asteroid.position.distanceTo(bulletPosition) < radius) {
return asteroid;
}
}
return false;
}
// Check if asteroid has hit local player
function asteroidHasHitLocalPlayer() {
var i, asteroid, radius;
for (i = 0; i < asteroids.length; i++) {
asteroid = asteroids[i];
// Skip this iteration if asteroid was removed during the loop e.g. (there may be a lag between server and client)
if (!asteroid) continue;
// Set hit radius
radius = asteroid.diameter/2 + Math.max(localPlayer.width, localPlayer.height);
// If asteroid actually hit local player
if (asteroid.position.distanceTo(localPlayer.position) < radius && !localPlayer.isImmune) {
return asteroid;
}
}
return false;
}
/**
* Helper functions
*/
// Get a random number
function random(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Get a remote player by id
function playerById(id) {
var i;
for (i = 0; i < remotePlayers.length; i++) {
if (remotePlayers[i].id == id)
return remotePlayers[i];
}
return false;
}
// Remove bullet from local player's array and emit to server
function removeLocalBulletAndEmitToServer(bulletIndex) {
// Remove bullet from local player's bullet array
localPlayer.bullets.splice(bulletIndex, 1);
// Remove bullet from server
socket.emit("remove bullet", {index: bulletIndex});
}
// Get HSL from hue
function hslFromHue(hue) {
return "hsl(" + hue + ", 75%, 50%)";
}
// Get HTML <b> tag of player alias for printing in log e.g.
function aliasTag(player) {
var bTag = "<b style='color:" + hslFromHue(player.hue) + "'>" + player.alias + "</b>";
return bTag;
}
// Get time in MM:SS format from ms
function msToMMSS(time) {
var time = parseInt(time),
min = parseInt(time / 1000 / 60, 10),
sec = parseInt(time / 1000 % 60, 10);
if (time <= 0 || typeof time !== "number") {
return "0:00";
}
if (sec < 10) sec = "0" + sec;
return min + ":" + sec;
}
// Get sound effect playback volume based on event's distance to local player
function getVolume(position) {
var c = 0.005, // Volume decrease coefficient
distance = position.distanceTo(localPlayer.position),
volume = 1 / (1 + distance*c);
return volume;
}
|
game.PlayScreenVictory = me.ScreenObject.extend({
/**
* action to perform on state change
*/
onResetEvent: function() {
me.levelDirector.loadLevel("victory-level");
me.timer.setTimeout(function () {me.state.change(me.state.SPORT)},20000);
},
/**
* action to perform when leaving this screen (state change)
*/
onDestroyEvent: function() {
}
});
|
const sequelize = require('../db/connection');
const SQ = require('sequelize');
var MessageRoom = sequelize.define('messageStatus', {
number: {
type: SQ.INTEGER,
}
});
module.exports = MessageRoom;
|
/**
* Table 数值型单元格渲染器
* @author Brian Li
* @email lbxxlht@163.com
* @version 0.0.2.1
*/
define(function (require) {
var React = require('react');
return React.createClass({
/**
* @properties
* @param {String} className 加在单元格td上的类
* @param {String} style 加在单元格td上的样式表
* @param {String} content 单元格中显示的内容
* @param {String} renderType 数字显示类型:
* int:整形
* float:浮点
* percent:百分比
* @param {Number} fixed 显示保留的小数位数,renderType = 'int' 时无效
*/
getDefaultProps: function getDefaultProps() {
return {
className: '',
style: {},
content: '',
renderType: 'int',
fixed: 2
};
},
getInitialState: function getInitialState() {
return {};
},
render: function render() {
var tdProp = {
className: 'td-number ' + this.props.className,
style: this.props.style
};
var value = this.props.content;
if (isNaN(value)) {
value = '-';
} else {
value = value * 1;
switch (this.props.renderType) {
case 'int':
value = parseInt(value, 10);
break;
case 'float':
value = value.toFixed(isNaN(this.props.fixed) ? 2 : parseInt(this.props.fixed, 10));
break;
case 'percent':
value = (value * 100).toFixed(2) + '%';
break;
default:
}
}
return React.createElement(
'td',
tdProp,
value
);
}
});
});
|
'use strict';
module.exports = {
up: function (queryInterface, Sequelize) {
return queryInterface.addColumn(
'Channels',
'TeamId',
{
type: Sequelize.STRING
}
);
},
down: function (queryInterface, Sequelize) {
// remove user reference
return queryInterface.removeColumn('Channels', 'TeamId');
}
};
|
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// A bit simpler than readable streams.
// Implement an async ._write(chunk, cb), and it'll handle all
// the drain event emission and buffering.
module.exports = Writable;
/*<replacement>*/
var Buffer = require('buffer').Buffer;
/*</replacement>*/
Writable.WritableState = WritableState;
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
var Stream = require('stream');
util.inherits(Writable, Stream);
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
}
function WritableState(options, stream) {
var Duplex = require('./_stream_duplex');
options = options || {};
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
var hwm = options.highWaterMark;
var defaultHwm = options.objectMode ? 16 : 16 * 1024;
this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex)
this.objectMode = this.objectMode || !!options.writableObjectMode;
// cast to ints.
this.highWaterMark = ~~this.highWaterMark;
this.needDrain = false;
// at the start of calling end()
this.ending = false;
// when end() has been called, and returned
this.ended = false;
// when 'finish' is emitted
this.finished = false;
// should we decode strings into buffers before passing to _write?
// this is here so that some node-core streams can optimize string
// handling at a lower level.
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// not an actual buffer we keep track of, but a measurement
// of how much we're waiting to get pushed to some underlying
// socket or file.
this.length = 0;
// a flag to see when we're in the middle of a write.
this.writing = false;
// when true all writes will be buffered until .uncork() call
this.corked = 0;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// a flag to know if we're processing previously buffered items, which
// may call the _write() callback in the same tick, so that we don't
// end up in an overlapped onwrite situation.
this.bufferProcessing = false;
// the callback that's passed to _write(chunk,cb)
this.onwrite = function(er) {
onwrite(stream, er);
};
// the callback that the user supplies to write(chunk,encoding,cb)
this.writecb = null;
// the amount that is being written when _write is called.
this.writelen = 0;
this.buffer = [];
// number of pending user-supplied write callbacks
// this must be 0 before 'finish' can be emitted
this.pendingcb = 0;
// emit prefinish if the only thing we're waiting for is _write cbs
// This is relevant for synchronous Transform streams
this.prefinished = false;
// True if the error was already emitted and should not be thrown again
this.errorEmitted = false;
}
function Writable(options) {
var Duplex = require('./_stream_duplex');
// Writable ctor is applied to Duplexes, though they're not
// instanceof Writable, they're instanceof Readable.
if (!(this instanceof Writable) && !(this instanceof Duplex))
return new Writable(options);
this._writableState = new WritableState(options, this);
// legacy.
this.writable = true;
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function() {
this.emit('error', new Error('Cannot pipe. Not readable.'));
};
function writeAfterEnd(stream, state, cb) {
var er = new Error('write after end');
// TODO: defer error events consistently everywhere, not just the cb
stream.emit('error', er);
process.nextTick(function() {
cb(er);
});
}
// If we get something that is not a buffer, string, null, or undefined,
// and we're not in objectMode, then that's an error.
// Otherwise stream chunks are all considered to be of length=1, and the
// watermarks determine how many objects to keep in the buffer, rather than
// how many bytes or characters.
function validChunk(stream, state, chunk, cb) {
var valid = true;
if (!util.isBuffer(chunk) &&
!util.isString(chunk) &&
!util.isNullOrUndefined(chunk) &&
!state.objectMode) {
var er = new TypeError('Invalid non-string/buffer chunk');
stream.emit('error', er);
process.nextTick(function() {
cb(er);
});
valid = false;
}
return valid;
}
Writable.prototype.write = function(chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
if (util.isFunction(encoding)) {
cb = encoding;
encoding = null;
}
if (util.isBuffer(chunk))
encoding = 'buffer';
else if (!encoding)
encoding = state.defaultEncoding;
if (!util.isFunction(cb))
cb = function() {};
if (state.ended)
writeAfterEnd(this, state, cb);
else if (validChunk(this, state, chunk, cb)) {
state.pendingcb++;
ret = writeOrBuffer(this, state, chunk, encoding, cb);
}
return ret;
};
Writable.prototype.cork = function() {
var state = this._writableState;
state.corked++;
};
Writable.prototype.uncork = function() {
var state = this._writableState;
if (state.corked) {
state.corked--;
if (!state.writing &&
!state.corked &&
!state.finished &&
!state.bufferProcessing &&
state.buffer.length)
clearBuffer(this, state);
}
};
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode &&
state.decodeStrings !== false &&
util.isString(chunk)) {
chunk = new Buffer(chunk, encoding);
}
return chunk;
}
// if we're already writing something, then just put this
// in the queue, and wait our turn. Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, chunk, encoding, cb) {
chunk = decodeChunk(state, chunk, encoding);
if (util.isBuffer(chunk))
encoding = 'buffer';
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous needDrain will not be reset to false.
if (!ret)
state.needDrain = true;
if (state.writing || state.corked)
state.buffer.push(new WriteReq(chunk, encoding, cb));
else
doWrite(stream, state, false, len, chunk, encoding, cb);
return ret;
}
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
if (writev)
stream._writev(chunk, state.onwrite);
else
stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
if (sync)
process.nextTick(function() {
state.pendingcb--;
cb(er);
});
else {
state.pendingcb--;
cb(er);
}
stream._writableState.errorEmitted = true;
stream.emit('error', er);
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
onwriteStateUpdate(state);
if (er)
onwriteError(stream, state, sync, er, cb);
else {
// Check if we're actually ready to finish, but don't emit yet
var finished = ne
|
var tests = require('./test-fns');
var testOK = tests.testOK, testFail = tests.testFail, testSkip = tests.testSkip;
module.exports = {
'evaluation': {
'should eval nothing':
testOK('', ''),
'should eval comments, i.e. nothing':
testOK(';aaaa', ''),
'should eval definition':
testOK('(define a 1)', ''),
'should eval assignment':
testOK('(define a 1)(set! a 2)', ''),
'should raise error for extra right parentheses':
testFail('(define a 1))', 'Unnecessary usage of right parentheses'),
'should raise error for invalid tokens':
testFail('\\#a', 'Invalid content'),
'simple staff':
testOK('\n\
(define a 1)\n\
(set! a 2)\n\
(define foo (lambda (x) (+ a x)))\n\
(foo 4)\n\
((lambda (x) x) #t)', true),
'should generate stack info':
testOK('\n\
(define (foo)\n\
(bar)1)\n\
(define (bar)\n\
(baz)1)\n\
(define (baz)\n\
(raise (quote opala)))\n\
(foo)', 'Error: opala\nraise [native code]\nbaz (line: 7, column: 12)\nbar (line: 5, column: 12)\nfoo (line: 3, column: 12)\nglobal (line: 8, column: 10)'),
// TODO
// 'should generate stack info 2':
// testSkip('\n\
// (define (foo)\n\
// (let ()\n\
// (bar))1)\n\
// (define (bar)\n\
// (baz)1)\n\
// (define (baz)\n\
// (raise (quote opala)))\n\
// (foo)', 'opala\nraise\nbaz\nbar\nfoo'),
// },
'begin': {
'begin':
testOK('\n\
(define foo (lambda (x)\n\
(define y 1)\n\
(begin\n\
(set! y (+ x y))\n\
y)))\n\
(foo 5)', 6),
'nested begins':
testOK('\n\
(begin\n\
(begin\n\
(begin 1)))', 1),
'empty begin':
testOK('(begin)', ''),
},
'conditionals': {
'if': {
'should eval if then':
testOK('(if #t 1 2)', 1),
'should eval if else':
testOK('(if #f 1 2)', 2),
'should eval nested if':
testOK('(if #f (if #t 1 2) (if #f 3 4))', 4),
'should eval if then no else':
testOK('(if #t 1)', 1),
'should eval if else no else':
testOK('(if #f 1)', ''),
},
'cond': {
'should eval simple cond':
testOK('(cond (#t 1))', 1),
'should eval cond no true':
testOK('(cond (#f 1))', ''),
'should eval cond no else':
testOK('\n\
(define a 1)\n\
(cond\n\
((< a 0) (set! a -1) (+ a 1))\n\
((> a 0) (- a 1) a)\n\
((= a 0) #f))', 1),
'should eval cond with only test':
testOK('\n\
(define a 1)\n\
(cond\n\
((< a 0) (set! a -1) (+ a 1))\n\
((> a 0))\n\
((= a 0) #f))', true),
'should eval cond with only test at the end':
testOK('\n\
(define a 0)\n\
(cond\n\
((< a 0) (set! a -1) (+ a 1))\n\
((> a 0) #f)\n\
((= a 0)))', true),
'should eval cond with only test at the end 2':
testOK('\n\
(define a 0)\n\
(cond\n\
((< a 0) (set! a -1) (+ a 1))\n\
((> a 0)))', ''),
'should eval cond with else':
testOK('\n\
(define a 1)\n\
(cond\n\
((< a 0) (set! a -1) (+ a 1))\n\
((= a 0) (- a 1) a)\n\
(else (set! a 10) 5))', 5),
'should raise error for cond with else in the middle':
testFail('\n\
(define a 1)\n\
(cond\n\
((< a 0) (set! a -1) (+ a 1))\n\
(else (set! a 10) 5)\n\
((= a 0) (- a 1) a))', '"else" can be used only at the last part of a "cond" expression'),
'should eval cond with =>':
testOK('\n\
(define a 1)\n\
(cond\n\
((< a 0) => number?)\n\
((> a 0) => (lambda (x) (if x 1 0)))\n\
(else (set! a 10) 5))', 1),
},
},
'let': {
'simple let':
testOK('\n\
(let ((x 1))\n\
(+ x 1))', 2),
'let':
testOK('\n\
(define foo (lambda (x)\n\
(let ((y 1))\n\
(+ x y))))\n\
(foo 5)', 6),
'named let':
testOK('\n\
(define foo (lambda (x)\n\
(let bar ((y 0))\n\
(if (= x y)\n\
y\n\
(bar (+ y 1))))))\n\
(foo 5)', 5),
'named let should not exaust stack':
testOK('\n\
(let foo ((x 0))\n\
(if (= x 2000)\n\
x\n\
(foo (+ x 1))))', 2000),
'let variables scope':
testOK('\n\
(let ((x 2) (y 3))\n\
(let ((x 7)\n\
(z (+ x y)))\n\
(* z x)))', 35),
'let internal definitions':
testOK('\n\
(let ((x 5))\n\
(define foo (lambda (y) (bar x y)))\n\
(define bar (lambda (a b) (+ (* a b) a)))\n\
(foo (+ x 3)))', 45),
'letrec lambdas':
testOK('\n\
(letrec ((even?\n\
(lambda (n)\n\
(if (= 0 n)\n\
#t\n\
(odd? (- n 1)))))\n\
(odd?\n\
(lambda (n)\n\
(if (= 0 n)\n\
#f\n\
(even? (- n 1))))))\n\
(even? 88))', true),
'should raise error for letrec':
testFail('\n\
(let ((x 2) (y 3))\n\
(letrec ((z (+ x y))(x 7))\n\
(* z x)))', 'Expected a number'),
'should eval let*':
testOK('\n\
(let ((x 2) (y 3))\n\
(let* ((x 7)\n\
(z (+ x y)))\n\
(* z x)))', 70),
'should eval let* with no bindings':
testOK('(let* () 0 (+ 1 2))', 3),
},
'definitions': {
'should raise error for incorrect usage of "define"':
testFail('define', 'Syntax keywords cannot be used as variables'),
'should raise error for accessing unbound variable':
testFail('(+ 1 a)', 'Undefined variable with name "a"'),
'should raise error for setting unbound variable':
testFail('(set! a 5)', 'Undefined variable with name "a"'),
'should set a variable to a parent environment':
testOK('\n\
(define a 1)\n\
(define foo (lambda (x) (set! a x)))\n\
(foo 4)\n\
a', 4),
'should set a variable to an already defined one':
testOK('\n\
(define a 1)\n\
(define a 2)\n\
a', 2),
'should raise error for invalid boolean token.':
testFail('(if #t1)', 'Invalid content'), // TODO return a better message
'should raise error for improper position of definitions in begin':
testFail('\n\
(define (foo)\n\
(define x 1)\n\
((lambda ()\n\
(begin\n\
(+ 1 2)\n\
(begin\n\
(define x 2)\n\
(define y 2)))\n\
y)))\n\
(foo)', 'Expected a definition but found an expression'),
'should raise error for improper position of definitions in lambda':
testFail('\n\
(define (foo)\n\
(define x 1)\n\
(+ 1 2)\n\
(define y 2)\n\
y)\n\
(foo)', 'Expected an expression but found a definition'),
'should eval duplicate global definitions':
testOK('\n\
(define x 1)\n\
(define x 2)\n\
x', 2),
'should raise error for duplicate definitions in lambda':
testFail('\n\
(define (foo)\n\
(define x 1)\n\
(define x 2)\n\
x)\n\
(foo)', 'Found multiple definitions for variable'),
'should eval definitions before assignments':
testOK('\n\
(define (foo)\n\
(define x 1)\n\
((lambda ()\n\
(define y x)\n\
(define x 2)\n\
y)))\n\
(foo)', ''),
},
'lambda and calls': {
'should eval procedure call':
testOK('(define a 1)(+ a 1)', 2),
'tail call':
testOK('\n\
(define foo (lambda (x)\n\
(if (= x 1001)\n\
x\n\
(foo (+ x 1)))\n\
))\n\
(foo 0)', 1001),
'lambda list formal':
testOK('\n\
(define foo (lambda x\n\
x))\n\
(foo 5 6)', "(5 6)"),
'lambda rest formals':
testOK('\n\
(define foo (lambda (x . y)\n\
y))\n\
(foo 4 5 6)', '(5 6)'),
'define procedure':
testOK('\n\
(define (foo x)\n\
x)\n\
(foo 5)', 5),
'define procedure list formal':
testOK('\n\
(define (foo . x)\n\
x)\n\
(foo 5 6)', '(5 6)'),
'define procedure rest formals':
testOK('\n\
(define (foo x . y)\n\
y)\n\
(foo 4 5 6)', '(5 6)'),
},
'quotations': {
'quote pair':
testOK('(quote (1 . 2))', '(1 . 2)'),
'quote abbr pair':
testOK("'(1 . 2)", '(1 . 2)'),
'quote list':
testOK('(quote (1 2))', '(1 2)'),
'quote vector':
testOK('(quote #(1 2))', '#(1 2)'),
'quote nested lists':
testOK('(quote ((1 2) (3 4) 5))', '((1 2) (3 4) 5)'),
'should quote quotations':
testOK("(car (car '('(1 2 5) '(1 3 4) '(1 2 4))))", 'quote'),
},
'call/cc': {
'simple call/cc':
testOK('(+ 1 (call/cc (lambda (x) (x 1) 2)))', 2),
'simple call/cc no call':
testOK('(+ 1 (call/cc (lambda (x) 2)))', 3),
'simple call/cc in lambda':
testOK('\n\
(define (foo a)\n\
(call/cc (lambda (return)\n\
(if (> a 0)\n\
(return a)\n\
(return (- a)) ) )) )\n\
(foo -5)', 5),
// TODO
// it.skip('simple recurring call/cc', function () {
// testOK('\n\
// (define r #f)\n\
// (+ 1 (call/cc\n\
// (lambda (k)\n\
// (set! r k)\n\
// (+ 2 (k 3)))))\n\
// (r 5)', 6),
'call/cc sample 1':
testOK('\n\
(define list-product\n\
(lambda (s)\n\
(call/cc\n\
(lambda (exit)\n\
(let recur ((s s))\n\
(if (null? s) 1\n\
(if (= (car s) 0) (exit 0)\n\
(* (car s) (recur (cdr s))))))))))\n\
(list-product (list 1 2 3 4))', 24),
},
'do': {
'should evaluate simple do':
testOK('\n\
(do ((vec (vector 0 0 0 0 0))\n\
(i 0 (+ i 1)))\n\
((= i 5) vec)\n\
(vector-set! vec i i))', '#(0 1 2 3 4)'),
'should evaluate simple do 2':
testOK('\n\
(let ((x \'(1 3 5 7 9)))\n\
(do ((x x (cdr x))\n\
(sum 0 (+ sum (car x))))\n\
((null? x) sum)))', 25),
'should not exaust stack':
testOK('\n\
(do ((i 0 (+ i 1)))\n\
((= i 2000) i))', 2000),
'should not intermingle internal symbols used for do forms': [
testOK('\n\
(do ((i 0 (+ i 1))\n\
(j 0))\n\
((= i 10) (* i j))\n\
(set! j (do ((j 0 (+ j 1)))\n\
((= j 10) j))))', 100),
testOK('\n\
(do ((i 0 (+ i 1))\n\
(j 0 (do ((j 0 (+ j 1)))\n\
((= j 10) j))))\n\
((= i 10) (* i j)))', 100)
],
},
'conjunction': {
'should eval with 0 args':
testOK('(and)', true),
'should eval with 1 args':
testOK('(and 1)', 1),
'should eval with 2 args: false, true':
testOK('(and #f 1)', false),
'should eval with 2 args: true, false':
testOK('(and 1 #f)', false),
'should eval with 2 args: true, true':
testOK('(and #t 1)', 1),
'should eval with 2 args: false, false':
testOK('(and #f #f)', false),
},
'disjunction': {
'should eval with 0 args':
testOK('(or)', false),
'should eval with 1 args':
testOK('(or 1)', 1),
'should eval with 2 args: false, true':
testOK('(or #f 1)', 1),
'should eval with 2 args: true, false':
testOK('(or 1 #f)', 1),
'should eval with 2 args: true, true':
testOK('(or #t 1)', true),
'should eval with 2 args: false, false':
testOK('(or #f #f)', false),
},
'primitives': {
'number procedures': {
'"+"': {
'should raise error for calling with non-numbers':
testFail('(+ #t #f)', 'Expected a number'),
'should return result for 0 args':
testOK('(+)', 0),
'should return result for 1 arg':
testOK('(+ 5)', 5),
'should return result for 2 args':
testOK('(+ 5 1)', 6),
'should return result for more than 2 args':
testOK('(+ 5 1 2)', 8),
},
'"-"': {
'should raise error for calling with non-numbers':
testFail('(- #t #f)', 'Expected a number'),
'should raise error for calling with wrong number of args':
testFail('(-)', 'Expected at least 1 arguments, but got 0'),
'should return result for 1 arg':
testOK('(- 5)', -5),
'should return result for 2 args':
testOK('(- 5 1)', 4),
'should return result for more than 2 args':
testOK('(- 5 1 2)', 2),
},
'"*"': {
'should raise error for calling with non-numbers':
testFail('(* #t #f)', 'Expected a number'),
'should return result for 0 args':
testOK('(*)', 1),
'should return result for 1 arg':
testOK('(* 5)', 5),
'should return result for 2 args':
testOK('(* 5 2)', 10),
'should return result for more than 2 args':
testOK('(* 5 2 2)', 20),
},
'"/"': {
'should raise error for calling with non-numbers':
testFail('(/ #t #f)', 'Expected a number'),
'should raise error for calling with wrong number of args':
testFail('(/)', 'Expected at least 1 arguments, but got 0'),
'should return result for 1 arg':
testOK('(/ 5)', 0.2),
'should return result for 2 args':
testOK('(/ 6 2)', 3),
'should return result for more than 2 args':
testOK('(/ 20 2 2)', 5),
},
'number?': {
'should raise error for calling with wrong number of args':
testFail('(number?)', 'Expected 1 arguments, but got 0'),
'should return true for a number value':
testOK('(number? 1)', true),
'should return false for a non-number value':
testOK('(number? #t)', false),
},
'nonnegative-integer?': {
'should raise error for calling with wrong number of args':
testFail('(nonnegative-integer?)', 'Expected 1 arguments, but got 0'),
'should return true for a non-negative integer':
testOK('(nonnegative-integer? 1)', true),
'should return false for a non-number value':
testOK('(nonnegative-integer? #t)', false),
'should return false for a non-integer value':
testOK('(nonnegative-integer? 1.5)', false),
'should return false for a negative value':
testOK('(nonnegative-integer? -1)', false),
},
},
'boolean procedures': {
'boolean?': {
'should raise error for calling with wrong number of args':
testFail('(boolean?)', 'Expected 1 arguments, but got 0'),
'should return true for a boolean value':
testOK('(boolean? #t)', true),
'should return false for a non-boolean value':
testOK('(boolean? 1)', false),
},
'not': {
'should raise error for calling with wrong number of args':
testFail('(not)', 'Expected 1 arguments, but got 0'),
'should return true for a false value':
testOK('(not #f)', true),
'should return false for a truthy value':
testOK('(not 1)', false),
},
'boolean=?': {
'should raise error for calling with wrong number of args':
testFail('(boolean=?)', 'Expected at least 2 arguments, but got 0'),
'should raise error for calling with wrong type of args':
testFail('(boolean=? #t #f 1)', 'Expected argument on position 2 to satisfy predicate boolean?'),
'should return true if all arguments are true':
testOK('(boolean=? #t #t #t)', true),
'should return true if all arguments are false':
testOK('(boolean=? #f #f)', true),
'should return false some arguments are different':
testOK('(boolean=? #t #f #f)', false),
},
},
},
'procedure application': {
'should raise error for calling a procedure with wrong number of args':
testFail('(define foo (lambda (x) x))(foo 5 6)', 'Expected 1 arguments, but got 2'),
},
'scheme to js ffi': {
'should execute simple script':
testOK('(js-eval "1")', 1),
'should return vector':
testOK('(js-eval "[1, 2]")', '#(1 2)'),
'should return alist':
testOK(
'(js-eval "({ a: 1, b: 2, c: { d: 3, e: 4 } })")',
'(("a" . 1) ("b" . 2) ("c" ("d" . 3) ("e" . 4)))'),
},
'lambda names': {
'should name lambda definition':
testOK('(define (foo) 1)foo', '#<procedure foo>'),
'should name lambda definition by value 1':
testOK('(define foo (lambda () 1))foo', '#<procedure foo>'),
'should name lambda definition by value 2':
testOK('(define foo ((lambda()(lambda()1))))foo', '#<procedure foo>'),
},
// it.only('ops', function () {
// testOK('\n\
// (define foo (lambda (x)\n\
// (if (= x 100)\n\
// x\n\
// (foo (+ x 1)))\n\
// ))\n\
// (foo 0)';
// var program = parser.parse(text),
// console.log(program),
// }),
}
};
|
import 'docs/src/modules/components/bootstrap';
// --- Post bootstrap -----
import React from 'react';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
import markdown from './march-2019-update.md';
function Page() {
return <MarkdownDocs markdown={markdown} blog disableAd disableToc disableEdit />;
}
export default Page;
|
/*global define, Backbone, _ */
define([], function () {
'use strict';
// setting underscore delimiters
_.templateSettings = {
interpolate: /\{\{(.+?)\}\}/g
};
var RabbitTask = {
Views: {},
Models: {},
Collections: {},
Helpers: {}
};
/* Template helper */
RabbitTask.Helpers.template = function (selector) {
return _.template($(selector).html());
};
/* Error helper */
RabbitTask.Helpers.modalError = function (model) {
this.$el = $('#alertModal');
this.$el.find('.message-placeholder').html('<p>'+ model.validationError +'</p>');
this.$el.modal('show');
};
/* Task unit model */
RabbitTask.Models.Task = Backbone.Model.extend({
initialize: function() {
this.setPriorityName();
this.on('change', this.setPriorityName);
},
validate:function (attrs) {
if (_.isEmpty(attrs.title)) {
return 'The task name cant be null';
}
if (_.isEmpty(attrs.priority) || _.isNaN(attrs.priority)) {
return 'Select a priority value';
}
},
setPriorityName: function () {
var priority = parseInt(this.get('priority'));
switch(priority) {
case 1 :
this.set('priority_name', 'info');
break;
case 2 :
this.set('priority_name', 'warning');
break;
case 3 :
this.set('priority_name', 'danger');
break;
default :
this.set('priority_name', 'info');
break;
}
return this;
}
});
/* Task collection */
RabbitTask.Collections.Tasks = Backbone.Collection.extend({
model: RabbitTask.Models.Task,
comparator: function (task) {
return -task.get('priority');
}
});
/* View for one task */
RabbitTask.Views.Task = Backbone.View.extend({
tagName: 'tr',
template: RabbitTask.Helpers.template('[data-template="task"]'),
events: {
'click a[href="#editModal"]' : 'setEdition'
},
setEdition: function () {
this.setPriority(this.model.get('priority'));
this.$title.val(this.model.get('title'));
this.$cid.val(this.model.cid);
},
setPriority: function(priority) {
this.$editForm.find('input[name="priority"][value="'+ priority +'"]').trigger('click');
},
initialize:function () {
this.render();
this.cacheElements();
},
render:function () {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
cacheElements: function () {
this.$editForm = $('#editModal');
this.$title = this.$editForm.find('input[name="title"]');
this.$cid = this.$editForm.find('input[name="cid"]');
}
});
/* Task view collection */
RabbitTask.Views.Tasks = Backbone.View.extend({
el: '#taskList',
initialize:function() {
this.render();
this.collection.on('add', this.render, this);
this.collection.on('change', this.render, this);
},
render:function () {
this.collection.sort();
this.$el.html('');
this.collection.each(function (model) {
this.addOne(model);
}, this);
},
addOne:function (model) {
var taskView = new RabbitTask.Views.Task({
model: model
});
this.$el.append(taskView.el);
}
});
/* Add task view */
RabbitTask.Views.addTask = Backbone.View.extend({
el: '#addTask',
initialize: function () {
},
getPriority: function () {
// this.$priority = this.$el.find('input[name="priority"]:checked');
},
events: {
'submit': 'onSubmit'
},
onSubmit: function(e) {
e.preventDefault();
console.log(this.$el.serializeArray());
var newTask = new RabbitTask.Models.Task();
if (!newTask.isValid()) {
RabbitTask.Helpers.modalError(newTask);
return;
}
this.collection.add(newTask);
}
});
/* Edit form view */
RabbitTask.Views.EditTask = Backbone.View.extend({
el: '.form-horizontal',
initialize: function () {
this.$modalBox = $('#editModal');
},
events: {
'submit' : 'onSubmit'
},
onSubmit: function (e) {
e.preventDefault();
this.setValues(this.$el.serializeArray());
this.setModel(this.cid.value);
this.set();
this.$modalBox.modal('hide');
},
setValues: function(arr) {
_.each(arr, function(obj) {
this.getValue(arr, obj.name);
}, this);
},
getValue: function(arr, name) {
this[name] = _.where(arr, {
name: name
})[0];
},
setModel: function (cid) {
this.model = this.collection.get(cid);
},
set: function() {
this.model.set({
title: this.title.value,
priority: this.priority.value
});
}
});
return RabbitTask;
});
|
import styled from 'styled-components'
import { transparentize, darken } from 'polished'
import * as colors from './colors'
const StyledButton = styled.button`
/*-webkit-border-radius: 4px;
-moz-border-radius: 4px;*/
border-radius: 4px;
font-family: ${(props) => props.theme.font || 'Source Sans Pro'};
font-size: ${(props) => props.theme.buttonSize.default.size || '18px'};
font-weight: ${(props) => props.theme.fontWeight || 300};
font-style: ${(props) => props.theme.fontStyle || 'normal'};
color: ${(props) => props.theme.button.color || colors.BUTTON_TEXT};
background: ${(props) => props.theme.button.background || colors.BUTTON_DEFAULT};
padding: ${(props) => props.theme.buttonSize.default.padding || '9px 20px 9px 15px'};
margin-right: 0.7rem;
border: none;
text-decoration: none;
&:focus {
border-color: ${colors.BUTTON_DEFAULT_FOCUS};
box-shadow: 0 0 0 3px ${transparentize(0.7, colors.BUTTON_DEFAULT)};
outline: none;
}
/*&.is-active,
&.active,*/
&&:active {
background: ${darken(0.1, colors.BUTTON_DEFAULT)};
border-color: ${darken(0.1, colors.BUTTON_DEFAULT)};
box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
transform: translateY(2px);
}
&:hover {
background: ${colors.BUTTON_DEFAULT_HOVER};
}
`
export default StyledButton
|
const Paginator = require('../../../lib/domain/paginator');
const expect = require('chai').expect;
describe('Paginator', () => {
describe('when there are no items to paginate', () => {
const paginator = new Paginator();
paginator.isValid();
it('should show an error', () => {
expect(paginator.error).to.be.eql('There are no items to paginate');
});
});
describe('when page is lower than 1', () => {
const paginator = new Paginator(0, 10, 100);
paginator.isValid();
it('should show an error', () => {
expect(paginator.error).to.be.eql('Page and / or Per Page cannot be lower than 1');
});
});
describe('when perPage is lower than 1', () => {
const paginator = new Paginator(1, 0, 100);
paginator.isValid();
it('should show an error', () => {
expect(paginator.error).to.be.eql('Page and / or Per Page cannot be lower than 1');
});
});
describe('when page is higher than totalPages', () => {
const paginator = new Paginator(12, 10, 100);
paginator.isValid();
it('should show an error', () => {
expect(paginator.error).to.be.eql(`Page cannot be higher than ${paginator.totalPages}`);
});
});
describe('when there are 100 items with 10 items per page to paginate', () => {
const paginator = new Paginator(1, 10, 100);
it('should have 10 pages', () => {
expect(paginator.totalPages).to.be.eql(10);
});
});
});
|
//--------------------------------------------------------------------------------------------------------
// Mercer Evolution - Core v3.0 - Accordion JS
// DATE - June 3, 2015
// AUTHOR - Doug Fraize, Matthew Holmes
//--------------------------------------------------------------------------------------------------------
$(document).foundation({
// FOUNDATION ACCORDION OPTIONS
/*
accordion: {
content_class: 'content', // specify the class used for accordion panels
active_class: 'active', // specify the class used for active (or open) accordion panels
multi_expand: false, // allow multiple accordion panels to be active at the same time
toggleable: true // allow accordion panels to be closed by clicking on their headers, setting to false only closes accordion panels when another is opened
}
*/
});
|
import test from 'ava';
var fs = require('fs')
var exec = require('co-exec');
test('init()', function * (t) {
var commit = yield exec('node index.js -i');
t.true(fs.existsSync('.travis.yml'));
});
test('badge()', function * (t) {
var commit = yield exec('node index.js -b');
var cfg = require('get-git-info')(__dirname);
t.regex(commit, new RegExp("/" + cfg.user + "/"));
t.regex(commit, new RegExp("" + cfg.project + ""));
});
|
/**
* Created by mattjohansen on 11/19/13.
*/
var shorturl = require('../scripts/short-url-expander.coffee');
var HttpClient = require('scoped-http-client');
describe('short url expander', function() {
var robot, msg = null;
beforeEach(function(){
robot = {
respond: function(regex, callback){},
http: function(url){}
}
spyOn(robot, 'respond').andCallThrough();
spyOn(robot, 'http').andCallFake(function(){
var url = robot.http.mostRecentCall.args[0];
var client = HttpClient.create(url);
spyOn(client, 'get').andReturn(function(){});
return client
});
shorturl(robot);
msg = {
match: 'expand url www.google.com'.match(robot.respond.mostRecentCall.args[0]),
send: function() {}
}
});
it('should be a function', function(){
expect(typeof(shorturl)).toBe('function');
});
it('should generate the correct URL', function() {
expect(robot.respond).toHaveBeenCalled();
robot.respond.mostRecentCall.args[1](msg);
expect(robot.http).toHaveBeenCalled();
expect(robot.http.mostRecentCall.args[0]).toBeDefined();
expect(robot.http.mostRecentCall.args[0]).toBe('http://api.longurl.org/v2/expand?format=json&all-redirects=1&title=1&url=www.google.com')
});
//TODO - More verbose tests to make sure this doesn't get called when Regex fails
//TODO - Get access to the callback to actually test the body and parsing
});
|
#!/usr/bin/env node
// Parse process.argv
var argv = require("yargs")
.alias("f", "file")
.alias("u", "user")
.alias("p", "password")
.alias("h", "hash")
.alias("e", "expire")
.alias("i", "id")
.alias("v", "verbose")
.argv;
// Import utils
var fs = require("fs"),
Path = require("path"),
detectLang = require("language-detect"),
async = require("async");
// ...and the fpaste module.
var fpaste = require("../");
process.title = "fpaste";
// Create handler object
// Export for sake of it, may be useful
var CLI = module.exports = {
// Get post from fpaste.org
get: function(cb){
var opts = {id: argv.id};
// Include auth if passed
if(argv.hash) opts.hash = argv.hash;
if(argv.password) opts.password = argv.password;
// Get data from fpaste
fpaste.get(opts, function(err, res){
cb(err, res, !argv.verbose && res.result ? res.result.data : res);
});
},
// Post file to fpaste.org
post: function(cb){
// Relevant post values
var values = ["user", "password", "private", "project", "expire"];
// Options object
var opts = {};
// Add any relevant values to opts
for(var key in argv)
if(argv[key] && values.indexOf(key) > -1)
opts[key] = argv[key];
// Mark as private if password provided
if(opts.password) opts.private = true;
// Create relative file path
var fpath = Path.resolve(process.cwd(), (argv.file || argv._[0]));
// Get language and contents of file
async.parallel({
language: function(cb){
detectLang(fpath, cb);
},
contents: function(cb){
fs.readFile(fpath, cb);
}
}, function(err, results){
if(err) throw err;
// File language from language-detect
opts.lang = results.language;
// Data buffer from fs.readFile
opts.data = results.contents;
fpaste.post(opts, function(err, data){
// Pass response if verbose passed, or just the URL if not.
cb(err, data, argv.verbose ? data : data.result.url);
});
});
}
}
// Call the relevant CLI option.
// Assume a GET operation if ID is present.
CLI[argv.id ? "get" : "post"](function(err, res, msg){
if(err) throw err;
console.log(msg);
});
|
/***/
var Server = require('./server');
var Socket = require('./socket');
module.exports = Socket;
// var WebSocket = require('websockets');
Socket.Server = Server;
Socket.WebSocket = Socket;
Socket.createServer = function(opts) {
return new Server(opts);
};
Socket.connect = function(opts) {
return new Socket(opts);
};
|
$( document ).ready(function() {
// Add scrolling to Nav-Bar links
$('.navbar [href^=#]').click(function (e) {
e.preventDefault();
var div = $(this).attr('href');
$("html, body").animate({
scrollTop: $(div).position().top
}, "slow");
});
// Init Masonry
$masonryContainer = $('.reviews');
$masonryContainer.imagesLoaded( function() {
$masonryContainer.masonry({
itemSelector: '.hreview',
columnWidth: '.grid-sizer',
percentPosition: true,
originTop: true
});
});
});
|
const Module = require('quantum/core/Module');
const devices = new Set();
module.exports = class DeviceManager extends Module {
install (device) {
device.connect(this[ Module.host ]);
devices.add(device);
}
find (name) {
return Array.from(devices).find(device => device.kind === name);
}
}
|
const puppeteer = require('puppeteer');
const CREDS = require('./creds');
const MAJORS = require('./majors');
/* Get Started:
* 1. Run `npm i --save puppeteer`
* 2. Make creds.js with module.exports = {
username: '<USERNAME>',
password: '<PASSWORD>'
}
* 3. node emailScraper.js
*/
async function run() {
const browser = await puppeteer.launch({
headless: false
});
const page = await browser.newPage();
await page.goto('https://tigernet.princeton.edu');
// dom element selectors (Chrome -> inspect -> copy selector)
const STUDENT_BUTTON_SELECTOR = '#cid_40_rptSsoProviders_ctl02_btnProvider';
const USERNAME_SELECTOR = '#username';
const PASSWORD_SELECTOR = '#password';
const LOGIN_BUTTON_SELECTOR = '#fm1 > div.login > p > input.btn-submit';
const ALUMNI_DIRECTORY_BUTTON_SELECTOR = '#imodcmscalendar1016 > div.cms-listing > div > div > div:nth-child(2) > div.thumb > a';
const YEAR_SELECTOR = '#mf_882 > option:nth-child(%d)';
const SUBMIT_BUTTON_SELECTOR = '#imod-view-content > section > div.imod-search-form.imod-field-label-align-left > div.imod-button-section > button';
const VIEW_DETAILS_SELECTOR = '#imod-view-content > div:nth-child(%s) > div > div > div.imod-directory-member-data-container > div.imod-directory-member-more > a';
const NEXT_BUTTON_SELECTOR = '#imod-view-content > div.imod-directory-search-results-pager.ng-isolate-scope > div > div.imod-pager-desktop > div.imod-pager-arrow.imod-pager-next.ng-scope > a';
const FIRST_NAME_SELECTOR = '#imod-view-content > div > div > div:nth-child(1) > div.imod-profile-step-content > div.imod-profile-category.ng-isolate-scope > div.imod-profile-fields > ul > li:nth-child(1) > div.imod-profile-field-data.ng-binding.ng-scope';
const LAST_NAME_SELECTOR = '#imod-view-content > div > div > div:nth-child(1) > div.imod-profile-step-content > div.imod-profile-category.ng-isolate-scope > div.imod-profile-fields > ul > li:nth-child(2) > div.imod-profile-field-data.ng-binding.ng-scope';
const EMAIL_SELECTOR = '#imod-view-content > div > div > div:nth-child(2) > div.imod-profile-step-content > div.imod-profile-category.ng-isolate-scope > div.imod-profile-fields > ul > li:nth-child(1) > div.imod-profile-field-data.ng-binding.ng-scope';
await page.click(STUDENT_BUTTON_SELECTOR);
await page.waitFor(1000);
await page.waitForSelector(USERNAME_SELECTOR);
await page.waitForSelector(PASSWORD_SELECTOR);
await page.waitForSelector(LOGIN_BUTTON_SELECTOR);
await page.type(USERNAME_SELECTOR, CREDS.username);
await page.type(PASSWORD_SELECTOR, CREDS.password);
await page.click(LOGIN_BUTTON_SELECTOR);
await page.waitFor(1000);
await page.waitForSelector(ALUMNI_DIRECTORY_BUTTON_SELECTOR);
await page.evaluate((selector) => {
document.querySelector(selector).click();
}, ALUMNI_DIRECTORY_BUTTON_SELECTOR);
//await page.$(ALUMNI_DIRECTORY_BUTTON_SELECTOR)
// await page.click(ALUMNI_DIRECTORY_BUTTON_SELECTOR);
await page.waitFor(1000);
// Choose the years
var years = [];
for (let i = 1; i <= 40; i++) {
let selector = YEAR_SELECTOR.replace("%d", i.toString());
await page.waitForSelector(selector);
const value = await page.evaluate((selector) => {
return document.querySelector(selector).value
}, selector);
years.push(value);
}
page.select('#mf_882', ...years) // spread operator
// Choose the majors
// Command click to select multiple options
var majors = []
for (let i = 0; i < MAJORS.selectors.length; i++) {
await page.waitForSelector(MAJORS.selectors[i]);
const value = await page.evaluate((selector) => {
return document.querySelector(selector).value
}, MAJORS.selectors[i]);
majors.push(value);
}
page.select('#mf_409', ...majors)
await page.waitForSelector(SUBMIT_BUTTON_SELECTOR);
await page.evaluate((selector) => {
document.querySelector(selector).click();
}, SUBMIT_BUTTON_SELECTOR);
await page.waitFor(1500);
let numPages = 35;
let toSkip = 6;
for (let i = 1; i <= numPages; i++) {
if (i > toSkip) {
for (let index = 9; index <= 28; index++) {
// First name on page is nth-child(9), last is 28
let currSelector = VIEW_DETAILS_SELECTOR.replace("%s", index.toString());
await page.waitForSelector(currSelector);
await page.evaluate((selector) => {
document.querySelector(selector).click();
}, currSelector);
await page.waitFor(1000);
await page.waitForSelector(FIRST_NAME_SELECTOR);
await page.waitForSelector(LAST_NAME_SELECTOR);
await page.waitForSelector(EMAIL_SELECTOR);
const result = await page.evaluate((FIRST_NAME_SELECTOR, LAST_NAME_SELECTOR, EMAIL_SELECTOR) => {
let firstName = document.querySelector(FIRST_NAME_SELECTOR).innerText;
let lastName = document.querySelector(LAST_NAME_SELECTOR).innerText;
let emailAddress = document.querySelector(EMAIL_SELECTOR).innerText;
return {firstName, lastName, emailAddress}
}, FIRST_NAME_SELECTOR, LAST_NAME_SELECTOR, EMAIL_SELECTOR);
if (i === 0 && index === 9) {
console.log('FirstName, LastName, Email');
}
console.log(result.firstName + ', ' + result.lastName + ', ' + result.emailAddress);
// Go back
await page.goBack();
await page.waitFor(1000);
}
}
await page.waitForSelector(NEXT_BUTTON_SELECTOR);
await page.evaluate((selector) => {
document.querySelector(selector).click();
}, NEXT_BUTTON_SELECTOR);
await page.waitFor(1000);
}
await browser.close();
}
run();
|
'use strict'
const assert = require('chai').assert
const uuid = require('uuid').v4
const index = require('./../src/index')
// Files must be in cwd so babel can load the plugins and presents
const fsify = require('fsify')({
persistent: false
})
describe('index()', function() {
it('should return an error when called without a filePath', async function() {
return index().then(() => {
throw new Error('Returned without error')
}, (err) => {
assert.strictEqual(err.message, `'filePath' must be a string`)
})
})
it('should return an error when called with invalid options', async function() {
const structure = await fsify([
{
type: fsify.FILE,
name: `${ uuid() }.js`
}
])
return index(structure[0].name, '').then(() => {
throw new Error('Returned without error')
}, (err) => {
assert.strictEqual(err.message, `'opts' must be undefined or an object`)
})
})
it('should return an error when called with a fictive filePath', async function() {
return index(`${ uuid() }.js`).then(() => {
throw new Error('Returned without error')
}, (err) => {
assert.isNotNull(err)
assert.isDefined(err)
})
})
it('should return an error when JS passes an error to the callback', async function() {
const input = uuid()
const structure = await fsify([
{
type: fsify.FILE,
name: `${ uuid() }.js`,
contents: `module.exports = (next) => next(new Error('${ input }'))`
}
])
return index(structure[0].name).then(() => {
throw new Error('Returned without error')
}, (err) => {
assert.strictEqual(err.message, input)
})
})
it('should return an error when JS contains errors but everything is specified', async function() {
const structure = await fsify([
{
type: fsify.FILE,
name: `${ uuid() }.js`,
contents: `module.exports = (next) =>`
}
])
return index(structure[0].name).then(() => {
throw new Error('Returned without error')
}, (err) => {
assert.isNotNull(err)
assert.isDefined(err)
})
})
it('should load callback JS and transform it to HTML when everything specified', async function() {
const input = uuid()
const structure = await fsify([
{
type: fsify.FILE,
name: `${ uuid() }.js`,
contents: `module.exports = (next) => next(null, '${ input }')`
}
])
const result = await index(structure[0].name)
assert.strictEqual(result, input)
})
it('should load async JS and transform it to HTML when everything specified', async function() {
const input = uuid()
const structure = await fsify([
{
type: fsify.FILE,
name: `${ uuid() }.js`,
contents: `module.exports = async () => '${ input }'`
}
])
const result = await index(structure[0].name)
assert.strictEqual(result, input)
})
it('should load JS with JSX and transform it to HTML when everything specified', async function() {
const input = `<p>${ uuid() }</p>`
const contents = `
const React = require('react')
const renderToStaticMarkup = require('react-dom/server').renderToStaticMarkup
const html = renderToStaticMarkup(${ input })
module.exports = (next) => next(null, html)
`
const structure = await fsify([
{
type: fsify.FILE,
name: `${ uuid() }.js`,
contents
}
])
const result = await index(structure[0].name)
assert.strictEqual(result, input)
})
it('should load JS with ES2015 syntax and transform it to HTML when everything specified', async function() {
const input = `<p>${ uuid() }</p>`
const contents = `
import React from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
const html = renderToStaticMarkup(${ input })
export default (next) => next(null, html)
`
const structure = await fsify([
{
type: fsify.FILE,
name: `${ uuid() }.js`,
contents
}
])
const result = await index(structure[0].name)
assert.strictEqual(result, input)
})
describe('.in()', function() {
it('should be a function', function() {
assert.isFunction(index.in)
})
it('should return a default extension', function() {
assert.strictEqual(index.in(), '.js')
})
it('should return a default extension when called with invalid options', function() {
assert.strictEqual(index.in(''), '.js')
})
it('should return a custom extension when called with options', function() {
assert.strictEqual(index.in({ in: '.jsx' }), '.jsx')
})
})
describe('.out()', function() {
it('should be a function', function() {
assert.isFunction(index.in)
})
it('should return a default extension', function() {
assert.strictEqual(index.out(), '.html')
})
it('should return a default extension when called with invalid options', function() {
assert.strictEqual(index.out(''), '.html')
})
it('should return a custom extension when called with options', function() {
assert.strictEqual(index.out({ out: '.xml' }), '.xml')
})
})
describe('.cache', function() {
it('should be an array', function() {
assert.isArray(index.cache)
})
})
})
|
var w2ui = w2ui || {};
var w2obj = w2obj || {}; // expose object to be able to overwrite default functions
/************************************************
* Library: Web 2.0 UI for jQuery
* - Following objects are defines
* - w2ui - object that will contain all widgets
* - w2obj - object with widget prototypes
* - w2utils - basic utilities
* - $().w2render - common render
* - $().w2destroy - common destroy
* - $().w2marker - marker plugin
* - $().w2tag - tag plugin
* - $().w2overlay - overlay plugin
* - $().w2menu - menu plugin
* - w2utils.event - generic event object
* - Dependencies: jQuery
*
* == NICE TO HAVE ==
* - overlay should be displayed where more space (on top or on bottom)
* - write and article how to replace certain framework functions
* - add maxHeight for the w2menu
* - add time zone
* - TEST On IOS
* - $().w2marker() -- only unmarks first instance
* - subitems for w2menus()
* - add w2utils.lang wrap for all captions in all buttons.
* - $().w2date(), $().w2dateTime()
* == 1.5
* - added message
* - w2utils.keyboard is removed
* - w2tag can be positioned with an array of valid values
* - decodeTags
* - added w2utils.testLocalStorage(), w2utils.hasLocalStorage
*
************************************************/
var w2utils = (function ($) {
var tmp = {}; // for some temp variables
var obj = {
version : '1.5.x',
settings : {
"locale" : "en-us",
"dateFormat" : "m/d/yyyy",
"timeFormat" : "hh:mi pm",
"datetimeFormat" : "m/d/yyyy|hh:mi pm",
"currencyPrefix" : "$",
"currencySuffix" : "",
"currencyPrecision" : 2,
"groupSymbol" : ",",
"decimalSymbol" : ".",
"shortmonths" : ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
"fullmonths" : ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
"shortdays" : ["M", "T", "W", "T", "F", "S", "S"],
"fulldays" : ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
"weekStarts" : "M", // can be "M" for Monday or "S" for Sunday
"dataType" : 'HTTPJSON', // can be HTTP, HTTPJSON, RESTFULL, RESTFULLJSON, JSON (case sensitive)
"phrases" : {}, // empty object for english phrases
"dateStartYear" : 1950, // start year for date-picker
"dateEndYear" : 2020 // end year for date picker
},
isBin : isBin,
isInt : isInt,
isFloat : isFloat,
isMoney : isMoney,
isHex : isHex,
isAlphaNumeric : isAlphaNumeric,
isEmail : isEmail,
isDate : isDate,
isTime : isTime,
isDateTime : isDateTime,
age : age,
interval : interval,
date : date,
formatSize : formatSize,
formatNumber : formatNumber,
formatDate : formatDate,
formatTime : formatTime,
formatDateTime : formatDateTime,
stripTags : stripTags,
encodeTags : encodeTags,
decodeTags : decodeTags,
escapeId : escapeId,
base64encode : base64encode,
base64decode : base64decode,
md5 : md5,
transition : transition,
lock : lock,
unlock : unlock,
message : message,
lang : lang,
locale : locale,
getSize : getSize,
getStrWidth : getStrWidth,
scrollBarSize : scrollBarSize,
checkName : checkName,
checkUniqueId : checkUniqueId,
parseRoute : parseRoute,
cssPrefix : cssPrefix,
getCursorPosition : getCursorPosition,
setCursorPosition : setCursorPosition,
testLocalStorage : testLocalStorage,
hasLocalStorage : testLocalStorage(),
// some internal variables
isIOS : ((navigator.userAgent.toLowerCase().indexOf('iphone') != -1 ||
navigator.userAgent.toLowerCase().indexOf('ipod') != -1 ||
navigator.userAgent.toLowerCase().indexOf('ipad') != -1)
? true : false),
isIE : ((navigator.userAgent.toLowerCase().indexOf('msie') != -1 ||
navigator.userAgent.toLowerCase().indexOf('trident') != -1 )
? true : false)
};
return obj;
function isBin (val) {
var re = /^[0-1]+$/;
return re.test(val);
}
function isInt (val) {
var re = /^[-+]?[0-9]+$/;
return re.test(val);
}
function isFloat (val) {
if (typeof val == 'string') val = val.replace(/\s+/g, '').replace(w2utils.settings.groupSymbol, '').replace(w2utils.settings.decimalSymbol, '.');
return (typeof val === 'number' || (typeof val === 'string' && val !== '')) && !isNaN(Number(val));
}
function isMoney (val) {
var se = w2utils.settings;
var re = new RegExp('^'+ (se.currencyPrefix ? '\\' + se.currencyPrefix + '?' : '') +
'[-+]?'+ (se.currencyPrefix ? '\\' + se.currencyPrefix + '?' : '') +
'[0-9]*[\\'+ se.decimalSymbol +']?[0-9]+'+ (se.currencySuffix ? '\\' + se.currencySuffix + '?' : '') +'$', 'i');
if (typeof val === 'string') {
val = val.replace(new RegExp(se.groupSymbol, 'g'), '');
}
if (typeof val === 'object' || val === '') return false;
return re.test(val);
}
function isHex (val) {
var re = /^[a-fA-F0-9]+$/;
return re.test(val);
}
function isAlphaNumeric (val) {
var re = /^[a-zA-Z0-9_-]+$/;
return re.test(val);
}
function isEmail (val) {
var email = /^[a-zA-Z0-9._%-+]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return email.test(val);
}
function isDate (val, format, retDate) {
if (!val) return false;
var dt = 'Invalid Date';
var month, day, year;
if (format == null) format = w2utils.settings.dateFormat;
if (typeof val.getUTCFullYear === 'function') { // date object
year = val.getUTCFullYear();
month = val.getUTCMonth() + 1;
day = val.getUTCDate();
} else if (parseInt(val) == val && parseInt(val) > 0) {
val = new Date(parseInt(val));
year = val.getUTCFullYear();
month = val.getUTCMonth() + 1;
day = val.getUTCDate();
} else {
val = String(val);
// convert month formats
if (new RegExp('mon', 'ig').test(format)) {
format = format.replace(/month/ig, 'm').replace(/mon/ig, 'm').replace(/dd/ig, 'd').replace(/[, ]/ig, '/').replace(/\/\//g, '/').toLowerCase();
val = val.replace(/[, ]/ig, '/').replace(/\/\//g, '/').toLowerCase();
for (var m = 0, len = w2utils.settings.fullmonths.length; m < len; m++) {
var t = w2utils.settings.fullmonths[m];
val = val.replace(new RegExp(t, 'ig'), (parseInt(m) + 1)).replace(new RegExp(t.substr(0, 3), 'ig'), (parseInt(m) + 1));
}
}
// format date
var tmp = val.replace(/-/g, '/').replace(/\./g, '/').toLowerCase().split('/');
var tmp2 = format.replace(/-/g, '/').replace(/\./g, '/').toLowerCase();
if (tmp2 === 'mm/dd/yyyy') { month = tmp[0]; day = tmp[1]; year = tmp[2]; }
if (tmp2 === 'm/d/yyyy') { month = tmp[0]; day = tmp[1]; year = tmp[2]; }
if (tmp2 === 'dd/mm/yyyy') { month = tmp[1]; day = tmp[0]; year = tmp[2]; }
if (tmp2 === 'd/m/yyyy') { month = tmp[1]; day = tmp[0]; year = tmp[2]; }
if (tmp2 === 'yyyy/dd/mm') { month = tmp[2]; day = tmp[1]; year = tmp[0]; }
if (tmp2 === 'yyyy/d/m') { month = tmp[2]; day = tmp[1]; year = tmp[0]; }
if (tmp2 === 'yyyy/mm/dd') { month = tmp[1]; day = tmp[2]; year = tmp[0]; }
if (tmp2 === 'yyyy/m/d') { month = tmp[1]; day = tmp[2]; year = tmp[0]; }
if (tmp2 === 'mm/dd/yy') { month = tmp[0]; day = tmp[1]; year = tmp[2]; }
if (tmp2 === 'm/d/yy') { month = tmp[0]; day = tmp[1]; year = parseInt(tmp[2]) + 1900; }
if (tmp2 === 'dd/mm/yy') { month = tmp[1]; day = tmp[0]; year = parseInt(tmp[2]) + 1900; }
if (tmp2 === 'd/m/yy') { month = tmp[1]; day = tmp[0]; year = parseInt(tmp[2]) + 1900; }
if (tmp2 === 'yy/dd/mm') { month = tmp[2]; day = tmp[1]; year = parseInt(tmp[0]) + 1900; }
if (tmp2 === 'yy/d/m') { month = tmp[2]; day = tmp[1]; year = parseInt(tmp[0]) + 1900; }
if (tmp2 === 'yy/mm/dd') { month = tmp[1]; day = tmp[2]; year = parseInt(tmp[0]) + 1900; }
if (tmp2 === 'yy/m/d') { month = tmp[1]; day = tmp[2]; year = parseInt(tmp[0]) + 1900; }
}
if (!isInt(year)) return false;
if (!isInt(month)) return false;
if (!isInt(day)) return false;
year = +year;
month = +month;
day = +day;
dt = new Date(year, month - 1, day);
// do checks
if (month == null) return false;
if (String(dt) == 'Invalid Date') return false;
if ((dt.getMonth() + 1 !== month) || (dt.getDate() !== day) || (dt.getFullYear() !== year)) return false;
if (retDate === true) return dt; else return true;
}
function isTime (val, retTime) {
// Both formats 10:20pm and 22:20
if (val == null) return false;
var max, am, pm;
// -- process american format
val = String(val);
val = val.toUpperCase();
am = val.indexOf('AM') >= 0;
pm = val.indexOf('PM') >= 0;
var ampm = (pm || am);
if (ampm) max = 12; else max = 24;
val = val.replace('AM', '').replace('PM', '');
val = $.trim(val);
// ---
var tmp = val.split(':');
var h = parseInt(tmp[0] || 0), m = parseInt(tmp[1] || 0), s = parseInt(tmp[2] || 0);
// accept edge case: 3PM is a good timestamp, but 3 (without AM or PM) is NOT:
if ((!ampm || tmp.length !== 1) && tmp.length !== 2 && tmp.length !== 3) { return false; }
if (tmp[0] === '' || h < 0 || h > max || !this.isInt(tmp[0]) || tmp[0].length > 2) { return false; }
if (tmp.length > 1 && (tmp[1] === '' || m < 0 || m > 59 || !this.isInt(tmp[1]) || tmp[1].length !== 2)) { return false; }
if (tmp.length > 2 && (tmp[2] === '' || s < 0 || s > 59 || !this.isInt(tmp[2]) || tmp[2].length !== 2)) { return false; }
// check the edge cases: 12:01AM is ok, as is 12:01PM, but 24:01 is NOT ok while 24:00 is (midnight; equivalent to 00:00).
// meanwhile, there is 00:00 which is ok, but 0AM nor 0PM are okay, while 0:01AM and 0:00AM are.
if (!ampm && max === h && (m !== 0 || s !== 0)) { return false; }
if (ampm && tmp.length === 1 && h === 0) { return false; }
if (retTime === true) {
if (pm && h !== 12) h += 12; // 12:00pm - is noon
if (am && h === 12) h += 12; // 12:00am - is midnight
return {
hours: h,
minutes: m,
seconds: s
};
}
return true;
}
function isDateTime (val, format, retDate) {
if (format == null) format = w2utils.settings.datetimeFormat;
var formats = format.split('|');
if (typeof val.getUTCFullYear === 'function') { // date object
if (retDate !== true) return true;
return val;
} else if (parseInt(val) == val && parseInt(val) > 0) {
val = new Date(parseInt(val));
if (retDate !== true) return true;
return val;
} else {
var tmp = String(val).indexOf(' ');
var values = [val.substr(0, tmp), val.substr(tmp).trim()];
formats[0] = formats[0].trim();
if (formats[1]) formats[1] = formats[1].trim();
// check
var tmp1 = w2utils.isDate(values[0], formats[0], true);
var tmp2 = w2utils.isTime(values[1], true);
if (tmp1 !== false && tmp2 !== false) {
if (retDate !== true) return true;
tmp1.setHours(tmp2.hours);
tmp1.setMinutes(tmp2.minutes);
tmp1.setSeconds(tmp2.seconds);
return tmp1;
} else {
return false;
}
}
}
function age(dateStr) {
var dt1;
if (dateStr === '' || dateStr == null) return '';
if (typeof dateStr.getUTCFullYear === 'function') { // date object
dt1 = dateStr;
} else if (parseInt(dateStr) == dateStr && parseInt(dateStr) > 0) {
d1 = new Date(parseInt(dateStr));
} else {
d1 = new Date(dateStr);
}
if (String(d1) == 'Invalid Date') return '';
var d2 = new Date();
var sec = (d2.getTime() - d1.getTime()) / 1000;
var amount = '';
var type = '';
if (sec < 0) {
amount = '<span style="color: #aaa">0 sec</span>';
type = '';
} else if (sec < 60) {
amount = Math.floor(sec);
type = 'sec';
if (sec < 0) { amount = 0; type = 'sec'; }
} else if (sec < 60*60) {
amount = Math.floor(sec/60);
type = 'min';
} else if (sec < 24*60*60) {
amount = Math.floor(sec/60/60);
type = 'hour';
} else if (sec < 30*24*60*60) {
amount = Math.floor(sec/24/60/60);
type = 'day';
} else if (sec < 365*24*60*60) {
amount = Math.floor(sec/30/24/60/60*10)/10;
type = 'month';
} else if (sec < 365*4*24*60*60) {
amount = Math.floor(sec/365/24/60/60*10)/10;
type = 'year';
} else if (sec >= 365*4*24*60*60) {
// factor in leap year shift (only older then 4 years)
amount = Math.floor(sec/365.25/24/60/60*10)/10;
type = 'year';
}
return amount + ' ' + type + (amount > 1 ? 's' : '');
}
function interval (value) {
var ret = '';
if (value < 1000) {
ret = "< 1 sec";
} else if (value < 60000) {
ret = Math.floor(value / 1000) + " secs";
} else if (value < 3600000) {
ret = Math.floor(value / 60000) + " mins";
} else if (value < 86400000) {
ret = Math.floor(value / 3600000 * 10) / 10 + " hours";
} else if (value < 2628000000) {
ret = Math.floor(value / 86400000 * 10) / 10 + " days";
} else if (value < 3.1536e+10) {
ret = Math.floor(value / 2628000000 * 10) / 10 + " months";
} else {
ret = Math.floor(value / 3.1536e+9) / 10 + " years";
}
return ret;
}
function date (dateStr) {
if (dateStr === '' || dateStr == null || (typeof dateStr == 'object' && !dateStr.getMonth)) return '';
var d1 = new Date(dateStr);
if (w2utils.isInt(dateStr)) d1 = new Date(Number(dateStr)); // for unix timestamps
if (String(d1) == 'Invalid Date') return '';
var months = w2utils.settings.shortmonths;
var d2 = new Date(); // today
var d3 = new Date();
d3.setTime(d3.getTime() - 86400000); // yesterday
var dd1 = months[d1.getMonth()] + ' ' + d1.getDate() + ', ' + d1.getFullYear();
var dd2 = months[d2.getMonth()] + ' ' + d2.getDate() + ', ' + d2.getFullYear();
var dd3 = months[d3.getMonth()] + ' ' + d3.getDate() + ', ' + d3.getFullYear();
var time = (d1.getHours() - (d1.getHours() > 12 ? 12 :0)) + ':' + (d1.getMinutes() < 10 ? '0' : '') + d1.getMinutes() + ' ' + (d1.getHours() >= 12 ? 'pm' : 'am');
var time2= (d1.getHours() - (d1.getHours() > 12 ? 12 :0)) + ':' + (d1.getMinutes() < 10 ? '0' : '') + d1.getMinutes() + ':' + (d1.getSeconds() < 10 ? '0' : '') + d1.getSeconds() + ' ' + (d1.getHours() >= 12 ? 'pm' : 'am');
var dsp = dd1;
if (dd1 === dd2) dsp = time;
if (dd1 === dd3) dsp = w2utils.lang('Yesterday');
return '<span title="'+ dd1 +' ' + time2 +'">'+ dsp +'</span>';
}
function formatSize (sizeStr) {
if (!w2utils.isFloat(sizeStr) || sizeStr === '') return '';
sizeStr = parseFloat(sizeStr);
if (sizeStr === 0) return 0;
var sizes = ['Bt', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB'];
var i = parseInt( Math.floor( Math.log(sizeStr) / Math.log(1024) ) );
return (Math.floor(sizeStr / Math.pow(1024, i) * 10) / 10).toFixed(i === 0 ? 0 : 1) + ' ' + (sizes[i] || '??');
}
function formatNumber (val, fraction, useGrouping) {
var options = {
minimumFractionDigits : fraction,
maximumFractionDigits : fraction,
useGrouping : useGrouping
};
if (fraction == null || fraction < 0) {
options.minimumFractionDigits = 0;
options.maximumFractionDigits = 20;
}
return parseFloat(val).toLocaleString(w2utils.settings.locale, options);
}
function formatDate (dateStr, format) { // IMPORTANT dateStr HAS TO BE valid JavaScript Date String
if (!format) format = this.settings.dateFormat;
if (dateStr === '' || dateStr == null || (typeof dateStr == 'object' && !dateStr.getMonth)) return '';
var dt = new Date(dateStr);
if (w2utils.isInt(dateStr)) dt = new Date(Number(dateStr)); // for unix timestamps
if (String(dt) == 'Invalid Date') return '';
var year = dt.getFullYear();
var month = dt.getMonth();
var date = dt.getDate();
return format.toLowerCase()
.replace('month', w2utils.settings.fullmonths[month])
.replace('mon', w2utils.settings.shortmonths[month])
.replace(/yyyy/g, year)
.replace(/yyy/g, year)
.replace(/yy/g, year > 2000 ? 100 + parseInt(String(year).substr(2)) : String(year).substr(2))
.replace(/(^|[^a-z$])y/g, '$1' + year) // only y's that are not preceded by a letter
.replace(/mm/g, (month + 1 < 10 ? '0' : '') + (month + 1))
.replace(/dd/g, (date < 10 ? '0' : '') + date)
.replace(/th/g, (date == 1 ? 'st' : 'th'))
.replace(/th/g, (date == 2 ? 'nd' : 'th'))
.replace(/th/g, (date == 3 ? 'rd' : 'th'))
.replace(/(^|[^a-z$])m/g, '$1' + (month + 1)) // only y's that are not preceded by a letter
.replace(/(^|[^a-z$])d/g, '$1' + date); // only y's that are not preceded by a letter
}
function formatTime (dateStr, format) { // IMPORTANT dateStr HAS TO BE valid JavaScript Date String
var months = w2utils.settings.shortmonths;
var fullMonths = w2utils.settings.fullmonths;
if (!format) format = this.settings.timeFormat;
if (dateStr === '' || dateStr == null || (typeof dateStr == 'object' && !dateStr.getMonth)) return '';
var dt = new Date(dateStr);
if (w2utils.isInt(dateStr)) dt = new Date(Number(dateStr)); // for unix timestamps
if (w2utils.isTime(dateStr)) {
var tmp = w2utils.isTime(dateStr, true);
dt = new Date();
dt.setHours(tmp.hours);
dt.setMinutes(tmp.minutes);
}
if (String(dt) == 'Invalid Date') return '';
var type = 'am';
var hour = dt.getHours();
var h24 = dt.getHours();
var min = dt.getMinutes();
var sec = dt.getSeconds();
if (min < 10) min = '0' + min;
if (sec < 10) sec = '0' + sec;
if (format.indexOf('am') !== -1 || format.indexOf('pm') !== -1) {
if (hour >= 12) type = 'pm';
if (hour > 12) hour = hour - 12;
}
return format.toLowerCase()
.replace('am', type)
.replace('pm', type)
.replace('hhh', (hour < 10 ? '0' + hour : hour))
.replace('hh24', (h24 < 10 ? '0' + h24 : h24))
.replace('h24', h24)
.replace('hh', hour)
.replace('mm', min)
.replace('mi', min)
.replace('ss', sec)
.replace(/(^|[^a-z$])h/g, '$1' + hour) // only y's that are not preceded by a letter
.replace(/(^|[^a-z$])m/g, '$1' + min) // only y's that are not preceded by a letter
.replace(/(^|[^a-z$])s/g, '$1' + sec); // only y's that are not preceded by a letter
}
function formatDateTime(dateStr, format) {
var fmt;
if (dateStr === '' || dateStr == null || (typeof dateStr == 'object' && !dateStr.getMonth)) return '';
if (typeof format !== 'string') {
fmt = [this.settings.dateFormat, this.settings.timeFormat];
} else {
fmt = format.split('|');
fmt[0] = fmt[0].trim();
fmt[1] = fmt[1].trim();
}
// older formats support
if (fmt[1] == 'h12') fmt[1] = 'h:m pm';
if (fmt[1] == 'h24') fmt[1] = 'h24:m';
return this.formatDate(dateStr, fmt[0]) + ' ' + this.formatTime(dateStr, fmt[1]);
}
function stripTags (html) {
if (html == null) return html;
switch (typeof html) {
case 'number':
break;
case 'string':
html = String(html).replace(/(<([^>]+)>)/ig, "");
break;
case 'object':
// does not modify original object, but creates a copy
if (Array.isArray(html)) {
html = $.extend(true, [], html);
for (var i = 0; i < html.length; i++) html[i] = this.stripTags(html[i]);
} else {
html = $.extend(true, {}, html);
for (var i in html) html[i] = this.stripTags(html[i]);
}
break;
}
return html;
}
function encodeTags (html) {
if (html == null) return html;
switch (typeof html) {
case 'number':
break;
case 'string':
html = String(html).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
break;
case 'object':
// does not modify original object, but creates a copy
if (Array.isArray(html)) {
html = $.extend(true, [], html);
for (var i = 0; i < html.length; i++) html[i] = this.encodeTags(html[i]);
} else {
html = $.extend(true, {}, html);
for (var i in html) html[i] = this.encodeTags(html[i]);
}
break;
}
return html;
}
function decodeTags (html) {
if (html == null) return html;
switch (typeof html) {
case 'number':
break;
case 'string':
html = String(html).replace(/>/g, ">").replace(/</g, "<").replace(/"/g, '"').replace(/&/g, "&");
break;
case 'object':
// does not modify original object, but creates a copy
if (Array.isArray(html)) {
html = $.extend(true, [], html);
for (var i = 0; i < html.length; i++) html[i] = this.decodeTags(html[i]);
} else {
html = $.extend(true, {}, html);
for (var i in html) html[i] = this.decodeTags(html[i]);
}
break;
}
return html;
}
function escapeId (id) {
if (id === '' || id == null) return '';
return String(id).replace(/([;&,\.\+\*\~'`:"\!\^#$%@\[\]\(\)=<>\|\/? {}\\])/g, '\\$1');
}
function base64encode (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
input = utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);
}
function utf8_encode (string) {
string = String(string).replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
}
return output;
}
function base64decode (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = keyStr.indexOf(input.charAt(i++));
enc2 = keyStr.indexOf(input.charAt(i++));
enc3 = keyStr.indexOf(input.charAt(i++));
enc4 = keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 !== 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 !== 64) {
output = output + String.fromCharCode(chr3);
}
}
output = utf8_decode(output);
function utf8_decode (utftext) {
var string = "";
var i = 0;
var c = 0, c2, c3;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
return output;
}
function md5(input) {
/*
* Based on http://pajhome.org.uk/crypt/md5
*/
var hexcase = 0;
var b64pad = "";
function __pj_crypt_hex_md5(s) {
return __pj_crypt_rstr2hex(__pj_crypt_rstr_md5(__pj_crypt_str2rstr_utf8(s)));
}
function __pj_crypt_b64_md5(s) {
return __pj_crypt_rstr2b64(__pj_crypt_rstr_md5(__pj_crypt_str2rstr_utf8(s)));
}
function __pj_crypt_any_md5(s, e) {
return __pj_crypt_rstr2any(__pj_crypt_rstr_md5(__pj_crypt_str2rstr_utf8(s)), e);
}
function __pj_crypt_hex_hmac_md5(k, d)
{
return __pj_crypt_rstr2hex(__pj_crypt_rstr_hmac_md5(__pj_crypt_str2rstr_utf8(k), __pj_crypt_str2rstr_utf8(d)));
}
function __pj_crypt_b64_hmac_md5(k, d)
{
return __pj_crypt_rstr2b64(__pj_crypt_rstr_hmac_md5(__pj_crypt_str2rstr_utf8(k), __pj_crypt_str2rstr_utf8(d)));
}
function __pj_crypt_any_hmac_md5(k, d, e)
{
return __pj_crypt_rstr2any(__pj_crypt_rstr_hmac_md5(__pj_crypt_str2rstr_utf8(k), __pj_crypt_str2rstr_utf8(d)), e);
}
/*
* Calculate the MD5 of a raw string
*/
function __pj_crypt_rstr_md5(s)
{
return __pj_crypt_binl2rstr(__pj_crypt_binl_md5(__pj_crypt_rstr2binl(s), s.length * 8));
}
/*
* Calculate the HMAC-MD5, of a key and some data (raw strings)
*/
function __pj_crypt_rstr_hmac_md5(key, data)
{
var bkey = __pj_crypt_rstr2binl(key);
if (bkey.length > 16)
bkey = __pj_crypt_binl_md5(bkey, key.length * 8);
var ipad = Array(16), opad = Array(16);
for (var i = 0; i < 16; i++)
{
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
var hash = __pj_crypt_binl_md5(ipad.concat(__pj_crypt_rstr2binl(data)), 512 + data.length * 8);
return __pj_crypt_binl2rstr(__pj_crypt_binl_md5(opad.concat(hash), 512 + 128));
}
/*
* Convert a raw string to a hex string
*/
function __pj_crypt_rstr2hex(input)
{
try {
hexcase
} catch (e) {
hexcase = 0;
}
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var output = "";
var x;
for (var i = 0; i < input.length; i++)
{
x = input.charCodeAt(i);
output += hex_tab.charAt((x >>> 4) & 0x0F)
+ hex_tab.charAt(x & 0x0F);
}
return output;
}
/*
* Convert a raw string to a base-64 string
*/
function __pj_crypt_rstr2b64(input)
{
try {
b64pad
} catch (e) {
b64pad = '';
}
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var output = "";
var len = input.length;
for (var i = 0; i < len; i += 3)
{
var triplet = (input.charCodeAt(i) << 16)
| (i + 1 < len ? input.charCodeAt(i + 1) << 8 : 0)
| (i + 2 < len ? input.charCodeAt(i + 2) : 0);
for (var j = 0; j < 4; j++)
{
if (i * 8 + j * 6 > input.length * 8)
output += b64pad;
else
output += tab.charAt((triplet >>> 6 * (3 - j)) & 0x3F);
}
}
return output;
}
/*
* Convert a raw string to an arbitrary string encoding
*/
function __pj_crypt_rstr2any(input, encoding)
{
var divisor = encoding.length;
var i, j, q, x, quotient;
/* Convert to an array of 16-bit big-endian values, forming the dividend */
var dividend = Array(Math.ceil(input.length / 2));
for (i = 0; i < dividend.length; i++)
{
dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1);
}
/*
* Repeatedly perform a long division. The binary array forms the dividend,
* the length of the encoding is the divisor. Once computed, the quotient
* forms the dividend for the next step. All remainders are stored for later
* use.
*/
var full_length = Math.ceil(input.length * 8 /
(Math.log(encoding.length) / Math.log(2)));
var remainders = Array(full_length);
for (j = 0; j < full_length; j++)
{
quotient = Array();
x = 0;
for (i = 0; i < dividend.length; i++)
{
x = (x << 16) + dividend[i];
q = Math.floor(x / divisor);
x -= q * divisor;
if (quotient.length > 0 || q > 0)
quotient[quotient.length] = q;
}
remainders[j] = x;
dividend = quotient;
}
/* Convert the remainders to the output string */
var output = "";
for (i = remainders.length - 1; i >= 0; i--)
output += encoding.charAt(remainders[i]);
return output;
}
/*
* Encode a string as utf-8.
* For efficiency, this assumes the input is valid utf-16.
*/
function __pj_crypt_str2rstr_utf8(input)
{
var output = "";
var i = -1;
var x, y;
while (++i < input.length)
{
/* Decode utf-16 surrogate pairs */
x = input.charCodeAt(i);
y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
if (0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF)
{
x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF);
i++;
}
/* Encode output as utf-8 */
if (x <= 0x7F)
output += String.fromCharCode(x);
else if (x <= 0x7FF)
output += String.fromCharCode(0xC0 | ((x >>> 6) & 0x1F),
0x80 | (x & 0x3F));
else if (x <= 0xFFFF)
output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F),
0x80 | ((x >>> 6) & 0x3F),
0x80 | (x & 0x3F));
else if (x <= 0x1FFFFF)
output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07),
0x80 | ((x >>> 12) & 0x3F),
0x80 | ((x >>> 6) & 0x3F),
0x80 | (x & 0x3F));
}
return output;
}
/*
* Encode a string as utf-16
*/
function __pj_crypt_str2rstr_utf16le(input)
{
var output = "";
for (var i = 0; i < input.length; i++)
output += String.fromCharCode(input.charCodeAt(i) & 0xFF,
(input.charCodeAt(i) >>> 8) & 0xFF);
return output;
}
function __pj_crypt_str2rstr_utf16be(input)
{
var output = "";
for (var i = 0; i < input.length; i++)
output += String.fromCharCode((input.charCodeAt(i) >>> 8) & 0xFF,
input.charCodeAt(i) & 0xFF);
return output;
}
/*
* Convert a raw string to an array of little-endian words
* Characters >255 have their high-byte silently ignored.
*/
function __pj_crypt_rstr2binl(input)
{
var output = Array(input.length >> 2);
for (var i = 0; i < output.length; i++)
output[i] = 0;
for (var i = 0; i < input.length * 8; i += 8)
output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32);
return output;
}
/*
* Convert an array of little-endian words to a string
*/
function __pj_crypt_binl2rstr(input)
{
var output = "";
for (var i = 0; i < input.length * 32; i += 8)
output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF);
return output;
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length.
*/
function __pj_crypt_binl_md5(x, len)
{
/* append padding */
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for (var i = 0; i < x.length; i += 16)
{
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = __pj_crypt_md5_ff(a, b, c, d, x[i + 0], 7, -680876936);
d = __pj_crypt_md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
c = __pj_crypt_md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
b = __pj_crypt_md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
a = __pj_crypt_md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
d = __pj_crypt_md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
c = __pj_crypt_md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
b = __pj_crypt_md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
a = __pj_crypt_md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
d = __pj_crypt_md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
c = __pj_crypt_md5_ff(c, d, a, b, x[i + 10], 17, -42063);
b = __pj_crypt_md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
a = __pj_crypt_md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
d = __pj_crypt_md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
c = __pj_crypt_md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
b = __pj_crypt_md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);
a = __pj_crypt_md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
d = __pj_crypt_md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
c = __pj_crypt_md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
b = __pj_crypt_md5_gg(b, c, d, a, x[i + 0], 20, -373897302);
a = __pj_crypt_md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
d = __pj_crypt_md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
c = __pj_crypt_md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
b = __pj_crypt_md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
a = __pj_crypt_md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
d = __pj_crypt_md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
c = __pj_crypt_md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
b = __pj_crypt_md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
a = __pj_crypt_md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
d = __pj_crypt_md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
c = __pj_crypt_md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
b = __pj_crypt_md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);
a = __pj_crypt_md5_hh(a, b, c, d, x[i + 5], 4, -378558);
d = __pj_crypt_md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
c = __pj_crypt_md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
b = __pj_crypt_md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
a = __pj_crypt_md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
d = __pj_crypt_md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
c = __pj_crypt_md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
b = __pj_crypt_md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
a = __pj_crypt_md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
d = __pj_crypt_md5_hh(d, a, b, c, x[i + 0], 11, -358537222);
c = __pj_crypt_md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
b = __pj_crypt_md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
a = __pj_crypt_md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
d = __pj_crypt_md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
c = __pj_crypt_md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
b = __pj_crypt_md5_hh(b, c, d, a, x[i + 2], 23, -995338651);
a = __pj_crypt_md5_ii(a, b, c, d, x[i + 0], 6, -198630844);
d = __pj_crypt_md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
c = __pj_crypt_md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
b = __pj_crypt_md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
a = __pj_crypt_md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
d = __pj_crypt_md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
c = __pj_crypt_md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
b = __pj_crypt_md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
a = __pj_crypt_md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
d = __pj_crypt_md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
c = __pj_crypt_md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
b = __pj_crypt_md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
a = __pj_crypt_md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
d = __pj_crypt_md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
c = __pj_crypt_md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
b = __pj_crypt_md5_ii(b, c, d, a, x[i + 9], 21, -343485551);
a = __pj_crypt_safe_add(a, olda);
b = __pj_crypt_safe_add(b, oldb);
c = __pj_crypt_safe_add(c, oldc);
d = __pj_crypt_safe_add(d, oldd);
}
return Array(a, b, c, d);
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function __pj_crypt_md5_cmn(q, a, b, x, s, t)
{
return __pj_crypt_safe_add(__pj_crypt_bit_rol(__pj_crypt_safe_add(__pj_crypt_safe_add(a, q), __pj_crypt_safe_add(x, t)), s), b);
}
function __pj_crypt_md5_ff(a, b, c, d, x, s, t)
{
return __pj_crypt_md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function __pj_crypt_md5_gg(a, b, c, d, x, s, t)
{
return __pj_crypt_md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function __pj_crypt_md5_hh(a, b, c, d, x, s, t)
{
return __pj_crypt_md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function __pj_crypt_md5_ii(a, b, c, d, x, s, t)
{
return __pj_crypt_md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function __pj_crypt_safe_add(x, y)
{
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function __pj_crypt_bit_rol(num, cnt)
{
return (num << cnt) | (num >>> (32 - cnt));
}
return __pj_crypt_hex_md5(input);
}
function transition (div_old, div_new, type, callBack) {
var width = $(div_old).width();
var height = $(div_old).height();
var time = 0.5;
if (!div_old || !div_new) {
console.log('ERROR: Cannot do transition when one of the divs is null');
return;
}
div_old.parentNode.style.cssText += 'perspective: 900px; overflow: hidden;';
div_old.style.cssText += '; position: absolute; z-index: 1019; backface-visibility: hidden';
div_new.style.cssText += '; position: absolute; z-index: 1020; backface-visibility: hidden';
switch (type) {
case 'slide-left':
// init divs
div_old.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0)';
div_new.style.cssText += 'overflow: hidden; transform: translate3d('+ width + 'px, 0, 0)';
$(div_new).show();
// -- need a timing function because otherwise not working
window.setTimeout(function() {
div_new.style.cssText += 'transition: '+ time +'s; transform: translate3d(0, 0, 0)';
div_old.style.cssText += 'transition: '+ time +'s; transform: translate3d(-'+ width +'px, 0, 0)';
}, 1);
break;
case 'slide-right':
// init divs
div_old.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0)';
div_new.style.cssText += 'overflow: hidden; transform: translate3d(-'+ width +'px, 0, 0)';
$(div_new).show();
// -- need a timing function because otherwise not working
window.setTimeout(function() {
div_new.style.cssText += 'transition: '+ time +'s; transform: translate3d(0px, 0, 0)';
div_old.style.cssText += 'transition: '+ time +'s; transform: translate3d('+ width +'px, 0, 0)';
}, 1);
break;
case 'slide-down':
// init divs
div_old.style.cssText += 'overflow: hidden; z-index: 1; transform: translate3d(0, 0, 0)';
div_new.style.cssText += 'overflow: hidden; z-index: 0; transform: translate3d(0, 0, 0)';
$(div_new).show();
// -- need a timing function because otherwise not working
window.setTimeout(function() {
div_new.style.cssText += 'transition: '+ time +'s; transform: translate3d(0, 0, 0)';
div_old.style.cssText += 'transition: '+ time +'s; transform: translate3d(0, '+ height +'px, 0)';
}, 1);
break;
case 'slide-up':
// init divs
div_old.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0)';
div_new.style.cssText += 'overflow: hidden; transform: translate3d(0, '+ height +'px, 0)';
$(div_new).show();
// -- need a timing function because otherwise not working
window.setTimeout(function() {
div_new.style.cssText += 'transition: '+ time +'s; transform: translate3d(0, 0, 0)';
div_old.style.cssText += 'transition: '+ time +'s; transform: translate3d(0, 0, 0)';
}, 1);
break;
case 'flip-left':
// init divs
div_old.style.cssText += 'overflow: hidden; transform: rotateY(0deg)';
div_new.style.cssText += 'overflow: hidden; transform: rotateY(-180deg)';
$(div_new).show();
// -- need a timing function because otherwise not working
window.setTimeout(function() {
div_new.style.cssText += 'transition: '+ time +'s; transform: rotateY(0deg)';
div_old.style.cssText += 'transition: '+ time +'s; transform: rotateY(180deg)';
}, 1);
break;
case 'flip-right':
// init divs
div_old.style.cssText += 'overflow: hidden; transform: rotateY(0deg)';
div_new.style.cssText += 'overflow: hidden; transform: rotateY(180deg)';
$(div_new).show();
// -- need a timing function because otherwise not working
window.setTimeout(function() {
div_new.style.cssText += 'transition: '+ time +'s; transform: rotateY(0deg)';
div_old.style.cssText += 'transition: '+ time +'s; transform: rotateY(-180deg)';
}, 1);
break;
case 'flip-down':
// init divs
div_old.style.cssText += 'overflow: hidden; transform: rotateX(0deg)';
div_new.style.cssText += 'overflow: hidden; transform: rotateX(180deg)';
$(div_new).show();
// -- need a timing function because otherwise not working
window.setTimeout(function() {
div_new.style.cssText += 'transition: '+ time +'s; transform: rotateX(0deg)';
div_old.style.cssText += 'transition: '+ time +'s; transform: rotateX(-180deg)';
}, 1);
break;
case 'flip-up':
// init divs
div_old.style.cssText += 'overflow: hidden; transform: rotateX(0deg)';
div_new.style.cssText += 'overflow: hidden; transform: rotateX(-180deg)';
$(div_new).show();
// -- need a timing function because otherwise not working
window.setTimeout(function() {
div_new.style.cssText += 'transition: '+ time +'s; transform: rotateX(0deg)';
div_old.style.cssText += 'transition: '+ time +'s; transform: rotateX(180deg)';
}, 1);
break;
case 'pop-in':
// init divs
div_old.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0)';
div_new.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0); transform: scale(.8); opacity: 0;';
$(div_new).show();
// -- need a timing function because otherwise not working
window.setTimeout(function() {
div_new.style.cssText += 'transition: '+ time +'s; transform: scale(1); opacity: 1;';
div_old.style.cssText += 'transition: '+ time +'s;';
}, 1);
break;
case 'pop-out':
// init divs
div_old.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0); transform: scale(1); opacity: 1;';
div_new.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0); opacity: 0;';
$(div_new).show();
// -- need a timing function because otherwise not working
window.setTimeout(function() {
div_new.style.cssText += 'transition: '+ time +'s; opacity: 1;';
div_old.style.cssText += 'transition: '+ time +'s; transform: scale(1.7); opacity: 0;';
}, 1);
break;
default:
// init divs
div_old.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0)';
div_new.style.cssText += 'overflow: hidden; translate3d(0, 0, 0); opacity: 0;';
$(div_new).show();
// -- need a timing function because otherwise not working
window.setTimeout(function() {
div_new.style.cssText += 'transition: '+ time +'s; opacity: 1;';
div_old.style.cssText += 'transition: '+ time +'s';
}, 1);
break;
}
setTimeout(function () {
if (type === 'slide-down') {
$(div_old).css('z-index', '1019');
$(div_new).css('z-index', '1020');
}
if (div_new) {
$(div_new).css({ 'opacity': '1' }).css(w2utils.cssPrefix({
'transition': '',
'transform' : ''
}));
}
if (div_old) {
$(div_old).css({ 'opacity': '1' }).css(w2utils.cssPrefix({
'transition': '',
'transform' : ''
}));
}
if (typeof callBack === 'function') callBack();
}, time * 1000);
}
function lock (box, msg, spinner) {
var options = {};
if (typeof msg === 'object') {
options = msg;
} else {
options.msg = msg;
options.spinner = spinner;
}
if (!options.msg && options.msg !== 0) options.msg = '';
w2utils.unlock(box);
$(box).prepend(
'<div class="w2ui-lock"></div>'+
'<div class="w2ui-lock-msg"></div>'
);
var $lock = $(box).find('.w2ui-lock');
var mess = $(box).find('.w2ui-lock-msg');
if (!options.msg) mess.css({ 'background-color': 'transparent', 'border': '0px' });
if (options.spinner === true) options.msg = '<div class="w2ui-spinner" '+ (!options.msg ? 'style="width: 35px; height: 35px"' : '') +'></div>' + options.msg;
if (options.opacity != null) $lock.css('opacity', options.opacity);
if (typeof $lock.fadeIn == 'function') {
$lock.fadeIn(200);
mess.html(options.msg).fadeIn(200);
} else {
$lock.show();
mess.html(options.msg).show(0);
}
}
function unlock (box, speed) {
if (isInt(speed)) {
$(box).find('.w2ui-lock').fadeOut(speed);
setTimeout(function () {
$(box).find('.w2ui-lock').remove();
$(box).find('.w2ui-lock-msg').remove();
}, speed);
} else {
$(box).find('.w2ui-lock').remove();
$(box).find('.w2ui-lock-msg').remove();
}
}
/**
* Used in w2popup, w2grid, w2form, w2layout
* should be called with .call(...) method
*/
function message(where, options) {
var obj = this, closeTimer, edata;
// var where.path = 'w2popup';
// var where.title = '.w2ui-popup-title';
// var where.body = '.w2ui-box';
$().w2tag(); // hide all tags
if (!options) options = { width: 200, height: 100 };
if (options.on == null) $.extend(options, w2utils.event);
if (options.width == null) options.width = 200;
if (options.height == null) options.height = 100;
var pWidth = parseInt($(where.box).width());
var pHeight = parseInt($(where.box).height());
var titleHeight = parseInt($(where.box).find(where.title).css('height') || 0);
if (options.width > pWidth) options.width = pWidth - 10;
if (options.height > pHeight - titleHeight) options.height = pHeight - 10 - titleHeight;
options.originalWidth = options.width;
options.originalHeight = options.height;
if (parseInt(options.width) < 0) options.width = pWidth + options.width;
if (parseInt(options.width) < 10) options.width = 10;
if (parseInt(options.height) < 0) options.height = pHeight + options.height - titleHeight;
if (parseInt(options.height) < 10) options.height = 10;
if (options.hideOnClick == null) options.hideOnClick = false;
var poptions = $(where.box).data('options') || {};
if (options.width == null || options.width > poptions.width - 10) {
options.width = poptions.width - 10;
}
if (options.height == null || options.height > poptions.height - titleHeight - 5) {
options.height = poptions.height - titleHeight - 5; // need margin from bottom only
}
// negative value means margin
if (options.originalHeight < 0) options.height = pHeight + options.originalHeight - titleHeight;
if (options.originalWidth < 0) options.width = pWidth + options.originalWidth * 2; // x 2 because there is left and right margin
var head = $(where.box).find(where.title);
// if some messages are closing, insta close them
var $tmp = $(where.box).find('.w2ui-message.w2ui-closing');
if ($(where.box).find('.w2ui-message.w2ui-closing').length > 0) {
clearTimeout(closeTimer);
closeCB($tmp, $tmp.data('options') || {});
}
var msgCount = $(where.box).find('.w2ui-message').length;
// remove message
if ($.trim(options.html) === '' && $.trim(options.body) === '' && $.trim(options.buttons) === '') {
if (msgCount === 0) return; // no messages at all
var $msg = $(where.box).find('#w2ui-message'+ (msgCount-1));
var options = $msg.data('options') || {};
// before event
edata = options.trigger({ phase: 'before', type: 'close', target: 'self' });
if (edata.isCancelled === true) return;
// default behavior
$msg.css(w2utils.cssPrefix({
'transition': '0.15s',
'transform': 'translateY(-' + options.height + 'px)'
})).addClass('w2ui-closing');
if (msgCount == 1) {
if (this.unlock) {
if (where.param) this.unlock(where.param, 150); else this.unlock(150);
}
} else {
$(where.box).find('#w2ui-message'+ (msgCount-2)).css('z-index', 1500);
}
closeTimer = setTimeout(function () { closeCB($msg, options) }, 150);
} else {
if ($.trim(options.body) !== '' || $.trim(options.buttons) !== '') {
options.html = '<div class="w2ui-message-body">'+ (options.body || '') +'</div>'+
'<div class="w2ui-message-buttons">'+ (options.buttons || '') +'</div>';
}
// hide previous messages
$(where.box).find('.w2ui-message').css('z-index', 1390);
head.data('old-z-index', head.css('z-index'));
head.css('z-index', 1501);
// add message
$(where.box).find(where.body)
.before('<div id="w2ui-message' + msgCount + '" onmousedown="event.stopPropagation();" '+
' class="w2ui-message" style="display: none; z-index: 1500; ' +
(head.length === 0 ? 'top: 0px;' : 'top: ' + w2utils.getSize(head, 'height') + 'px;') +
(options.width != null ? 'width: ' + options.width + 'px; left: ' + ((pWidth - options.width) / 2) + 'px;' : 'left: 10px; right: 10px;') +
(options.height != null ? 'height: ' + options.height + 'px;' : 'bottom: 6px;') +
w2utils.cssPrefix('transition', '.3s', true) + '"' +
(options.hideOnClick === true
? where.param
? 'onclick="'+ where.path +'.message(\''+ where.param +'\');"'
: 'onclick="'+ where.path +'.message();"'
: '') + '>' +
'</div>');
$(where.box).find('#w2ui-message'+ msgCount)
.data('options', options)
.data('prev_focus', $(':focus'));
var display = $(where.box).find('#w2ui-message'+ msgCount).css('display');
$(where.box).find('#w2ui-message'+ msgCount).css(w2utils.cssPrefix({
'transform': (display == 'none' ? 'translateY(-' + options.height + 'px)' : 'translateY(0px)')
}));
if (display == 'none') {
$(where.box).find('#w2ui-message'+ msgCount).show().html(options.html);
options.box = $(where.box).find('#w2ui-message'+ msgCount);
// before event
edata = options.trigger({ phase: 'before', type: 'open', target: 'self' });
if (edata.isCancelled === true) {
head.css('z-index', head.data('old-z-index'));
$(where.box).find('#w2ui-message'+ msgCount).remove();
return;
}
// timer needs to animation
setTimeout(function () {
$(where.box).find('#w2ui-message'+ msgCount).css(w2utils.cssPrefix({
'transform': (display == 'none' ? 'translateY(0px)' : 'translateY(-' + options.height + 'px)')
}));
}, 1);
// timer for lock
if (msgCount === 0 && this.lock) {
if (where.param) this.lock(where.param); else this.lock();
}
setTimeout(function() {
// has to be on top of lock
$(where.box).find('#w2ui-message'+ msgCount).css(w2utils.cssPrefix({ 'transition': '0s' }));
// event after
options.trigger($.extend(edata, { phase: 'after' }));
}, 350);
}
}
function closeCB($msg, options) {
if (edata == null) {
// before event
edata = options.trigger({ phase: 'before', type: 'open', target: 'self' });
if (edata.isCancelled === true) {
head.css('z-index', head.data('old-z-index'));
$(where.box).find('#w2ui-message'+ msgCount).remove();
return;
}
}
var $focus = $msg.data('prev_focus');
$msg.remove();
if ($focus && $focus.length > 0) {
$focus.focus();
} else {
if (obj && obj.focus) obj.focus();
}
head.css('z-index', head.data('old-z-index'));
// event after
options.trigger($.extend(edata, { phase: 'after' }));
}
}
function getSize (el, type) {
var $el = $(el);
var bwidth = {
left : parseInt($el.css('border-left-width')) || 0,
right : parseInt($el.css('border-right-width')) || 0,
top : parseInt($el.css('border-top-width')) || 0,
bottom : parseInt($el.css('border-bottom-width')) || 0
};
var mwidth = {
left : parseInt($el.css('margin-left')) || 0,
right : parseInt($el.css('margin-right')) || 0,
top : parseInt($el.css('margin-top')) || 0,
bottom : parseInt($el.css('margin-bottom')) || 0
};
var pwidth = {
left : parseInt($el.css('padding-left')) || 0,
right : parseInt($el.css('padding-right')) || 0,
top : parseInt($el.css('padding-top')) || 0,
bottom : parseInt($el.css('padding-bottom')) || 0
};
switch (type) {
case 'top' : return bwidth.top + mwidth.top + pwidth.top;
case 'bottom' : return bwidth.bottom + mwidth.bottom + pwidth.bottom;
case 'left' : return bwidth.left + mwidth.left + pwidth.left;
case 'right' : return bwidth.right + mwidth.right + pwidth.right;
case 'width' : return bwidth.left + bwidth.right + mwidth.left + mwidth.right + pwidth.left + pwidth.right + parseInt($el.width());
case 'height' : return bwidth.top + bwidth.bottom + mwidth.top + mwidth.bottom + pwidth.top + pwidth.bottom + parseInt($el.height());
case '+width' : return bwidth.left + bwidth.right + mwidth.left + mwidth.right + pwidth.left + pwidth.right;
case '+height' : return bwidth.top + bwidth.bottom + mwidth.top + mwidth.bottom + pwidth.top + pwidth.bottom;
}
return 0;
}
function getStrWidth (str, styles) {
var w, html = '<div id="_tmp_width" style="position: absolute; top: -900px;'+ (styles || '') +'">'+
encodeTags(str) +
'</div>';
$('body').append(html);
w = $('#_tmp_width').width();
$('#_tmp_width').remove();
return w;
}
function lang (phrase) {
var translation = this.settings.phrases[phrase];
if (translation == null) return phrase; else return translation;
}
function locale (locale) {
if (!locale) locale = 'en-us';
// if the locale is an object, not a string, than we assume it's a
if(typeof locale !== "string" ) {
w2utils.settings = $.extend(true, w2utils.settings, locale);
return;
}
if (locale.length === 5) locale = 'locale/'+ locale +'.json';
// clear phrases from language before
w2utils.settings.phrases = {};
// load from the file
$.ajax({
url : locale,
type : "GET",
dataType : "JSON",
async : false,
cache : false,
success : function (data, status, xhr) {
w2utils.settings = $.extend(true, w2utils.settings, data);
},
error : function (xhr, status, msg) {
console.log('ERROR: Cannot load locale '+ locale);
}
});
}
function scrollBarSize () {
if (tmp.scrollBarSize) return tmp.scrollBarSize;
var html =
'<div id="_scrollbar_width" style="position: absolute; top: -300px; width: 100px; height: 100px; overflow-y: scroll;">'+
' <div style="height: 120px">1</div>'+
'</div>';
$('body').append(html);
tmp.scrollBarSize = 100 - $('#_scrollbar_width > div').width();
$('#_scrollbar_width').remove();
if (String(navigator.userAgent).indexOf('MSIE') >= 0) tmp.scrollBarSize = tmp.scrollBarSize / 2; // need this for IE9+
return tmp.scrollBarSize;
}
function checkName (params, component) { // was w2checkNameParam
if (!params || params.name == null) {
console.log('ERROR: The parameter "name" is required but not supplied in $().'+ component +'().');
return false;
}
if (w2ui[params.name] != null) {
console.log('ERROR: The parameter "name" is not unique. There are other objects already created with the same name (obj: '+ params.name +').');
return false;
}
if (!w2utils.isAlphaNumeric(params.name)) {
console.log('ERROR: The parameter "name" has to be alpha-numeric (a-z, 0-9, dash and underscore). ');
return false;
}
return true;
}
function checkUniqueId (id, items, itemsDecription, objName) { // was w2checkUniqueId
if (!$.isArray(items)) items = [items];
for (var i = 0; i < items.length; i++) {
if (items[i].id === id) {
console.log('ERROR: The parameter "id='+ id +'" is not unique within the current '+ itemsDecription +'. (obj: '+ objName +')');
return false;
}
}
return true;
}
function parseRoute(route) {
var keys = [];
var path = route
.replace(/\/\(/g, '(?:/')
.replace(/\+/g, '__plus__')
.replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, function(_, slash, format, key, capture, optional) {
keys.push({ name: key, optional: !! optional });
slash = slash || '';
return '' + (optional ? '' : slash) + '(?:' + (optional ? slash : '') + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')' + (optional || '');
})
.replace(/([\/.])/g, '\\$1')
.replace(/__plus__/g, '(.+)')
.replace(/\*/g, '(.*)');
return {
path : new RegExp('^' + path + '$', 'i'),
keys : keys
};
}
function cssPrefix(field, value, returnString) {
var css = {};
var newCSS = {};
var ret = '';
if (!$.isPlainObject(field)) {
css[field] = value;
} else {
css = field;
if (value === true) returnString = true;
}
for (var c in css) {
newCSS[c] = css[c];
newCSS['-webkit-'+c] = css[c];
newCSS['-moz-'+c] = css[c].replace('-webkit-', '-moz-');
newCSS['-ms-'+c] = css[c].replace('-webkit-', '-ms-');
newCSS['-o-'+c] = css[c].replace('-webkit-', '-o-');
}
if (returnString === true) {
for (var c in newCSS) {
ret += c + ': ' + newCSS[c] + '; ';
}
} else {
ret = newCSS;
}
return ret;
}
function getCursorPosition(input) {
if (input == null) return null;
var caretOffset = 0;
var doc = input.ownerDocument || input.document;
var win = doc.defaultView || doc.parentWindow;
var sel;
if (input.tagName && input.tagName.toUpperCase() == 'INPUT' && input.selectionStart) {
// standards browser
caretOffset = input.selectionStart;
} else {
if (win.getSelection) {
sel = win.getSelection();
if (sel.rangeCount > 0) {
var range = sel.getRangeAt(0);
var preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(input);
preCaretRange.setEnd(range.endContainer, range.endOffset);
caretOffset = preCaretRange.toString().length;
}
} else if ( (sel = doc.selection) && sel.type != "Control") {
var textRange = sel.createRange();
var preCaretTextRange = doc.body.createTextRange();
preCaretTextRange.moveToElementText(input);
preCaretTextRange.setEndPoint("EndToEnd", textRange);
caretOffset = preCaretTextRange.text.length;
}
}
return caretOffset;
}
function setCursorPosition(input, pos, posEnd) {
var range = document.createRange();
var el, sel = window.getSelection();
if (input == null) return;
for (var i = 0; i < input.childNodes.length; i++) {
var tmp = $(input.childNodes[i]).text();
if (input.childNodes[i].tagName) {
tmp = $(input.childNodes[i]).html();
tmp = tmp.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/ /g, ' ');
}
if (pos <= tmp.length) {
el = input.childNodes[i];
if (el.childNodes && el.childNodes.length > 0) el = el.childNodes[0];
if (el.childNodes && el.childNodes.length > 0) el = el.childNodes[0];
break;
} else {
pos -= tmp.length;
}
}
if (el == null) return;
if (pos > el.length) pos = el.length;
range.setStart(el, pos);
if (posEnd) {
range.setEnd(el, posEnd);
} else {
range.collapse(true);
}
sel.removeAllRanges();
sel.addRange(range);
}
function testLocalStorage() {
// test if localStorage is available, see issue #1282
// original code: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js
var str = 'w2ui_test';
try {
localStorage.setItem(str, str);
localStorage.removeItem(str);
return true;
} catch (e) {
return false;
}
}
})(jQuery);
/***********************************************************
* Formatters object
* --- Primariy used in grid
*
*********************************************************/
w2utils.formatters = {
'number': function (value, params) {
if (parseInt(params) > 20) params = 20;
if (parseInt(params) < 0) params = 0;
if (value == null || value === '') return '';
return w2utils.formatNumber(parseFloat(value), params, true);
},
'float': function (value, params) {
return w2utils.formatters['number'](value, params);
},
'int': function (value, params) {
return w2utils.formatters['number'](value, 0);
},
'money': function (value, params) {
if (value == null || value === '') return '';
var data = w2utils.formatNumber(Number(value), w2utils.settings.currencyPrecision || 2);
return (w2utils.settings.currencyPrefix || '') + data + (w2utils.settings.currencySuffix || '');
},
'currency': function (value, params) {
return w2utils.formatters['money'](value, params);
},
'percent': function (value, params) {
if (value == null || value === '') return '';
return w2utils.formatNumber(value, params || 1) + '%';
},
'size': function (value, params) {
if (value == null || value === '') return '';
return w2utils.formatSize(parseInt(value));
},
'date': function (value, params) {
if (params === '') params = w2utils.settings.dateFormat;
if (value == null || value === 0) return '';
var dt = w2utils.isDateTime(value, params, true);
if (dt === '') dt = w2utils.isDate(value, params, true);
return '<span title="'+ dt +'">' + w2utils.formatDate(dt, params) + '</span>';
},
'datetime': function (value, params) {
if (params === '') params = w2utils.settings.datetimeFormat;
if (value == null || value === 0) return '';
var dt = w2utils.isDateTime(value, params, true);
if (dt === '') dt = w2utils.isDate(value, params, true);
return '<span title="'+ dt +'">' + w2utils.formatDateTime(dt, params) + '</span>';
},
'time': function (value, params) {
if (params === '') params = w2utils.settings.timeFormat;
if (params === 'h12') params = 'hh:mi pm';
if (params === 'h24') params = 'h24:mi';
if (value == null || value === 0) return '';
var dt = w2utils.isDateTime(value, params, true);
if (dt === '') dt = w2utils.isDate(value, params, true);
return '<span title="'+ dt +'">' + w2utils.formatTime(value, params) + '</span>';
},
'timestamp': function (value, params) {
if (params === '') params = w2utils.settings.datetimeFormat;
if (value == null || value === 0) return '';
var dt = w2utils.isDateTime(value, params, true);
if (dt === '') dt = w2utils.isDate(value, params, true);
return dt.toString ? dt.toString() : '';
},
'gmt': function (value, params) {
if (params === '') params = w2utils.settings.datetimeFormat;
if (value == null || value === 0) return '';
var dt = w2utils.isDateTime(value, params, true);
if (dt === '') dt = w2utils.isDate(value, params, true);
return dt.toUTCString ? dt.toUTCString() : '';
},
'age': function (value, params) {
if (value == null || value === 0) return '';
var dt = w2utils.isDateTime(value, null, true);
if (dt === '') dt = w2utils.isDate(value, null, true);
return '<span title="'+ dt +'">' + w2utils.age(value) + (params ? (' ' + params) : '') + '</span>';
},
'interval': function (value, params) {
if (value == null || value === 0) return '';
return w2utils.interval(value) + (params ? (' ' + params) : '');
},
'toggle': function (value, params) {
return (value ? 'Yes' : '');
},
'password': function (value, params) {
var ret = "";
for (var i=0; i < value.length; i++) {
ret += "*";
}
return ret;
}
};
/***********************************************************
* Generic Event Object
* --- This object is reused across all other
* --- widgets in w2ui.
*
*********************************************************/
w2utils.event = {
on: function (edata, handler) {
var $ = jQuery;
// allow 'eventName:after' syntax
if (typeof edata == 'string' && edata.indexOf(':') != -1) {
var tmp = edata.split(':');
if (['complete', 'done'].indexOf(edata[1]) != -1) edata[1] = 'after';
edata = {
type : tmp[0],
execute : tmp[1]
};
}
if (!$.isPlainObject(edata)) edata = { type: edata };
edata = $.extend({ type: null, execute: 'before', target: null, onComplete: null }, edata);
// errors
if (!edata.type) { console.log('ERROR: You must specify event type when calling .on() method of '+ this.name); return; }
if (!handler) { console.log('ERROR: You must specify event handler function when calling .on() method of '+ this.name); return; }
if (!$.isArray(this.handlers)) this.handlers = [];
this.handlers.push({ edata: edata, handler: handler });
},
off: function (edata, handler) {
var $ = jQuery;
// allow 'eventName:after' syntax
if (typeof edata == 'string' && edata.indexOf(':') != -1) {
var tmp = edata.split(':');
if (['complete', 'done'].indexOf(edata[1]) != -1) edata[1] = 'after';
edata = {
type : tmp[0],
execute : tmp[1]
}
}
if (!$.isPlainObject(edata)) edata = { type: edata };
edata = $.extend({}, { type: null, execute: 'before', target: null, onComplete: null }, edata);
// errors
if (!edata.type) { console.log('ERROR: You must specify event type when calling .off() method of '+ this.name); return; }
if (!handler) { handler = null; }
// remove handlers
var newHandlers = [];
for (var h = 0, len = this.handlers.length; h < len; h++) {
var t = this.handlers[h];
if ((t.edata.type === edata.type || edata.type === '*') &&
(t.edata.target === edata.target || edata.target == null) &&
(t.edata.execute === edata.execute || edata.execute == null) &&
(t.handler === handler || handler == null))
{
// match
} else {
newHandlers.push(t);
}
}
this.handlers = newHandlers;
},
trigger: function (edata) {
var $ = jQuery;
var edata = $.extend({ type: null, phase: 'before', target: null, doneHandlers: [] }, edata, {
isStopped : false,
isCancelled : false,
done : function (handler) { this.doneHandlers.push(handler); },
preventDefault : function () { this.isCancelled = true; },
stopPropagation : function () { this.isStopped = true; }
});
if (edata.phase === 'before') edata.onComplete = null;
var args, fun, tmp;
if (edata.target == null) edata.target = null;
if (!$.isArray(this.handlers)) this.handlers = [];
// process events in REVERSE order
for (var h = this.handlers.length-1; h >= 0; h--) {
var item = this.handlers[h];
if ((item.edata.type === edata.type || item.edata.type === '*') &&
(item.edata.target === edata.target || item.edata.target == null) &&
(item.edata.execute === edata.phase || item.edata.execute === '*' || item.edata.phase === '*'))
{
edata = $.extend({}, item.edata, edata);
// check handler arguments
args = [];
tmp = new RegExp(/\((.*?)\)/).exec(item.handler);
if (tmp) args = tmp[1].split(/\s*,\s*/);
if (args.length === 2) {
item.handler.call(this, edata.target, edata); // old way for back compatibility
} else {
item.handler.call(this, edata); // new way
}
if (edata.isStopped === true || edata.stop === true) return edata; // back compatibility edata.stop === true
}
}
// main object events
var funName = 'on' + edata.type.substr(0,1).toUpperCase() + edata.type.substr(1);
if (edata.phase === 'before' && typeof this[funName] === 'function') {
fun = this[funName];
// check handler arguments
args = [];
tmp = new RegExp(/\((.*?)\)/).exec(fun);
if (tmp) args = tmp[1].split(/\s*,\s*/);
if (args.length === 2) {
fun.call(this, edata.target, edata); // old way for back compatibility
} else {
fun.call(this, edata); // new way
}
if (edata.isStopped === true || edata.stop === true) return edata; // back compatibility edata.stop === true
}
// item object events
if (edata.object != null && edata.phase === 'before' &&
typeof edata.object[funName] === 'function')
{
fun = edata.object[funName];
// check handler arguments
args = [];
tmp = new RegExp(/\((.*?)\)/).exec(fun);
if (tmp) args = tmp[1].split(/\s*,\s*/);
if (args.length === 2) {
fun.call(this, edata.target, edata); // old way for back compatibility
} else {
fun.call(this, edata); // new way
}
if (edata.isStopped === true || edata.stop === true) return edata;
}
// execute onComplete
if (edata.phase === 'after') {
if (typeof edata.onComplete === 'function') edata.onComplete.call(this, edata);
for (var i = 0; i < edata.doneHandlers.length; i++) {
if (typeof edata.doneHandlers[i] == 'function') {
edata.doneHandlers[i].call(this, edata);
}
}
}
return edata;
}
};
/***********************************************************
* Commonly used plugins
* --- used primarily in grid and form
*
*********************************************************/
(function ($) {
$.fn.w2render = function (name) {
if ($(this).length > 0) {
if (typeof name === 'string' && w2ui[name]) w2ui[name].render($(this)[0]);
if (typeof name === 'object') name.render($(this)[0]);
}
};
$.fn.w2destroy = function (name) {
if (!name && this.length > 0) name = this.attr('name');
if (typeof name === 'string' && w2ui[name]) w2ui[name].destroy();
if (typeof name === 'object') name.destroy();
};
$.fn.w2marker = function () {
var str = Array.prototype.slice.call(arguments, 0);
if (Array.isArray(str[0])) str = str[0];
if (str.length === 0 || !str[0]) { // remove marker
return $(this).each(clearMarkedText);
} else { // add marker
return $(this).each(function (index, el) {
clearMarkedText(index, el);
for (var s = 0; s < str.length; s++) {
var tmp = str[s];
if (typeof tmp !== 'string') tmp = String(tmp);
// escape regex special chars
tmp = tmp.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&").replace(/&/g, '&').replace(/</g, '>').replace(/>/g, '<');
var regex = new RegExp(tmp + '(?!([^<]+)?>)', "gi"); // only outside tags
el.innerHTML = el.innerHTML.replace(regex, replaceValue);
}
function replaceValue(matched) { // mark new
return '<span class="w2ui-marker">' + matched + '</span>';
}
});
}
function clearMarkedText(index, el) {
while (el.innerHTML.indexOf('<span class="w2ui-marker">') != -1) {
el.innerHTML = el.innerHTML.replace(/\<span class=\"w2ui\-marker\"\>((.|\n|\r)*)\<\/span\>/ig, '$1'); // unmark
}
}
};
// -- w2tag - there can be multiple on screen at a time
$.fn.w2tag = function (text, options) {
// only one argument
if (arguments.length == 1 && typeof text == 'object') {
options = text;
if (options.html != null) text = options.html;
}
// default options
options = $.extend({
id : null, // id for the tag, otherwise input id is used
html : text, // or html
position : 'right', // can be left, right, top, bottom
align : 'none', // can be none, left, right (only works for potision: top | bottom)
left : 0, // delta for left coordinate
top : 0, // delta for top coordinate
style : '', // adition style for the tag
css : {}, // add css for input when tag is shown
className : '', // add class bubble
inputClass : '', // add class for input when tag is shown
onShow : null, // callBack when shown
onHide : null, // callBack when hidden
hideOnKeyPress : true, // hide tag if key pressed
hideOnBlur : false, // hide tag on blur
hideOnClick : false // hide tag on document click
}, options);
if (options.name != null && options.id == null) options.id = options.name;
// for backward compatibility
if (options['class'] !== '' && options.inputClass === '') options.inputClass = options['class'];
// remove all tags
if ($(this).length === 0) {
$('.w2ui-tag').each(function (index, el) {
var opt = $(el).data('options');
if (opt == null) opt = {};
$($(el).data('taged-el')).removeClass(opt.inputClass);
clearInterval($(el).data('timer'));
$(el).remove();
});
return;
}
return $(this).each(function (index, el) {
// show or hide tag
var origID = (options.id ? options.id : el.id);
var tagID = w2utils.escapeId(origID);
var $tags = $('#w2ui-tag-'+tagID);
if (text === '' || text == null) {
// remmove element
$tags.css('opacity', 0);
clearInterval($tags.data('timer'));
$tags.remove();
return;
} else if ($tags.length !== 0) {
// if already present
options = $.extend($tags.data('options'), options);
$tags.data('options', options);
$tags.find('.w2ui-tag-body')
.attr('style', options.style)
.addClass(options.className)
.html(options.html);
} else {
var originalCSS = '';
if ($(el).length > 0) originalCSS = $(el)[0].style.cssText;
// insert
$('body').append(
'<div onclick="event.stopPropagation()" style="display:none;" id="w2ui-tag-'+ origID +'" '+
' class="w2ui-tag '+ ($(el).parents('.w2ui-popup, .w2ui-overlay-popup, .w2ui-message').length > 0 ? 'w2ui-tag-popup' : '') + '">'+
' <div style="margin: -2px 0px 0px -2px; white-space: nowrap;">'+
' <div class="w2ui-tag-body '+ options.className +'" style="'+ (options.style || '') +'">'+ text +'</div>'+
' </div>' +
'</div>');
$tags = $('#w2ui-tag-'+tagID);
$(el).data('w2tag', $tags.get(0));
}
// need time out to allow tag to be rendered
setTimeout(function () {
$tags.css('display', 'block');
if (!$(el).offset()) return;
var pos = checkIfMoved(true);
if (pos == null) return;
$tags.css({
opacity : '1',
left : pos.left + 'px',
top : pos.top + 'px'
})
.data('options', options)
.data('taged-el', el)
.data('position', pos.left + 'x' + pos.top)
.data('timer', setTimeout(checkIfMoved, 100))
.find('.w2ui-tag-body').addClass(pos['posClass']);
$(el).css(options.css)
.off('.w2tag')
.addClass(options.inputClass);
if (options.hideOnKeyPress) {
$(el).on('keypress.w2tag', hideTag);
}
if (options.hideOnBlur) {
$(el).on('blur.w2tag', hideTag);
}
if (options.hideOnClick) {
$(document).on('click.w2tag', hideTag)
}
if (typeof options.onShow === 'function') options.onShow();
}, 1);
// bind event to hide it
function hideTag() {
$tags = $('#w2ui-tag-'+tagID);
if ($tags.length <= 0) return;
clearInterval($tags.data('timer'));
$tags.remove();
$(document).off('.w2tag');
$(el).off('.w2tag', hideTag)
.removeClass(options.inputClass)
.removeData('w2tag');
if ($(el).length > 0) $(el)[0].style.cssText = originalCSS;
if (typeof options.onHide === 'function') options.onHide();
}
function checkIfMoved(skipTransition) {
// monitor if destroyed
var offset = $(el).offset();
if ($(el).length === 0 || (offset.left === 0 && offset.top === 0) || $tags.find('.w2ui-tag-body').length === 0) {
clearInterval($tags.data('timer'));
hideTag();
return;
}
setTimeout(checkIfMoved, 100);
// monitor if moved
var posClass = 'w2ui-tag-right';
var posLeft = parseInt(offset.left + el.offsetWidth + (options.left ? options.left : 0));
var posTop = parseInt(offset.top + (options.top ? options.top : 0));
var tagBody = $tags.find('.w2ui-tag-body');
var width = tagBody[0].offsetWidth;
var height = tagBody[0].offsetHeight;
if (options.position == 'top') {
posClass = 'w2ui-tag-top';
posLeft = parseInt(offset.left + (options.left ? options.left : 0)) - 14;
posTop = parseInt(offset.top + (options.top ? options.top : 0)) - height - 10;
}
else if (options.position == 'bottom') {
posClass = 'w2ui-tag-bottom';
posLeft = parseInt(offset.left + (options.left ? options.left : 0)) - 14;
posTop = parseInt(offset.top + el.offsetHeight + (options.top ? options.top : 0)) + 10;
}
else if (options.position == 'left') {
posClass = 'w2ui-tag-left';
posLeft = parseInt(offset.left + (options.left ? options.left : 0)) - width - 20;
posTop = parseInt(offset.top + (options.top ? options.top : 0));
}
else if (Array.isArray(options.position)) {
// try to fit the tag on screen in the order defined in the array
var maxWidth = window.innerWidth;
var maxHeight = window.innerHeight
for( var i=0; i<options.position.length; i++ ){
var pos = options.position[i];
if(pos == 'right'){
posClass = 'w2ui-tag-right';
posLeft = parseInt(offset.left + el.offsetWidth + (options.left ? options.left : 0));
posTop = parseInt(offset.top + (options.top ? options.top : 0));
if(posLeft+width <= maxWidth) break;
}
else if(pos == 'left'){
posClass = 'w2ui-tag-left';
posLeft = parseInt(offset.left + (options.left ? options.left : 0)) - width - 20;
posTop = parseInt(offset.top + (options.top ? options.top : 0));
if(posLeft >= 0) break;
}
else if(pos == 'top'){
posClass = 'w2ui-tag-top';
posLeft = parseInt(offset.left + (options.left ? options.left : 0)) - 14;
posTop = parseInt(offset.top + (options.top ? options.top : 0)) - height - 10;
if(posLeft+width <= maxWidth && posTop >= 0) break;
}
else if(pos == 'bottom'){
posClass = 'w2ui-tag-bottom';
posLeft = parseInt(offset.left + (options.left ? options.left : 0)) - 14;
posTop = parseInt(offset.top + el.offsetHeight + (options.top ? options.top : 0)) + 10;
if(posLeft+width <= maxWidth && posTop+height <= maxHeight) break;
}
}
if (tagBody.data('posClass') !== posClass) {
tagBody.removeClass('w2ui-tag-right w2ui-tag-left w2ui-tag-top w2ui-tag-bottom')
.addClass(posClass)
.data('posClass', posClass);
}
}
if ($tags.data('position') !== posLeft + 'x' + posTop && skipTransition !== true) {
$tags.css(w2utils.cssPrefix({ 'transition': '.2s' })).css({
left: posLeft + 'px',
top : posTop + 'px'
}).data('position', posLeft + 'x' + posTop);
}
return { left: posLeft, top: posTop, posClass: posClass };
}
});
};
// w2overlay - appears under the element, there can be only one at a time
$.fn.w2overlay = function (html, options) {
var obj = this;
var name = '';
var defaults = {
name : null, // it not null, then allows multiple concurrent overlays
html : '', // html text to display
align : 'none', // can be none, left, right, both
left : 0, // offset left
top : 0, // offset top
tipLeft : 30, // tip offset left
noTip : false, // if true - no tip will be displayed
selectable : false,
width : 0, // fixed width
height : 0, // fixed height
maxWidth : null, // max width if any
maxHeight : null, // max height if any
contextMenu : false, // if true, it will be opened at mouse position
pageX : null,
pageY : null,
originalEvent : null,
style : '', // additional style for main div
'class' : '', // additional class name for main div
overlayStyle: '',
onShow : null, // event on show
onHide : null, // event on hide
openAbove : false, // show above control
tmp : {}
};
if (arguments.length == 1) {
if (typeof html == 'object') {
options = html;
} else {
options = { html: html };
}
}
if (arguments.length == 2) options.html = html;
if (!$.isPlainObject(options)) options = {};
options = $.extend({}, defaults, options);
if (options.name) name = '-' + options.name;
// hide
var tmp_hide;
if (this.length === 0 || options.html === '' || options.html == null) {
if ($('#w2ui-overlay'+ name).length > 0) {
tmp_hide = $('#w2ui-overlay'+ name)[0].hide;
if (typeof tmp_hide === 'function') tmp_hide();
} else {
$('#w2ui-overlay'+ name).remove();
}
return $(this);
}
// hide previous if any
if ($('#w2ui-overlay'+ name).length > 0) {
tmp_hide = $('#w2ui-overlay'+ name)[0].hide;
$(document).off('.w2overlayHide');
if (typeof tmp_hide === 'function') tmp_hide();
}
if (obj.length > 0 && (obj[0].tagName == null || obj[0].tagName.toUpperCase() == 'BODY')) options.contextMenu = true;
if (options.contextMenu && options.originalEvent) {
options.pageX = options.originalEvent.pageX;
options.pageY = options.originalEvent.pageY;
}
if (options.contextMenu && (options.pageX == null || options.pageY == null)) {
console.log('ERROR: to display menu at mouse location, pass options.pageX and options.pageY.');
}
// append
$('body').append(
'<div id="w2ui-overlay'+ name +'" style="display: none; left: 0px; top: 0px; '+ options.overlayStyle +'"'+
' class="w2ui-reset w2ui-overlay '+ ($(this).parents('.w2ui-popup, .w2ui-overlay-popup, .w2ui-message').length > 0 ? 'w2ui-overlay-popup' : '') +'">'+
' <style></style>'+
' <div style="min-width: 100%; '+ options.style +'" class="'+ options['class'] +'"></div>'+
'</div>'
);
// init
var div1 = $('#w2ui-overlay'+ name);
var div2 = div1.find(' > div');
div2.html(options.html);
// pick bg color of first div
var bc = div2.css('background-color');
if (bc != null && bc !== 'rgba(0, 0, 0, 0)' && bc !== 'transparent') div1.css({ 'background-color': bc, 'border-color': bc });
var offset = $(obj).offset() || {};
div1.data('element', obj.length > 0 ? obj[0] : null)
.data('options', options)
.data('position', offset.left + 'x' + offset.top)
.fadeIn('fast')
.on('click', function (event) {
// if there is label for input, it will produce 2 click events
if (event.target.tagName.toUpperCase() == 'LABEL') event.stopPropagation();
})
.on('mousedown', function (event) {
$('#w2ui-overlay'+ name).data('keepOpen', true);
if (['INPUT', 'TEXTAREA', 'SELECT'].indexOf(event.target.tagName.toUpperCase()) == -1 && !options.selectable) {
event.preventDefault();
}
});
div1[0].hide = hide;
div1[0].resize = resize;
// need time to display
setTimeout(function () {
resize();
$(document).off('.w2overlayHide').on('click.w2overlayHide', hide);
if (typeof options.onShow === 'function') options.onShow();
}, 10);
monitor();
return $(this);
// monitor position
function monitor() {
var tmp = $('#w2ui-overlay'+ name);
if (tmp.data('element') !== obj[0]) return; // it if it different overlay
if (tmp.length === 0) return;
var offset = $(obj).offset() || {};
var pos = offset.left + 'x' + offset.top;
if (tmp.data('position') !== pos) {
hide();
} else {
setTimeout(monitor, 250);
}
}
// click anywhere else hides the drop down
function hide(event) {
if (event && event.button !== 0) return; // only for left click button
var div1 = $('#w2ui-overlay'+ name);
if (div1.data('keepOpen') === true) {
div1.removeData('keepOpen');
return;
}
var result;
if (typeof options.onHide === 'function') result = options.onHide();
if (result === false) return;
div1.remove();
$(document).off('click', hide);
clearInterval(div1.data('timer'));
}
function resize () {
var div1 = $('#w2ui-overlay'+ name);
var div2 = div1.find(' > div');
var menu = $('#w2ui-overlay'+ name +' div.menu');
menu.css('overflow-y', 'hidden');
// if goes over the screen, limit height and width
if (div1.length > 0) {
div2.height('auto').width('auto');
// width/height
var overflowX = false;
var overflowY = false;
var h = div2.height();
var w = div2.width();
if (options.width && options.width < w) w = options.width;
if (w < 30) w = 30;
// if content of specific height
if (options.tmp.contentHeight) {
h = parseInt(options.tmp.contentHeight);
div2.height(h);
setTimeout(function () {
var $div = div2.find('div.menu');
if (h > $div.height()) {
div2.find('div.menu').css('overflow-y', 'hidden');
}
}, 1);
setTimeout(function () {
var $div = div2.find('div.menu');
if ($div.css('overflow-y') != 'auto') $div.css('overflow-y', 'auto');
}, 10);
}
if (options.tmp.contentWidth && options.align != 'both') {
w = parseInt(options.tmp.contentWidth);
div2.width(w);
setTimeout(function () {
if (w > div2.find('div.menu > table').width()) {
div2.find('div.menu > table').css('overflow-x', 'hidden');
}
}, 1);
setTimeout(function () {
div2.find('div.menu > table').css('overflow-x', 'auto');
}, 10);
}
// adjust position
var boxLeft = options.left;
var boxWidth = options.width;
var tipLeft = options.tipLeft;
// alignment
switch (options.align) {
case 'both':
boxLeft = 17;
if (options.width === 0) options.width = w2utils.getSize($(obj), 'width');
if (options.maxWidth && options.width > options.maxWidth) options.width = options.maxWidth;
break;
case 'left':
boxLeft = 17;
break;
case 'right':
boxLeft = w2utils.getSize($(obj), 'width') - w + 10;
tipLeft = w - 40;
break;
}
if (w === 30 && !boxWidth) boxWidth = 30; else boxWidth = (options.width ? options.width : 'auto');
var tmp = (w - 17) / 2;
if (boxWidth != 'auto') tmp = (boxWidth - 17) / 2;
if (tmp < 25) {
boxLeft = 25 - tmp;
tipLeft = Math.floor(tmp);
}
// Y coord
var X, Y, offsetTop;
if (options.contextMenu) { // context menu
X = options.pageX + 8;
Y = options.pageY - 0;
offsetTop = options.pageY;
} else {
var offset = obj.offset() || {};
X = ((offset.left > 25 ? offset.left : 25) + boxLeft);
Y = (offset.top + w2utils.getSize(obj, 'height') + options.top + 7);
offsetTop = offset.top;
}
div1.css({
left : X + 'px',
top : Y + 'px',
'min-width' : boxWidth,
'min-height': (options.height ? options.height : 'auto')
});
// $(window).height() - has a problem in FF20
var offset = div2.offset() || {};
var maxHeight = window.innerHeight + $(document).scrollTop() - offset.top - 7;
var maxWidth = window.innerWidth + $(document).scrollLeft() - offset.left - 7;
if (options.contextMenu) { // context menu
maxHeight = window.innerHeight + $(document).scrollTop() - options.pageY - 15;
maxWidth = window.innerWidth + $(document).scrollLeft() - options.pageX;
}
if ((maxHeight > -50 && maxHeight < 210) || options.openAbove === true) {
var tipOffset;
// show on top
if (options.contextMenu) { // context menu
maxHeight = options.pageY - 7;
tipOffset = 5;
} else {
maxHeight = offset.top - $(document).scrollTop() - 7;
tipOffset = 24;
}
if (options.maxHeight && maxHeight > options.maxHeight) maxHeight = options.maxHeight;
if (h > maxHeight) {
overflowY = true;
div2.height(maxHeight).width(w).css({ 'overflow-y': 'auto' });
h = maxHeight;
}
div1.addClass('bottom-arrow');
div1.css('top', (offsetTop - h - tipOffset + options.top) + 'px');
div1.find('>style').html(
'#w2ui-overlay'+ name +':before { margin-left: '+ parseInt(tipLeft) +'px; }'+
'#w2ui-overlay'+ name +':after { margin-left: '+ parseInt(tipLeft) +'px; }'
);
} else {
// show under
if (options.maxHeight && maxHeight > options.maxHeight) maxHeight = options.maxHeight;
if (h > maxHeight) {
overflowY = true;
div2.height(maxHeight).width(w).css({ 'overflow-y': 'auto' });
}
div1.addClass('top-arrow');
div1.find('>style').html(
'#w2ui-overlay'+ name +':before { margin-left: '+ parseInt(tipLeft) +'px; }'+
'#w2ui-overlay'+ name +':after { margin-left: '+ parseInt(tipLeft) +'px; }'
);
}
// check width
w = div2.width();
maxWidth = window.innerWidth + $(document).scrollLeft() - offset.left - 7;
if (options.maxWidth && maxWidth > options.maxWidth) maxWidth = options.maxWidth;
if (w > maxWidth && options.align !== 'both') {
options.align = 'right';
setTimeout(function () { resize(); }, 1);
}
// don't show tip
if (options.contextMenu || options.noTip) { // context menu
div1.find('>style').html(
'#w2ui-overlay'+ name +':before { display: none; }'+
'#w2ui-overlay'+ name +':after { display: none; }'
);
}
// check scroll bar (needed to avoid horizontal scrollbar)
if (overflowY && options.align != 'both') div2.width(w + w2utils.scrollBarSize() + 2);
}
menu.css('overflow-y', 'auto');
}
};
$.fn.w2menu = function (menu, options) {
/*
ITEM STRUCTURE
item : {
id : null,
text : '',
style : '',
img : '',
icon : '',
count : '',
tooltip : '',
hidden : false,
checked : null,
disabled : false
...
}
*/
var defaults = {
type : 'normal', // can be normal, radio, check
index : null, // current selected
items : [],
render : null,
msgNoItems : 'No items',
onSelect : null,
tmp : {}
};
var obj = this;
var name = '';
if (menu === 'refresh') {
// if not show - call blur
if ($('#w2ui-overlay'+ name).length > 0) {
options = $.extend($.fn.w2menuOptions, options);
var scrTop = $('#w2ui-overlay'+ name +' div.menu').scrollTop();
$('#w2ui-overlay'+ name +' div.menu').html(getMenuHTML());
$('#w2ui-overlay'+ name +' div.menu').scrollTop(scrTop);
mresize();
} else {
$(this).w2menu(options);
}
} else if (menu === 'refresh-index') {
var $menu = $('#w2ui-overlay'+ name +' div.menu');
var cur = $menu.find('tr[index='+ options.index +']');
var scrTop = $menu.scrollTop();
$menu.find('tr.w2ui-selected').removeClass('w2ui-selected'); // clear all
cur.addClass('w2ui-selected'); // select current
// scroll into view
if (cur.length > 0) {
var top = cur[0].offsetTop - 5; // 5 is margin top
var height = $menu.height();
$menu.scrollTop(scrTop);
if (top < scrTop || top + cur.height() > scrTop + height) {
$menu.animate({ 'scrollTop': top - (height - cur.height() * 2) / 2 }, 200, 'linear');
}
}
mresize();
} else {
if (arguments.length === 1) options = menu; else options.items = menu;
if (typeof options !== 'object') options = {};
options = $.extend({}, defaults, options);
$.fn.w2menuOptions = options;
if (options.name) name = '-' + options.name;
if (typeof options.select === 'function' && typeof options.onSelect !== 'function') options.onSelect = options.select;
if (typeof options.onRender === 'function' && typeof options.render !== 'function') options.render = options.onRender;
// since only one overlay can exist at a time
$.fn.w2menuClick = function (event, index) {
var keepOpen = false;
if (['radio', 'check'].indexOf(options.type) != -1) {
if (event.shiftKey || event.metaKey || event.ctrlKey) keepOpen = true;
}
if (typeof options.onSelect === 'function') {
// need time so that menu first hides
setTimeout(function () {
options.onSelect({
index: index,
item: options.items[index],
keepOpen: keepOpen,
originalEvent: event
});
}, 10);
}
// do not uncomment (or enum search type is not working in grid)
// setTimeout(function () { $(document).click(); }, 50);
// -- hide
var div = $('#w2ui-overlay'+ name);
div.removeData('keepOpen');
if (typeof div[0].hide === 'function' && !keepOpen) {
div[0].hide();
}
};
$.fn.w2menuDown = function (event, index) {
var $el = $(event.target).parents('tr');
var tmp = $el.find('.w2ui-icon');
if ((options.type == 'check') || (options.type == 'radio')) {
var item = options.items[index];
item.checked = !item.checked;
if (item.checked) {
if (options.type == 'radio') {
tmp.parents('table').find('.w2ui-icon')
.removeClass('w2ui-icon-check')
.addClass('w2ui-icon-empty');
}
tmp.removeClass('w2ui-icon-empty').addClass('w2ui-icon-check');
} else if (options.type == 'check') {
tmp.removeClass('w2ui-icon-check').addClass('w2ui-icon-empty');
}
}
// highlight record
$el.parent().find('tr').removeClass('w2ui-selected');
$el.addClass('w2ui-selected');
};
var html = '';
if (options.search) {
html +=
'<div style="position: absolute; top: 0px; height: 40px; left: 0px; right: 0px; border-bottom: 1px solid silver; background-color: #ECECEC; padding: 8px 5px;">'+
' <div class="w2ui-icon icon-search" style="position: absolute; margin-top: 4px; margin-left: 6px; width: 11px; background-position: left !important;"></div>'+
' <input id="menu-search" type="text" style="width: 100%; outline: none; padding-left: 20px;" onclick="event.stopPropagation();"/>'+
'</div>';
options.style += ';background-color: #ECECEC';
options.index = 0;
for (var i = 0; i < options.items.length; i++) options.items[i].hidden = false;
}
html += '<div class="menu" style="position: absolute; top: '+ (options.search ? 40 : 0) + 'px; bottom: 0px; width: 100%;">' +
getMenuHTML() +
'</div>';
var ret = $(this).w2overlay(html, options);
setTimeout(function () {
$('#w2ui-overlay'+ name +' #menu-search')
.on('keyup', change)
.on('keydown', function (event) {
// cancel tab key
if (event.keyCode === 9) { event.stopPropagation(); event.preventDefault(); }
});
if (options.search) {
if (['text', 'password'].indexOf($(obj)[0].type) != -1 || $(obj)[0].tagName.toUpperCase() == 'TEXTAREA') return;
$('#w2ui-overlay'+ name +' #menu-search').focus();
}
mresize();
}, 200);
mresize();
return ret;
}
return;
function mresize() {
setTimeout(function () {
// show selected
$('#w2ui-overlay'+ name +' tr.w2ui-selected').removeClass('w2ui-selected');
var cur = $('#w2ui-overlay'+ name +' tr[index='+ options.index +']');
var scrTop = $('#w2ui-overlay'+ name +' div.menu').scrollTop();
cur.addClass('w2ui-selected');
if (options.tmp) options.tmp.contentHeight = $('#w2ui-overlay'+ name +' table').height() + (options.search ? 50 : 10);
if (options.tmp) options.tmp.contentWidth = $('#w2ui-overlay'+ name +' table').width();
if ($('#w2ui-overlay'+ name).length > 0) $('#w2ui-overlay'+ name)[0].resize();
// scroll into view
if (cur.length > 0) {
var top = cur[0].offsetTop - 5; // 5 is margin top
var el = $('#w2ui-overlay'+ name +' div.menu');
var height = el.height();
$('#w2ui-overlay'+ name +' div.menu').scrollTop(scrTop);
if (top < scrTop || top + cur.height() > scrTop + height) {
$('#w2ui-overlay'+ name +' div.menu').animate({ 'scrollTop': top - (height - cur.height() * 2) / 2 }, 200, 'linear');
}
}
}, 1);
}
function change(event) {
var search = this.value;
var key = event.keyCode;
var cancel = false;
switch (key) {
case 13: // enter
$('#w2ui-overlay'+ name).remove();
$.fn.w2menuClick(event, options.index);
break;
case 9: // tab
case 27: // escape
$('#w2ui-overlay'+ name).remove();
$.fn.w2menuClick(event, -1);
break;
case 38: // up
options.index = w2utils.isInt(options.index) ? parseInt(options.index) : 0;
options.index--;
while (options.index > 0 && options.items[options.index].hidden) options.index--;
if (options.index === 0 && options.items[options.index].hidden) {
while (options.items[options.index] && options.items[options.index].hidden) options.index++;
}
if (options.index < 0) options.index = 0;
cancel = true;
break;
case 40: // down
options.index = w2utils.isInt(options.index) ? parseInt(options.index) : 0;
options.index++;
while (options.index < options.items.length-1 && options.items[options.index].hidden) options.index++;
if (options.index === options.items.length-1 && options.items[options.index].hidden) {
while (options.items[options.index] && options.items[options.index].hidden) options.index--;
}
if (options.index >= options.items.length) options.index = options.items.length - 1;
cancel = true;
break;
}
// filter
if (!cancel) {
var shown = 0;
for (var i = 0; i < options.items.length; i++) {
var item = options.items[i];
var prefix = '';
var suffix = '';
if (['is', 'begins with'].indexOf(options.match) !== -1) prefix = '^';
if (['is', 'ends with'].indexOf(options.match) !== -1) suffix = '$';
try {
var re = new RegExp(prefix + search + suffix, 'i');
if (re.test(item.text) || item.text === '...') item.hidden = false; else item.hidden = true;
} catch (e) {}
// do not show selected items
if (obj.type === 'enum' && $.inArray(item.id, ids) !== -1) item.hidden = true;
if (item.hidden !== true) shown++;
}
options.index = 0;
while (options.index < options.items.length-1 && options.items[options.index].hidden) options.index++;
if (shown <= 0) options.index = -1;
}
$(obj).w2menu('refresh', options);
mresize();
}
function getMenuHTML() {
if (options.spinner) {
return '<table class="w2ui-drop-menu"><tbody><tr><td style="padding: 5px 10px 10px 10px; text-align: center">'+
' <div class="w2ui-spinner" style="width: 18px; height: 18px; position: relative; top: 5px;"></div> '+
' <div style="display: inline-block; padding: 3px; color: #999;">'+ w2utils.lang('Loading...') +'</div>'+
'</td></tr></tbody></table>';
}
var count = 0;
var menu_html = '<table cellspacing="0" cellpadding="0" class="w2ui-drop-menu"><tbody>';
var img = null, icon = null;
for (var f = 0; f < options.items.length; f++) {
var mitem = options.items[f];
if (typeof mitem === 'string') {
mitem = { id: mitem, text: mitem };
} else {
if (mitem.text != null && mitem.id == null) mitem.id = mitem.text;
if (mitem.text == null && mitem.id != null) mitem.text = mitem.id;
if (mitem.caption != null) mitem.text = mitem.caption;
img = mitem.img;
icon = mitem.icon;
if (img == null) img = null; // img might be undefined
if (icon == null) icon = null; // icon might be undefined
}
if (['radio', 'check'].indexOf(options.type) != -1) {
if (mitem.checked === true) icon = 'w2ui-icon-check'; else icon = 'w2ui-icon-empty';
}
if (mitem.hidden !== true) {
var imgd = '';
var txt = mitem.text;
if (typeof options.render === 'function') txt = options.render(mitem, options);
if (img) imgd = '<td class="menu-icon"><div class="w2ui-tb-image w2ui-icon '+ img +'"></div></td>';
if (icon) imgd = '<td class="menu-icon" align="center"><span class="w2ui-icon '+ icon +'"></span></td>';
// render only if non-empty
if (txt != null && txt !== '' && !(/^-+$/.test(txt))) {
var bg = (count % 2 === 0 ? 'w2ui-item-even' : 'w2ui-item-odd');
if (options.altRows !== true) bg = '';
var colspan = 1;
if (imgd === '') colspan++;
if (mitem.count == null && mitem.hotkey == null) colspan++;
if (mitem.tooltip == null && mitem.hint != null) mitem.tooltip = mitem.hint; // for backward compatibility
menu_html +=
'<tr index="'+ f + '" style="'+ (mitem.style ? mitem.style : '') +'" '+ (mitem.tooltip ? 'title="'+ w2utils.lang(mitem.tooltip) +'"' : '') +
' class="'+ bg +' '+ (options.index === f ? 'w2ui-selected' : '') + ' ' + (mitem.disabled === true ? 'w2ui-disabled' : '') +'"'+
' onmousedown="if ('+ (mitem.disabled === true ? 'true' : 'false') + ') return;'+
' jQuery.fn.w2menuDown(event, \''+ f +'\');"'+
' onclick="event.stopPropagation(); '+
' if ('+ (mitem.disabled === true ? 'true' : 'false') + ') return;'+
' jQuery.fn.w2menuClick(event, \''+ f +'\');">'+
imgd +
' <td class="menu-text" colspan="'+ colspan +'">'+ w2utils.lang(txt) +'</td>'+
' <td class="menu-count">'+
(mitem.count != null ? '<span>' + mitem.count + '</span>' : '') +
(mitem.hotkey != null ? '<span class="hotkey">' + mitem.hotkey + '</span>' : '') +
'</td>' +
'</tr>';
count++;
} else {
// horizontal line
menu_html += '<tr><td colspan="3" style="padding: 6px; pointer-events: none"><div style="border-top: 1px solid silver;"></div></td></tr>';
}
}
options.items[f] = mitem;
}
if (count === 0) {
menu_html += '<tr><td style="padding: 13px; color: #999; text-align: center">'+ options.msgNoItems +'</div></td></tr>';
}
menu_html += "</tbody></table>";
return menu_html;
}
};
$.fn.w2color = function (options, callBack) {
var obj = this;
var el = $(this)[0];
var index = [-1, -1];
if ($.fn.w2colorPalette == null) {
$.fn.w2colorPalette = [
['000000', '555555', '888888', 'BBBBBB', 'DDDDDD', 'EEEEEE', 'F7F7F7', 'FFFFFF'],
['FF011B', 'FF9838', 'FFFD59', '01FD55', '00FFFE', '006CE7', '9B24F4', 'FF21F5'],
['FFEAEA', 'FCEFE1', 'FCF5E1', 'EBF7E7', 'E9F3F5', 'ECF4FC', 'EAE6F4', 'F5E7ED'],
['F4CCCC', 'FCE5CD', 'FFF2CC', 'D9EAD3', 'D0E0E3', 'CFE2F3', 'D9D1E9', 'EAD1DC'],
['EA9899', 'F9CB9C', 'FEE599', 'B6D7A8', 'A2C4C9', '9FC5E8', 'B4A7D6', 'D5A6BD'],
['E06666', 'F6B26B', 'FED966', '93C47D', '76A5AF', '6FA8DC', '8E7CC3', 'C27BA0'],
['CC0814', 'E69138', 'F1C232', '6AA84F', '45818E', '3D85C6', '674EA7', 'A54D79'],
['99050C', 'B45F17', 'BF901F', '37761D', '124F5C', '0A5394', '351C75', '741B47'],
// ['660205', '783F0B', '7F6011', '274E12', '0C343D', '063762', '20124D', '4C1030'],
['F2F2F2', 'F2F2F2', 'F2F2F2', 'F2F2F2', 'F2F2F2'] // custom colors (up to 4)
];
}
var pal = $.fn.w2colorPalette;
if (typeof options == 'string') options = {
color: options,
transparent: true
};
// add remove transarent color
if (options.transparent && pal[0][1] == '555555') {
pal[0].splice(1, 1);
pal[0].push('');
}
if (!options.transparent && pal[0][1] != '555555') {
pal[0].splice(1, 0, '555555');
pal[0].pop();
}
if (options.color) options.color = String(options.color).toUpperCase();
if ($('#w2ui-overlay').length === 0) {
$(el).w2overlay(getColorHTML(options), {
onHide: function () {
if (typeof callBack == 'function') callBack($(el).data('_color'));
$(el).removeData('_color');
}
});
} else { // only refresh contents
$('#w2ui-overlay .w2ui-color').parent().html(getColorHTML(options));
}
// bind events
$('#w2ui-overlay .color')
.off('.w2color')
.on('mousedown.w2color', function (event) {
var color = $(event.originalEvent.target).attr('name');
index = $(event.originalEvent.target).attr('index').split(':');
$(el).data('_color', color);
})
.on('mouseup.w2color', function () {
setTimeout(function () {
if ($("#w2ui-overlay").length > 0) $('#w2ui-overlay').removeData('keepOpen')[0].hide();
}, 10);
});
$('#w2ui-overlay input')
.off('.w2color')
.on('mousedown.w2color', function (event) {
$('#w2ui-overlay').data('keepOpen', true);
setTimeout(function () { $('#w2ui-overlay').data('keepOpen', true); }, 10);
event.stopPropagation();
})
.on('keyup.w2color', function (event) {
if (this.value !== '' && this.value[0] !== '#') this.value = '#' + this.value;
})
.on('change.w2color', function (event) {
var tmp = this.value;
if (tmp.substr(0, 1) == '#') tmp = tmp.substr(1);
if (tmp.length != 6) {
$(this).w2tag('Invalid color.');
return;
}
$.fn.w2colorPalette[pal.length - 1].unshift(tmp.toUpperCase());
$(el).w2color(options, callBack);
setTimeout(function() { $('#w2ui-overlay input')[0].focus(); }, 100);
})
.w2field('hex');
el.nav = function (direction) {
switch (direction) {
case 'up':
index[0]--;
break;
case 'down':
index[0]++;
break;
case 'right':
index[1]++;
break;
case 'left':
index[1]--;
break;
}
if (index[0] < 0) index[0] = 0;
if (index[0] > pal.length - 2) index[0] = pal.length - 2;
if (index[1] < 0) index[1] = 0;
if (index[1] > pal[0].length - 1) index[1] = pal[0].length - 1;
color = pal[index[0]][index[1]];
$(el).data('_color', color);
return color;
};
function getColorHTML(options) {
var color = options.color;
var html = '<div class="w2ui-color" onmousedown="event.stopPropagation(); event.preventDefault()">'+ // prevent default is needed otherwiser selection gets unselected
'<table cellspacing="5"><tbody>';
for (var i = 0; i < pal.length - 1; i++) {
html += '<tr>';
for (var j = 0; j < pal[i].length; j++) {
html += '<td>'+
' <div class="color '+ (pal[i][j] === '' ? 'no-color' : '') +'" style="background-color: #'+ pal[i][j] +';" ' +
' name="'+ pal[i][j] +'" index="'+ i + ':' + j +'">'+ (options.color == pal[i][j] ? '•' : ' ') +
' </div>'+
'</td>';
if (options.color == pal[i][j]) index = [i, j];
}
html += '</tr>';
if (i < 2) html += '<tr><td style="height: 8px" colspan="8"></td></tr>';
}
var tmp = pal[pal.length - 1];
html += '<tr><td style="height: 8px" colspan="8"></td></tr>'+
'<tr>'+
' <td colspan="4" style="text-align: left"><input placeholder="#FFF000" style="margin-left: 1px; width: 74px" maxlength="7"/></td>'+
' <td><div class="color" style="background-color: #'+ tmp[0] +';" name="'+ tmp[0] +'" index="8:0">'+ (options.color == tmp[0] ? '•' : ' ') +'</div></td>'+
' <td><div class="color" style="background-color: #'+ tmp[1] +';" name="'+ tmp[1] +'" index="8:0">'+ (options.color == tmp[1] ? '•' : ' ') +'</div></td>'+
' <td><div class="color" style="background-color: #'+ tmp[2] +';" name="'+ tmp[2] +'" index="8:0">'+ (options.color == tmp[2] ? '•' : ' ') +'</div></td>'+
' <td><div class="color" style="background-color: #'+ tmp[3] +';" name="'+ tmp[3] +'" index="8:0">'+ (options.color == tmp[3] ? '•' : ' ') +'</div></td>'+
'</tr>'+
'<tr><td style="height: 4px" colspan="8"></td></tr>';
html += '</tbody></table></div>';
return html;
}
};
})(jQuery);
|
const test = require('tape');
const _ = require('lodash');
module.exports = (compose) => {
const build = (num) => {
const composable = function () {};
composable.compose = function () {};
composable.compose.initializers = [() => {
return {num};
}];
return composable;
};
const buildInitializers = () => {
const composable = function () {};
composable.compose = function () {};
composable.compose.initializers = [
(options, {instance}) => {
return _.assign(instance, {
a: 'a',
override: 'a'
});
},
(options, {instance}) => {
return _.assign(instance, {
b: 'b'
});
},
(options, {instance}) => {
return _.assign(instance, {
override: 'c'
});
}
];
return composable;
};
test('compose()', nest => {
nest.test('...with no initializers', assert => {
const expected = _.size(compose().compose.initializers);
const subject = compose({initializers: [0, 'a', null, undefined, {}, NaN, /regexp/]});
const actual = _.size(subject.compose.initializers);
assert.equal(actual, expected,
'should not add any initializers');
assert.end();
});
nest.test('...with two initializers', assert => {
const subject = compose(build(1), build(2));
const initializers = subject.compose.initializers;
const actual = initializers[0]().num;
const expected = 1;
assert.equal(actual, expected,
'should add initializer from first composable');
assert.end();
});
nest.test('...with two initializers', assert => {
const subject = compose(build(1), build(2));
const initializers = subject.compose.initializers;
const actual = initializers[1]().num;
const expected = 2;
assert.equal(actual, expected,
'should add initializer from second composable');
assert.end();
});
nest.test('...with three initializers', assert => {
const subject = compose(build(1), build(2), build(3));
const initializers = subject.compose.initializers;
const actual = initializers[2]().num;
const expected = 3;
assert.equal(actual, expected,
'should add initializer from subsequent composables');
assert.end();
});
nest.test('...with identical initializers', assert => {
const stamp1 = build(1);
const stamp2 = build(2);
const stamp3 = build(3);
stamp2.compose.initializers = stamp1.compose.initializers.slice();
stamp3.compose.initializers = stamp1.compose.initializers.slice();
stamp3.compose.initializers.push(stamp3.compose.initializers[0]);
const subject = compose(stamp1, stamp2, stamp3);
const initializers = subject.compose.initializers;
const actual = initializers.length;
const expected = 1;
assert.equal(actual, expected,
'should not add same initializer more than once');
assert.end();
});
nest.test('...with identical initializers in a single argument', assert => {
const stamp1 = build(1);
stamp1.compose.initializers.push(stamp1.compose.initializers[0]);
const subject = compose(stamp1);
const initializers = subject.compose.initializers;
const actual = initializers.length;
const expected = 1;
assert.equal(actual, expected,
'should not add same initializer more than once');
assert.end();
});
});
test('stamp()', nest => {
nest.test('...with initializers', assert => {
const composable = function () {};
composable.compose = function () {};
composable.compose.properties = {
'instanceProps': true
};
composable.compose.initializers = [
function ({stampOption}, {instance, stamp, args}) {
const expected = {
correctThisValue: true,
hasOptions: true,
hasInstance: true,
hasStamp: true,
argsLength: true
};
const actual = _.pick({
correctThisValue: this === instance,
hasOptions: Boolean(stampOption),
hasInstance: Boolean(instance.instanceProps),
hasStamp: Boolean(stamp.compose),
argsLength: args.length === 3
}, _.keys(expected));
assert.deepEqual(actual, expected,
'should call initializer with correct signature');
assert.end();
}
];
const testStamp = compose(composable);
testStamp({stampOption: true}, 1, 2);
});
nest.test('...with overrides in initializer', assert => {
const stamp = buildInitializers();
const expected = {
a: 'a',
b: 'b',
override: 'c'
};
const actual = _.pick(compose(stamp)(), _.keys(expected));
assert.deepEqual(actual, expected,
'should apply initializers with last-in priority');
assert.end();
});
nest.test('...with options defaulting to empty object', assert => {
const composable = function () {};
composable.compose = function () {};
composable.compose.initializers = [
function (options) {
assert.ok(typeof options === 'object' && options !== null,
'should receive options as object');
assert.end();
}
];
const testStamp = compose(composable);
testStamp();
});
nest.test('...with args in initializer', assert => {
const expected = [0, 'string', {obj: {}}, [1, 2, 3]];
const composable = function () {};
composable.compose = function () {};
composable.compose.initializers = [
function (options, {args}) {
assert.deepEqual(args, expected,
'should receive all given arguments');
assert.end();
}
];
const testStamp = compose(composable);
testStamp(expected[0], expected[1], expected[2], expected[3]);
});
nest.test('...with `this` in initializer', assert => {
const composable = function () {};
composable.compose = function () {};
composable.compose.initializers = [
function () {
return _.assign(this, {
a: 'a'
});
}
];
const stamp = compose(composable);
const expected = {
a: 'a'
};
const actual = _.pick(compose(stamp)(), _.keys(expected));
assert.deepEqual(actual, expected,
'should use object instance as `this` inside initializers');
assert.end();
});
nest.test('...with rubbish` in initializer', assert => {
const composable = function () {};
composable.compose = function () {};
composable.compose.initializers = [0, 1, null, NaN, 'string', true, false];
const stamp = compose(composable);
stamp.compose.initializers = [0, 1, null, NaN, 'string', true, false];
const actual = compose(stamp)();
const expected = compose()();
assert.deepEqual(actual, expected,
'should avoid non functions in initializers array');
assert.end();
});
nest.test('...with accidental rubbish in initializer', assert => {
const stamp = compose();
stamp.compose.initializers = [() =>{}, 0, 1, null, NaN, 'string', true, false];
const actual = stamp();
const expected = compose()();
assert.deepEqual(actual, expected,
'should avoid non functions in initializers array');
assert.end();
});
});
};
|
/*
main module setup...
*/
define(function (require) {
'use strict';
/**
* Module dependencies
*/
var sections = require('model/sections');
var playbox = require('component/playbox');
var toolbar = require('component/toolbar');
var thumbnails = require('component/thumbnails');
var centralstage = require('component/centralstage');
var alert = require('component/alert');
/**
* Module exports
*/
return initialize;
/**
* Module function
*/
function initialize() {
sections.attachTo(document);//import first
playbox.attachTo(document);
toolbar.attachTo(document);
thumbnails.attachTo(document);
centralstage.attachTo(document);
alert.attachTo(document);
}
});
|
var mainapp = angular.module('mainapp', ['ui.router', 'ui.bootstrap', 'ngResource'])
.config(function($stateProvider, $urlRouterProvider, $interpolateProvider, $httpProvider){
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
$urlRouterProvider.otherwise("/todolist");
$stateProvider
.state('todolist', {
url: "/todolist",
views:{
"viewBody": { templateUrl: "/static/js/app/templates/todolist.html" },
"viewFooter": { templateUrl: "/static/js/app/templates/footer.html" }
}
})
.state('addtodo', {
url: "/addtodo",
views:{
"viewBody": { templateUrl: "/static/js/app/templates/addtodo.html" },
"viewFooter": { templateUrl: "/static/js/app/templates/footer.html" }
}
});
});
|
/**
*
*/
$(document)
.ready(
function() {
var taskCount = $('#tasktable tbody>tr').length;
$('.ui.dropdown').dropdown();
$("#datepicker-input").datepicker();
$('#datepicker-btn').click(function() {
$("#datepicker-input").focus();
});
$("#addTask")
.click(
function() {
var rowContent = '<tr><td><div class="ui form"><div class="field"><input type="text" name="taskDetailsDVOs[' + taskCount + '].taskName" id="taskName' + taskCount + '" placeholder="Task name" /></div></div></td>' +
'<td><div class="ui form"><div class="field"><select name="taskDetailsDVOs[' + taskCount + '].phase" id="phase' + taskCount + '"><option value=""></option><option value="coding">Requirement</option><option value="review">Design</option><option value="rework">Coding</option><option value="rework">Testing</option></select></div></div></td>' +
'<td><div class="ui form"><div class="field"><select name="taskDetailsDVOs[' + taskCount + '].activity" id="activity' + taskCount + '"><option value=""></option><option value="coding">Coding</option><option value="review">Review</option><option value="rework">Rework</option></select></div></div></td>' +
'<td><div class="ui form"><div class="field"><input type="text" name="taskDetailsDVOs[' + taskCount + '].remark" id="remark' + taskCount + '" placeholder="Remark" /></div></div></td>' +
'<td><div class="ui form"><div class="field"><input type="text" name="taskDetailsDVOs[' + taskCount + '].hour" id="hour' + taskCount + '" placeholder="Hour" /></div></div></td>' +
'<td><button id="editbtn' + taskCount + '" class="ui circular yellow compact mini icon button edtbtn"><span class="glyphicon glyphicon-pencil" style="color:black;margin-right: 0px;"></span></button> <button id="removebtn' + taskCount + '" class="ui circular inverted red compact mini icon button delbtn"><span class="glyphicon glyphicon-remove" style="margin-right: 0px;"></span></button></td></tr>';
$(rowContent).insertAfter(
'#tasktable tbody>tr:last');
$('#tasktable tbody>tr:last input')
.val('');
$('#tasktable tbody>tr:last select')
.val('');
taskCount++;
return false;
});
$('body').on('click', '.delbtn', function() {
$(this).closest('tr').remove();
});
$('.ui.form').form({
inline : true,
on : 'blur'
});
/*$('form').bind('submit', function () {
$(this).find(':input').prop('disabled', false);
$(this).find(':select').prop('disabled', false);
});*/
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.