code
stringlengths 2
1.05M
|
---|
/*!
* # Semantic UI 1.11.2 - Dimmer
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2014 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ( $, window, document, undefined ) {
"use strict";
$.fn.dimmer = function(parameters) {
var
$allModules = $(this),
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
returnedValue
;
$allModules
.each(function() {
var
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.dimmer.settings, parameters)
: $.extend({}, $.fn.dimmer.settings),
selector = settings.selector,
namespace = settings.namespace,
className = settings.className,
error = settings.error,
eventNamespace = '.' + namespace,
moduleNamespace = 'module-' + namespace,
moduleSelector = $allModules.selector || '',
clickEvent = ('ontouchstart' in document.documentElement)
? 'touchstart'
: 'click',
$module = $(this),
$dimmer,
$dimmable,
element = this,
instance = $module.data(moduleNamespace),
module
;
module = {
preinitialize: function() {
if( module.is.dimmer() ) {
$dimmable = $module.parent();
$dimmer = $module;
}
else {
$dimmable = $module;
if( module.has.dimmer() ) {
if(settings.dimmerName) {
$dimmer = $dimmable.children(selector.dimmer).filter('.' + settings.dimmerName);
}
else {
$dimmer = $dimmable.children(selector.dimmer);
}
}
else {
$dimmer = module.create();
}
}
},
initialize: function() {
module.debug('Initializing dimmer', settings);
if(settings.on == 'hover') {
$dimmable
.on('mouseenter' + eventNamespace, module.show)
.on('mouseleave' + eventNamespace, module.hide)
;
}
else if(settings.on == 'click') {
$dimmable
.on(clickEvent + eventNamespace, module.toggle)
;
}
if( module.is.page() ) {
module.debug('Setting as a page dimmer', $dimmable);
module.set.pageDimmer();
}
if( module.is.closable() ) {
module.verbose('Adding dimmer close event', $dimmer);
$dimmer
.on(clickEvent + eventNamespace, module.event.click)
;
}
module.set.dimmable();
module.instantiate();
},
instantiate: function() {
module.verbose('Storing instance of module', module);
instance = module;
$module
.data(moduleNamespace, instance)
;
},
destroy: function() {
module.verbose('Destroying previous module', $dimmer);
$module
.removeData(moduleNamespace)
;
$dimmable
.off(eventNamespace)
;
$dimmer
.off(eventNamespace)
;
},
event: {
click: function(event) {
module.verbose('Determining if event occured on dimmer', event);
if( $dimmer.find(event.target).length === 0 || $(event.target).is(selector.content) ) {
module.hide();
event.stopImmediatePropagation();
}
}
},
addContent: function(element) {
var
$content = $(element)
;
module.debug('Add content to dimmer', $content);
if($content.parent()[0] !== $dimmer[0]) {
$content.detach().appendTo($dimmer);
}
},
create: function() {
var
$element = $( settings.template.dimmer() )
;
if(settings.variation) {
module.debug('Creating dimmer with variation', settings.variation);
$element.addClass(className.variation);
}
if(settings.dimmerName) {
module.debug('Creating named dimmer', settings.dimmerName);
$element.addClass(settings.dimmerName);
}
$element
.appendTo($dimmable)
;
return $element;
},
show: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
module.debug('Showing dimmer', $dimmer, settings);
if( (!module.is.dimmed() || module.is.animating()) && module.is.enabled() ) {
module.animate.show(callback);
settings.onShow.call(element);
settings.onChange.call(element);
}
else {
module.debug('Dimmer is already shown or disabled');
}
},
hide: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
if( module.is.dimmed() || module.is.animating() ) {
module.debug('Hiding dimmer', $dimmer);
module.animate.hide(callback);
settings.onHide.call(element);
settings.onChange.call(element);
}
else {
module.debug('Dimmer is not visible');
}
},
toggle: function() {
module.verbose('Toggling dimmer visibility', $dimmer);
if( !module.is.dimmed() ) {
module.show();
}
else {
module.hide();
}
},
animate: {
show: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
if(settings.useCSS && $.fn.transition !== undefined && $dimmer.transition('is supported')) {
if(settings.opacity !== 'auto') {
module.set.opacity();
}
$dimmer
.transition({
animation : settings.transition + ' in',
queue : false,
duration : module.get.duration(),
useFailSafe : true,
onStart : function() {
module.set.dimmed();
},
onComplete : function() {
module.set.active();
callback();
}
})
;
}
else {
module.verbose('Showing dimmer animation with javascript');
module.set.dimmed();
if(settings.opacity == 'auto') {
settings.opacity = 0.8;
}
$dimmer
.stop()
.css({
opacity : 0,
width : '100%',
height : '100%'
})
.fadeTo(module.get.duration(), settings.opacity, function() {
$dimmer.removeAttr('style');
module.set.active();
callback();
})
;
}
},
hide: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
if(settings.useCSS && $.fn.transition !== undefined && $dimmer.transition('is supported')) {
module.verbose('Hiding dimmer with css');
$dimmer
.transition({
animation : settings.transition + ' out',
queue : false,
duration : module.get.duration(),
useFailSafe : true,
onStart : function() {
module.remove.dimmed();
},
onComplete : function() {
module.remove.active();
callback();
}
})
;
}
else {
module.verbose('Hiding dimmer with javascript');
module.remove.dimmed();
$dimmer
.stop()
.fadeOut(module.get.duration(), function() {
module.remove.active();
$dimmer.removeAttr('style');
callback();
})
;
}
}
},
get: {
dimmer: function() {
return $dimmer;
},
duration: function() {
if(typeof settings.duration == 'object') {
if( module.is.active() ) {
return settings.duration.hide;
}
else {
return settings.duration.show;
}
}
return settings.duration;
}
},
has: {
dimmer: function() {
if(settings.dimmerName) {
return ($module.children(selector.dimmer).filter('.' + settings.dimmerName).length > 0);
}
else {
return ( $module.children(selector.dimmer).length > 0 );
}
}
},
is: {
active: function() {
return $dimmer.hasClass(className.active);
},
animating: function() {
return ( $dimmer.is(':animated') || $dimmer.hasClass(className.animating) );
},
closable: function() {
if(settings.closable == 'auto') {
if(settings.on == 'hover') {
return false;
}
return true;
}
return settings.closable;
},
dimmer: function() {
return $module.is(selector.dimmer);
},
dimmable: function() {
return $module.is(selector.dimmable);
},
dimmed: function() {
return $dimmable.hasClass(className.dimmed);
},
disabled: function() {
return $dimmable.hasClass(className.disabled);
},
enabled: function() {
return !module.is.disabled();
},
page: function () {
return $dimmable.is('body');
},
pageDimmer: function() {
return $dimmer.hasClass(className.pageDimmer);
}
},
can: {
show: function() {
return !$dimmer.hasClass(className.disabled);
}
},
set: {
opacity: function(opacity) {
var
opacity = settings.opacity || opacity,
color = $dimmer.css('background-color'),
colorArray = color.split(','),
isRGBA = (colorArray && colorArray.length == 4)
;
if(isRGBA) {
colorArray[3] = opacity + ')';
color = colorArray.join(',');
}
else {
color = 'rgba(0, 0, 0, ' + opacity + ')';
}
module.debug('Setting opacity to', opacity);
$dimmer.css('background-color', color);
},
active: function() {
$dimmer.addClass(className.active);
},
dimmable: function() {
$dimmable.addClass(className.dimmable);
},
dimmed: function() {
$dimmable.addClass(className.dimmed);
},
pageDimmer: function() {
$dimmer.addClass(className.pageDimmer);
},
disabled: function() {
$dimmer.addClass(className.disabled);
}
},
remove: {
active: function() {
$dimmer
.removeClass(className.active)
;
},
dimmed: function() {
$dimmable.removeClass(className.dimmed);
},
disabled: function() {
$dimmer.removeClass(className.disabled);
}
},
setting: function(name, value) {
module.debug('Changing setting', name, value);
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
settings[name] = value;
}
else {
return settings[name];
}
},
internal: function(name, value) {
if( $.isPlainObject(name) ) {
$.extend(true, module, name);
}
else if(value !== undefined) {
module[name] = value;
}
else {
return module[name];
}
},
debug: function() {
if(settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.debug.apply(console, arguments);
}
}
},
verbose: function() {
if(settings.verbose && settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.verbose.apply(console, arguments);
}
}
},
error: function() {
module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
module.error.apply(console, arguments);
},
performance: {
log: function(message) {
var
currentTime,
executionTime,
previousTime
;
if(settings.performance) {
currentTime = new Date().getTime();
previousTime = time || currentTime;
executionTime = currentTime - previousTime;
time = currentTime;
performance.push({
'Name' : message[0],
'Arguments' : [].slice.call(message, 1) || '',
'Element' : element,
'Execution Time' : executionTime
});
}
clearTimeout(module.performance.timer);
module.performance.timer = setTimeout(module.performance.display, 100);
},
display: function() {
var
title = settings.name + ':',
totalTime = 0
;
time = false;
clearTimeout(module.performance.timer);
$.each(performance, function(index, data) {
totalTime += data['Execution Time'];
});
title += ' ' + totalTime + 'ms';
if(moduleSelector) {
title += ' \'' + moduleSelector + '\'';
}
if($allModules.length > 1) {
title += ' ' + '(' + $allModules.length + ')';
}
if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
console.groupCollapsed(title);
if(console.table) {
console.table(performance);
}
else {
$.each(performance, function(index, data) {
console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
});
}
console.groupEnd();
}
performance = [];
}
},
invoke: function(query, passedArguments, context) {
var
object = instance,
maxDepth,
found,
response
;
passedArguments = passedArguments || queryArguments;
context = element || context;
if(typeof query == 'string' && object !== undefined) {
query = query.split(/[\. ]/);
maxDepth = query.length - 1;
$.each(query, function(depth, value) {
var camelCaseValue = (depth != maxDepth)
? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
: query
;
if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
object = object[camelCaseValue];
}
else if( object[camelCaseValue] !== undefined ) {
found = object[camelCaseValue];
return false;
}
else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
object = object[value];
}
else if( object[value] !== undefined ) {
found = object[value];
return false;
}
else {
module.error(error.method, query);
return false;
}
});
}
if ( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
module.preinitialize();
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.dimmer.settings = {
name : 'Dimmer',
namespace : 'dimmer',
debug : false,
verbose : true,
performance : true,
// name to distinguish between multiple dimmers in context
dimmerName : false,
// whether to add a variation type
variation : false,
// whether to bind close events
closable : 'auto',
// whether to use css animations
useCSS : true,
// css animation to use
transition : 'fade',
// event to bind to
on : false,
// overriding opacity value
opacity : 'auto',
// transition durations
duration : {
show : 500,
hide : 500
},
onChange : function(){},
onShow : function(){},
onHide : function(){},
error : {
method : 'The method you called is not defined.'
},
selector: {
dimmable : '.dimmable',
dimmer : '.ui.dimmer',
content : '.ui.dimmer > .content, .ui.dimmer > .content > .center'
},
template: {
dimmer: function() {
return $('<div />').attr('class', 'ui dimmer');
}
},
className : {
active : 'active',
animating : 'animating',
dimmable : 'dimmable',
dimmed : 'dimmed',
disabled : 'disabled',
hide : 'hide',
pageDimmer : 'page',
show : 'show'
}
};
})( jQuery, window , document );
|
/* global hexo */
'use strict';
hexo.extend.filter.register('after_generate', () => {
const theme = hexo.theme.config;
if (!theme.minify) return;
const lists = hexo.route.list();
const velocity = lists.filter(list => list.includes('lib/velocity'));
const fontawesome = lists.filter(list => list.includes('lib/font-awesome'));
if (!theme.bookmark.enable) {
hexo.route.remove('js/bookmark.js');
}
if (!theme.motion.enable) {
hexo.route.remove('js/motion.js');
velocity.forEach(path => {
hexo.route.remove(path);
});
}
if (theme.motion.enable && theme.vendors.velocity && theme.vendors.velocity_ui) {
velocity.forEach(path => {
hexo.route.remove(path);
});
}
if (theme.vendors.fontawesome) {
fontawesome.forEach(path => {
hexo.route.remove(path);
});
}
if (theme.vendors.anime) {
hexo.route.remove('lib/anime.min.js');
}
if (!theme.algolia_search.enable) {
hexo.route.remove('js/algolia-search.js');
}
if (!theme.local_search.enable) {
hexo.route.remove('js/local-search.js');
}
if (theme.scheme === 'Muse' || theme.scheme === 'Mist') {
hexo.route.remove('js/schemes/pisces.js');
} else if (theme.scheme === 'Pisces' || theme.scheme === 'Gemini') {
hexo.route.remove('js/schemes/muse.js');
}
});
|
/**
* Gumby Parallax
*/
!function() {
'use strict';
// define module class and init only if we're on touch devices
if(Gumby.gumbyTouch) {
return;
}
function Parallax($el) {
Gumby.debug('Initializing Parallax', $el);
this.$el = $el;
this.$holder = {};
this.ratio = this.offset = 0;
var scope = this;
this.setup();
// re-initialize module
this.$el.on('gumby.initialize', function() {
Gumby.debug('Re-initializing Parallax', scope.$el);
scope.setup();
});
// set starting position of background image
this.setPosition();
this.$holder.scroll(function() {
scope.scroll();
});
// this should update windows that load scrolled
this.scroll();
}
Parallax.prototype.setup = function() {
this.$holder = Gumby.selectAttr.apply(this.$el, ['holder']);
this.ratio = Number(Gumby.selectAttr.apply(this.$el, ['parallax'])) || 1;
this.offset = Number(Gumby.selectAttr.apply(this.$el, ['offset'])) || 0;
// calculate starting bg position
this.startPos = ((this.$el.offset().top - this.offset) * this.ratio);
// find holder element
if(this.$holder) {
this.$holder = $(this.$holder);
}
// no holder element so default to window
if(!this.$holder || !this.$holder.length) {
this.$holder = $(window);
// holder is set and not window so add to offset calc
} else {
// calculate starting bg position
this.startPos -= this.$holder.offset().top;
}
};
// update bg position based on scroll and parallax ratio
Parallax.prototype.scroll = function() {
this.setPosition(this.startPos - (this.$holder.scrollTop() * this.ratio));
};
// set background y axis position with 50% x axis
Parallax.prototype.setPosition = function(yPos) {
this.$el.css('backgroundPosition', '50% '+yPos+'px');
};
// add initialisation
Gumby.addInitalisation('parallax', function() {
// wait for window to load as this could effect position of element
$(window).load(function() {
setTimeout(function() {
$('.parallax').each(function() {
var $this = $(this);
// this element has already been initialized
if($this.data('isParallax')) {
return true;
}
// mark element as initialized
$this.data('isParallax', true);
new Parallax($this);
});
}, 200);
});
});
// register UI module
Gumby.UIModule({
module: 'parallax',
events: [],
init: function() {
Gumby.initialize('parallax');
}
});
}();
|
steal('can/util', 'can/observe', function(can, Observe) {
var unique = function( items ) {
var collect = [];
// check unique property, if it isn't there, add to collect
can.each(items, function( item ) {
if (!item["__u Nique"] ) {
collect.push(item);
item["__u Nique"] = 1;
}
});
// remove unique
return can.each(collect, function( item ) {
delete item["__u Nique"];
});
}
can.extend(can.Observe.prototype,{
/**
* Returns a unique identifier for the observe instance. For example:
*
* @codestart
* new Todo({id: 5}).identity() //-> 'todo_5'
* @codeend
*
* Typically this is used in an element's shortName property so you can find all elements
* for a observe with [$.Observe.prototype.elements elements].
*
* If your observe id has special characters that are not permitted as CSS class names,
* you can set the `escapeIdentity` on the observe instance's constructor
* which will `encodeURIComponent` the `id` of the observe.
*
* @return {String}
*/
identity: function() {
var constructor = this.constructor,
id = this[constructor.id] || this._cid.replace(/./, ''),
name = constructor._fullName ? constructor._fullName + '_' : '';
return (name + (constructor.escapeIdentity ? encodeURIComponent(id) : id)).replace(/ /g, '_');
},
/**
* Returns elements that represent this observe instance. For this to work, your element's should
* us the [$.Observe.prototype.identity identity] function in their class name. Example:
*
* <div class='todo <%= todo.identity() %>'> ... </div>
*
* This also works if you hooked up the observe:
*
* <div <%= todo %>> ... </div>
*
* Typically, you'll use this as a response to a Observe Event:
*
* "{Todo} destroyed": function(Todo, event, todo){
* todo.elements(this.element).remove();
* }
*
*
* @param {String|jQuery|element} context If provided, only elements inside this element
* that represent this observe will be returned.
*
* @return {jQuery} Returns a jQuery wrapped nodelist of elements that have this observe instances
* identity in their class name.
*/
elements: function( context ) {
var id = this.identity();
if( this.constructor.escapeIdentity ) {
id = id.replace(/([ #;&,.+*~\'%:"!^$[\]()=>|\/])/g,'\\$1')
}
return can.$("." + id, context);
},
hookup: function( el ) {
var shortName = this.constructor._shortName || '',
$el = can.$(el),
observes;
(observes = can.data($el, "instances") )|| can.data($el, "instances", observes = {});
can.addClass($el,shortName + " " + this.identity());
observes[shortName] = this;
}
});
/**
* @add jQuery.fn
*/
// break
/**
* @function instances
* Returns a list of observes. If the observes are of the same
* type, and have a [$.Observe.List], it will return
* the observes wrapped with the list.
*
* @codestart
* $(".recipes").instances() //-> [recipe, ...]
* @codeend
*
* @param {jQuery.Class} [type] if present only returns observes of the provided type.
* @return {Array|$.Observe.List} returns an array of observes instances that are represented by the contained elements.
*/
$.fn.instances = function( type ) {
//get it from the data
var collection = [],
kind, ret, retType;
this.each(function() {
can.each($.data(this, "instances") || {}, function( instance, name ) {
//either null or the list type shared by all classes
kind = kind === undefined ? instance.constructor.List || null : (instance.constructor.List === kind ? kind : null);
collection.push(instance);
});
});
ret = kind ? new kind : new can.Observe.List;
ret.push.apply(ret, unique(collection));
return ret;
};
/**
* @function instance
*
* Returns the first observe instance found from [jQuery.fn.instances] or
* sets the instance on an element.
*
* //gets an instance
* ".edit click" : function(el) {
* el.closest('.todo').instance().destroy()
* },
* // sets an instance
* list : function(items){
* var el = this.element;
* $.each(item, function(item){
* $('<div/>').instance(item)
* .appendTo(el)
* })
* }
*
* @param {Object} [type] The type of instance to return. If a instance is provided
* it will add the instance to the element.
*/
$.fn.instance = function( type ) {
if ( type && type instanceof can.Observe ) {
type.hookup(this[0]);
return this;
} else {
return this.instances.apply(this, arguments)[0];
}
};
return can.Observe;
})
|
/*!
* CanJS - 2.0.3
* http://canjs.us/
* Copyright (c) 2013 Bitovi
* Tue, 26 Nov 2013 18:21:22 GMT
* Licensed MIT
* Includes: CanJS default build
* Download from: http://canjs.us/
*/
define(["jquery", "can/util/library", "can/control"], function($, can) {
//used to determine if a control instance is one of controllers
//controllers can be strings or classes
var i,
isAControllerOf = function( instance, controllers ) {
var name = instance.constructor.pluginName || instance.constructor._shortName;
for ( i = 0; i < controllers.length; i++ ) {
if ( typeof controllers[i] == 'string' ? name == controllers[i] : instance instanceof controllers[i] ) {
return true;
}
}
return false;
},
makeArray = can.makeArray,
old = can.Control.setup;
/*
* static
*/
can.Control.setup = function() {
// if you didn't provide a name, or are control, don't do anything
if ( this !== can.Control ) {
/**
* @property {String} can.Control.plugin.static.pluginName pluginName
* @parent can.Control.plugin
*
* @description
*
* Allows you to define the name of the jQuery plugin.
*
* @body
*
* Setting the static `pluginName` property allows you to override the default name
* with your own.
*
* var Filler = can.Control({
* pluginName: 'fillWith'
* },{});
*
* $("#foo").fillWith();
*
* If you don't provide a `pluginName`, the control falls back to the
* [can.Construct.fullName fullName] attribute:
*
* can.Control('Ui.Layout.FillWith', {}, {});
* $("#foo").ui_layout_fill_with();
*
*/
var pluginName = this.pluginName || this._fullName;
// create jQuery plugin
if(pluginName !== 'can_control'){
this.plugin(pluginName);
}
old.apply(this, arguments);
}
};
/*
* prototype
*/
$.fn.extend({
/**
* @function jQuery.fn.controls jQuery.fn.controls
* @parent can.Control.plugin
* @description Get the Controls associated with elements.
* @signature `jQuery.fn.controls([type])`
* @param {String|can.Control} [control] The type of Controls to find.
* @return {can.Control} The controls associated with the given elements.
*
* @body
* When the widget is initialized, the plugin control creates an array
* of control instance(s) with the DOM element it was initialized on using
* [can.data] method.
*
* The `controls` method allows you to get the control instance(s) for any element
* either by their type or pluginName.
*
* var MyBox = can.Control({
* pluginName : 'myBox'
* }, {});
*
* var MyClock = can.Control({
* pluginName : 'myClock'
* }, {});
*
*
* //- Inits the widgets
* $('.widgets:eq(0)').myBox();
* $('.widgets:eq(1)').myClock();
*
* $('.widgets').controls() //-> [ MyBox, MyClock ]
* $('.widgets').controls('myBox') // -> [MyBox]
* $('.widgets').controls(MyClock) // -> MyClock
*
*/
controls: function() {
var controllerNames = makeArray(arguments),
instances = [],
controls, c, cname;
//check if arguments
this.each(function() {
controls = can.$(this).data("controls");
if(!controls){
return;
}
for(var i=0; i<controls.length; i++){
c = controls[i];
if (!controllerNames.length || isAControllerOf(c, controllerNames) ) {
instances.push(c);
}
}
});
return instances;
},
/**
* @function jQuery.fn.control jQuery.fn.control
* @parent can.Control.plugin
* @description Get the Control associated with elements.
* @signature `jQuery.fn.control([type])`
* @param {String|can.Control} [control] The type of Control to find.
* @return {can.Control} The first control found.
*
* @body
* This is the same as [jQuery.fn.controls $().controls] except that
* it only returns the first Control found.
*
* //- Init MyBox widget
* $('.widgets').my_box();
*
* <div class="widgets my_box" />
*
* $('.widgets').controls() //-> MyBox
*/
control: function( control ) {
return this.controls.apply(this, arguments)[0];
}
});
can.Control.plugin = function(pluginname){
var control = this;
if (!$.fn[pluginname]) {
$.fn[pluginname] = function(options){
var args = makeArray(arguments), //if the arg is a method on this control
isMethod = typeof options == "string" && $.isFunction(control.prototype[options]), meth = args[0],
returns;
this.each(function(){
//check if created
var plugin = can.$(this).control(control);
if (plugin) {
if (isMethod) {
// call a method on the control with the remaining args
returns = plugin[meth].apply(plugin, args.slice(1));
}
else {
// call the plugin's update method
plugin.update.apply(plugin, args);
}
}
else {
//create a new control instance
control.newInstance.apply(control, [this].concat(args));
}
});
return returns !== undefined ? returns : this;
};
}
}
/**
* @function can.Control.plugin.prototype.update update
* @parent can.Control.plugin
*
* @description Reconfigure a control.
* @signature `update(newOptions)`
* @param {Object} newOptions Options to merge into the current options.
*
* @body
* Update extends [can.Control.prototype.options options]
* with the `options` argument and rebinds all events. It
* re-configures the control.
*
* For example, the following control wraps a recipe form. When the form
* is submitted, it creates the recipe on the server. When the recipe
* is `created`, it resets the form with a new instance.
*
* var Creator = can.Control({
* "{recipe} created" : function(){
* this.update({recipe : new Recipe()});
* this.element[0].reset();
* this.element.find("[type=submit]").val("Create Recipe")
* },
* "submit" : function(el, ev){
* ev.preventDefault();
* var recipe = this.options.recipe;
* recipe.attrs( this.element.formParams() );
* this.element.find("[type=submit]").val("Saving...")
* recipe.save();
* }
* });
*
* $('#createRecipes').creator({ recipe : new Recipe() })
*
* *Update* is called if a control's plugin helper is called with the plugin options on an element
* that already has a control instance of the same type. If you want to implement your
* own update method make sure to call the old one either using the [can.Construct.super super] plugin or
* by calling `can.Control.prototype.update.apply(this, arguments);`.
* For example, you can change the content of the control element every time the options change:
*
* var Plugin = can.Control({
* pluginName: 'myPlugin'
* }, {
* init : function(el, options) {
* this.updateCount = 0;
* this.update({
* text : 'Initialized'
* });
* },
* update : function(options) {
* // Call the can.Control update first.
* // Use this._super when using can/construct/super
* can.Control.prototype.update.call(this, options);
* this.element.html(this.options.text + ' ' +
* (++this.updateCount) + ' times');
* }
* });
*
* $('#control').myPlugin();
* $('#control').html();
* // Initialized. Updated 1 times
*
* $('#control').myPlugin({ text : 'Calling update. Updated' });
* $('#control').html();
* // Calling update. Updated 2 times
*
* @demo can/control/plugin/demo-update.html
*
* @param {Object} options A list of options to merge with
* [can.Control.prototype.options this.options]. Often this method
* is called by the [can.Control.plugin jQuery helper function].
*/
can.Control.prototype.update = function( options ) {
can.extend(this.options, options);
this.on();
};
return can;
});
|
!function(root, factory) {
"function" == typeof define && define.amd ? // AMD. Register as an anonymous module unless amdModuleId is set
define([], function() {
return root.svg4everybody = factory();
}) : "object" == typeof module && module.exports ? // Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory() : root.svg4everybody = factory();
}(this, function() {
/*! svg4everybody v2.1.9 | github.com/jonathantneal/svg4everybody */
function embed(parent, svg, target) {
// if the target exists
if (target) {
// create a document fragment to hold the contents of the target
var fragment = document.createDocumentFragment(), viewBox = !svg.hasAttribute("viewBox") && target.getAttribute("viewBox");
// conditionally set the viewBox on the svg
viewBox && svg.setAttribute("viewBox", viewBox);
// copy the contents of the clone into the fragment
for (// clone the target
var clone = target.cloneNode(!0); clone.childNodes.length; ) {
fragment.appendChild(clone.firstChild);
}
// append the fragment into the svg
parent.appendChild(fragment);
}
}
function loadreadystatechange(xhr) {
// listen to changes in the request
xhr.onreadystatechange = function() {
// if the request is ready
if (4 === xhr.readyState) {
// get the cached html document
var cachedDocument = xhr._cachedDocument;
// ensure the cached html document based on the xhr response
cachedDocument || (cachedDocument = xhr._cachedDocument = document.implementation.createHTMLDocument(""),
cachedDocument.body.innerHTML = xhr.responseText, xhr._cachedTarget = {}), // clear the xhr embeds list and embed each item
xhr._embeds.splice(0).map(function(item) {
// get the cached target
var target = xhr._cachedTarget[item.id];
// ensure the cached target
target || (target = xhr._cachedTarget[item.id] = cachedDocument.getElementById(item.id)),
// embed the target into the svg
embed(item.parent, item.svg, target);
});
}
}, // test the ready state change immediately
xhr.onreadystatechange();
}
function svg4everybody(rawopts) {
function oninterval() {
// while the index exists in the live <use> collection
for (// get the cached <use> index
var index = 0; index < uses.length; ) {
// get the current <use>
var use = uses[index], parent = use.parentNode, svg = getSVGAncestor(parent), src = use.getAttribute("xlink:href") || use.getAttribute("href");
if (!src && opts.attributeName && (src = use.getAttribute(opts.attributeName)),
svg && src) {
// if running with legacy support
if (nosvg) {
// create a new fallback image
var img = document.createElement("img");
// force display in older IE
img.style.cssText = "display:inline-block;height:100%;width:100%", // set the fallback size using the svg size
img.setAttribute("width", svg.getAttribute("width") || svg.clientWidth), img.setAttribute("height", svg.getAttribute("height") || svg.clientHeight),
// set the fallback src
img.src = fallback(src, svg, use), // replace the <use> with the fallback image
parent.replaceChild(img, use);
} else {
if (polyfill) {
if (!opts.validate || opts.validate(src, svg, use)) {
// remove the <use> element
parent.removeChild(use);
// parse the src and get the url and id
var srcSplit = src.split("#"), url = srcSplit.shift(), id = srcSplit.join("#");
// if the link is external
if (url.length) {
// get the cached xhr request
var xhr = requests[url];
// ensure the xhr request exists
xhr || (xhr = requests[url] = new XMLHttpRequest(), xhr.open("GET", url), xhr.send(),
xhr._embeds = []), // add the svg and id as an item to the xhr embeds list
xhr._embeds.push({
parent: parent,
svg: svg,
id: id
}), // prepare the xhr ready state change event
loadreadystatechange(xhr);
} else {
// embed the local id into the svg
embed(parent, svg, document.getElementById(id));
}
} else {
// increase the index when the previous value was not "valid"
++index, ++numberOfSvgUseElementsToBypass;
}
}
}
} else {
// increase the index when the previous value was not "valid"
++index;
}
}
// continue the interval
(!uses.length || uses.length - numberOfSvgUseElementsToBypass > 0) && requestAnimationFrame(oninterval, 67);
}
var nosvg, fallback, opts = Object(rawopts);
// configure the fallback method
fallback = opts.fallback || function(src) {
return src.replace(/\?[^#]+/, "").replace("#", ".").replace(/^\./, "") + ".png" + (/\?[^#]+/.exec(src) || [ "" ])[0];
}, // set whether to shiv <svg> and <use> elements and use image fallbacks
nosvg = "nosvg" in opts ? opts.nosvg : /\bMSIE [1-8]\b/.test(navigator.userAgent),
// conditionally shiv <svg> and <use>
nosvg && (document.createElement("svg"), document.createElement("use"));
// set whether the polyfill will be activated or not
var polyfill, olderIEUA = /\bMSIE [1-8]\.0\b/, newerIEUA = /\bTrident\/[567]\b|\bMSIE (?:9|10)\.0\b/, webkitUA = /\bAppleWebKit\/(\d+)\b/, olderEdgeUA = /\bEdge\/12\.(\d+)\b/, edgeUA = /\bEdge\/.(\d+)\b/, inIframe = window.top !== window.self;
polyfill = "polyfill" in opts ? opts.polyfill : olderIEUA.test(navigator.userAgent) || newerIEUA.test(navigator.userAgent) || (navigator.userAgent.match(olderEdgeUA) || [])[1] < 10547 || (navigator.userAgent.match(webkitUA) || [])[1] < 537 || edgeUA.test(navigator.userAgent) && inIframe;
// create xhr requests object
var requests = {}, requestAnimationFrame = window.requestAnimationFrame || setTimeout, uses = document.getElementsByTagName("use"), numberOfSvgUseElementsToBypass = 0;
// conditionally start the interval if the polyfill is active
polyfill && oninterval();
}
function getSVGAncestor(node) {
for (var svg = node; "svg" !== svg.nodeName.toLowerCase() && (svg = svg.parentNode); ) {}
return svg;
}
return svg4everybody;
});
|
/* eslint-disable */
// adapted based on rackt/history (MIT)
// Node 0.10+
var execSync = require('child_process').execSync;
var stat = require('fs').stat;
// Node 0.10 check
if (!execSync) {
execSync = require('sync-exec');
}
function exec(command) {
execSync(command, {
stdio: [0, 1, 2]
});
}
stat('dist-modules', function(error, stat) {
// Skip building on Travis
if (process.env.TRAVIS) {
return;
}
if (error || !stat.isDirectory()) {
exec('npm i babel-cli babel-preset-es2015 babel-preset-react');
exec('npm run dist:modules');
}
});
|
/*
YUI 3.17.2 (build 9c3c78e)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('align-plugin', function (Y, NAME) {
/**
* Provides advanced positioning support for Node via a Plugin
* for centering and alignment.
* @module align-plugin
*/
var OFFSET_WIDTH = 'offsetWidth',
OFFSET_HEIGHT = 'offsetHeight',
undefined = undefined;
/**
* Node plugin which can be used to align a node with another node,
* region, or the viewport.
*
* @class Plugin.Align
* @param {Object} User configuration object
*/
function Align(config) {
if (config.host) {
this._host = config.host;
}
}
Align.prototype = {
/**
* Aligns node with a point on another node or region.
* Possible alignment points are:
* <dl>
* <dt>tl</dt>
* <dd>top left</dd>
* <dt>tr</dt>
* <dd>top right</dd>
* <dt>bl</dt>
* <dd>bottom left</dd>
* <dt>br</dt>
* <dd>bottom right</dd>
* <dt>tc</dt>
* <dd>top center</dd>
* <dt>bc</dt>
* <dd>bottom center</dd>
* <dt>rc</dt>
* <dd>right center</dd>
* <dt>lc</dt>
* <dd>left center</dd>
* <dt>cc</dt>
* <dd>center center</dd>
* </dl>
* @method to
* @param region {String|Node|HTMLElement|Object} The node or
* region to align with. Defaults to the viewport region.
* @param regionPoint {String} The point of the region to align with.
* @param point {String} The point of the node aligned to the region.
* @param resize {Boolean} Whether or not the node should re-align when
* the window is resized. Defaults to false.
*/
to: function(region, regionPoint, point, syncOnResize) {
// cache original args for syncing
this._syncArgs = Y.Array(arguments);
if (region.top === undefined) {
region = Y.one(region).get('region');
}
if (region) {
var xy = [region.left, region.top],
offxy = [region.width, region.height],
points = Align.points,
node = this._host,
NULL = null,
size = node.getAttrs([OFFSET_HEIGHT, OFFSET_WIDTH]),
nodeoff = [0 - size[OFFSET_WIDTH], 0 - size[OFFSET_HEIGHT]], // reverse offsets
regionFn0 = regionPoint ? points[regionPoint.charAt(0)]: NULL,
regionFn1 = (regionPoint && regionPoint !== 'cc') ? points[regionPoint.charAt(1)] : NULL,
nodeFn0 = point ? points[point.charAt(0)] : NULL,
nodeFn1 = (point && point !== 'cc') ? points[point.charAt(1)] : NULL;
if (regionFn0) {
xy = regionFn0(xy, offxy, regionPoint);
}
if (regionFn1) {
xy = regionFn1(xy, offxy, regionPoint);
}
if (nodeFn0) {
xy = nodeFn0(xy, nodeoff, point);
}
if (nodeFn1) {
xy = nodeFn1(xy, nodeoff, point);
}
if (xy && node) {
node.setXY(xy);
}
this._resize(syncOnResize);
}
return this;
},
sync: function() {
this.to.apply(this, this._syncArgs);
return this;
},
_resize: function(add) {
var handle = this._handle;
if (add && !handle) {
this._handle = Y.on('resize', this._onresize, window, this);
} else if (!add && handle) {
handle.detach();
}
},
_onresize: function() {
var self = this;
setTimeout(function() { // for performance
self.sync();
});
},
/**
* Aligns the center of a node to the center of another node or region.
* @method center
* @param region {Node|HTMLElement|Object} optional The node or
* region to align with. Defaults to the viewport region.
* the window is resized. If centering to viewport, this defaults
* to true, otherwise default is false.
*/
center: function(region, resize) {
this.to(region, 'cc', 'cc', resize);
return this;
},
/**
* Removes the resize handler, if any. This is called automatically
* when unplugged from the host node.
* @method destroy
*/
destroy: function() {
var handle = this._handle;
if (handle) {
handle.detach();
}
}
};
Align.points = {
't': function(xy, off) {
return xy;
},
'r': function(xy, off) {
return [xy[0] + off[0], xy[1]];
},
'b': function(xy, off) {
return [xy[0], xy[1] + off[1]];
},
'l': function(xy, off) {
return xy;
},
'c': function(xy, off, point) {
var axis = (point[0] === 't' || point[0] === 'b') ? 0 : 1,
ret, val;
if (point === 'cc') {
ret = [xy[0] + off[0] / 2, xy[1] + off[1] / 2];
} else {
val = xy[axis] + off[axis] / 2;
ret = (axis) ? [xy[0], val] : [val, xy[1]];
}
return ret;
}
};
Align.NAME = 'Align';
Align.NS = 'align';
Align.prototype.constructor = Align;
Y.namespace('Plugin');
Y.Plugin.Align = Align;
}, '3.17.2', {"requires": ["node-screen", "node-pluginhost"]});
|
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2015 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
var addon = require('./build/Release/addon');
var calculations = process.argv[2] || 100000000;
function printResult(type, pi, ms) {
console.log(type, 'method:')
console.log('\tπ ≈ ' + pi
+ ' (' + Math.abs(pi - Math.PI) + ' away from actual)')
console.log('\tTook ' + ms + 'ms');
console.log()
}
function runSync () {
var start = Date.now();
// Estimate() will execute in the current thread,
// the next line won't return until it is finished
var result = addon.calculateSync(calculations);
printResult('Sync', result, Date.now() - start)
}
function runAsync () {
// how many batches should we split the work in to?
var batches = process.argv[3] || 16;
var ended = 0;
var total = 0;
var start = Date.now();
function done (err, result) {
total += result;
// have all the batches finished executing?
if (++ended == batches) {
printResult('Async', total / batches, Date.now() - start)
}
}
// for each batch of work, request an async Estimate() for
// a portion of the total number of calculations
for (var i = 0; i < batches; i++) {
addon.calculateAsync(calculations / batches, done);
}
}
runSync()
runAsync()
|
(function ($) {
var materialChipsDefaults = {
data: [],
placeholder: '',
secondaryPlaceholder: '',
autocompleteOptions: {},
};
$(document).ready(function() {
// Handle removal of static chips.
$(document).on('click', '.chip .close', function(e){
var $chips = $(this).closest('.chips');
if ($chips.attr('data-initialized')) {
return;
}
$(this).closest('.chip').remove();
});
});
$.fn.material_chip = function (options) {
var self = this;
this.$el = $(this);
this.$document = $(document);
this.SELS = {
CHIPS: '.chips',
CHIP: '.chip',
INPUT: 'input',
DELETE: '.material-icons',
SELECTED_CHIP: '.selected',
};
if ('data' === options) {
return this.$el.data('chips');
}
var curr_options = $.extend({}, materialChipsDefaults, options);
self.hasAutocomplete = !$.isEmptyObject(curr_options.autocompleteOptions.data);
// Initialize
this.init = function() {
var i = 0;
var chips;
self.$el.each(function(){
var $chips = $(this);
var chipId = Materialize.guid();
self.chipId = chipId;
if (!curr_options.data || !(curr_options.data instanceof Array)) {
curr_options.data = [];
}
$chips.data('chips', curr_options.data);
$chips.attr('data-index', i);
$chips.attr('data-initialized', true);
if (!$chips.hasClass(self.SELS.CHIPS)) {
$chips.addClass('chips');
}
self.chips($chips, chipId);
i++;
});
};
this.handleEvents = function() {
var SELS = self.SELS;
self.$document.off('click.chips-focus', SELS.CHIPS).on('click.chips-focus', SELS.CHIPS, function(e){
$(e.target).find(SELS.INPUT).focus();
});
self.$document.off('click.chips-select', SELS.CHIP).on('click.chips-select', SELS.CHIP, function(e){
var $chip = $(e.target);
if ($chip.length) {
var wasSelected = $chip.hasClass('selected');
var $chips = $chip.closest(SELS.CHIPS);
$(SELS.CHIP).removeClass('selected');
if (!wasSelected) {
self.selectChip($chip.index(), $chips);
}
}
});
self.$document.off('keydown.chips').on('keydown.chips', function(e){
if ($(e.target).is('input, textarea')) {
return;
}
// delete
var $chip = self.$document.find(SELS.CHIP + SELS.SELECTED_CHIP);
var $chips = $chip.closest(SELS.CHIPS);
var length = $chip.siblings(SELS.CHIP).length;
var index;
if (!$chip.length) {
return;
}
if (e.which === 8 || e.which === 46) {
e.preventDefault();
index = $chip.index();
self.deleteChip(index, $chips);
var selectIndex = null;
if ((index + 1) < length) {
selectIndex = index;
} else if (index === length || (index + 1) === length) {
selectIndex = length - 1;
}
if (selectIndex < 0) selectIndex = null;
if (null !== selectIndex) {
self.selectChip(selectIndex, $chips);
}
if (!length) $chips.find('input').focus();
// left
} else if (e.which === 37) {
index = $chip.index() - 1;
if (index < 0) {
return;
}
$(SELS.CHIP).removeClass('selected');
self.selectChip(index, $chips);
// right
} else if (e.which === 39) {
index = $chip.index() + 1;
$(SELS.CHIP).removeClass('selected');
if (index > length) {
$chips.find('input').focus();
return;
}
self.selectChip(index, $chips);
}
});
self.$document.off('focusin.chips', SELS.CHIPS + ' ' + SELS.INPUT).on('focusin.chips', SELS.CHIPS + ' ' + SELS.INPUT, function(e){
var $currChips = $(e.target).closest(SELS.CHIPS);
$currChips.addClass('focus');
$currChips.siblings('label, .prefix').addClass('active');
$(SELS.CHIP).removeClass('selected');
});
self.$document.off('focusout.chips', SELS.CHIPS + ' ' + SELS.INPUT).on('focusout.chips', SELS.CHIPS + ' ' + SELS.INPUT, function(e){
var $currChips = $(e.target).closest(SELS.CHIPS);
$currChips.removeClass('focus');
// Remove active if empty
if ($currChips.data('chips') === undefined || !$currChips.data('chips').length) {
$currChips.siblings('label').removeClass('active');
}
$currChips.siblings('.prefix').removeClass('active');
});
self.$document.off('keydown.chips-add', SELS.CHIPS + ' ' + SELS.INPUT).on('keydown.chips-add', SELS.CHIPS + ' ' + SELS.INPUT, function(e){
var $target = $(e.target);
var $chips = $target.closest(SELS.CHIPS);
var chipsLength = $chips.children(SELS.CHIP).length;
// enter
if (13 === e.which) {
// Override enter if autocompleting.
if (self.hasAutocomplete &&
$chips.find('.autocomplete-content.dropdown-content').length &&
$chips.find('.autocomplete-content.dropdown-content').children().length) {
return;
}
e.preventDefault();
self.addChip({tag: $target.val()}, $chips);
$target.val('');
return;
}
// delete or left
if ((8 === e.keyCode || 37 === e.keyCode) && '' === $target.val() && chipsLength) {
e.preventDefault();
self.selectChip(chipsLength - 1, $chips);
$target.blur();
return;
}
});
// Click on delete icon in chip.
self.$document.off('click.chips-delete', SELS.CHIPS + ' ' + SELS.DELETE).on('click.chips-delete', SELS.CHIPS + ' ' + SELS.DELETE, function(e) {
var $target = $(e.target);
var $chips = $target.closest(SELS.CHIPS);
var $chip = $target.closest(SELS.CHIP);
e.stopPropagation();
self.deleteChip($chip.index(), $chips);
$chips.find('input').focus();
});
};
this.chips = function($chips, chipId) {
$chips.empty();
$chips.data('chips').forEach(function(elem){
$chips.append(self.renderChip(elem));
});
$chips.append($('<input id="' + chipId +'" class="input" placeholder="">'));
self.setPlaceholder($chips);
// Set for attribute for label
var label = $chips.next('label');
if (label.length) {
label.attr('for', chipId);
if ($chips.data('chips')!== undefined && $chips.data('chips').length) {
label.addClass('active');
}
}
// Setup autocomplete if needed.
var input = $('#' + chipId);
if (self.hasAutocomplete) {
curr_options.autocompleteOptions.onAutocomplete = function(val) {
self.addChip({tag: val}, $chips);
input.val('');
input.focus();
}
input.autocomplete(curr_options.autocompleteOptions);
}
};
/**
* Render chip jQuery element.
* @param {Object} elem
* @return {jQuery}
*/
this.renderChip = function(elem) {
if (!elem.tag) return;
var $renderedChip = $('<div class="chip"></div>');
$renderedChip.text(elem.tag);
if (elem.image) {
$renderedChip.prepend($('<img />').attr('src', elem.image))
}
$renderedChip.append($('<i class="material-icons close">close</i>'));
return $renderedChip;
};
this.setPlaceholder = function($chips) {
if ($chips.data('chips') !== undefined && $chips.data('chips').length && curr_options.placeholder) {
$chips.find('input').prop('placeholder', curr_options.placeholder);
} else if (($chips.data('chips') === undefined || !$chips.data('chips').length) && curr_options.secondaryPlaceholder) {
$chips.find('input').prop('placeholder', curr_options.secondaryPlaceholder);
}
};
this.isValid = function($chips, elem) {
var chips = $chips.data('chips');
var exists = false;
for (var i=0; i < chips.length; i++) {
if (chips[i].tag === elem.tag) {
exists = true;
return;
}
}
return '' !== elem.tag && !exists;
};
this.addChip = function(elem, $chips) {
if (!self.isValid($chips, elem)) {
return;
}
var $renderedChip = self.renderChip(elem);
var newData = [];
var oldData = $chips.data('chips');
for (var i = 0; i < oldData.length; i++) {
newData.push(oldData[i]);
}
newData.push(elem);
$chips.data('chips', newData);
$renderedChip.insertBefore($chips.find('input'));
$chips.trigger('chip.add', elem);
self.setPlaceholder($chips);
};
this.deleteChip = function(chipIndex, $chips) {
var chip = $chips.data('chips')[chipIndex];
$chips.find('.chip').eq(chipIndex).remove();
var newData = [];
var oldData = $chips.data('chips');
for (var i = 0; i < oldData.length; i++) {
if (i !== chipIndex) {
newData.push(oldData[i]);
}
}
$chips.data('chips', newData);
$chips.trigger('chip.delete', chip);
self.setPlaceholder($chips);
};
this.selectChip = function(chipIndex, $chips) {
var $chip = $chips.find('.chip').eq(chipIndex);
if ($chip && false === $chip.hasClass('selected')) {
$chip.addClass('selected');
$chips.trigger('chip.select', $chips.data('chips')[chipIndex]);
}
};
this.getChipsElement = function(index, $chips) {
return $chips.eq(index);
};
// init
this.init();
this.handleEvents();
};
}( jQuery ));
|
/* globals LivechatIntegration */
Template.livechatIntegrations.helpers({
webhookUrl() {
let setting = LivechatIntegration.findOne('Livechat_webhookUrl');
return setting && setting.value;
},
secretToken() {
let setting = LivechatIntegration.findOne('Livechat_secret_token');
return setting && setting.value;
},
disableTest() {
return Template.instance().disableTest.get();
},
sendOnCloseChecked() {
let setting = LivechatIntegration.findOne('Livechat_webhook_on_close');
return setting && setting.value;
},
sendOnOfflineChecked() {
let setting = LivechatIntegration.findOne('Livechat_webhook_on_offline_msg');
return setting && setting.value;
}
});
Template.livechatIntegrations.onCreated(function() {
this.disableTest = new ReactiveVar(true);
this.autorun(() => {
let webhook = LivechatIntegration.findOne('Livechat_webhookUrl');
this.disableTest.set(!webhook || _.isEmpty(webhook.value));
});
this.subscribe('livechat:integration');
});
Template.livechatIntegrations.events({
'change #webhookUrl, blur #webhookUrl'(e, instance) {
let setting = LivechatIntegration.findOne('Livechat_webhookUrl');
instance.disableTest.set(!setting || e.currentTarget.value !== setting.value);
},
'click .test'(e, instance) {
if (!instance.disableTest.get()) {
Meteor.call('livechat:webhookTest', (err) => {
if (err) {
return handleError(err);
}
swal(t('It_works'), null, 'success');
});
}
},
'click .reset-settings'(e, instance) {
e.preventDefault();
let webhookUrl = LivechatIntegration.findOne('Livechat_webhookUrl');
let secretToken = LivechatIntegration.findOne('Livechat_secret_token');
let webhookOnClose = LivechatIntegration.findOne('Livechat_webhook_on_close');
let webhookOnOfflineMsg = LivechatIntegration.findOne('Livechat_webhook_on_offline_msg');
instance.$('#webhookUrl').val(webhookUrl && webhookUrl.value);
instance.$('#secretToken').val(secretToken && secretToken.value);
instance.$('#sendOnClose').get(0).checked = webhookOnClose && webhookOnClose.value;
instance.$('#sendOnOffline').get(0).checked = webhookOnOfflineMsg && webhookOnOfflineMsg.value;
instance.disableTest.set(!webhookUrl || _.isEmpty(webhookUrl.value));
},
'submit .rocket-form'(e, instance) {
e.preventDefault();
var settings = {
'Livechat_webhookUrl': s.trim(instance.$('#webhookUrl').val()),
'Livechat_secret_token': s.trim(instance.$('#secretToken').val()),
'Livechat_webhook_on_close': instance.$('#sendOnClose').get(0).checked,
'Livechat_webhook_on_offline_msg': instance.$('#sendOnOffline').get(0).checked
};
Meteor.call('livechat:saveIntegration', settings, (err) => {
if (err) {
return handleError(err);
}
toastr.success(t('Saved'));
});
}
});
|
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'removeformat', 'en-ca', {
toolbar: 'Remove Format'
} );
|
var Util = {};
Util.Arguments = require('./util/arguments');
Util.Exception = require('./util/exception');
Util.RegExp = require('./util/reg_exp');
Util.String = require('./util/string');
Util.ConsoleColor = require('./util/colors');
module.exports = Util;
|
/**
* filesize
*
* @copyright 2017 Jason Mulligan <jason.mulligan@avoidwork.com>
* @license BSD-3-Clause
* @version 3.5.9
*/
(function (global) {
const b = /^(b|B)$/,
symbol = {
iec: {
bits: ["b", "Kib", "Mib", "Gib", "Tib", "Pib", "Eib", "Zib", "Yib"],
bytes: ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]
},
jedec: {
bits: ["b", "Kb", "Mb", "Gb", "Tb", "Pb", "Eb", "Zb", "Yb"],
bytes: ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
}
},
fullform = {
iec: ["", "kibi", "mebi", "gibi", "tebi", "pebi", "exbi", "zebi", "yobi"],
jedec: ["", "kilo", "mega", "giga", "tera", "peta", "exa", "zetta", "yotta"]
};
/**
* filesize
*
* @method filesize
* @param {Mixed} arg String, Int or Float to transform
* @param {Object} descriptor [Optional] Flags
* @return {String} Readable file size String
*/
function filesize (arg, descriptor = {}) {
let result = [],
val = 0,
e, base, bits, ceil, full, fullforms, neg, num, output, round, unix, spacer, standard, symbols;
if (isNaN(arg)) {
throw new Error("Invalid arguments");
}
bits = descriptor.bits === true;
unix = descriptor.unix === true;
base = descriptor.base || 2;
round = descriptor.round !== undefined ? descriptor.round : unix ? 1 : 2;
spacer = descriptor.spacer !== undefined ? descriptor.spacer : unix ? "" : " ";
symbols = descriptor.symbols || descriptor.suffixes || {};
standard = base === 2 ? descriptor.standard || "jedec" : "jedec";
output = descriptor.output || "string";
full = descriptor.fullform === true;
fullforms = descriptor.fullforms instanceof Array ? descriptor.fullforms : [];
e = descriptor.exponent !== undefined ? descriptor.exponent : -1;
num = Number(arg);
neg = num < 0;
ceil = base > 2 ? 1000 : 1024;
// Flipping a negative number to determine the size
if (neg) {
num = -num;
}
// Determining the exponent
if (e === -1 || isNaN(e)) {
e = Math.floor(Math.log(num) / Math.log(ceil));
if (e < 0) {
e = 0;
}
}
// Exceeding supported length, time to reduce & multiply
if (e > 8) {
e = 8;
}
// Zero is now a special case because bytes divide by 1
if (num === 0) {
result[0] = 0;
result[1] = unix ? "" : symbol[standard][bits ? "bits" : "bytes"][e];
} else {
val = num / (base === 2 ? Math.pow(2, e * 10) : Math.pow(1000, e));
if (bits) {
val = val * 8;
if (val >= ceil && e < 8) {
val = val / ceil;
e++;
}
}
result[0] = Number(val.toFixed(e > 0 ? round : 0));
result[1] = base === 10 && e === 1 ? bits ? "kb" : "kB" : symbol[standard][bits ? "bits" : "bytes"][e];
if (unix) {
result[1] = standard === "jedec" ? result[1].charAt(0) : e > 0 ? result[1].replace(/B$/, "") : result[1];
if (b.test(result[1])) {
result[0] = Math.floor(result[0]);
result[1] = "";
}
}
}
// Decorating a 'diff'
if (neg) {
result[0] = -result[0];
}
// Applying custom symbol
result[1] = symbols[result[1]] || result[1];
// Returning Array, Object, or String (default)
if (output === "array") {
return result;
}
if (output === "exponent") {
return e;
}
if (output === "object") {
return {value: result[0], suffix: result[1], symbol: result[1]};
}
if (full) {
result[1] = fullforms[e] ? fullforms[e] : fullform[standard][e] + (bits ? "bit" : "byte") + (result[0] === 1 ? "" : "s");
}
return result.join(spacer);
}
// Partial application for functional programming
filesize.partial = opt => arg => filesize(arg, opt);
// CommonJS, AMD, script tag
if (typeof exports !== "undefined") {
module.exports = filesize;
} else if (typeof define === "function" && define.amd) {
define(() => {
return filesize;
});
} else {
global.filesize = filesize;
}
}(typeof window !== "undefined" ? window : global));
|
(function(angular) {
'use strict';
angular.module('app', []).directive('setFocusIf', function() {
return function link($scope, $element, $attr) {
$scope.$watch($attr.setFocusIf, function(value) {
if ( value ) { $element[0].focus(); }
});
};
});
})(window.angular);
|
Type.registerNamespace('dnn.util');dnn.extend(dnn.util, { tableReorderMove: function (ctl, bUp, sKey) {
var oTR = dnn.dom.getParentByTagName(ctl, 'tr'); if (oTR != null) {
var oCtr = oTR.parentNode; if (oCtr.childNodes[oCtr.childNodes.length - 1].nodeName == "#text") { dnn.dom.removeChild(oCtr.childNodes[oCtr.childNodes.length - 1]); }; var iIdx = oTR.rowIndex; if (dnn.dom.getAttr(oTR, 'origidx', '') == '-1')
this.tableReorderSetOriginalIndexes(oCtr); var iNextIdx = (bUp ? this.tableReorderGetPrev(oCtr, iIdx - 1) : this.tableReorderGetNext(oCtr, iIdx + 1)); if (iNextIdx > -1) {
var aryValues = this.getInputValues(oTR); var aryValues2; var oSwapNode; dnn.dom.removeChild(oTR); if (oCtr.childNodes.length > iNextIdx)
{ oSwapNode = oCtr.childNodes[iNextIdx]; aryValues2 = this.getInputValues(oSwapNode); oCtr.insertBefore(oTR, oSwapNode); }
else
oCtr.appendChild(oTR); this.setInputValues(oTR, aryValues); if (oSwapNode)
this.setInputValues(oSwapNode, aryValues2); dnn.setVar(sKey, this.tableReorderGetNewRowOrder(oCtr));
}
return true;
}
return false;
}, getInputValues: function (oCtl) {
var aryInputs = dnn.dom.getByTagName('input', oCtl); var aryValues = new Array(); for (var i = 0; i < aryInputs.length; i++) {
if (aryInputs[i].type == 'checkbox')
aryValues[i] = aryInputs[i].checked;
}
return aryValues;
}, setInputValues: function (oCtl, aryValues) {
var aryInputs = dnn.dom.getByTagName('input', oCtl); for (var i = 0; i < aryInputs.length; i++) {
if (aryInputs[i].type == 'checkbox')
aryInputs[i].checked = aryValues[i];
}
}, tableReorderGetNext: function (oParent, iStartIdx) {
for (var i = iStartIdx; i < oParent.childNodes.length; i++) {
var oCtl = oParent.childNodes[i]; if (dnn.dom.getAttr(oCtl, 'origidx', '') != '')
return i;
}
return -1;
}, tableReorderGetPrev: function (oParent, iStartIdx) {
for (var i = iStartIdx; i >= 0; i--) {
var oCtl = oParent.childNodes[i]; if (dnn.dom.getAttr(oCtl, 'origidx', '') != '')
return i;
}
return -1;
}, tableReorderSetOriginalIndexes: function (oParent) {
var iIdx = 0; for (var i = 0; i < oParent.childNodes.length; i++) {
var oCtl = oParent.childNodes[i]; if (dnn.dom.getAttr(oCtl, 'origidx', '') != '')
{ oCtl.setAttribute('origidx', iIdx.toString()); iIdx++; }
}
}, tableReorderGetNewRowOrder: function (oParent) {
var sIdx; var sRet = ''; for (var i = 0; i < oParent.childNodes.length; i++) {
var oCtl = oParent.childNodes[i]; sIdx = dnn.dom.getAttr(oCtl, 'origidx', ''); if (sIdx != '')
sRet += (sRet.length > 0 ? ',' : '') + sIdx;
}
return sRet;
}, checkallChecked: function (oCtl, iCellIndex) {
setTimeout(function () {
var bChecked = oCtl.checked; var oTD = dnn.dom.getParentByTagName(oCtl, 'td'); var oTR = oTD.parentNode; var oCtr = oTR.parentNode; var iOffset = 0; var oTemp;
for (var i = 0; i < iCellIndex; i++) {
if (oTR.childNodes[i].tagName == null)
iOffset++;
}
var oChk; for (var i = 0; i < oCtr.childNodes.length; i++) {
oTR = oCtr.childNodes[i]; oTD = oTR.childNodes[iCellIndex + iOffset]; if (oTD != null) {
oChk = dnn.dom.getByTagName('input', oTD); if (oChk.length > 0)
oChk[0].checked = bChecked;
}
}
}, 10);
}
});
|
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.ShadowMapPlugin = function () {
var _gl,
_renderer,
_depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
_frustum = new THREE.Frustum(),
_projScreenMatrix = new THREE.Matrix4(),
_min = new THREE.Vector3(),
_max = new THREE.Vector3(),
_matrixPosition = new THREE.Vector3();
this.init = function ( renderer ) {
_gl = renderer.context;
_renderer = renderer;
var depthShader = THREE.ShaderLib[ "depthRGBA" ];
var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
_depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
_depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
_depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
_depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
_depthMaterial._shadowPass = true;
_depthMaterialMorph._shadowPass = true;
_depthMaterialSkin._shadowPass = true;
_depthMaterialMorphSkin._shadowPass = true;
};
this.render = function ( scene, camera ) {
if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
this.update( scene, camera );
};
this.update = function ( scene, camera ) {
var i, il, j, jl, n,
shadowMap, shadowMatrix, shadowCamera,
program, buffer, material,
webglObject, object, light,
renderList,
lights = [],
k = 0,
fog = null;
// set GL state for depth map
_gl.clearColor( 1, 1, 1, 1 );
_gl.disable( _gl.BLEND );
_gl.enable( _gl.CULL_FACE );
_gl.frontFace( _gl.CCW );
if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
_gl.cullFace( _gl.FRONT );
} else {
_gl.cullFace( _gl.BACK );
}
_renderer.setDepthTest( true );
// preprocess lights
// - skip lights that are not casting shadows
// - create virtual lights for cascaded shadow maps
for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
light = scene.__lights[ i ];
if ( ! light.castShadow ) continue;
if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
var virtualLight;
if ( ! light.shadowCascadeArray[ n ] ) {
virtualLight = createVirtualLight( light, n );
virtualLight.originalCamera = camera;
var gyro = new THREE.Gyroscope();
gyro.position = light.shadowCascadeOffset;
gyro.add( virtualLight );
gyro.add( virtualLight.target );
camera.add( gyro );
light.shadowCascadeArray[ n ] = virtualLight;
console.log( "Created virtualLight", virtualLight );
} else {
virtualLight = light.shadowCascadeArray[ n ];
}
updateVirtualLight( light, n );
lights[ k ] = virtualLight;
k ++;
}
} else {
lights[ k ] = light;
k ++;
}
}
// render depth map
for ( i = 0, il = lights.length; i < il; i ++ ) {
light = lights[ i ];
if ( ! light.shadowMap ) {
var shadowFilter = THREE.LinearFilter;
if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
shadowFilter = THREE.NearestFilter;
}
var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
light.shadowMatrix = new THREE.Matrix4();
}
if ( ! light.shadowCamera ) {
if ( light instanceof THREE.SpotLight ) {
light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
} else if ( light instanceof THREE.DirectionalLight ) {
light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
} else {
console.error( "Unsupported light type for shadow" );
continue;
}
scene.add( light.shadowCamera );
if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
}
if ( light.shadowCameraVisible && ! light.cameraHelper ) {
light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
light.shadowCamera.add( light.cameraHelper );
}
if ( light.isVirtual && virtualLight.originalCamera == camera ) {
updateShadowCamera( camera, light );
}
shadowMap = light.shadowMap;
shadowMatrix = light.shadowMatrix;
shadowCamera = light.shadowCamera;
shadowCamera.position.setFromMatrixPosition( light.matrixWorld );
_matrixPosition.setFromMatrixPosition( light.target.matrixWorld );
shadowCamera.lookAt( _matrixPosition );
shadowCamera.updateMatrixWorld();
shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
if ( light.shadowCameraVisible ) light.cameraHelper.update();
// compute shadow matrix
shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
0.0, 0.5, 0.0, 0.5,
0.0, 0.0, 0.5, 0.5,
0.0, 0.0, 0.0, 1.0 );
shadowMatrix.multiply( shadowCamera.projectionMatrix );
shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
// update camera matrices and frustum
_projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
_frustum.setFromMatrix( _projScreenMatrix );
// render shadow map
_renderer.setRenderTarget( shadowMap );
_renderer.clear();
// set object matrices & frustum culling
renderList = scene.__webglObjects;
for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
webglObject = renderList[ j ];
object = webglObject.object;
webglObject.render = false;
if ( object.visible && object.castShadow ) {
if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
webglObject.render = true;
}
}
}
// render regular objects
var objectMaterial, useMorphing, useSkinning;
for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
webglObject = renderList[ j ];
if ( webglObject.render ) {
object = webglObject.object;
buffer = webglObject.buffer;
// culling is overriden globally for all objects
// while rendering depth map
// need to deal with MeshFaceMaterial somehow
// in that case just use the first of material.materials for now
// (proper solution would require to break objects by materials
// similarly to regular rendering and then set corresponding
// depth materials per each chunk instead of just once per object)
objectMaterial = getObjectMaterial( object );
useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
if ( object.customDepthMaterial ) {
material = object.customDepthMaterial;
} else if ( useSkinning ) {
material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
} else if ( useMorphing ) {
material = _depthMaterialMorph;
} else {
material = _depthMaterial;
}
if ( buffer instanceof THREE.BufferGeometry ) {
_renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
} else {
_renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
}
}
}
// set matrices and render immediate objects
renderList = scene.__webglObjectsImmediate;
for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
webglObject = renderList[ j ];
object = webglObject.object;
if ( object.visible && object.castShadow ) {
object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
_renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
}
}
}
// restore GL state
var clearColor = _renderer.getClearColor(),
clearAlpha = _renderer.getClearAlpha();
_gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
_gl.enable( _gl.BLEND );
if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
_gl.cullFace( _gl.BACK );
}
};
function createVirtualLight( light, cascade ) {
var virtualLight = new THREE.DirectionalLight();
virtualLight.isVirtual = true;
virtualLight.onlyShadow = true;
virtualLight.castShadow = true;
virtualLight.shadowCameraNear = light.shadowCameraNear;
virtualLight.shadowCameraFar = light.shadowCameraFar;
virtualLight.shadowCameraLeft = light.shadowCameraLeft;
virtualLight.shadowCameraRight = light.shadowCameraRight;
virtualLight.shadowCameraBottom = light.shadowCameraBottom;
virtualLight.shadowCameraTop = light.shadowCameraTop;
virtualLight.shadowCameraVisible = light.shadowCameraVisible;
virtualLight.shadowDarkness = light.shadowDarkness;
virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
virtualLight.pointsWorld = [];
virtualLight.pointsFrustum = [];
var pointsWorld = virtualLight.pointsWorld,
pointsFrustum = virtualLight.pointsFrustum;
for ( var i = 0; i < 8; i ++ ) {
pointsWorld[ i ] = new THREE.Vector3();
pointsFrustum[ i ] = new THREE.Vector3();
}
var nearZ = light.shadowCascadeNearZ[ cascade ];
var farZ = light.shadowCascadeFarZ[ cascade ];
pointsFrustum[ 0 ].set( -1, -1, nearZ );
pointsFrustum[ 1 ].set( 1, -1, nearZ );
pointsFrustum[ 2 ].set( -1, 1, nearZ );
pointsFrustum[ 3 ].set( 1, 1, nearZ );
pointsFrustum[ 4 ].set( -1, -1, farZ );
pointsFrustum[ 5 ].set( 1, -1, farZ );
pointsFrustum[ 6 ].set( -1, 1, farZ );
pointsFrustum[ 7 ].set( 1, 1, farZ );
return virtualLight;
}
// Synchronize virtual light with the original light
function updateVirtualLight( light, cascade ) {
var virtualLight = light.shadowCascadeArray[ cascade ];
virtualLight.position.copy( light.position );
virtualLight.target.position.copy( light.target.position );
virtualLight.lookAt( virtualLight.target );
virtualLight.shadowCameraVisible = light.shadowCameraVisible;
virtualLight.shadowDarkness = light.shadowDarkness;
virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
var nearZ = light.shadowCascadeNearZ[ cascade ];
var farZ = light.shadowCascadeFarZ[ cascade ];
var pointsFrustum = virtualLight.pointsFrustum;
pointsFrustum[ 0 ].z = nearZ;
pointsFrustum[ 1 ].z = nearZ;
pointsFrustum[ 2 ].z = nearZ;
pointsFrustum[ 3 ].z = nearZ;
pointsFrustum[ 4 ].z = farZ;
pointsFrustum[ 5 ].z = farZ;
pointsFrustum[ 6 ].z = farZ;
pointsFrustum[ 7 ].z = farZ;
}
// Fit shadow camera's ortho frustum to camera frustum
function updateShadowCamera( camera, light ) {
var shadowCamera = light.shadowCamera,
pointsFrustum = light.pointsFrustum,
pointsWorld = light.pointsWorld;
_min.set( Infinity, Infinity, Infinity );
_max.set( -Infinity, -Infinity, -Infinity );
for ( var i = 0; i < 8; i ++ ) {
var p = pointsWorld[ i ];
p.copy( pointsFrustum[ i ] );
THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
p.applyMatrix4( shadowCamera.matrixWorldInverse );
if ( p.x < _min.x ) _min.x = p.x;
if ( p.x > _max.x ) _max.x = p.x;
if ( p.y < _min.y ) _min.y = p.y;
if ( p.y > _max.y ) _max.y = p.y;
if ( p.z < _min.z ) _min.z = p.z;
if ( p.z > _max.z ) _max.z = p.z;
}
shadowCamera.left = _min.x;
shadowCamera.right = _max.x;
shadowCamera.top = _max.y;
shadowCamera.bottom = _min.y;
// can't really fit near/far
//shadowCamera.near = _min.z;
//shadowCamera.far = _max.z;
shadowCamera.updateProjectionMatrix();
}
// For the moment just ignore objects that have multiple materials with different animation methods
// Only the first material will be taken into account for deciding which depth material to use for shadow maps
function getObjectMaterial( object ) {
return object.material instanceof THREE.MeshFaceMaterial
? object.material.materials[ 0 ]
: object.material;
};
};
THREE.ShadowMapPlugin.__projector = new THREE.Projector();
|
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("specialchar","ug",{euro:"ياۋرو بەلگىسى",lsquo:"يالاڭ پەش سول",rsquo:"يالاڭ پەش ئوڭ",ldquo:"قوش پەش سول",rdquo:"قوش پەش ئوڭ",ndash:"سىزىقچە",mdash:"سىزىق",iexcl:"ئۈندەش",cent:"تىيىن بەلگىسى",pound:"فوند ستېرلىڭ",curren:"پۇل بەلگىسى",yen:"ياپونىيە يىنى",brvbar:"ئۈزۈك بالداق",sect:"پاراگراف بەلگىسى",uml:"تاۋۇش ئايرىش بەلگىسى",copy:"نەشر ھوقۇقى بەلگىسى",ordf:"Feminine ordinal indicator",laquo:"قوش تىرناق سول",not:"غەيرى بەلگە",reg:"خەتلەتكەن تاۋار ماركىسى",macr:"سوزۇش بەلگىسى",
deg:"گىرادۇس بەلگىسى",sup2:"يۇقىرى ئىندېكىس 2",sup3:"يۇقىرى ئىندېكىس 3",acute:"ئۇرغۇ بەلگىسى",micro:"Micro sign",para:"ئابزاس بەلگىسى",middot:"ئوتتۇرا چېكىت",cedil:"ئاستىغا قوشۇلىدىغان بەلگە",sup1:"يۇقىرى ئىندېكىس 1",ordm:"Masculine ordinal indicator",raquo:"قوش تىرناق ئوڭ",frac14:"ئاددىي كەسىر تۆتتىن بىر",frac12:"ئاددىي كەسىر ئىككىدىن بىر",frac34:"ئاددىي كەسىر ئۈچتىن تۆرت",iquest:"Inverted question mark",Agrave:"Latin capital letter A with grave accent",Aacute:"Latin capital letter A with acute accent",
Acirc:"Latin capital letter A with circumflex",Atilde:"Latin capital letter A with tilde",Auml:"Latin capital letter A with diaeresis",Aring:"Latin capital letter A with ring above",AElig:"Latin Capital letter Æ",Ccedil:"Latin capital letter C with cedilla",Egrave:"Latin capital letter E with grave accent",Eacute:"Latin capital letter E with acute accent",Ecirc:"Latin capital letter E with circumflex",Euml:"Latin capital letter E with diaeresis",Igrave:"Latin capital letter I with grave accent",Iacute:"Latin capital letter I with acute accent",
Icirc:"Latin capital letter I with circumflex",Iuml:"Latin capital letter I with diaeresis",ETH:"Latin capital letter Eth",Ntilde:"Latin capital letter N with tilde",Ograve:"قوش پەش ئوڭ",Oacute:"Latin capital letter O with acute accent",Ocirc:"Latin capital letter O with circumflex",Otilde:"Latin capital letter O with tilde",Ouml:"Latin capital letter O with diaeresis",times:"Multiplication sign",Oslash:"Latin capital letter O with stroke",Ugrave:"Latin capital letter U with grave accent",Uacute:"Latin capital letter U with acute accent",
Ucirc:"Latin capital letter U with circumflex",Uuml:"Latin capital letter U with diaeresis",Yacute:"Latin capital letter Y with acute accent",THORN:"Latin capital letter Thorn",szlig:"Latin small letter sharp s",agrave:"Latin small letter a with grave accent",aacute:"Latin small letter a with acute accent",acirc:"Latin small letter a with circumflex",atilde:"Latin small letter a with tilde",auml:"Latin small letter a with diaeresis",aring:"Latin small letter a with ring above",aelig:"Latin small letter æ",
ccedil:"Latin small letter c with cedilla",egrave:"Latin small letter e with grave accent",eacute:"Latin small letter e with acute accent",ecirc:"Latin small letter e with circumflex",euml:"Latin small letter e with diaeresis",igrave:"Latin small letter i with grave accent",iacute:"Latin small letter i with acute accent",icirc:"Latin small letter i with circumflex",iuml:"Latin small letter i with diaeresis",eth:"Latin small letter eth",ntilde:"تىك موللاق سوئال بەلگىسى",ograve:"Latin small letter o with grave accent",
oacute:"Latin small letter o with acute accent",ocirc:"Latin small letter o with circumflex",otilde:"Latin small letter o with tilde",ouml:"Latin small letter o with diaeresis",divide:"بۆلۈش بەلگىسى",oslash:"Latin small letter o with stroke",ugrave:"Latin small letter u with grave accent",uacute:"Latin small letter u with acute accent",ucirc:"Latin small letter u with circumflex",uuml:"Latin small letter u with diaeresis",yacute:"Latin small letter y with acute accent",thorn:"Latin small letter thorn",
yuml:"Latin small letter y with diaeresis",OElig:"Latin capital ligature OE",oelig:"Latin small ligature oe",372:"Latin capital letter W with circumflex",374:"Latin capital letter Y with circumflex",373:"Latin small letter w with circumflex",375:"Latin small letter y with circumflex",sbquo:"Single low-9 quotation mark",8219:"Single high-reversed-9 quotation mark",bdquo:"Double low-9 quotation mark",hellip:"Horizontal ellipsis",trade:"خەتلەتكەن تاۋار ماركىسى بەلگىسى",9658:"Black right-pointing pointer",
bull:"Bullet",rarr:"ئوڭ يا ئوق",rArr:"ئوڭ قوش سىزىق يا ئوق",hArr:"ئوڭ سول قوش سىزىق يا ئوق",diams:"ئۇيۇل غىچ",asymp:"تەخمىنەن تەڭ"});
|
import { compile } from '../../index';
QUnit.module('ember-template-compiler: transform-input-on');
QUnit.test('Using `action` without `on` provides a deprecation', function() {
expect(1);
expectDeprecation(() => {
compile('{{input action="foo"}}', {
moduleName: 'foo/bar/baz'
});
}, `Using '{{input action="foo"}}' ('foo/bar/baz' @ L1:C0) is deprecated. Please use '{{input enter="foo"}}' instead.`);
});
QUnit.test('Using `action` with `on` provides a deprecation', function() {
expect(1);
expectDeprecation(() => {
compile('{{input on="focus-in" action="foo"}}', {
moduleName: 'foo/bar/baz'
});
}, `Using '{{input on="focus-in" action="foo"}}' ('foo/bar/baz' @ L1:C0) is deprecated. Please use '{{input focus-in="foo"}}' instead.`);
});
QUnit.test('Using `on=\'keyPress\'` does not clobber `keyPress`', function() {
expect(1);
expectDeprecation(() => {
compile('{{input on="keyPress" action="foo"}}', {
moduleName: 'foo/bar/baz'
});
}, `Using '{{input on="keyPress" action="foo"}}' ('foo/bar/baz' @ L1:C0) is deprecated. Please use '{{input key-press="foo"}}' instead.`);
});
QUnit.test('Using `on=\'foo\'` without `action=\'asdf\'` raises specific deprecation', function() {
expect(1);
expectDeprecation(() => {
compile('{{input on="asdf"}}', {
moduleName: 'foo/bar/baz'
});
}, `Using '{{input on="asdf" ...}}' without specifying an action ('foo/bar/baz' @ L1:C0) will do nothing.`);
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:aaac047574907860fbb772401132a0ace58a07850b1ccc158781380348a10d00
size 7696
|
import fs from 'fs';
import rrs from 'recursive-readdir-sync';
const outArray = [];
rrs('./').forEach((file) => {
if (file !== 'index-generator.js' && file !== 'index.js') {
let fileLines = fs.readFileSync(file, 'utf8').split('\n');
let index = 0;
let found = false;
while (found === false && index < fileLines.length) {
if (fileLines[index].indexOf('export default') > -1) {
const moduleName = fileLines[index].split(' ')[2].replace(';', '').trim();
const modulePath = file.substring(0, file.length - 4);
outArray.push(`import ${moduleName} from './${modulePath}';\nexport { ${moduleName} };\n`);
found = true;
} else {
index++;
}
}
}
});
fs.writeFileSync('index.js', outArray.join(''));
|
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-karma');
grunt.loadNpmTasks('grunt-zip');
grunt.loadNpmTasks('grunt-jquerymanifest');
grunt.loadNpmTasks('grunt-bower-task');
grunt.loadNpmTasks('grunt-banner');
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
bower: {
install: {
options: {
targetDir: './lib',
layout: 'byType',
install: true,
verbose: true,
cleanTargetDir: false,
cleanBowerDir: true,
bowerOptions: {
forceLatest: true
}
}
}
},
copy: {
versioned: {
files: [
{ expand: true, flatten: true, src: ['src/*.*'], dest: 'versioned/', filter: 'isFile' }
]
},
build: {
files: [
{ expand: true, flatten: true, src: ['versioned/*.*'], dest: 'dist/', filter: 'isFile' }
]
}
},
uglify: {
options: {
banner: '<%= pkg.banner %>',
sourceMap: 'dist/<%= pkg.name %>.min.js.map',
sourceMappingURL: '<%= pkg.name %>.min.js.map'
},
build: {
files: {
'dist/<%= pkg.name %>.min.js': 'src/<%= pkg.name %>.js',
'dist/<%= pkg.name %>-angular.min.js': 'src/<%= pkg.name %>-angular.js'
}
}
},
karma: {
unit: {
configFile: 'karma.conf.js',
runnerPort: 9999,
singleRun: true,
autoWatch: false,
browsers: ['PhantomJS']
}
},
zip: {
delpoy: {
// cwd: 'dist/',
src: [
'dist/bootstrap-tagsinput*.js',
'dist/bootstrap-tagsinput*.css',
'dist/bootstrap-tagsinput*.less',
'dist/bootstrap-tagsinput*.map'
],
dest: 'dist/<%= pkg.name %>.zip'
}
},
jquerymanifest: {
options: {
source: grunt.file.readJSON('package.json'),
overrides: {
title: '<%= pkg.title %>'
}
}
},
usebanner: {
taskName: {
options: {
position: 'top',
banner: '<%= pkg.banner %>',
linebreak: true
},
files: {
src: [ 'versioned/*.*' ]
}
}
}
});
grunt.registerTask('install', ['bower']);
grunt.registerTask('compile', ['copy:versioned', 'usebanner', 'uglify', 'copy:build']);
grunt.registerTask('test', ['compile', 'karma']);
grunt.registerTask('build', ['test', 'jquerymanifest', 'zip']);
};
|
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Base class for containers that host {@link goog.ui.Control}s,
* such as menus and toolbars. Provides default keyboard and mouse event
* handling and child management, based on a generalized version of
* {@link goog.ui.Menu}.
*
* @see ../demos/container.html
*/
// TODO(user): Fix code/logic duplication between this and goog.ui.Control.
// TODO(user): Maybe pull common stuff all the way up into Component...?
goog.provide('goog.ui.Container');
goog.provide('goog.ui.Container.EventType');
goog.provide('goog.ui.Container.Orientation');
goog.require('goog.dom');
goog.require('goog.dom.a11y');
goog.require('goog.dom.a11y.State');
goog.require('goog.events.EventType');
goog.require('goog.events.KeyCodes');
goog.require('goog.events.KeyHandler');
goog.require('goog.events.KeyHandler.EventType');
goog.require('goog.style');
goog.require('goog.ui.Component');
goog.require('goog.ui.Component.Error');
goog.require('goog.ui.Component.EventType');
goog.require('goog.ui.Component.State');
goog.require('goog.ui.ContainerRenderer');
/**
* Base class for containers. Extends {@link goog.ui.Component} by adding
* the following:
* <ul>
* <li>a {@link goog.events.KeyHandler}, to simplify keyboard handling,
* <li>a pluggable <em>renderer</em> framework, to simplify the creation of
* containers without the need to subclass this class,
* <li>methods to manage child controls hosted in the container,
* <li>default mouse and keyboard event handling methods.
* </ul>
* @param {?goog.ui.Container.Orientation=} opt_orientation Container
* orientation; defaults to {@code VERTICAL}.
* @param {?goog.ui.ContainerRenderer=} opt_renderer Renderer used to render or
* decorate the container; defaults to {@link goog.ui.ContainerRenderer}.
* @param {?goog.dom.DomHelper=} opt_domHelper DOM helper, used for document
* interaction.
* @extends {goog.ui.Component}
* @constructor
*/
goog.ui.Container = function(opt_orientation, opt_renderer, opt_domHelper) {
goog.ui.Component.call(this, opt_domHelper);
this.renderer_ = opt_renderer || goog.ui.ContainerRenderer.getInstance();
this.orientation_ = opt_orientation || this.renderer_.getDefaultOrientation();
};
goog.inherits(goog.ui.Container, goog.ui.Component);
/**
* Container-specific events.
* @enum {string}
*/
goog.ui.Container.EventType = {
/**
* Dispatched after a goog.ui.Container becomes visible. Non-cancellable.
* NOTE(user): This event really shouldn't exist, because the
* goog.ui.Component.EventType.SHOW event should behave like this one. But the
* SHOW event for containers has been behaving as other components'
* BEFORE_SHOW event for a long time, and too much code relies on that old
* behavior to fix it now.
*/
AFTER_SHOW: 'aftershow',
/**
* Dispatched after a goog.ui.Container becomes invisible. Non-cancellable.
*/
AFTER_HIDE: 'afterhide'
};
/**
* Container orientation constants.
* @enum {string}
*/
goog.ui.Container.Orientation = {
HORIZONTAL: 'horizontal',
VERTICAL: 'vertical'
};
/**
* Allows an alternative element to be set to recieve key events, otherwise
* defers to the renderer's element choice.
* @type {Element|undefined}
* @private
*/
goog.ui.Container.prototype.keyEventTarget_ = null;
/**
* Keyboard event handler.
* @type {goog.events.KeyHandler?}
* @private
*/
goog.ui.Container.prototype.keyHandler_ = null;
/**
* Renderer for the container. Defaults to {@link goog.ui.ContainerRenderer}.
* @type {goog.ui.ContainerRenderer?}
* @private
*/
goog.ui.Container.prototype.renderer_ = null;
/**
* Container orientation; determines layout and default keyboard navigation.
* @type {?goog.ui.Container.Orientation}
* @private
*/
goog.ui.Container.prototype.orientation_ = null;
/**
* Whether the container is set to be visible. Defaults to true.
* @type {boolean}
* @private
*/
goog.ui.Container.prototype.visible_ = true;
/**
* Whether the container is enabled and reacting to keyboard and mouse events.
* Defaults to true.
* @type {boolean}
* @private
*/
goog.ui.Container.prototype.enabled_ = true;
/**
* Whether the container supports keyboard focus. Defaults to true. Focusable
* containers have a {@code tabIndex} and can be navigated to via the keyboard.
* @type {boolean}
* @private
*/
goog.ui.Container.prototype.focusable_ = true;
/**
* The 0-based index of the currently highlighted control in the container
* (-1 if none).
* @type {number}
* @private
*/
goog.ui.Container.prototype.highlightedIndex_ = -1;
/**
* The currently open (expanded) control in the container (null if none).
* @type {goog.ui.Control?}
* @private
*/
goog.ui.Container.prototype.openItem_ = null;
/**
* Whether the mouse button is held down. Defaults to false. This flag is set
* when the user mouses down over the container, and remains set until they
* release the mouse button.
* @type {boolean}
* @private
*/
goog.ui.Container.prototype.mouseButtonPressed_ = false;
/**
* Whether focus of child components should be allowed. Only effective if
* focusable_ is set to false.
* @type {boolean}
* @private
*/
goog.ui.Container.prototype.allowFocusableChildren_ = false;
/**
* Whether highlighting a child component should also open it.
* @type {boolean}
* @private
*/
goog.ui.Container.prototype.openFollowsHighlight_ = true;
/**
* Map of DOM IDs to child controls. Each key is the DOM ID of a child
* control's root element; each value is a reference to the child control
* itself. Used for looking up the child control corresponding to a DOM
* node in O(1) time.
* @type {Object}
* @private
*/
goog.ui.Container.prototype.childElementIdMap_ = null;
// Event handler and renderer management.
/**
* Returns the DOM element on which the container is listening for keyboard
* events (null if none).
* @return {Element} Element on which the container is listening for key
* events.
*/
goog.ui.Container.prototype.getKeyEventTarget = function() {
// Delegate to renderer, unless we've set an explicit target.
return this.keyEventTarget_ || this.renderer_.getKeyEventTarget(this);
};
/**
* Attaches an element on which to listen for key events.
* @param {Element|undefined} element The element to attach, or null/undefined
* to attach to the default element.
*/
goog.ui.Container.prototype.setKeyEventTarget = function(element) {
if (this.focusable_) {
var oldTarget = this.getKeyEventTarget();
var inDocument = this.isInDocument();
this.keyEventTarget_ = element;
var newTarget = this.getKeyEventTarget();
if (inDocument) {
// Unlisten for events on the old key target. Requires us to reset
// key target state temporarily.
this.keyEventTarget_ = oldTarget;
this.enableFocusHandling_(false);
this.keyEventTarget_ = element;
// Listen for events on the new key target.
this.getKeyHandler().attach(newTarget);
this.enableFocusHandling_(true);
}
} else {
throw Error('Can\'t set key event target for container ' +
'that doesn\'t support keyboard focus!');
}
};
/**
* Returns the keyboard event handler for this container, lazily created the
* first time this method is called. The keyboard event handler listens for
* keyboard events on the container's key event target, as determined by its
* renderer.
* @return {goog.events.KeyHandler} Keyboard event handler for this container.
*/
goog.ui.Container.prototype.getKeyHandler = function() {
return this.keyHandler_ ||
(this.keyHandler_ = new goog.events.KeyHandler(this.getKeyEventTarget()));
};
/**
* Returns the renderer used by this container to render itself or to decorate
* an existing element.
* @return {goog.ui.ContainerRenderer} Renderer used by the container.
*/
goog.ui.Container.prototype.getRenderer = function() {
return this.renderer_;
};
/**
* Registers the given renderer with the container. Changing renderers after
* the container has already been rendered or decorated is an error.
* @param {goog.ui.ContainerRenderer} renderer Renderer used by the container.
*/
goog.ui.Container.prototype.setRenderer = function(renderer) {
if (this.getElement()) {
// Too late.
throw Error(goog.ui.Component.Error.ALREADY_RENDERED);
}
this.renderer_ = renderer;
};
// Standard goog.ui.Component implementation.
/**
* Creates the container's DOM. Overrides {@link goog.ui.Component#createDom}.
*/
goog.ui.Container.prototype.createDom = function() {
// Delegate to renderer.
this.setElementInternal(this.renderer_.createDom(this));
};
/**
* Returns the DOM element into which child components are to be rendered,
* or null if the container itself hasn't been rendered yet. Overrides
* {@link goog.ui.Component#getContentElement} by delegating to the renderer.
* @return {Element} Element to contain child elements (null if none).
*/
goog.ui.Container.prototype.getContentElement = function() {
// Delegate to renderer.
return this.renderer_.getContentElement(this.getElement());
};
/**
* Returns true if the given element can be decorated by this container.
* Overrides {@link goog.ui.Component#canDecorate}.
* @param {Element} element Element to decorate.
* @return {boolean} True iff the element can be decorated.
*/
goog.ui.Container.prototype.canDecorate = function(element) {
// Delegate to renderer.
return this.renderer_.canDecorate(element);
};
/**
* Decorates the given element with this container. Overrides {@link
* goog.ui.Component#decorateInternal}. Considered protected.
* @param {Element} element Element to decorate.
*/
goog.ui.Container.prototype.decorateInternal = function(element) {
// Delegate to renderer.
this.setElementInternal(this.renderer_.decorate(this, element));
// Check whether the decorated element is explicitly styled to be invisible.
if (element.style.display == 'none') {
this.visible_ = false;
}
};
/**
* Configures the container after its DOM has been rendered, and sets up event
* handling. Overrides {@link goog.ui.Component#enterDocument}.
*/
goog.ui.Container.prototype.enterDocument = function() {
goog.ui.Container.superClass_.enterDocument.call(this);
this.forEachChild(function(child) {
if (child.isInDocument()) {
this.registerChildId_(child);
}
}, this);
// Detect right-to-left direction.
var elem = this.getElement();
// Call the renderer's initializeDom method to initialize the container's DOM.
this.renderer_.initializeDom(this);
// Initialize visibility (opt_force = true, so we don't dispatch events).
this.setVisible(this.visible_, true);
// Handle events dispatched by child controls.
this.getHandler().
listen(this, goog.ui.Component.EventType.ENTER,
this.handleEnterItem).
listen(this, goog.ui.Component.EventType.HIGHLIGHT,
this.handleHighlightItem).
listen(this, goog.ui.Component.EventType.UNHIGHLIGHT,
this.handleUnHighlightItem).
listen(this, goog.ui.Component.EventType.OPEN, this.handleOpenItem).
listen(this, goog.ui.Component.EventType.CLOSE, this.handleCloseItem).
// Handle mouse events.
listen(elem, goog.events.EventType.MOUSEDOWN, this.handleMouseDown).
listen(goog.dom.getOwnerDocument(elem), goog.events.EventType.MOUSEUP,
this.handleDocumentMouseUp).
// Handle mouse events on behalf of controls in the container.
listen(elem, [
goog.events.EventType.MOUSEDOWN,
goog.events.EventType.MOUSEUP,
goog.events.EventType.MOUSEOVER,
goog.events.EventType.MOUSEOUT
], this.handleChildMouseEvents);
// If the container is focusable, set up keyboard event handling.
if (this.isFocusable()) {
this.enableFocusHandling_(true);
}
};
/**
* Sets up listening for events applicable to focusable containers.
* @param {boolean} enable Whether to enable or disable focus handling.
* @private
*/
goog.ui.Container.prototype.enableFocusHandling_ = function(enable) {
var handler = this.getHandler();
var keyTarget = this.getKeyEventTarget();
if (enable) {
handler.
listen(keyTarget, goog.events.EventType.FOCUS, this.handleFocus).
listen(keyTarget, goog.events.EventType.BLUR, this.handleBlur).
listen(this.getKeyHandler(), goog.events.KeyHandler.EventType.KEY,
this.handleKeyEvent);
} else {
handler.
unlisten(keyTarget, goog.events.EventType.FOCUS, this.handleFocus).
unlisten(keyTarget, goog.events.EventType.BLUR, this.handleBlur).
unlisten(this.getKeyHandler(), goog.events.KeyHandler.EventType.KEY,
this.handleKeyEvent);
}
};
/**
* Cleans up the container before its DOM is removed from the document, and
* removes event handlers. Overrides {@link goog.ui.Component#exitDocument}.
*/
goog.ui.Container.prototype.exitDocument = function() {
// {@link #setHighlightedIndex} has to be called before
// {@link goog.ui.Component#exitDocument}, otherwise it has no effect.
this.setHighlightedIndex(-1);
if (this.openItem_) {
this.openItem_.setOpen(false);
}
this.mouseButtonPressed_ = false;
goog.ui.Container.superClass_.exitDocument.call(this);
};
/** @inheritDoc */
goog.ui.Container.prototype.disposeInternal = function() {
goog.ui.Container.superClass_.disposeInternal.call(this);
if (this.keyHandler_) {
this.keyHandler_.dispose();
this.keyHandler_ = null;
}
this.childElementIdMap_ = null;
this.openItem_ = null;
this.renderer_ = null;
};
// Default event handlers.
/**
* Handles ENTER events raised by child controls when they are navigated to.
* @param {goog.events.Event} e ENTER event to handle.
* @return {boolean} Whether to prevent handleMouseOver from handling
* the event.
*/
goog.ui.Container.prototype.handleEnterItem = function(e) {
// Allow the Control to highlight itself.
return true;
};
/**
* Handles HIGHLIGHT events dispatched by items in the container when
* they are highlighted.
* @param {goog.events.Event} e Highlight event to handle.
*/
goog.ui.Container.prototype.handleHighlightItem = function(e) {
var index = this.indexOfChild(/** @type {goog.ui.Control} */ (e.target));
if (index > -1 && index != this.highlightedIndex_) {
var item = this.getHighlighted();
if (item) {
// Un-highlight previously highlighted item.
item.setHighlighted(false);
}
this.highlightedIndex_ = index;
item = this.getHighlighted();
if (this.isMouseButtonPressed()) {
// Activate item when mouse button is pressed, to allow MacOS-style
// dragging to choose menu items. Although this should only truly
// happen if the highlight is due to mouse movements, there is little
// harm in doing it for keyboard or programmatic highlights.
item.setActive(true);
}
// Update open item if open item needs follow highlight.
if (this.openFollowsHighlight_ &&
this.openItem_ && item != this.openItem_) {
if (item.isSupportedState(goog.ui.Component.State.OPENED)) {
item.setOpen(true);
} else {
this.openItem_.setOpen(false);
}
}
}
goog.dom.a11y.setState(this.getElement(),
goog.dom.a11y.State.ACTIVEDESCENDANT, e.target.getElement().id);
};
/**
* Handles UNHIGHLIGHT events dispatched by items in the container when
* they are unhighlighted.
* @param {goog.events.Event} e Unhighlight event to handle.
*/
goog.ui.Container.prototype.handleUnHighlightItem = function(e) {
if (e.target == this.getHighlighted()) {
this.highlightedIndex_ = -1;
}
goog.dom.a11y.setState(this.getElement(),
goog.dom.a11y.State.ACTIVEDESCENDANT, '');
};
/**
* Handles OPEN events dispatched by items in the container when they are
* opened.
* @param {goog.events.Event} e Open event to handle.
*/
goog.ui.Container.prototype.handleOpenItem = function(e) {
var item = /** @type {goog.ui.Control} */ (e.target);
if (item && item != this.openItem_ && item.getParent() == this) {
if (this.openItem_) {
this.openItem_.setOpen(false);
}
this.openItem_ = item;
}
};
/**
* Handles CLOSE events dispatched by items in the container when they are
* closed.
* @param {goog.events.Event} e Close event to handle.
*/
goog.ui.Container.prototype.handleCloseItem = function(e) {
if (e.target == this.openItem_) {
this.openItem_ = null;
}
};
/**
* Handles mousedown events over the container. The default implementation
* sets the "mouse button pressed" flag and, if the container is focusable,
* grabs keyboard focus.
* @param {goog.events.BrowserEvent} e Mousedown event to handle.
*/
goog.ui.Container.prototype.handleMouseDown = function(e) {
if (this.enabled_) {
this.setMouseButtonPressed(true);
}
var keyTarget = this.getKeyEventTarget();
if (keyTarget && goog.dom.isFocusableTabIndex(keyTarget)) {
// The container is configured to receive keyboard focus.
keyTarget.focus();
} else {
// The control isn't configured to receive keyboard focus; prevent it
// from stealing focus or destroying the selection.
e.preventDefault();
}
};
/**
* Handles mouseup events over the document. The default implementation
* clears the "mouse button pressed" flag.
* @param {goog.events.BrowserEvent} e Mouseup event to handle.
*/
goog.ui.Container.prototype.handleDocumentMouseUp = function(e) {
this.setMouseButtonPressed(false);
};
/**
* Handles mouse events originating from nodes belonging to the controls hosted
* in the container. Locates the child control based on the DOM node that
* dispatched the event, and forwards the event to the control for handling.
* @param {goog.events.BrowserEvent} e Mouse event to handle.
*/
goog.ui.Container.prototype.handleChildMouseEvents = function(e) {
var control = this.getOwnerControl(/** @type {Node} */ (e.target));
if (control) {
// Child control identified; forward the event.
switch (e.type) {
case goog.events.EventType.MOUSEDOWN:
control.handleMouseDown(e);
break;
case goog.events.EventType.MOUSEUP:
control.handleMouseUp(e);
break;
case goog.events.EventType.MOUSEOVER:
control.handleMouseOver(e);
break;
case goog.events.EventType.MOUSEOUT:
control.handleMouseOut(e);
break;
}
}
};
/**
* Returns the child control that owns the given DOM node, or null if no such
* control is found.
* @param {Node} node DOM node whose owner is to be returned.
* @return {goog.ui.Control?} Control hosted in the container to which the node
* belongs (if found).
* @protected
*/
goog.ui.Container.prototype.getOwnerControl = function(node) {
// Ensure that this container actually has child controls before
// looking up the owner.
if (this.childElementIdMap_) {
var elem = this.getElement();
// See http://b/2964418 . IE9 appears to evaluate '!=' incorrectly, so
// using '!==' instead.
// TODO(user): Possibly revert this change if/when IE9 fixes the issue.
while (node && node !== elem) {
var id = node.id;
if (id in this.childElementIdMap_) {
return this.childElementIdMap_[id];
}
node = node.parentNode;
}
}
return null;
};
/**
* Handles focus events raised when the container's key event target receives
* keyboard focus.
* @param {goog.events.BrowserEvent} e Focus event to handle.
*/
goog.ui.Container.prototype.handleFocus = function(e) {
// No-op in the base class.
};
/**
* Handles blur events raised when the container's key event target loses
* keyboard focus. The default implementation clears the highlight index.
* @param {goog.events.BrowserEvent} e Blur event to handle.
*/
goog.ui.Container.prototype.handleBlur = function(e) {
this.setHighlightedIndex(-1);
this.setMouseButtonPressed(false);
// If the container loses focus, and one of its children is open, close it.
if (this.openItem_) {
this.openItem_.setOpen(false);
}
};
/**
* Attempts to handle a keyboard event, if the control is enabled, by calling
* {@link handleKeyEventInternal}. Considered protected; should only be used
* within this package and by subclasses.
* @param {goog.events.KeyEvent} e Key event to handle.
* @return {boolean} Whether the key event was handled.
*/
goog.ui.Container.prototype.handleKeyEvent = function(e) {
if (this.isEnabled() && this.isVisible() &&
(this.getChildCount() != 0 || this.keyEventTarget_) &&
this.handleKeyEventInternal(e)) {
e.preventDefault();
e.stopPropagation();
return true;
}
return false;
};
/**
* Attempts to handle a keyboard event; returns true if the event was handled,
* false otherwise. If the container is enabled, and a child is highlighted,
* calls the child control's {@code handleKeyEvent} method to give the control
* a chance to handle the event first.
* @param {goog.events.KeyEvent} e Key event to handle.
* @return {boolean} Whether the event was handled by the container (or one of
* its children).
*/
goog.ui.Container.prototype.handleKeyEventInternal = function(e) {
// Give the highlighted control the chance to handle the key event.
var highlighted = this.getHighlighted();
if (highlighted && typeof highlighted.handleKeyEvent == 'function' &&
highlighted.handleKeyEvent(e)) {
return true;
}
// Give the open control the chance to handle the key event.
if (this.openItem_ && this.openItem_ != highlighted &&
typeof this.openItem_.handleKeyEvent == 'function' &&
this.openItem_.handleKeyEvent(e)) {
return true;
}
// Do not handle the key event if any modifier key is pressed.
if (e.shiftKey || e.ctrlKey || e.metaKey || e.altKey) {
return false;
}
// Either nothing is highlighted, or the highlighted control didn't handle
// the key event, so attempt to handle it here.
switch (e.keyCode) {
case goog.events.KeyCodes.ESC:
if (this.isFocusable()) {
this.getKeyEventTarget().blur();
} else {
return false;
}
break;
case goog.events.KeyCodes.HOME:
this.highlightFirst();
break;
case goog.events.KeyCodes.END:
this.highlightLast();
break;
case goog.events.KeyCodes.UP:
if (this.orientation_ == goog.ui.Container.Orientation.VERTICAL) {
this.highlightPrevious();
} else {
return false;
}
break;
case goog.events.KeyCodes.LEFT:
if (this.orientation_ == goog.ui.Container.Orientation.HORIZONTAL) {
if (this.isRightToLeft()) {
this.highlightNext();
} else {
this.highlightPrevious();
}
} else {
return false;
}
break;
case goog.events.KeyCodes.DOWN:
if (this.orientation_ == goog.ui.Container.Orientation.VERTICAL) {
this.highlightNext();
} else {
return false;
}
break;
case goog.events.KeyCodes.RIGHT:
if (this.orientation_ == goog.ui.Container.Orientation.HORIZONTAL) {
if (this.isRightToLeft()) {
this.highlightPrevious();
} else {
this.highlightNext();
}
} else {
return false;
}
break;
default:
return false;
}
return true;
};
// Child component management.
/**
* Creates a DOM ID for the child control and registers it to an internal
* hash table to be able to find it fast by id.
* @param {goog.ui.Control} child The child control. Its root element has
* to be created yet.
* @private
*/
goog.ui.Container.prototype.registerChildId_ = function(child) {
// Map the DOM ID of the control's root element to the control itself.
var childElem = child.getElement();
// If the control's root element doesn't have a DOM ID assign one.
var id = childElem.id || (childElem.id = child.getId());
// Lazily create the child element ID map on first use.
if (!this.childElementIdMap_) {
this.childElementIdMap_ = {};
}
this.childElementIdMap_[id] = child;
};
/**
* Adds the specified control as the last child of this container. See
* {@link goog.ui.Container#addChildAt} for detailed semantics.
* @param {goog.ui.Control} child The new child control.
* @param {boolean=} opt_render Whether the new child should be rendered
* immediately after being added (defaults to false).
*/
goog.ui.Container.prototype.addChild = function(child, opt_render) {
goog.ui.Container.superClass_.addChild.call(this, child, opt_render);
};
/**
* Overrides {@link goog.ui.Container#getChild} to make it clear that it
* only returns {@link goog.ui.Control}s.
* @param {string} id Child component ID.
* @return {goog.ui.Control} The child with the given ID; null if none.
* @override
*/
goog.ui.Container.prototype.getChild;
/**
* Overrides {@link goog.ui.Container#getChildAt} to make it clear that it
* only returns {@link goog.ui.Control}s.
* @param {number} index 0-based index.
* @return {goog.ui.Control} The child with the given ID; null if none.
* @override
*/
goog.ui.Container.prototype.getChildAt;
/**
* Adds the control as a child of this container at the given 0-based index.
* Overrides {@link goog.ui.Component#addChildAt} by also updating the
* container's highlight index. Since {@link goog.ui.Component#addChild} uses
* {@link #addChildAt} internally, we only need to override this method.
* @param {goog.ui.Control} control New child.
* @param {number} index Index at which the new child is to be added.
* @param {boolean=} opt_render Whether the new child should be rendered
* immediately after being added (defaults to false).
*/
goog.ui.Container.prototype.addChildAt = function(control, index, opt_render) {
// Make sure the child control dispatches HIGHLIGHT, UNHIGHLIGHT, OPEN, and
// CLOSE events, and that it doesn't steal keyboard focus.
control.setDispatchTransitionEvents(goog.ui.Component.State.HOVER, true);
control.setDispatchTransitionEvents(goog.ui.Component.State.OPENED, true);
if (this.isFocusable() || !this.isFocusableChildrenAllowed()) {
control.setSupportedState(goog.ui.Component.State.FOCUSED, false);
}
// Disable mouse event handling by child controls.
control.setHandleMouseEvents(false);
// Let the superclass implementation do the work.
goog.ui.Container.superClass_.addChildAt.call(this, control, index,
opt_render);
if (opt_render && this.isInDocument()) {
this.registerChildId_(control);
}
// Update the highlight index, if needed.
if (index <= this.highlightedIndex_) {
this.highlightedIndex_++;
}
};
/**
* Removes a child control. Overrides {@link goog.ui.Component#removeChild} by
* updating the highlight index. Since {@link goog.ui.Component#removeChildAt}
* uses {@link #removeChild} internally, we only need to override this method.
* @param {string|goog.ui.Control} control The ID of the child to remove, or
* the control itself.
* @param {boolean=} opt_unrender Whether to call {@code exitDocument} on the
* removed control, and detach its DOM from the document (defaults to
* false).
* @return {goog.ui.Control} The removed control, if any.
*/
goog.ui.Container.prototype.removeChild = function(control, opt_unrender) {
control = goog.isString(control) ? this.getChild(control) : control;
if (control) {
var index = this.indexOfChild(control);
if (index != -1) {
if (index == this.highlightedIndex_) {
control.setHighlighted(false);
} else if (index < this.highlightedIndex_) {
this.highlightedIndex_--;
}
}
// Remove the mapping from the child element ID map.
var childElem = control.getElement();
if (childElem && childElem.id) {
goog.object.remove(this.childElementIdMap_, childElem.id);
}
}
control = /** @type {goog.ui.Control} */ (
goog.ui.Container.superClass_.removeChild.call(this, control,
opt_unrender));
// Re-enable mouse event handling (in case the control is reused elsewhere).
control.setHandleMouseEvents(true);
return control;
};
// Container state management.
/**
* Returns the container's orientation.
* @return {?goog.ui.Container.Orientation} Container orientation.
*/
goog.ui.Container.prototype.getOrientation = function() {
return this.orientation_;
};
/**
* Sets the container's orientation.
* @param {goog.ui.Container.Orientation} orientation Container orientation.
*/
// TODO(user): Do we need to support containers with dynamic orientation?
goog.ui.Container.prototype.setOrientation = function(orientation) {
if (this.getElement()) {
// Too late.
throw Error(goog.ui.Component.Error.ALREADY_RENDERED);
}
this.orientation_ = orientation;
};
/**
* Returns true if the container's visibility is set to visible, false if
* it is set to hidden. A container that is set to hidden is guaranteed
* to be hidden from the user, but the reverse isn't necessarily true.
* A container may be set to visible but can otherwise be obscured by another
* element, rendered off-screen, or hidden using direct CSS manipulation.
* @return {boolean} Whether the container is set to be visible.
*/
goog.ui.Container.prototype.isVisible = function() {
return this.visible_;
};
/**
* Shows or hides the container. Does nothing if the container already has
* the requested visibility. Otherwise, dispatches a SHOW or HIDE event as
* appropriate, giving listeners a chance to prevent the visibility change.
* @param {boolean} visible Whether to show or hide the container.
* @param {boolean=} opt_force If true, doesn't check whether the container
* already has the requested visibility, and doesn't dispatch any events.
* @return {boolean} Whether the visibility was changed.
*/
goog.ui.Container.prototype.setVisible = function(visible, opt_force) {
if (opt_force || (this.visible_ != visible && this.dispatchEvent(visible ?
goog.ui.Component.EventType.SHOW : goog.ui.Component.EventType.HIDE))) {
this.visible_ = visible;
var elem = this.getElement();
if (elem) {
goog.style.showElement(elem, visible);
if (this.isFocusable()) {
// Enable keyboard access only for enabled & visible containers.
this.renderer_.enableTabIndex(this.getKeyEventTarget(),
this.enabled_ && this.visible_);
}
if (!opt_force) {
this.dispatchEvent(this.visible_ ?
goog.ui.Container.EventType.AFTER_SHOW :
goog.ui.Container.EventType.AFTER_HIDE);
}
}
return true;
}
return false;
};
/**
* Returns true if the container is enabled, false otherwise.
* @return {boolean} Whether the container is enabled.
*/
goog.ui.Container.prototype.isEnabled = function() {
return this.enabled_;
};
/**
* Enables/disables the container based on the {@code enable} argument.
* Dispatches an {@code ENABLED} or {@code DISABLED} event prior to changing
* the container's state, which may be caught and canceled to prevent the
* container from changing state. Also enables/disables child controls.
* @param {boolean} enable Whether to enable or disable the container.
*/
goog.ui.Container.prototype.setEnabled = function(enable) {
if (this.enabled_ != enable && this.dispatchEvent(enable ?
goog.ui.Component.EventType.ENABLE :
goog.ui.Component.EventType.DISABLE)) {
if (enable) {
// Flag the container as enabled first, then update children. This is
// because controls can't be enabled if their parent is disabled.
this.enabled_ = true;
this.forEachChild(function(child) {
// Enable child control unless it is flagged.
if (child.wasDisabled) {
delete child.wasDisabled;
} else {
child.setEnabled(true);
}
});
} else {
// Disable children first, then flag the container as disabled. This is
// because controls can't be disabled if their parent is already disabled.
this.forEachChild(function(child) {
// Disable child control, or flag it if it's already disabled.
if (child.isEnabled()) {
child.setEnabled(false);
} else {
child.wasDisabled = true;
}
});
this.enabled_ = false;
this.setMouseButtonPressed(false);
}
if (this.isFocusable()) {
// Enable keyboard access only for enabled & visible components.
this.renderer_.enableTabIndex(this.getKeyEventTarget(),
enable && this.visible_);
}
}
};
/**
* Returns true if the container is focusable, false otherwise. The default
* is true. Focusable containers always have a tab index and allocate a key
* handler to handle keyboard events while focused.
* @return {boolean} Whether the component is focusable.
*/
goog.ui.Container.prototype.isFocusable = function() {
return this.focusable_;
};
/**
* Sets whether the container is focusable. The default is true. Focusable
* containers always have a tab index and allocate a key handler to handle
* keyboard events while focused.
* @param {boolean} focusable Whether the component is to be focusable.
*/
goog.ui.Container.prototype.setFocusable = function(focusable) {
if (focusable != this.focusable_ && this.isInDocument()) {
this.enableFocusHandling_(focusable);
}
this.focusable_ = focusable;
if (this.enabled_ && this.visible_) {
this.renderer_.enableTabIndex(this.getKeyEventTarget(), focusable);
}
};
/**
* Returns true if the container allows children to be focusable, false
* otherwise. Only effective if the container is not focusable.
* @return {boolean} Whether children should be focusable.
*/
goog.ui.Container.prototype.isFocusableChildrenAllowed = function() {
return this.allowFocusableChildren_;
};
/**
* Sets whether the container allows children to be focusable, false
* otherwise. Only effective if the container is not focusable.
* @param {boolean} focusable Whether the children should be focusable.
*/
goog.ui.Container.prototype.setFocusableChildrenAllowed = function(focusable) {
this.allowFocusableChildren_ = focusable;
};
/**
* @return {boolean} Whether highlighting a child component should also open it.
*/
goog.ui.Container.prototype.isOpenFollowsHighlight = function() {
return this.openFollowsHighlight_;
};
/**
* Sets whether highlighting a child component should also open it.
* @param {boolean} follow Whether highlighting a child component also opens it.
*/
goog.ui.Container.prototype.setOpenFollowsHighlight = function(follow) {
this.openFollowsHighlight_ = follow;
};
// Highlight management.
/**
* Returns the index of the currently highlighted item (-1 if none).
* @return {number} Index of the currently highlighted item.
*/
goog.ui.Container.prototype.getHighlightedIndex = function() {
return this.highlightedIndex_;
};
/**
* Highlights the item at the given 0-based index (if any). If another item
* was previously highlighted, it is un-highlighted.
* @param {number} index Index of item to highlight (-1 removes the current
* highlight).
*/
goog.ui.Container.prototype.setHighlightedIndex = function(index) {
var child = this.getChildAt(index);
if (child) {
child.setHighlighted(true);
} else if (this.highlightedIndex_ > -1) {
this.getHighlighted().setHighlighted(false);
}
};
/**
* Highlights the given item if it exists and is a child of the container;
* otherwise un-highlights the currently highlighted item.
* @param {goog.ui.Control} item Item to highlight.
*/
goog.ui.Container.prototype.setHighlighted = function(item) {
this.setHighlightedIndex(this.indexOfChild(item));
};
/**
* Returns the currently highlighted item (if any).
* @return {goog.ui.Control?} Highlighted item (null if none).
*/
goog.ui.Container.prototype.getHighlighted = function() {
return this.getChildAt(this.highlightedIndex_);
};
/**
* Highlights the first highlightable item in the container
*/
goog.ui.Container.prototype.highlightFirst = function() {
this.highlightHelper(function(index, max) {
return (index + 1) % max;
}, this.getChildCount() - 1);
};
/**
* Highlights the last highlightable item in the container.
*/
goog.ui.Container.prototype.highlightLast = function() {
this.highlightHelper(function(index, max) {
index--;
return index < 0 ? max - 1 : index;
}, 0);
};
/**
* Highlights the next highlightable item (or the first if nothing is currently
* highlighted).
*/
goog.ui.Container.prototype.highlightNext = function() {
this.highlightHelper(function(index, max) {
return (index + 1) % max;
}, this.highlightedIndex_);
};
/**
* Highlights the previous highlightable item (or the last if nothing is
* currently highlighted).
*/
goog.ui.Container.prototype.highlightPrevious = function() {
this.highlightHelper(function(index, max) {
index--;
return index < 0 ? max - 1 : index;
}, this.highlightedIndex_);
};
/**
* Helper function that manages the details of moving the highlight among
* child controls in response to keyboard events.
* @param {function(number, number) : number} fn Function that accepts the
* current and maximum indices, and returns the next index to check.
* @param {number} startIndex Start index.
* @return {boolean} Whether the highlight has changed.
* @protected
*/
goog.ui.Container.prototype.highlightHelper = function(fn, startIndex) {
// If the start index is -1 (meaning there's nothing currently highlighted),
// try starting from the currently open item, if any.
var curIndex = startIndex < 0 ?
this.indexOfChild(this.openItem_) : startIndex;
var numItems = this.getChildCount();
curIndex = fn.call(this, curIndex, numItems);
var visited = 0;
while (visited <= numItems) {
var control = this.getChildAt(curIndex);
if (control && this.canHighlightItem(control)) {
this.setHighlightedIndexFromKeyEvent(curIndex);
return true;
}
visited++;
curIndex = fn.call(this, curIndex, numItems);
}
return false;
};
/**
* Returns whether the given item can be highlighted.
* @param {goog.ui.Control} item The item to check.
* @return {boolean} Whether the item can be highlighted.
* @protected
*/
goog.ui.Container.prototype.canHighlightItem = function(item) {
return item.isVisible() && item.isEnabled() &&
item.isSupportedState(goog.ui.Component.State.HOVER);
};
/**
* Helper method that sets the highlighted index to the given index in response
* to a keyboard event. The base class implementation simply calls the
* {@link #setHighlightedIndex} method, but subclasses can override this
* behavior as needed.
* @param {number} index Index of item to highlight.
* @protected
*/
goog.ui.Container.prototype.setHighlightedIndexFromKeyEvent = function(index) {
this.setHighlightedIndex(index);
};
/**
* Returns the currently open (expanded) control in the container (null if
* none).
* @return {goog.ui.Control?} The currently open control.
*/
goog.ui.Container.prototype.getOpenItem = function() {
return this.openItem_;
};
/**
* Returns true if the mouse button is pressed, false otherwise.
* @return {boolean} Whether the mouse button is pressed.
*/
goog.ui.Container.prototype.isMouseButtonPressed = function() {
return this.mouseButtonPressed_;
};
/**
* Sets or clears the "mouse button pressed" flag.
* @param {boolean} pressed Whether the mouse button is presed.
*/
goog.ui.Container.prototype.setMouseButtonPressed = function(pressed) {
this.mouseButtonPressed_ = pressed;
};
|
/*
* DarkTooltip v0.3.0
* Simple customizable tooltip with confirm option and 3d effects
* (c)2014 Rubén Torres - rubentdlh@gmail.com
* Released under the MIT license
*/
(function($) {
function DarkTooltip(element, options){
this.bearer = element;
this.options = options;
this.hideEvent;
this.mouseOverMode=(this.options.trigger == "hover" || this.options.trigger == "mouseover" || this.options.trigger == "onmouseover");
}
DarkTooltip.prototype = {
show: function(){
var dt = this;
if(this.options.modal){
this.modalLayer.css('display', 'block');
}
//Close all other tooltips
this.tooltip.css('display', 'block');
//Set event to prevent tooltip from closig when mouse is over the tooltip
if(dt.mouseOverMode){
this.tooltip.mouseover( function(){
clearTimeout(dt.hideEvent);
});
this.tooltip.mouseout( function(){
clearTimeout(dt.hideEvent);
dt.hide();
});
}
},
hide: function(){
var dt=this;
this.hideEvent = setTimeout( function(){
dt.tooltip.hide();
}, 100);
if(dt.options.modal){
dt.modalLayer.hide();
}
},
toggle: function(){
if(this.tooltip.is(":visible")){
this.hide();
}else{
this.show();
}
},
addAnimation: function(){
switch(this.options.animation){
case 'none':
break;
case 'fadeIn':
this.tooltip.addClass('animated');
this.tooltip.addClass('fadeIn');
break;
case 'flipIn':
this.tooltip.addClass('animated');
this.tooltip.addClass('flipIn');
break;
}
},
setContent: function(){
$(this.bearer).css('cursor', 'pointer');
//Get tooltip content
if(this.options.content){
this.content = this.options.content;
}else if(this.bearer.attr("data-tooltip")){
this.content = this.bearer.attr("data-tooltip");
}else{
// console.log("No content for tooltip: " + this.bearer.selector);
return;
}
if(this.content.charAt(0) == '#'){
$(this.content).hide();
this.content = $(this.content).html();
this.contentType='html';
}else{
this.contentType='text';
}
tooltipId = "";
if(this.bearer.attr("id") != ""){
tooltipId = "id='darktooltip-" + this.bearer.attr("id") + "'";
}
//Create modal layer
this.modalLayer = $("<ins class='darktooltip-modal-layer'></ins>");
//Create tooltip container
this.tooltip = $("<ins " + tooltipId + " class = 'dark-tooltip " + this.options.theme + " " + this.options.size + " "
+ this.options.gravity + "'><div>" + this.content + "</div><div class = 'tip'></div></ins>");
this.tip = this.tooltip.find(".tip");
$("body").append(this.modalLayer);
$("body").append(this.tooltip);
//Adjust size for html tooltip
if(this.contentType == 'html'){
this.tooltip.css('max-width','none');
}
this.tooltip.css('opacity', this.options.opacity);
this.addAnimation();
if(this.options.confirm){
this.addConfirm();
}
},
setPositions: function(){
var leftPos = this.bearer.offset().left;
var topPos = this.bearer.offset().top;
switch(this.options.gravity){
case 'south':
leftPos += this.bearer.outerWidth()/2 - this.tooltip.outerWidth()/2;
topPos += -this.tooltip.outerHeight() - this.tip.outerHeight()/2;
break;
case 'west':
leftPos += this.bearer.outerWidth() + this.tip.outerWidth()/2;
topPos += this.bearer.outerHeight()/2 - (this.tooltip.outerHeight()/2);
break;
case 'north':
leftPos += this.bearer.outerWidth()/2 - (this.tooltip.outerWidth()/2);
topPos += this.bearer.outerHeight() + this.tip.outerHeight()/2;
break;
case 'east':
leftPos += -this.tooltip.outerWidth() - this.tip.outerWidth()/2;
topPos += this.bearer.outerHeight()/2 - this.tooltip.outerHeight()/2;
break;
}
this.tooltip.css('left', leftPos);
this.tooltip.css('top', topPos);
},
setEvents: function(){
var dt = this;
var delay = dt.options.hoverDelay;
var setTimeoutConst;
if(dt.mouseOverMode){
this.bearer.mouseover( function(){
//Timeout for hover mouse delay
setTimeoutConst = setTimeout( function(){
dt.setPositions();
dt.show();
}, delay);
}).mouseout( function(){
clearTimeout(setTimeoutConst );
dt.hide();
});
}else if(this.options.trigger == "click" || this.options.trigger == "onclik"){
this.tooltip.click( function(e){
e.stopPropagation();
});
this.bearer.click( function(e){
e.preventDefault();
dt.setPositions();
dt.toggle();
e.stopPropagation();
});
$('html').click(function(){
dt.hide();
})
}
},
activate: function(){
this.setContent();
if(this.content){
this.setEvents();
}
},
addConfirm: function(){
this.tooltip.append("<ul class = 'confirm'><li class = 'darktooltip-yes'>"
+ this.options.yes +"</li><li class = 'darktooltip-no'>"+ this.options.no +"</li></ul>");
this.setConfirmEvents();
},
setConfirmEvents: function(){
var dt = this;
this.tooltip.find('li.darktooltip-yes').click( function(e){
dt.onYes();
e.stopPropagation();
});
this.tooltip.find('li.darktooltip-no').click( function(e){
dt.onNo();
e.stopPropagation();
});
},
finalMessage: function(){
if(this.options.finalMessage){
var dt = this;
dt.tooltip.find('div:first').html(this.options.finalMessage);
dt.tooltip.find('ul').remove();
dt.setPositions();
setTimeout( function(){
dt.hide();
dt.setContent();
}, dt.options.finalMessageDuration);
}else{
this.hide();
}
},
onYes: function(){
this.options.onYes(this.bearer);
this.finalMessage();
},
onNo: function(){
this.options.onNo(this.bearer);
this.hide();
}
}
$.fn.darkTooltip = function(options) {
return this.each(function(){
options = $.extend({}, $.fn.darkTooltip.defaults, options);
var tooltip = new DarkTooltip($(this), options);
tooltip.activate();
});
}
$.fn.darkTooltip.defaults = {
animation: 'none',
confirm: false,
content:'',
finalMessage: '',
finalMessageDuration: 1000,
gravity: 'south',
hoverDelay: 0,
modal: false,
no: 'No',
onNo: function(){},
onYes: function(){},
opacity: 0.9,
size: 'medium',
theme: 'dark',
trigger: 'hover',
yes: 'Yes',
};
})(jQuery);
|
$(document).ready(function() {
// hide the save and edit button on startup
$('#save-page').hide();
$('#edit-page').hide();
// hide the log message container
$("#log").hide();
// load navigation
$("#navigation").load("./sitemap.html #sitemap li");
// and set active navigation item
setTimeout("setActiveNavItem()",100);
// load title
$("#brand").load("./sitemap.html #brand a");
// load footer
$("#footer").load("./sitemap.html #footer p");
});
function setActiveNavItem() {
$(".nav li").each(function() {
if (getFilename($(this).find('a').attr('href')) == getFilename(window.location.pathname)) {
$(this).addClass( 'active' );
}
});
}
function getFilename( path ) {
var filename = './',
index = path.lastIndexOf("/");
if ( index ) {
filename = path.substr( index );
}
return filename.toLowerCase();
}
|
var path = require('path'),
url = require('url'),
request,
fs = require('fs');
var less = {
version: [1, 6, 0],
Parser: require('./parser').Parser,
tree: require('./tree'),
render: function (input, options, callback) {
options = options || {};
if (typeof(options) === 'function') {
callback = options;
options = {};
}
var parser = new(less.Parser)(options),
ee;
if (callback) {
parser.parse(input, function (e, root) {
try { callback(e, root && root.toCSS && root.toCSS(options)); }
catch (err) { callback(err); }
});
} else {
ee = new (require('events').EventEmitter)();
process.nextTick(function () {
parser.parse(input, function (e, root) {
if (e) { return ee.emit('error', e); }
try { ee.emit('success', root.toCSS(options)); }
catch (err) { ee.emit('error', err); }
});
});
return ee;
}
},
formatError: function(ctx, options) {
options = options || {};
var message = "";
var extract = ctx.extract;
var error = [];
var stylize = options.color ? require('./lessc_helper').stylize : function (str) { return str; };
// only output a stack if it isn't a less error
if (ctx.stack && !ctx.type) { return stylize(ctx.stack, 'red'); }
if (!ctx.hasOwnProperty('index') || !extract) {
return ctx.stack || ctx.message;
}
if (typeof(extract[0]) === 'string') {
error.push(stylize((ctx.line - 1) + ' ' + extract[0], 'grey'));
}
if (typeof(extract[1]) === 'string') {
var errorTxt = ctx.line + ' ';
if (extract[1]) {
errorTxt += extract[1].slice(0, ctx.column) +
stylize(stylize(stylize(extract[1][ctx.column], 'bold') +
extract[1].slice(ctx.column + 1), 'red'), 'inverse');
}
error.push(errorTxt);
}
if (typeof(extract[2]) === 'string') {
error.push(stylize((ctx.line + 1) + ' ' + extract[2], 'grey'));
}
error = error.join('\n') + stylize('', 'reset') + '\n';
message += stylize(ctx.type + 'Error: ' + ctx.message, 'red');
if (ctx.filename) {
message += stylize(' in ', 'red') + ctx.filename +
stylize(' on line ' + ctx.line + ', column ' + (ctx.column + 1) + ':', 'grey');
}
message += '\n' + error;
if (ctx.callLine) {
message += stylize('from ', 'red') + (ctx.filename || '') + '/n';
message += stylize(ctx.callLine, 'grey') + ' ' + ctx.callExtract + '/n';
}
return message;
},
writeError: function (ctx, options) {
options = options || {};
if (options.silent) { return; }
console.error(less.formatError(ctx, options));
}
};
['color', 'directive', 'operation', 'dimension',
'keyword', 'variable', 'ruleset', 'element',
'selector', 'quoted', 'expression', 'rule',
'call', 'url', 'alpha', 'import',
'mixin', 'comment', 'anonymous', 'value',
'javascript', 'assignment', 'condition', 'paren',
'media', 'unicode-descriptor', 'negative', 'extend'
].forEach(function (n) {
require('./tree/' + n);
});
var isUrlRe = /^(?:https?:)?\/\//i;
less.Parser.fileLoader = function (file, currentFileInfo, callback, env) {
var pathname, dirname, data,
newFileInfo = {
relativeUrls: env.relativeUrls,
entryPath: currentFileInfo.entryPath,
rootpath: currentFileInfo.rootpath,
rootFilename: currentFileInfo.rootFilename
};
function handleDataAndCallCallback(data) {
var j = file.lastIndexOf('/');
// Pass on an updated rootpath if path of imported file is relative and file
// is in a (sub|sup) directory
//
// Examples:
// - If path of imported file is 'module/nav/nav.less' and rootpath is 'less/',
// then rootpath should become 'less/module/nav/'
// - If path of imported file is '../mixins.less' and rootpath is 'less/',
// then rootpath should become 'less/../'
if(newFileInfo.relativeUrls && !/^(?:[a-z-]+:|\/)/.test(file) && j != -1) {
var relativeSubDirectory = file.slice(0, j+1);
newFileInfo.rootpath = newFileInfo.rootpath + relativeSubDirectory; // append (sub|sup) directory path of imported file
}
newFileInfo.currentDirectory = pathname.replace(/[^\\\/]*$/, "");
newFileInfo.filename = pathname;
callback(null, data, pathname, newFileInfo);
}
var isUrl = isUrlRe.test( file );
if (isUrl || isUrlRe.test(currentFileInfo.currentDirectory)) {
if (request === undefined) {
try { request = require('request'); }
catch(e) { request = null; }
}
if (!request) {
callback({ type: 'File', message: "optional dependency 'request' required to import over http(s)\n" });
return;
}
var urlStr = isUrl ? file : url.resolve(currentFileInfo.currentDirectory, file),
urlObj = url.parse(urlStr);
request.get({uri: urlStr, strictSSL: !env.insecure }, function (error, res, body) {
if (res.statusCode === 404) {
callback({ type: 'File', message: "resource '" + urlStr + "' was not found\n" });
return;
}
if (!body) {
console.error( 'Warning: Empty body (HTTP '+ res.statusCode + ') returned by "' + urlStr +'"' );
}
if (error) {
callback({ type: 'File', message: "resource '" + urlStr + "' gave this Error:\n "+ error +"\n" });
}
pathname = urlStr;
dirname = urlObj.protocol +'//'+ urlObj.host + urlObj.pathname.replace(/[^\/]*$/, '');
handleDataAndCallCallback(body);
});
} else {
var paths = [currentFileInfo.currentDirectory].concat(env.paths);
paths.push('.');
if (env.syncImport) {
for (var i = 0; i < paths.length; i++) {
try {
pathname = path.join(paths[i], file);
fs.statSync(pathname);
break;
} catch (e) {
pathname = null;
}
}
if (!pathname) {
callback({ type: 'File', message: "'" + file + "' wasn't found" });
return;
}
try {
data = fs.readFileSync(pathname, 'utf-8');
handleDataAndCallCallback(data);
} catch (e) {
callback(e);
}
} else {
(function tryPathIndex(i) {
if (i < paths.length) {
pathname = path.join(paths[i], file);
fs.stat(pathname, function (err) {
if (err) {
tryPathIndex(i + 1);
} else {
fs.readFile(pathname, 'utf-8', function(e, data) {
if (e) { callback(e); }
handleDataAndCallCallback(data);
});
}
});
} else {
callback({ type: 'File', message: "'" + file + "' wasn't found" });
}
}(0));
}
}
};
require('./env');
require('./functions');
require('./colors');
require('./visitor.js');
require('./import-visitor.js');
require('./extend-visitor.js');
require('./join-selector-visitor.js');
require('./to-css-visitor.js');
require('./source-map-output.js');
for (var k in less) { exports[k] = less[k]; }
|
/**
* Package: svedit.select
*
* Licensed under the MIT License
*
* Copyright(c) 2010 Alexis Deveria
* Copyright(c) 2010 Jeff Schiller
*/
// Dependencies:
// 1) jQuery
// 2) browser.js
// 3) math.js
// 4) svgutils.js
var svgedit = svgedit || {};
(function() {
if (!svgedit.select) {
svgedit.select = {};
}
var svgFactory_;
var config_;
var selectorManager_; // A Singleton
var gripRadius;
svgedit.browser.isTouch() ? gripRadius = 10 : gripRadius = 4;
// Class: svgedit.select.Selector
// Private class for DOM element selection boxes
//
// Parameters:
// id - integer to internally indentify the selector
// elem - DOM element associated with this selector
svgedit.select.Selector = function(id, elem) {
// this is the selector's unique number
this.id = id;
// this holds a reference to the element for which this selector is being used
this.selectedElement = elem;
// this is a flag used internally to track whether the selector is being used or not
this.locked = true;
// this holds a reference to the <g> element that holds all visual elements of the selector
this.selectorGroup = svgFactory_.createSVGElement({
'element': 'g',
'attr': {'id': ('selectorGroup' + this.id)}
});
// this holds a reference to the path rect
this.selectorRect = this.selectorGroup.appendChild(
svgFactory_.createSVGElement({
'element': 'path',
'attr': {
'id': ('selectedBox' + this.id),
'fill': 'none',
'stroke': '#22C',
'stroke-width': '1',
'stroke-dasharray': '5,5',
// need to specify this so that the rect is not selectable
'style': 'pointer-events:none'
}
})
);
// this holds a reference to the grip coordinates for this selector
this.gripCoords = {
'nw': null,
'n' : null,
'ne': null,
'e' : null,
'se': null,
's' : null,
'sw': null,
'w' : null
};
this.reset(this.selectedElement);
};
// Function: svgedit.select.Selector.reset
// Used to reset the id and element that the selector is attached to
//
// Parameters:
// e - DOM element associated with this selector
svgedit.select.Selector.prototype.reset = function(e) {
this.locked = true;
this.selectedElement = e;
this.resize();
this.selectorGroup.setAttribute('display', 'inline');
};
// Function: svgedit.select.Selector.updateGripCursors
// Updates cursors for corner grips on rotation so arrows point the right way
//
// Parameters:
// angle - Float indicating current rotation angle in degrees
svgedit.select.Selector.prototype.updateGripCursors = function(angle) {
var dir_arr = [];
var steps = Math.round(angle / 45);
if(steps < 0) steps += 8;
for (var dir in selectorManager_.selectorGrips) {
dir_arr.push(dir);
}
while(steps > 0) {
dir_arr.push(dir_arr.shift());
steps--;
}
var i = 0;
for (var dir in selectorManager_.selectorGrips) {
selectorManager_.selectorGrips[dir].setAttribute('style', ('cursor:' + dir_arr[i] + '-resize'));
i++;
};
};
// Function: svgedit.select.Selector.showGrips
// Show the resize grips of this selector
//
// Parameters:
// show - boolean indicating whether grips should be shown or not
svgedit.select.Selector.prototype.showGrips = function(show) {
// TODO: use suspendRedraw() here
var bShow = show ? 'inline' : 'none';
selectorManager_.selectorGripsGroup.setAttribute('display', bShow);
var elem = this.selectedElement;
this.hasGrips = show;
if(elem && show) {
this.selectorGroup.appendChild(selectorManager_.selectorGripsGroup);
this.updateGripCursors(svgedit.utilities.getRotationAngle(elem));
}
};
// Function: svgedit.select.Selector.resize
// Updates the selector to match the element's size
svgedit.select.Selector.prototype.resize = function() {
var selectedBox = this.selectorRect,
mgr = selectorManager_,
selectedGrips = mgr.selectorGrips,
selected = this.selectedElement,
sw = selected.getAttribute('stroke-width'),
current_zoom = svgFactory_.currentZoom();
var offset = 1/current_zoom;
if (selected.getAttribute('stroke') !== 'none' && !isNaN(sw)) {
offset += (sw/2);
}
var tagName = selected.tagName;
if (tagName === 'text') {
offset += 2/current_zoom;
}
// loop and transform our bounding box until we reach our first rotation
var tlist = svgedit.transformlist.getTransformList(selected);
var m = svgedit.math.transformListToTransform(tlist).matrix;
// This should probably be handled somewhere else, but for now
// it keeps the selection box correctly positioned when zoomed
m.e *= current_zoom;
m.f *= current_zoom;
var bbox = svgedit.utilities.getBBox(selected);
if(tagName === 'g' && !$.data(selected, 'gsvg')) {
// The bbox for a group does not include stroke vals, so we
// get the bbox based on its children.
var stroked_bbox = svgFactory_.getStrokedBBox(selected.childNodes);
if(stroked_bbox) {
bbox = stroked_bbox;
}
}
// apply the transforms
var l=bbox.x, t=bbox.y, w=bbox.width, h=bbox.height,
bbox = {x:l, y:t, width:w, height:h};
// we need to handle temporary transforms too
// if skewed, get its transformed box, then find its axis-aligned bbox
//*
offset *= current_zoom;
var nbox = svgedit.math.transformBox(l*current_zoom, t*current_zoom, w*current_zoom, h*current_zoom, m),
aabox = nbox.aabox,
nbax = aabox.x - offset,
nbay = aabox.y - offset,
nbaw = aabox.width + (offset * 2),
nbah = aabox.height + (offset * 2);
// now if the shape is rotated, un-rotate it
var cx = nbax + nbaw/2,
cy = nbay + nbah/2;
var angle = svgedit.utilities.getRotationAngle(selected);
if (angle) {
var rot = svgFactory_.svgRoot().createSVGTransform();
rot.setRotate(-angle,cx,cy);
var rotm = rot.matrix;
nbox.tl = svgedit.math.transformPoint(nbox.tl.x,nbox.tl.y,rotm);
nbox.tr = svgedit.math.transformPoint(nbox.tr.x,nbox.tr.y,rotm);
nbox.bl = svgedit.math.transformPoint(nbox.bl.x,nbox.bl.y,rotm);
nbox.br = svgedit.math.transformPoint(nbox.br.x,nbox.br.y,rotm);
// calculate the axis-aligned bbox
var tl = nbox.tl;
var minx = tl.x,
miny = tl.y,
maxx = tl.x,
maxy = tl.y;
var Min = Math.min, Max = Math.max;
minx = Min(minx, Min(nbox.tr.x, Min(nbox.bl.x, nbox.br.x) ) ) - offset;
miny = Min(miny, Min(nbox.tr.y, Min(nbox.bl.y, nbox.br.y) ) ) - offset;
maxx = Max(maxx, Max(nbox.tr.x, Max(nbox.bl.x, nbox.br.x) ) ) + offset;
maxy = Max(maxy, Max(nbox.tr.y, Max(nbox.bl.y, nbox.br.y) ) ) + offset;
nbax = minx;
nbay = miny;
nbaw = (maxx-minx);
nbah = (maxy-miny);
}
var sr_handle = svgFactory_.svgRoot().suspendRedraw(100);
var dstr = 'M' + nbax + ',' + nbay
+ ' L' + (nbax+nbaw) + ',' + nbay
+ ' ' + (nbax+nbaw) + ',' + (nbay+nbah)
+ ' ' + nbax + ',' + (nbay+nbah) + 'z';
selectedBox.setAttribute('d', dstr);
var xform = angle ? 'rotate(' + [angle,cx,cy].join(',') + ')' : '';
this.selectorGroup.setAttribute('transform', xform);
// TODO(codedread): Is this if needed?
// if(selected === selectedElements[0]) {
this.gripCoords = {
'nw': [nbax, nbay],
'ne': [nbax+nbaw, nbay],
'sw': [nbax, nbay+nbah],
'se': [nbax+nbaw, nbay+nbah],
'n': [nbax + (nbaw)/2, nbay],
'w': [nbax, nbay + (nbah)/2],
'e': [nbax + nbaw, nbay + (nbah)/2],
's': [nbax + (nbaw)/2, nbay + nbah]
};
for(var dir in this.gripCoords) {
var coords = this.gripCoords[dir];
selectedGrips[dir].setAttribute('cx', coords[0]);
selectedGrips[dir].setAttribute('cy', coords[1]);
};
// we want to go 20 pixels in the negative transformed y direction, ignoring scale
mgr.rotateGripConnector.setAttribute('x1', nbax + (nbaw)/2);
mgr.rotateGripConnector.setAttribute('y1', nbay);
mgr.rotateGripConnector.setAttribute('x2', nbax + (nbaw)/2);
mgr.rotateGripConnector.setAttribute('y2', nbay - (gripRadius*5));
mgr.rotateGrip.setAttribute('cx', nbax + (nbaw)/2);
mgr.rotateGrip.setAttribute('cy', nbay - (gripRadius*5));
// }
svgFactory_.svgRoot().unsuspendRedraw(sr_handle);
};
// Class: svgedit.select.SelectorManager
svgedit.select.SelectorManager = function() {
// this will hold the <g> element that contains all selector rects/grips
this.selectorParentGroup = null;
// this is a special rect that is used for multi-select
this.rubberBandBox = null;
// this will hold objects of type svgedit.select.Selector (see above)
this.selectors = [];
// this holds a map of SVG elements to their Selector object
this.selectorMap = {};
// this holds a reference to the grip elements
this.selectorGrips = {
'nw': null,
'n' : null,
'ne': null,
'e' : null,
'se': null,
's' : null,
'sw': null,
'w' : null
};
this.selectorGripsGroup = null;
this.rotateGripConnector = null;
this.rotateGrip = null;
this.initGroup();
};
// Function: svgedit.select.SelectorManager.initGroup
// Resets the parent selector group element
svgedit.select.SelectorManager.prototype.initGroup = function() {
// remove old selector parent group if it existed
if (this.selectorParentGroup && this.selectorParentGroup.parentNode) {
this.selectorParentGroup.parentNode.removeChild(this.selectorParentGroup);
}
// create parent selector group and add it to svgroot
this.selectorParentGroup = svgFactory_.createSVGElement({
'element': 'g',
'attr': {'id': 'selectorParentGroup'}
});
this.selectorGripsGroup = svgFactory_.createSVGElement({
'element': 'g',
'attr': {'display': 'none'}
});
this.selectorParentGroup.appendChild(this.selectorGripsGroup);
svgFactory_.svgRoot().appendChild(this.selectorParentGroup);
this.selectorMap = {};
this.selectors = [];
this.rubberBandBox = null;
// add the corner grips
for (var dir in this.selectorGrips) {
var grip = svgFactory_.createSVGElement({
'element': 'circle',
'attr': {
'id': ('selectorGrip_resize_' + dir),
'fill': '#22C',
'r': gripRadius,
'style': ('cursor:' + dir + '-resize'),
// This expands the mouse-able area of the grips making them
// easier to grab with the mouse.
// This works in Opera and WebKit, but does not work in Firefox
// see https://bugzilla.mozilla.org/show_bug.cgi?id=500174
'stroke-width': 2,
'pointer-events': 'all'
}
});
$.data(grip, 'dir', dir);
$.data(grip, 'type', 'resize');
this.selectorGrips[dir] = this.selectorGripsGroup.appendChild(grip);
}
// add rotator elems
this.rotateGripConnector = this.selectorGripsGroup.appendChild(
svgFactory_.createSVGElement({
'element': 'line',
'attr': {
'id': ('selectorGrip_rotateconnector'),
'stroke': '#22C',
'stroke-width': '1'
}
})
);
this.rotateGrip = this.selectorGripsGroup.appendChild(
svgFactory_.createSVGElement({
'element': 'circle',
'attr': {
'id': 'selectorGrip_rotate',
'fill': 'lime',
'r': gripRadius,
'stroke': '#22C',
'stroke-width': 2,
'style': 'cursor:url(' + config_.imgPath + 'rotate.png) 12 12, auto;'
}
})
);
$.data(this.rotateGrip, 'type', 'rotate');
if($('#canvasBackground').length) return;
var dims = config_.dimensions;
var canvasbg = svgFactory_.createSVGElement({
'element': 'svg',
'attr': {
'id': 'canvasBackground',
'width': dims[0],
'height': dims[1],
'x': 0,
'y': 0,
'overflow': (svgedit.browser.isWebkit() ? 'none' : 'visible'), // Chrome 7 has a problem with this when zooming out
'style': 'pointer-events:none'
}
});
var rect = svgFactory_.createSVGElement({
'element': 'rect',
'attr': {
'width': '100%',
'height': '100%',
'x': 0,
'y': 0,
'stroke-width': 1,
'stroke': '#000',
'fill': '#FFF',
'style': 'pointer-events:none'
}
});
// Both Firefox and WebKit are too slow with this filter region (especially at higher
// zoom levels) and Opera has at least one bug
// if (!svgedit.browser.isOpera()) rect.setAttribute('filter', 'url(#canvashadow)');
canvasbg.appendChild(rect);
svgFactory_.svgRoot().insertBefore(canvasbg, svgFactory_.svgContent());
};
// Function: svgedit.select.SelectorManager.requestSelector
// Returns the selector based on the given element
//
// Parameters:
// elem - DOM element to get the selector for
svgedit.select.SelectorManager.prototype.requestSelector = function(elem) {
if (elem == null) return null;
var N = this.selectors.length;
// If we've already acquired one for this element, return it.
if (typeof(this.selectorMap[elem.id]) == 'object') {
this.selectorMap[elem.id].locked = true;
return this.selectorMap[elem.id];
}
for (var i = 0; i < N; ++i) {
if (this.selectors[i] && !this.selectors[i].locked) {
this.selectors[i].locked = true;
this.selectors[i].reset(elem);
this.selectorMap[elem.id] = this.selectors[i];
return this.selectors[i];
}
}
// if we reached here, no available selectors were found, we create one
this.selectors[N] = new svgedit.select.Selector(N, elem);
this.selectorParentGroup.appendChild(this.selectors[N].selectorGroup);
this.selectorMap[elem.id] = this.selectors[N];
return this.selectors[N];
};
// Function: svgedit.select.SelectorManager.releaseSelector
// Removes the selector of the given element (hides selection box)
//
// Parameters:
// elem - DOM element to remove the selector for
svgedit.select.SelectorManager.prototype.releaseSelector = function(elem) {
if (elem == null) return;
var N = this.selectors.length,
sel = this.selectorMap[elem.id];
for (var i = 0; i < N; ++i) {
if (this.selectors[i] && this.selectors[i] == sel) {
if (sel.locked == false) {
// TODO(codedread): Ensure this exists in this module.
console.log('WARNING! selector was released but was already unlocked');
}
delete this.selectorMap[elem.id];
sel.locked = false;
sel.selectedElement = null;
sel.showGrips(false);
// remove from DOM and store reference in JS but only if it exists in the DOM
try {
sel.selectorGroup.setAttribute('display', 'none');
} catch(e) { }
break;
}
}
};
// Function: svgedit.select.SelectorManager.getRubberBandBox
// Returns the rubberBandBox DOM element. This is the rectangle drawn by the user for selecting/zooming
svgedit.select.SelectorManager.prototype.getRubberBandBox = function() {
if (!this.rubberBandBox) {
this.rubberBandBox = this.selectorParentGroup.appendChild(
svgFactory_.createSVGElement({
'element': 'rect',
'attr': {
'id': 'selectorRubberBand',
'fill': '#22C',
'fill-opacity': 0.15,
'stroke': '#22C',
'stroke-width': 0.5,
'display': 'none',
'style': 'pointer-events:none'
}
})
);
}
return this.rubberBandBox;
};
/**
* Interface: svgedit.select.SVGFactory
* An object that creates SVG elements for the canvas.
*
* interface svgedit.select.SVGFactory {
* SVGElement createSVGElement(jsonMap);
* SVGSVGElement svgRoot();
* SVGSVGElement svgContent();
*
* Number currentZoom();
* Object getStrokedBBox(Element[]); // TODO(codedread): Remove when getStrokedBBox() has been put into svgutils.js
* }
*/
/**
* Function: svgedit.select.init()
* Initializes this module.
*
* Parameters:
* config - an object containing configurable parameters (imgPath)
* svgFactory - an object implementing the SVGFactory interface (see above).
*/
svgedit.select.init = function(config, svgFactory) {
config_ = config;
svgFactory_ = svgFactory;
selectorManager_ = new svgedit.select.SelectorManager();
};
/**
* Function: svgedit.select.getSelectorManager
*
* Returns:
* The SelectorManager instance.
*/
svgedit.select.getSelectorManager = function() {
return selectorManager_;
};
})();
|
/*
AngularJS v1.3.0-beta.7
(c) 2010-2014 Google, Inc. http://angularjs.org
License: MIT
*/
(function(){'use strict';function d(a){return function(){var c=arguments[0],b,c="["+(a?a+":":"")+c+"] http://errors.angularjs.org/1.3.0-beta.7/"+(a?a+"/":"")+c;for(b=1;b<arguments.length;b++)c=c+(1==b?"?":"&")+"p"+(b-1)+"="+encodeURIComponent("function"==typeof arguments[b]?arguments[b].toString().replace(/ \{[\s\S]*$/,""):"undefined"==typeof arguments[b]?"undefined":"string"!=typeof arguments[b]?JSON.stringify(arguments[b]):arguments[b]);return Error(c)}}(function(a){var c=d("$injector"),b=d("ng");
a=a.angular||(a.angular={});a.$$minErr=a.$$minErr||d;return a.module||(a.module=function(){var a={};return function(e,d,f){if("hasOwnProperty"===e)throw b("badname","module");d&&a.hasOwnProperty(e)&&(a[e]=null);return a[e]||(a[e]=function(){function a(c,d,e){return function(){b[e||"push"]([c,d,arguments]);return g}}if(!d)throw c("nomod",e);var b=[],h=[],k=a("$injector","invoke"),g={_invokeQueue:b,_runBlocks:h,requires:d,name:e,provider:a("$provide","provider"),factory:a("$provide","factory"),service:a("$provide",
"service"),value:a("$provide","value"),constant:a("$provide","constant","unshift"),animation:a("$animateProvider","register"),filter:a("$filterProvider","register"),controller:a("$controllerProvider","register"),directive:a("$compileProvider","directive"),config:k,run:function(a){h.push(a);return this}};f&&k(f);return g}())}}())})(window)})(window);
//# sourceMappingURL=angular-loader.min.js.map
|
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang("language","gl",{button:"Estabelezer o idioma",remove:"Retirar o idioma"});
|
exports.BattleAbilities = {
"frisk": {
inherit: true,
desc: "When this Pokemon enters the field, it identifies the opponent's held item; in double battles, the held item of an unrevealed, randomly selected opponent is identified.",
shortDesc: "On switch-in, this Pokemon identifies a random foe's held item.",
onStart: function (pokemon) {
var target = pokemon.side.foe.randomActive();
if (target && target.item) {
this.add('-item', target, target.getItem().name, '[from] ability: Frisk', '[of] ' + pokemon);
}
}
},
"keeneye": {
inherit: true,
onModifyMove: function () {}
},
"infiltrator": {
inherit: true,
onModifyMove: function (move) {
move.ignoreScreens = true;
}
},
"oblivious": {
inherit: true,
desc: "This Pokemon cannot be infatuated (by Attract or Cute Charm). Gaining this Ability while infatuated cures it.",
shortDesc: "This Pokemon cannot be infatuated. Gaining this Ability while infatuated cures it.",
onUpdate: function (pokemon) {
if (pokemon.volatiles['attract']) {
pokemon.removeVolatile('attract');
this.add('-end', pokemon, 'move: Attract');
}
},
onTryHit: function (pokemon, target, move) {
if (move.id === 'captivate') {
this.add('-immune', pokemon, '[msg]', '[from] Oblivious');
return null;
}
}
},
"overcoat": {
inherit: true,
onTryHit: function () {}
},
"sapsipper": {
inherit: true,
desc: "This Pokemon is immune to Grass moves. If hit by a Grass move, its Attack is increased by one stage (once for each hit of Bullet Seed). Does not affect Aromatherapy.",
onAllyTryHitSide: function () {}
}
};
|
module.exports={title:"TikTok",slug:"tiktok",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>TikTok icon</title><path d="M12.53.02C13.84 0 15.14.01 16.44 0c.08 1.53.63 3.09 1.75 4.17 1.12 1.11 2.7 1.62 4.24 1.79v4.03c-1.44-.05-2.89-.35-4.2-.97-.57-.26-1.1-.59-1.62-.93-.01 2.92.01 5.84-.02 8.75-.08 1.4-.54 2.79-1.35 3.94-1.31 1.92-3.58 3.17-5.91 3.21-1.43.08-2.86-.31-4.08-1.03-2.02-1.19-3.44-3.37-3.65-5.71-.02-.5-.03-1-.01-1.49.18-1.9 1.12-3.72 2.58-4.96 1.66-1.44 3.98-2.13 6.15-1.72.02 1.48-.04 2.96-.04 4.44-.99-.32-2.15-.23-3.02.37-.63.41-1.11 1.04-1.36 1.75-.21.51-.15 1.07-.14 1.61.24 1.64 1.82 3.02 3.5 2.87 1.12-.01 2.19-.66 2.77-1.61.19-.33.4-.67.41-1.06.1-1.79.06-3.57.07-5.36.01-4.03-.01-8.05.02-12.07z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://tiktok.com",hex:"000000"};
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* The Canvas class handles everything related to creating the `canvas` DOM tag that Phaser will use,
* including styles, offset and aspect ratio.
*
* @class Phaser.Canvas
* @static
*/
Phaser.Canvas = {
/**
* Creates a `canvas` DOM element. The element is not automatically added to the document.
*
* @method Phaser.Canvas.create
* @param {object} parent - The object that will own the canvas that is created.
* @param {number} [width=256] - The width of the canvas element.
* @param {number} [height=256] - The height of the canvas element..
* @param {string} [id=(none)] - If specified, and not the empty string, this will be set as the ID of the canvas element. Otherwise no ID will be set.
* @param {boolean} [skipPool=false] - If `true` the canvas will not be placed in the CanvasPool global.
* @return {HTMLCanvasElement} The newly created canvas element.
*/
create: function (parent, width, height, id, skipPool) {
width = width || 256;
height = height || 256;
var canvas = (skipPool) ? document.createElement('canvas') : PIXI.CanvasPool.create(parent, width, height);
if (typeof id === 'string' && id !== '')
{
canvas.id = id;
}
canvas.width = width;
canvas.height = height;
canvas.style.display = 'block';
return canvas;
},
/**
* Sets the background color behind the canvas. This changes the canvas style property.
*
* @method Phaser.Canvas.setBackgroundColor
* @param {HTMLCanvasElement} canvas - The canvas to set the background color on.
* @param {string} [color='rgb(0,0,0)'] - The color to set. Can be in the format 'rgb(r,g,b)', or '#RRGGBB' or any valid CSS color.
* @return {HTMLCanvasElement} Returns the source canvas.
*/
setBackgroundColor: function (canvas, color) {
color = color || 'rgb(0,0,0)';
canvas.style.backgroundColor = color;
return canvas;
},
/**
* Sets the touch-action property on the canvas style. Can be used to disable default browser touch actions.
*
* @method Phaser.Canvas.setTouchAction
* @param {HTMLCanvasElement} canvas - The canvas to set the touch action on.
* @param {string} [value] - The touch action to set. Defaults to 'none'.
* @return {HTMLCanvasElement} The source canvas.
*/
setTouchAction: function (canvas, value) {
value = value || 'none';
canvas.style.msTouchAction = value;
canvas.style['ms-touch-action'] = value;
canvas.style['touch-action'] = value;
return canvas;
},
/**
* Sets the user-select property on the canvas style. Can be used to disable default browser selection actions.
*
* @method Phaser.Canvas.setUserSelect
* @param {HTMLCanvasElement} canvas - The canvas to set the touch action on.
* @param {string} [value] - The touch action to set. Defaults to 'none'.
* @return {HTMLCanvasElement} The source canvas.
*/
setUserSelect: function (canvas, value) {
value = value || 'none';
canvas.style['-webkit-touch-callout'] = value;
canvas.style['-webkit-user-select'] = value;
canvas.style['-khtml-user-select'] = value;
canvas.style['-moz-user-select'] = value;
canvas.style['-ms-user-select'] = value;
canvas.style['user-select'] = value;
canvas.style['-webkit-tap-highlight-color'] = 'rgba(0, 0, 0, 0)';
return canvas;
},
/**
* Adds the given canvas element to the DOM. The canvas will be added as a child of the given parent.
* If no parent is given it will be added as a child of the document.body.
*
* @method Phaser.Canvas.addToDOM
* @param {HTMLCanvasElement} canvas - The canvas to be added to the DOM.
* @param {string|HTMLElement} parent - The DOM element to add the canvas to.
* @param {boolean} [overflowHidden=true] - If set to true it will add the overflow='hidden' style to the parent DOM element.
* @return {HTMLCanvasElement} Returns the source canvas.
*/
addToDOM: function (canvas, parent, overflowHidden) {
var target;
if (overflowHidden === undefined) { overflowHidden = true; }
if (parent)
{
if (typeof parent === 'string')
{
// hopefully an element ID
target = document.getElementById(parent);
}
else if (typeof parent === 'object' && parent.nodeType === 1)
{
// quick test for a HTMLelement
target = parent;
}
}
// Fallback, covers an invalid ID and a non HTMLelement object
if (!target)
{
target = document.body;
}
if (overflowHidden && target.style)
{
target.style.overflow = 'hidden';
}
target.appendChild(canvas);
return canvas;
},
/**
* Removes the given canvas element from the DOM.
*
* @method Phaser.Canvas.removeFromDOM
* @param {HTMLCanvasElement} canvas - The canvas to be removed from the DOM.
*/
removeFromDOM: function (canvas) {
if (canvas.parentNode)
{
canvas.parentNode.removeChild(canvas);
}
},
/**
* Sets the transform of the given canvas to the matrix values provided.
*
* @method Phaser.Canvas.setTransform
* @param {CanvasRenderingContext2D} context - The context to set the transform on.
* @param {number} translateX - The value to translate horizontally by.
* @param {number} translateY - The value to translate vertically by.
* @param {number} scaleX - The value to scale horizontally by.
* @param {number} scaleY - The value to scale vertically by.
* @param {number} skewX - The value to skew horizontaly by.
* @param {number} skewY - The value to skew vertically by.
* @return {CanvasRenderingContext2D} Returns the source context.
*/
setTransform: function (context, translateX, translateY, scaleX, scaleY, skewX, skewY) {
context.setTransform(scaleX, skewX, skewY, scaleY, translateX, translateY);
return context;
},
/**
* Sets the Image Smoothing property on the given context. Set to false to disable image smoothing.
* By default browsers have image smoothing enabled, which isn't always what you visually want, especially
* when using pixel art in a game. Note that this sets the property on the context itself, so that any image
* drawn to the context will be affected. This sets the property across all current browsers but support is
* patchy on earlier browsers, especially on mobile.
*
* @method Phaser.Canvas.setSmoothingEnabled
* @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on.
* @param {boolean} value - If set to true it will enable image smoothing, false will disable it.
* @return {CanvasRenderingContext2D} Returns the source context.
*/
setSmoothingEnabled: function (context, value) {
var s = Phaser.Canvas.getSmoothingPrefix(context);
if (s)
{
context[s] = value;
}
return context;
},
/**
* Gets the Smoothing Enabled vendor prefix being used on the given context, or null if not set.
*
* @method Phaser.Canvas.getSmoothingPrefix
* @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on.
* @return {string|null} Returns the smoothingEnabled vendor prefix, or null if not set on the context.
*/
getSmoothingPrefix: function (context) {
var vendor = [ 'i', 'webkitI', 'msI', 'mozI', 'oI' ];
for (var prefix in vendor)
{
var s = vendor[prefix] + 'mageSmoothingEnabled';
if (s in context)
{
return s;
}
}
return null;
},
/**
* Returns `true` if the given context has image smoothing enabled, otherwise returns `false`.
*
* @method Phaser.Canvas.getSmoothingEnabled
* @param {CanvasRenderingContext2D} context - The context to check for smoothing on.
* @return {boolean} True if the given context has image smoothing enabled, otherwise false.
*/
getSmoothingEnabled: function (context) {
var s = Phaser.Canvas.getSmoothingPrefix(context);
if (s)
{
return context[s];
}
},
/**
* Sets the CSS image-rendering property on the given canvas to be 'crisp' (aka 'optimize contrast' on webkit).
* Note that if this doesn't given the desired result then see the setSmoothingEnabled.
*
* @method Phaser.Canvas.setImageRenderingCrisp
* @param {HTMLCanvasElement} canvas - The canvas to set image-rendering crisp on.
* @return {HTMLCanvasElement} Returns the source canvas.
*/
setImageRenderingCrisp: function (canvas) {
var types = [ 'optimizeSpeed', 'crisp-edges', '-moz-crisp-edges', '-webkit-optimize-contrast', 'optimize-contrast', 'pixelated' ];
for (var i = 0; i < types.length; i++)
{
canvas.style['image-rendering'] = types[i];
}
canvas.style.msInterpolationMode = 'nearest-neighbor';
return canvas;
},
/**
* Sets the CSS image-rendering property on the given canvas to be 'bicubic' (aka 'auto').
* Note that if this doesn't given the desired result then see the CanvasUtils.setSmoothingEnabled method.
*
* @method Phaser.Canvas.setImageRenderingBicubic
* @param {HTMLCanvasElement} canvas The canvas to set image-rendering bicubic on.
* @return {HTMLCanvasElement} Returns the source canvas.
*/
setImageRenderingBicubic: function (canvas) {
canvas.style['image-rendering'] = 'auto';
canvas.style.msInterpolationMode = 'bicubic';
return canvas;
}
};
|
/**
* Bullet module
*/
import { __extends } from "tslib";
/**
* ============================================================================
* IMPORTS
* ============================================================================
* @hidden
*/
import { Bullet } from "../../charts/elements/Bullet";
import { Circle } from "../../core/elements/Circle";
import { PointedCircle } from "./PointedCircle";
import { registry } from "../../core/Registry";
import * as $math from "../../core/utils/Math";
import { percent, Percent } from "../../core/utils/Percent";
import { InterfaceColorSet } from "../../core/utils/InterfaceColorSet";
/**
* ============================================================================
* MAIN CLASS
* ============================================================================
* @hidden
*/
/**
* Creates a pin-shaped bullet with an optional text label and/or image inside
* it.
*
* The background/body of the flag is a [[PointedCircle]] element. Most of
* its the visual appearance is configured via `background` property.
*
* Uses [[Label]] instance to draw the label, so the label itself is
* configurable.
*
* Example:
*
* ```TypeScript
* let series = chart.series.push(new am4charts.LineSeries());
* // ...
* let pinBullet = series.bullets.push(new am4plugins_bullets.PinBullet());
* pinBullet.poleHeight = 15;
* pinBullet.label.text = "{valueY}";
* ```
* ```JavaScript
* var series = chart.series.push(new am4charts.LineSeries());
* // ...
* var pinBullet = series.bullets.push(new am4plugins_bullets.PinBullet());
* pinBullet.poleHeight = 15;
* pinBullet.label.text = "{valueY}";
* ```
* ```JSON
* {
* // ...
* "series": [{
* // ...
* "bullets": [{
* "type": "PinBullet",
* "poleHeight": 15,
* "label": {
* "text": "{valueY}"
* }
* }]
* }]
* }
* ```
*
* @since 4.5.7
* @see {@link https://www.amcharts.com/docs/v4/tutorials/plugin-bullets/} for usage instructions.
* @see {@link IBulletEvents} for a list of available events
* @see {@link IBulletAdapters} for a list of available Adapters
*/
var PinBullet = /** @class */ (function (_super) {
__extends(PinBullet, _super);
/**
* Constructor
*/
function PinBullet() {
var _this = _super.call(this) || this;
_this.className = "PinBullet";
var interfaceColors = new InterfaceColorSet();
var circle = _this.createChild(Circle);
circle.shouldClone = false;
circle.isMeasured = false;
circle.fill = interfaceColors.getFor("background");
circle.radius = percent(85);
_this.circle = circle;
var background = _this.background;
background.fill = interfaceColors.getFor("alternativeBackground");
background.fillOpacity = 1;
background.pointerBaseWidth = 20;
background.pointerLength = 20;
background.radius = 25;
background.events.on("propertychanged", _this.invalidate, _this, false);
_this.applyTheme();
return _this;
}
/**
* Validates element:
* * Triggers events
* * Redraws the element
*
* @ignore Exclude from docs
*/
PinBullet.prototype.validate = function () {
_super.prototype.validate.call(this);
var background = this.background;
var px = background.pointerX;
var py = background.pointerY;
var pl = background.pointerLength;
var pw = background.pointerBaseWidth;
var pa = background.pointerAngle + 180;
var r = background.radius;
if (pw > 2 * r) {
pw = 2 * r;
}
var da = $math.DEGREES * Math.atan(pw / 2 / pl);
if (da <= 0.001) {
da = 0.001;
}
var a1 = pa - da;
var a2 = pa + da;
var p1 = { x: px + pl * $math.cos(a1), y: py + pl * $math.sin(a1) };
var p2 = { x: px + pl * $math.cos(a2), y: py + pl * $math.sin(a2) };
var x1 = p1.x;
var x2 = p2.x;
var y1 = p1.y;
var y2 = p2.y;
var radsq = r * r;
var q = Math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)));
var x3 = (x1 + x2) / 2;
var cx = x3 - Math.sqrt(radsq - ((q / 2) * (q / 2))) * ((y1 - y2) / q);
var y3 = (y1 + y2) / 2;
var cy = y3 - Math.sqrt(radsq - ((q / 2) * (q / 2))) * ((x2 - x1) / q);
if (this.circle) {
var circleRadius = this.circle.radius;
if (circleRadius instanceof Percent) {
this.circle.width = r * 2;
this.circle.height = r * 2;
}
}
var image = this.image;
if (image) {
image.x = cx;
image.y = cy;
image.width = r * 2;
image.height = r * 2;
image.element.attr({ preserveAspectRatio: "xMidYMid slice" });
if (this.circle) {
this.circle.scale = 1 / image.scale;
}
}
else {
if (this.circle) {
this.circle.x = cx;
this.circle.y = cy;
}
}
var label = this.label;
if (label) {
label.x = cx;
label.y = cy;
}
};
Object.defineProperty(PinBullet.prototype, "image", {
/**
* @return Image
*/
get: function () {
return this._image;
},
/**
* An element of type [[Image]] to show inside pin's circle.
*
* @param image Image
*/
set: function (image) {
if (image) {
this._image = image;
this._disposers.push(image);
image.shouldClone = false;
image.parent = this;
image.horizontalCenter = "middle";
image.verticalCenter = "middle";
if (this.circle) {
image.mask = this.circle;
}
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(PinBullet.prototype, "label", {
/**
* @return Label
*/
get: function () {
return this._label;
},
/**
* A [[Label]] element for displaying within flag.
*
* Use it's `text` property to set actual text, e.g.:
*
* ```TypeScript
* pinBullet.text = "Hello";
* ```
* ```JavaScript
* pinBullet.text = "Hello";
* ```
* ```JSON
* {
* // ...
* "series": [{
* // ...
* "bullets": [{
* "type": "PinBullet",
* "label": {
* "text": "Hello"
* }
* }]
* }]
* }
* ```
* @param label Label
*/
set: function (label) {
if (label) {
this._label = label;
this._disposers.push(label);
label.shouldClone = false;
label.parent = this;
label.horizontalCenter = "middle";
label.verticalCenter = "middle";
label.textAlign = "middle";
label.dy = 2;
}
},
enumerable: true,
configurable: true
});
/**
* Copies all proprities and related stuff from another instance of
* [[PinBullet]].
*
* @param source Source element
*/
PinBullet.prototype.copyFrom = function (source) {
_super.prototype.copyFrom.call(this, source);
if (source.image) {
if (!this._image) {
this.image = source.image.clone();
}
this._image.copyFrom(source.image);
}
if (this.circle && source.circle) {
this.circle.copyFrom(source.circle);
}
if (source.label) {
if (!this._label) {
this.label = source.label.clone();
}
this._label.copyFrom(source.label);
}
};
/**
* Creates and returns a background element.
*
* @ignore Exclude from docs
* @return Background
*/
PinBullet.prototype.createBackground = function () {
return new PointedCircle();
};
return PinBullet;
}(Bullet));
export { PinBullet };
/**
* Register class in system, so that it can be instantiated using its name from
* anywhere.
*
* @ignore
*/
registry.registeredClasses["PinBullet"] = PinBullet;
//# sourceMappingURL=PinBullet.js.map
|
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v6.4.0
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var utils_1 = require("../utils");
var gridOptionsWrapper_1 = require("../gridOptionsWrapper");
var context_1 = require("../context/context");
var gridPanel_1 = require("../gridPanel/gridPanel");
var selectionController_1 = require("../selectionController");
var sortController_1 = require("../sortController");
var eventService_1 = require("../eventService");
var events_1 = require("../events");
var filterManager_1 = require("../filter/filterManager");
var constants_1 = require("../constants");
var template = '<div class="ag-paging-panel ag-font-style">' +
'<span id="pageRowSummaryPanel" class="ag-paging-row-summary-panel">' +
'<span id="firstRowOnPage"></span>' +
' [TO] ' +
'<span id="lastRowOnPage"></span>' +
' [OF] ' +
'<span id="recordCount"></span>' +
'</span>' +
'<span class="ag-paging-page-summary-panel">' +
'<button type="button" class="ag-paging-button" id="btFirst">[FIRST]</button>' +
'<button type="button" class="ag-paging-button" id="btPrevious">[PREVIOUS]</button>' +
'[PAGE] ' +
'<span id="current"></span>' +
' [OF] ' +
'<span id="total"></span>' +
'<button type="button" class="ag-paging-button" id="btNext">[NEXT]</button>' +
'<button type="button" class="ag-paging-button" id="btLast">[LAST]</button>' +
'</span>' +
'</div>';
var PaginationController = (function () {
function PaginationController() {
}
PaginationController.prototype.init = function () {
var _this = this;
// if we are doing pagination, we are guaranteed that the model type
// is normal. if it is not, then this paginationController service
// will never be called.
if (this.rowModel.getType() === constants_1.Constants.ROW_MODEL_TYPE_NORMAL) {
this.inMemoryRowModel = this.rowModel;
}
this.setupComponents();
this.callVersion = 0;
var paginationEnabled = this.gridOptionsWrapper.isRowModelPagination();
this.eventService.addEventListener(events_1.Events.EVENT_FILTER_CHANGED, function () {
if (paginationEnabled && _this.gridOptionsWrapper.isEnableServerSideFilter()) {
_this.reset(false);
}
});
this.eventService.addEventListener(events_1.Events.EVENT_SORT_CHANGED, function () {
if (paginationEnabled && _this.gridOptionsWrapper.isEnableServerSideSorting()) {
_this.reset(false);
}
});
if (paginationEnabled && this.gridOptionsWrapper.getDatasource()) {
this.setDatasource(this.gridOptionsWrapper.getDatasource());
}
};
PaginationController.prototype.setDatasource = function (datasource) {
this.datasource = datasource;
if (!datasource) {
// only continue if we have a valid datasource to work with
return;
}
this.reset(true);
};
PaginationController.prototype.checkForDeprecated = function () {
var ds = this.datasource;
if (utils_1.Utils.exists(ds.pageSize)) {
console.error('ag-Grid: since version 5.1.x, pageSize is replaced with grid property paginationPageSize');
}
};
PaginationController.prototype.reset = function (freshDatasource) {
// important to return here, as the user could be setting filter or sort before
// data-source is set
if (utils_1.Utils.missing(this.datasource)) {
return;
}
this.checkForDeprecated();
// if user is providing id's, then this means we can keep the selection between datsource hits,
// as the rows will keep their unique id's even if, for example, server side sorting or filtering
// is done. if it's a new datasource, then always clear the selection.
var userGeneratingRows = utils_1.Utils.exists(this.gridOptionsWrapper.getRowNodeIdFunc());
var resetSelectionController = freshDatasource || !userGeneratingRows;
if (resetSelectionController) {
this.selectionController.reset();
}
// copy pageSize, to guard against it changing the the datasource between calls
this.pageSize = this.gridOptionsWrapper.getPaginationPageSize();
if (!(this.pageSize >= 1)) {
this.pageSize = 100;
}
// see if we know the total number of pages, or if it's 'to be decided'
if (typeof this.datasource.rowCount === 'number' && this.datasource.rowCount >= 0) {
this.rowCount = this.datasource.rowCount;
this.foundMaxRow = true;
this.calculateTotalPages();
}
else {
this.rowCount = 0;
this.foundMaxRow = false;
this.totalPages = null;
}
this.currentPage = 0;
// hide the summary panel until something is loaded
this.ePageRowSummaryPanel.style.visibility = 'hidden';
this.setTotalLabels();
this.loadPage();
};
// the native method number.toLocaleString(undefined, {minimumFractionDigits: 0}) puts in decimal places in IE
PaginationController.prototype.myToLocaleString = function (input) {
if (typeof input !== 'number') {
return '';
}
else {
// took this from: http://blog.tompawlak.org/number-currency-formatting-javascript
return input.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
}
};
PaginationController.prototype.setTotalLabels = function () {
if (this.foundMaxRow) {
this.lbTotal.innerHTML = this.myToLocaleString(this.totalPages);
this.lbRecordCount.innerHTML = this.myToLocaleString(this.rowCount);
}
else {
var moreText = this.gridOptionsWrapper.getLocaleTextFunc()('more', 'more');
this.lbTotal.innerHTML = moreText;
this.lbRecordCount.innerHTML = moreText;
}
};
PaginationController.prototype.calculateTotalPages = function () {
this.totalPages = Math.floor((this.rowCount - 1) / this.pageSize) + 1;
};
PaginationController.prototype.pageLoaded = function (rows, lastRowIndex) {
var firstId = this.currentPage * this.pageSize;
this.inMemoryRowModel.setRowData(rows, true, firstId);
// see if we hit the last row
if (!this.foundMaxRow && typeof lastRowIndex === 'number' && lastRowIndex >= 0) {
this.foundMaxRow = true;
this.rowCount = lastRowIndex;
this.calculateTotalPages();
this.setTotalLabels();
// if overshot pages, go back
if (this.currentPage > this.totalPages) {
this.currentPage = this.totalPages - 1;
this.loadPage();
}
}
this.enableOrDisableButtons();
this.updateRowLabels();
};
PaginationController.prototype.updateRowLabels = function () {
var startRow;
var endRow;
if (this.isZeroPagesToDisplay()) {
startRow = 0;
endRow = 0;
}
else {
startRow = (this.pageSize * this.currentPage) + 1;
endRow = startRow + this.pageSize - 1;
if (this.foundMaxRow && endRow > this.rowCount) {
endRow = this.rowCount;
}
}
this.lbFirstRowOnPage.innerHTML = this.myToLocaleString(startRow);
this.lbLastRowOnPage.innerHTML = this.myToLocaleString(endRow);
// show the summary panel, when first shown, this is blank
this.ePageRowSummaryPanel.style.visibility = "";
};
PaginationController.prototype.loadPage = function () {
var _this = this;
this.enableOrDisableButtons();
var startRow = this.currentPage * this.pageSize;
var endRow = (this.currentPage + 1) * this.pageSize;
this.lbCurrent.innerHTML = this.myToLocaleString(this.currentPage + 1);
this.callVersion++;
var callVersionCopy = this.callVersion;
var that = this;
this.gridPanel.showLoadingOverlay();
var sortModel;
if (this.gridOptionsWrapper.isEnableServerSideSorting()) {
sortModel = this.sortController.getSortModel();
}
var filterModel;
if (this.gridOptionsWrapper.isEnableServerSideFilter()) {
filterModel = this.filterManager.getFilterModel();
}
var params = {
startRow: startRow,
endRow: endRow,
successCallback: successCallback,
failCallback: failCallback,
sortModel: sortModel,
filterModel: filterModel,
context: this.gridOptionsWrapper.getContext()
};
// check if old version of datasource used
var getRowsParams = utils_1.Utils.getFunctionParameters(this.datasource.getRows);
if (getRowsParams.length > 1) {
console.warn('ag-grid: It looks like your paging datasource is of the old type, taking more than one parameter.');
console.warn('ag-grid: From ag-grid 1.9.0, now the getRows takes one parameter. See the documentation for details.');
}
// put in timeout, to force result to be async
setTimeout(function () {
_this.datasource.getRows(params);
}, 0);
function successCallback(rows, lastRowIndex) {
if (that.isCallDaemon(callVersionCopy)) {
return;
}
that.pageLoaded(rows, lastRowIndex);
}
function failCallback() {
if (that.isCallDaemon(callVersionCopy)) {
return;
}
// set in an empty set of rows, this will at
// least get rid of the loading panel, and
// stop blocking things
that.inMemoryRowModel.setRowData([], true);
}
};
PaginationController.prototype.isCallDaemon = function (versionCopy) {
return versionCopy !== this.callVersion;
};
PaginationController.prototype.onBtNext = function () {
this.currentPage++;
this.loadPage();
};
PaginationController.prototype.onBtPrevious = function () {
this.currentPage--;
this.loadPage();
};
PaginationController.prototype.onBtFirst = function () {
this.currentPage = 0;
this.loadPage();
};
PaginationController.prototype.onBtLast = function () {
this.currentPage = this.totalPages - 1;
this.loadPage();
};
PaginationController.prototype.isZeroPagesToDisplay = function () {
return this.foundMaxRow && this.totalPages === 0;
};
PaginationController.prototype.enableOrDisableButtons = function () {
var disablePreviousAndFirst = this.currentPage === 0;
this.btPrevious.disabled = disablePreviousAndFirst;
this.btFirst.disabled = disablePreviousAndFirst;
var zeroPagesToDisplay = this.isZeroPagesToDisplay();
var onLastPage = this.foundMaxRow && this.currentPage === (this.totalPages - 1);
var disableNext = onLastPage || zeroPagesToDisplay;
this.btNext.disabled = disableNext;
var disableLast = !this.foundMaxRow || zeroPagesToDisplay || this.currentPage === (this.totalPages - 1);
this.btLast.disabled = disableLast;
};
PaginationController.prototype.createTemplate = function () {
var localeTextFunc = this.gridOptionsWrapper.getLocaleTextFunc();
return template
.replace('[PAGE]', localeTextFunc('page', 'Page'))
.replace('[TO]', localeTextFunc('to', 'to'))
.replace('[OF]', localeTextFunc('of', 'of'))
.replace('[OF]', localeTextFunc('of', 'of'))
.replace('[FIRST]', localeTextFunc('first', 'First'))
.replace('[PREVIOUS]', localeTextFunc('previous', 'Previous'))
.replace('[NEXT]', localeTextFunc('next', 'Next'))
.replace('[LAST]', localeTextFunc('last', 'Last'));
};
PaginationController.prototype.getGui = function () {
return this.eGui;
};
PaginationController.prototype.setupComponents = function () {
this.eGui = utils_1.Utils.loadTemplate(this.createTemplate());
this.btNext = this.eGui.querySelector('#btNext');
this.btPrevious = this.eGui.querySelector('#btPrevious');
this.btFirst = this.eGui.querySelector('#btFirst');
this.btLast = this.eGui.querySelector('#btLast');
this.lbCurrent = this.eGui.querySelector('#current');
this.lbTotal = this.eGui.querySelector('#total');
this.lbRecordCount = this.eGui.querySelector('#recordCount');
this.lbFirstRowOnPage = this.eGui.querySelector('#firstRowOnPage');
this.lbLastRowOnPage = this.eGui.querySelector('#lastRowOnPage');
this.ePageRowSummaryPanel = this.eGui.querySelector('#pageRowSummaryPanel');
var that = this;
this.btNext.addEventListener('click', function () {
that.onBtNext();
});
this.btPrevious.addEventListener('click', function () {
that.onBtPrevious();
});
this.btFirst.addEventListener('click', function () {
that.onBtFirst();
});
this.btLast.addEventListener('click', function () {
that.onBtLast();
});
};
__decorate([
context_1.Autowired('filterManager'),
__metadata('design:type', filterManager_1.FilterManager)
], PaginationController.prototype, "filterManager", void 0);
__decorate([
context_1.Autowired('gridPanel'),
__metadata('design:type', gridPanel_1.GridPanel)
], PaginationController.prototype, "gridPanel", void 0);
__decorate([
context_1.Autowired('gridOptionsWrapper'),
__metadata('design:type', gridOptionsWrapper_1.GridOptionsWrapper)
], PaginationController.prototype, "gridOptionsWrapper", void 0);
__decorate([
context_1.Autowired('selectionController'),
__metadata('design:type', selectionController_1.SelectionController)
], PaginationController.prototype, "selectionController", void 0);
__decorate([
context_1.Autowired('sortController'),
__metadata('design:type', sortController_1.SortController)
], PaginationController.prototype, "sortController", void 0);
__decorate([
context_1.Autowired('eventService'),
__metadata('design:type', eventService_1.EventService)
], PaginationController.prototype, "eventService", void 0);
__decorate([
context_1.Autowired('rowModel'),
__metadata('design:type', Object)
], PaginationController.prototype, "rowModel", void 0);
__decorate([
context_1.PostConstruct,
__metadata('design:type', Function),
__metadata('design:paramtypes', []),
__metadata('design:returntype', void 0)
], PaginationController.prototype, "init", null);
PaginationController = __decorate([
context_1.Bean('paginationController'),
__metadata('design:paramtypes', [])
], PaginationController);
return PaginationController;
})();
exports.PaginationController = PaginationController;
|
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v6.4.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var Events = (function () {
function Events() {
}
/** A new set of columns has been entered, everything has potentially changed. */
Events.EVENT_COLUMN_EVERYTHING_CHANGED = 'columnEverythingChanged';
Events.EVENT_NEW_COLUMNS_LOADED = 'newColumnsLoaded';
/** The reduce flag was changed */
Events.EVENT_COLUMN_PIVOT_MODE_CHANGED = 'columnPivotModeChanged';
/** A row group column was added, removed or order changed. */
Events.EVENT_COLUMN_ROW_GROUP_CHANGED = 'columnRowGroupChanged';
/** A pivot column was added, removed or order changed. */
Events.EVENT_COLUMN_PIVOT_CHANGED = 'columnPivotChanged';
/** The list of grid columns has changed. */
Events.EVENT_GRID_COLUMNS_CHANGED = 'gridColumnsChanged';
/** A value column was added, removed or agg function was changed. */
Events.EVENT_COLUMN_VALUE_CHANGED = 'columnValueChanged';
/** A column was moved */
Events.EVENT_COLUMN_MOVED = 'columnMoved';
/** One or more columns was shown / hidden */
Events.EVENT_COLUMN_VISIBLE = 'columnVisible';
/** One or more columns was pinned / unpinned*/
Events.EVENT_COLUMN_PINNED = 'columnPinned';
/** A column group was opened / closed */
Events.EVENT_COLUMN_GROUP_OPENED = 'columnGroupOpened';
/** One or more columns was resized. If just one, the column in the event is set. */
Events.EVENT_COLUMN_RESIZED = 'columnResized';
/** The list of displayed columns has changed, can result from columns open / close, column move, pivot, group, etc */
Events.EVENT_DISPLAYED_COLUMNS_CHANGED = 'displayedColumnsChanged';
/** The list of virtual columns has changed, results from viewport changing */
Events.EVENT_VIRTUAL_COLUMNS_CHANGED = 'virtualColumnsChanged';
/** A row group was opened / closed */
Events.EVENT_ROW_GROUP_OPENED = 'rowGroupOpened';
Events.EVENT_ROW_DATA_CHANGED = 'rowDataChanged';
Events.EVENT_FLOATING_ROW_DATA_CHANGED = 'floatingRowDataChanged';
Events.EVENT_RANGE_SELECTION_CHANGED = 'rangeSelectionChanged';
Events.EVENT_COLUMN_ROW_GROUP_CHANGE_REQUEST = 'columnRowGroupChangeRequest';
Events.EVENT_COLUMN_PIVOT_CHANGE_REQUEST = 'columnPivotChangeRequest';
Events.EVENT_COLUMN_VALUE_CHANGE_REQUEST = 'columnValueChangeRequest';
Events.EVENT_COLUMN_AGG_FUNC_CHANGE_REQUEST = 'columnAggFuncChangeRequest';
Events.EVENT_FLASH_CELLS = 'clipboardPaste';
Events.EVENT_MODEL_UPDATED = 'modelUpdated';
Events.EVENT_CELL_CLICKED = 'cellClicked';
Events.EVENT_CELL_DOUBLE_CLICKED = 'cellDoubleClicked';
Events.EVENT_CELL_CONTEXT_MENU = 'cellContextMenu';
Events.EVENT_CELL_VALUE_CHANGED = 'cellValueChanged';
Events.EVENT_ROW_VALUE_CHANGED = 'rowValueChanged';
Events.EVENT_CELL_FOCUSED = 'cellFocused';
Events.EVENT_ROW_SELECTED = 'rowSelected';
Events.EVENT_SELECTION_CHANGED = 'selectionChanged';
Events.EVENT_BEFORE_FILTER_CHANGED = 'beforeFilterChanged';
Events.EVENT_FILTER_CHANGED = 'filterChanged';
Events.EVENT_AFTER_FILTER_CHANGED = 'afterFilterChanged';
Events.EVENT_FILTER_MODIFIED = 'filterModified';
Events.EVENT_BEFORE_SORT_CHANGED = 'beforeSortChanged';
Events.EVENT_SORT_CHANGED = 'sortChanged';
Events.EVENT_AFTER_SORT_CHANGED = 'afterSortChanged';
Events.EVENT_VIRTUAL_ROW_REMOVED = 'virtualRowRemoved';
Events.EVENT_ROW_CLICKED = 'rowClicked';
Events.EVENT_ROW_DOUBLE_CLICKED = 'rowDoubleClicked';
Events.EVENT_GRID_READY = 'gridReady';
Events.EVENT_GRID_SIZE_CHANGED = 'gridSizeChanged';
Events.EVENT_VIEWPORT_CHANGED = 'viewportChanged';
Events.EVENT_DRAG_STARTED = 'dragStarted';
Events.EVENT_DRAG_STOPPED = 'dragStopped';
Events.EVENT_ITEMS_ADDED = 'itemsAdded';
Events.EVENT_ITEMS_REMOVED = 'itemsRemoved';
Events.EVENT_BODY_SCROLL = 'bodyScroll';
return Events;
})();
exports.Events = Events;
|
// Fine Uploader 5.11.6 - (c) 2013-present Widen Enterprises, Inc. MIT licensed. http://fineuploader.com
(function(global) {
var qq = function(element) {
"use strict";
return {
hide: function() {
element.style.display = "none";
return this;
},
attach: function(type, fn) {
if (element.addEventListener) {
element.addEventListener(type, fn, false);
} else if (element.attachEvent) {
element.attachEvent("on" + type, fn);
}
return function() {
qq(element).detach(type, fn);
};
},
detach: function(type, fn) {
if (element.removeEventListener) {
element.removeEventListener(type, fn, false);
} else if (element.attachEvent) {
element.detachEvent("on" + type, fn);
}
return this;
},
contains: function(descendant) {
if (!descendant) {
return false;
}
if (element === descendant) {
return true;
}
if (element.contains) {
return element.contains(descendant);
} else {
return !!(descendant.compareDocumentPosition(element) & 8);
}
},
insertBefore: function(elementB) {
elementB.parentNode.insertBefore(element, elementB);
return this;
},
remove: function() {
element.parentNode.removeChild(element);
return this;
},
css: function(styles) {
if (element.style == null) {
throw new qq.Error("Can't apply style to node as it is not on the HTMLElement prototype chain!");
}
if (styles.opacity != null) {
if (typeof element.style.opacity !== "string" && typeof element.filters !== "undefined") {
styles.filter = "alpha(opacity=" + Math.round(100 * styles.opacity) + ")";
}
}
qq.extend(element.style, styles);
return this;
},
hasClass: function(name, considerParent) {
var re = new RegExp("(^| )" + name + "( |$)");
return re.test(element.className) || !!(considerParent && re.test(element.parentNode.className));
},
addClass: function(name) {
if (!qq(element).hasClass(name)) {
element.className += " " + name;
}
return this;
},
removeClass: function(name) {
var re = new RegExp("(^| )" + name + "( |$)");
element.className = element.className.replace(re, " ").replace(/^\s+|\s+$/g, "");
return this;
},
getByClass: function(className, first) {
var candidates, result = [];
if (first && element.querySelector) {
return element.querySelector("." + className);
} else if (element.querySelectorAll) {
return element.querySelectorAll("." + className);
}
candidates = element.getElementsByTagName("*");
qq.each(candidates, function(idx, val) {
if (qq(val).hasClass(className)) {
result.push(val);
}
});
return first ? result[0] : result;
},
getFirstByClass: function(className) {
return qq(element).getByClass(className, true);
},
children: function() {
var children = [], child = element.firstChild;
while (child) {
if (child.nodeType === 1) {
children.push(child);
}
child = child.nextSibling;
}
return children;
},
setText: function(text) {
element.innerText = text;
element.textContent = text;
return this;
},
clearText: function() {
return qq(element).setText("");
},
hasAttribute: function(attrName) {
var attrVal;
if (element.hasAttribute) {
if (!element.hasAttribute(attrName)) {
return false;
}
return /^false$/i.exec(element.getAttribute(attrName)) == null;
} else {
attrVal = element[attrName];
if (attrVal === undefined) {
return false;
}
return /^false$/i.exec(attrVal) == null;
}
}
};
};
(function() {
"use strict";
qq.canvasToBlob = function(canvas, mime, quality) {
return qq.dataUriToBlob(canvas.toDataURL(mime, quality));
};
qq.dataUriToBlob = function(dataUri) {
var arrayBuffer, byteString, createBlob = function(data, mime) {
var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder, blobBuilder = BlobBuilder && new BlobBuilder();
if (blobBuilder) {
blobBuilder.append(data);
return blobBuilder.getBlob(mime);
} else {
return new Blob([ data ], {
type: mime
});
}
}, intArray, mimeString;
if (dataUri.split(",")[0].indexOf("base64") >= 0) {
byteString = atob(dataUri.split(",")[1]);
} else {
byteString = decodeURI(dataUri.split(",")[1]);
}
mimeString = dataUri.split(",")[0].split(":")[1].split(";")[0];
arrayBuffer = new ArrayBuffer(byteString.length);
intArray = new Uint8Array(arrayBuffer);
qq.each(byteString, function(idx, character) {
intArray[idx] = character.charCodeAt(0);
});
return createBlob(arrayBuffer, mimeString);
};
qq.log = function(message, level) {
if (window.console) {
if (!level || level === "info") {
window.console.log(message);
} else {
if (window.console[level]) {
window.console[level](message);
} else {
window.console.log("<" + level + "> " + message);
}
}
}
};
qq.isObject = function(variable) {
return variable && !variable.nodeType && Object.prototype.toString.call(variable) === "[object Object]";
};
qq.isFunction = function(variable) {
return typeof variable === "function";
};
qq.isArray = function(value) {
return Object.prototype.toString.call(value) === "[object Array]" || value && window.ArrayBuffer && value.buffer && value.buffer.constructor === ArrayBuffer;
};
qq.isItemList = function(maybeItemList) {
return Object.prototype.toString.call(maybeItemList) === "[object DataTransferItemList]";
};
qq.isNodeList = function(maybeNodeList) {
return Object.prototype.toString.call(maybeNodeList) === "[object NodeList]" || maybeNodeList.item && maybeNodeList.namedItem;
};
qq.isString = function(maybeString) {
return Object.prototype.toString.call(maybeString) === "[object String]";
};
qq.trimStr = function(string) {
if (String.prototype.trim) {
return string.trim();
}
return string.replace(/^\s+|\s+$/g, "");
};
qq.format = function(str) {
var args = Array.prototype.slice.call(arguments, 1), newStr = str, nextIdxToReplace = newStr.indexOf("{}");
qq.each(args, function(idx, val) {
var strBefore = newStr.substring(0, nextIdxToReplace), strAfter = newStr.substring(nextIdxToReplace + 2);
newStr = strBefore + val + strAfter;
nextIdxToReplace = newStr.indexOf("{}", nextIdxToReplace + val.length);
if (nextIdxToReplace < 0) {
return false;
}
});
return newStr;
};
qq.isFile = function(maybeFile) {
return window.File && Object.prototype.toString.call(maybeFile) === "[object File]";
};
qq.isFileList = function(maybeFileList) {
return window.FileList && Object.prototype.toString.call(maybeFileList) === "[object FileList]";
};
qq.isFileOrInput = function(maybeFileOrInput) {
return qq.isFile(maybeFileOrInput) || qq.isInput(maybeFileOrInput);
};
qq.isInput = function(maybeInput, notFile) {
var evaluateType = function(type) {
var normalizedType = type.toLowerCase();
if (notFile) {
return normalizedType !== "file";
}
return normalizedType === "file";
};
if (window.HTMLInputElement) {
if (Object.prototype.toString.call(maybeInput) === "[object HTMLInputElement]") {
if (maybeInput.type && evaluateType(maybeInput.type)) {
return true;
}
}
}
if (maybeInput.tagName) {
if (maybeInput.tagName.toLowerCase() === "input") {
if (maybeInput.type && evaluateType(maybeInput.type)) {
return true;
}
}
}
return false;
};
qq.isBlob = function(maybeBlob) {
if (window.Blob && Object.prototype.toString.call(maybeBlob) === "[object Blob]") {
return true;
}
};
qq.isXhrUploadSupported = function() {
var input = document.createElement("input");
input.type = "file";
return input.multiple !== undefined && typeof File !== "undefined" && typeof FormData !== "undefined" && typeof qq.createXhrInstance().upload !== "undefined";
};
qq.createXhrInstance = function() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
try {
return new ActiveXObject("MSXML2.XMLHTTP.3.0");
} catch (error) {
qq.log("Neither XHR or ActiveX are supported!", "error");
return null;
}
};
qq.isFolderDropSupported = function(dataTransfer) {
return dataTransfer.items && dataTransfer.items.length > 0 && dataTransfer.items[0].webkitGetAsEntry;
};
qq.isFileChunkingSupported = function() {
return !qq.androidStock() && qq.isXhrUploadSupported() && (File.prototype.slice !== undefined || File.prototype.webkitSlice !== undefined || File.prototype.mozSlice !== undefined);
};
qq.sliceBlob = function(fileOrBlob, start, end) {
var slicer = fileOrBlob.slice || fileOrBlob.mozSlice || fileOrBlob.webkitSlice;
return slicer.call(fileOrBlob, start, end);
};
qq.arrayBufferToHex = function(buffer) {
var bytesAsHex = "", bytes = new Uint8Array(buffer);
qq.each(bytes, function(idx, byt) {
var byteAsHexStr = byt.toString(16);
if (byteAsHexStr.length < 2) {
byteAsHexStr = "0" + byteAsHexStr;
}
bytesAsHex += byteAsHexStr;
});
return bytesAsHex;
};
qq.readBlobToHex = function(blob, startOffset, length) {
var initialBlob = qq.sliceBlob(blob, startOffset, startOffset + length), fileReader = new FileReader(), promise = new qq.Promise();
fileReader.onload = function() {
promise.success(qq.arrayBufferToHex(fileReader.result));
};
fileReader.onerror = promise.failure;
fileReader.readAsArrayBuffer(initialBlob);
return promise;
};
qq.extend = function(first, second, extendNested) {
qq.each(second, function(prop, val) {
if (extendNested && qq.isObject(val)) {
if (first[prop] === undefined) {
first[prop] = {};
}
qq.extend(first[prop], val, true);
} else {
first[prop] = val;
}
});
return first;
};
qq.override = function(target, sourceFn) {
var super_ = {}, source = sourceFn(super_);
qq.each(source, function(srcPropName, srcPropVal) {
if (target[srcPropName] !== undefined) {
super_[srcPropName] = target[srcPropName];
}
target[srcPropName] = srcPropVal;
});
return target;
};
qq.indexOf = function(arr, elt, from) {
if (arr.indexOf) {
return arr.indexOf(elt, from);
}
from = from || 0;
var len = arr.length;
if (from < 0) {
from += len;
}
for (;from < len; from += 1) {
if (arr.hasOwnProperty(from) && arr[from] === elt) {
return from;
}
}
return -1;
};
qq.getUniqueId = function() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
return v.toString(16);
});
};
qq.ie = function() {
return navigator.userAgent.indexOf("MSIE") !== -1 || navigator.userAgent.indexOf("Trident") !== -1;
};
qq.ie7 = function() {
return navigator.userAgent.indexOf("MSIE 7") !== -1;
};
qq.ie8 = function() {
return navigator.userAgent.indexOf("MSIE 8") !== -1;
};
qq.ie10 = function() {
return navigator.userAgent.indexOf("MSIE 10") !== -1;
};
qq.ie11 = function() {
return qq.ie() && navigator.userAgent.indexOf("rv:11") !== -1;
};
qq.edge = function() {
return navigator.userAgent.indexOf("Edge") >= 0;
};
qq.safari = function() {
return navigator.vendor !== undefined && navigator.vendor.indexOf("Apple") !== -1;
};
qq.chrome = function() {
return navigator.vendor !== undefined && navigator.vendor.indexOf("Google") !== -1;
};
qq.opera = function() {
return navigator.vendor !== undefined && navigator.vendor.indexOf("Opera") !== -1;
};
qq.firefox = function() {
return !qq.edge() && !qq.ie11() && navigator.userAgent.indexOf("Mozilla") !== -1 && navigator.vendor !== undefined && navigator.vendor === "";
};
qq.windows = function() {
return navigator.platform === "Win32";
};
qq.android = function() {
return navigator.userAgent.toLowerCase().indexOf("android") !== -1;
};
qq.androidStock = function() {
return qq.android() && navigator.userAgent.toLowerCase().indexOf("chrome") < 0;
};
qq.ios6 = function() {
return qq.ios() && navigator.userAgent.indexOf(" OS 6_") !== -1;
};
qq.ios7 = function() {
return qq.ios() && navigator.userAgent.indexOf(" OS 7_") !== -1;
};
qq.ios8 = function() {
return qq.ios() && navigator.userAgent.indexOf(" OS 8_") !== -1;
};
qq.ios800 = function() {
return qq.ios() && navigator.userAgent.indexOf(" OS 8_0 ") !== -1;
};
qq.ios = function() {
return navigator.userAgent.indexOf("iPad") !== -1 || navigator.userAgent.indexOf("iPod") !== -1 || navigator.userAgent.indexOf("iPhone") !== -1;
};
qq.iosChrome = function() {
return qq.ios() && navigator.userAgent.indexOf("CriOS") !== -1;
};
qq.iosSafari = function() {
return qq.ios() && !qq.iosChrome() && navigator.userAgent.indexOf("Safari") !== -1;
};
qq.iosSafariWebView = function() {
return qq.ios() && !qq.iosChrome() && !qq.iosSafari();
};
qq.preventDefault = function(e) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
};
qq.toElement = function() {
var div = document.createElement("div");
return function(html) {
div.innerHTML = html;
var element = div.firstChild;
div.removeChild(element);
return element;
};
}();
qq.each = function(iterableItem, callback) {
var keyOrIndex, retVal;
if (iterableItem) {
if (window.Storage && iterableItem.constructor === window.Storage) {
for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) {
retVal = callback(iterableItem.key(keyOrIndex), iterableItem.getItem(iterableItem.key(keyOrIndex)));
if (retVal === false) {
break;
}
}
} else if (qq.isArray(iterableItem) || qq.isItemList(iterableItem) || qq.isNodeList(iterableItem)) {
for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) {
retVal = callback(keyOrIndex, iterableItem[keyOrIndex]);
if (retVal === false) {
break;
}
}
} else if (qq.isString(iterableItem)) {
for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) {
retVal = callback(keyOrIndex, iterableItem.charAt(keyOrIndex));
if (retVal === false) {
break;
}
}
} else {
for (keyOrIndex in iterableItem) {
if (Object.prototype.hasOwnProperty.call(iterableItem, keyOrIndex)) {
retVal = callback(keyOrIndex, iterableItem[keyOrIndex]);
if (retVal === false) {
break;
}
}
}
}
}
};
qq.bind = function(oldFunc, context) {
if (qq.isFunction(oldFunc)) {
var args = Array.prototype.slice.call(arguments, 2);
return function() {
var newArgs = qq.extend([], args);
if (arguments.length) {
newArgs = newArgs.concat(Array.prototype.slice.call(arguments));
}
return oldFunc.apply(context, newArgs);
};
}
throw new Error("first parameter must be a function!");
};
qq.obj2url = function(obj, temp, prefixDone) {
var uristrings = [], prefix = "&", add = function(nextObj, i) {
var nextTemp = temp ? /\[\]$/.test(temp) ? temp : temp + "[" + i + "]" : i;
if (nextTemp !== "undefined" && i !== "undefined") {
uristrings.push(typeof nextObj === "object" ? qq.obj2url(nextObj, nextTemp, true) : Object.prototype.toString.call(nextObj) === "[object Function]" ? encodeURIComponent(nextTemp) + "=" + encodeURIComponent(nextObj()) : encodeURIComponent(nextTemp) + "=" + encodeURIComponent(nextObj));
}
};
if (!prefixDone && temp) {
prefix = /\?/.test(temp) ? /\?$/.test(temp) ? "" : "&" : "?";
uristrings.push(temp);
uristrings.push(qq.obj2url(obj));
} else if (Object.prototype.toString.call(obj) === "[object Array]" && typeof obj !== "undefined") {
qq.each(obj, function(idx, val) {
add(val, idx);
});
} else if (typeof obj !== "undefined" && obj !== null && typeof obj === "object") {
qq.each(obj, function(prop, val) {
add(val, prop);
});
} else {
uristrings.push(encodeURIComponent(temp) + "=" + encodeURIComponent(obj));
}
if (temp) {
return uristrings.join(prefix);
} else {
return uristrings.join(prefix).replace(/^&/, "").replace(/%20/g, "+");
}
};
qq.obj2FormData = function(obj, formData, arrayKeyName) {
if (!formData) {
formData = new FormData();
}
qq.each(obj, function(key, val) {
key = arrayKeyName ? arrayKeyName + "[" + key + "]" : key;
if (qq.isObject(val)) {
qq.obj2FormData(val, formData, key);
} else if (qq.isFunction(val)) {
formData.append(key, val());
} else {
formData.append(key, val);
}
});
return formData;
};
qq.obj2Inputs = function(obj, form) {
var input;
if (!form) {
form = document.createElement("form");
}
qq.obj2FormData(obj, {
append: function(key, val) {
input = document.createElement("input");
input.setAttribute("name", key);
input.setAttribute("value", val);
form.appendChild(input);
}
});
return form;
};
qq.parseJson = function(json) {
if (window.JSON && qq.isFunction(JSON.parse)) {
return JSON.parse(json);
} else {
return eval("(" + json + ")");
}
};
qq.getExtension = function(filename) {
var extIdx = filename.lastIndexOf(".") + 1;
if (extIdx > 0) {
return filename.substr(extIdx, filename.length - extIdx);
}
};
qq.getFilename = function(blobOrFileInput) {
if (qq.isInput(blobOrFileInput)) {
return blobOrFileInput.value.replace(/.*(\/|\\)/, "");
} else if (qq.isFile(blobOrFileInput)) {
if (blobOrFileInput.fileName !== null && blobOrFileInput.fileName !== undefined) {
return blobOrFileInput.fileName;
}
}
return blobOrFileInput.name;
};
qq.DisposeSupport = function() {
var disposers = [];
return {
dispose: function() {
var disposer;
do {
disposer = disposers.shift();
if (disposer) {
disposer();
}
} while (disposer);
},
attach: function() {
var args = arguments;
this.addDisposer(qq(args[0]).attach.apply(this, Array.prototype.slice.call(arguments, 1)));
},
addDisposer: function(disposeFunction) {
disposers.push(disposeFunction);
}
};
};
})();
(function() {
"use strict";
if (typeof define === "function" && define.amd) {
define(function() {
return qq;
});
} else if (typeof module !== "undefined" && module.exports) {
module.exports = qq;
} else {
global.qq = qq;
}
})();
(function() {
"use strict";
qq.Error = function(message) {
this.message = "[Fine Uploader " + qq.version + "] " + message;
};
qq.Error.prototype = new Error();
})();
qq.version = "5.11.6";
qq.supportedFeatures = function() {
"use strict";
var supportsUploading, supportsUploadingBlobs, supportsFileDrop, supportsAjaxFileUploading, supportsFolderDrop, supportsChunking, supportsResume, supportsUploadViaPaste, supportsUploadCors, supportsDeleteFileXdr, supportsDeleteFileCorsXhr, supportsDeleteFileCors, supportsFolderSelection, supportsImagePreviews, supportsUploadProgress;
function testSupportsFileInputElement() {
var supported = true, tempInput;
try {
tempInput = document.createElement("input");
tempInput.type = "file";
qq(tempInput).hide();
if (tempInput.disabled) {
supported = false;
}
} catch (ex) {
supported = false;
}
return supported;
}
function isChrome21OrHigher() {
return (qq.chrome() || qq.opera()) && navigator.userAgent.match(/Chrome\/[2][1-9]|Chrome\/[3-9][0-9]/) !== undefined;
}
function isChrome14OrHigher() {
return (qq.chrome() || qq.opera()) && navigator.userAgent.match(/Chrome\/[1][4-9]|Chrome\/[2-9][0-9]/) !== undefined;
}
function isCrossOriginXhrSupported() {
if (window.XMLHttpRequest) {
var xhr = qq.createXhrInstance();
return xhr.withCredentials !== undefined;
}
return false;
}
function isXdrSupported() {
return window.XDomainRequest !== undefined;
}
function isCrossOriginAjaxSupported() {
if (isCrossOriginXhrSupported()) {
return true;
}
return isXdrSupported();
}
function isFolderSelectionSupported() {
return document.createElement("input").webkitdirectory !== undefined;
}
function isLocalStorageSupported() {
try {
return !!window.localStorage && qq.isFunction(window.localStorage.setItem);
} catch (error) {
return false;
}
}
function isDragAndDropSupported() {
var span = document.createElement("span");
return ("draggable" in span || "ondragstart" in span && "ondrop" in span) && !qq.android() && !qq.ios();
}
supportsUploading = testSupportsFileInputElement();
supportsAjaxFileUploading = supportsUploading && qq.isXhrUploadSupported();
supportsUploadingBlobs = supportsAjaxFileUploading && !qq.androidStock();
supportsFileDrop = supportsAjaxFileUploading && isDragAndDropSupported();
supportsFolderDrop = supportsFileDrop && isChrome21OrHigher();
supportsChunking = supportsAjaxFileUploading && qq.isFileChunkingSupported();
supportsResume = supportsAjaxFileUploading && supportsChunking && isLocalStorageSupported();
supportsUploadViaPaste = supportsAjaxFileUploading && isChrome14OrHigher();
supportsUploadCors = supportsUploading && (window.postMessage !== undefined || supportsAjaxFileUploading);
supportsDeleteFileCorsXhr = isCrossOriginXhrSupported();
supportsDeleteFileXdr = isXdrSupported();
supportsDeleteFileCors = isCrossOriginAjaxSupported();
supportsFolderSelection = isFolderSelectionSupported();
supportsImagePreviews = supportsAjaxFileUploading && window.FileReader !== undefined;
supportsUploadProgress = function() {
if (supportsAjaxFileUploading) {
return !qq.androidStock() && !qq.iosChrome();
}
return false;
}();
return {
ajaxUploading: supportsAjaxFileUploading,
blobUploading: supportsUploadingBlobs,
canDetermineSize: supportsAjaxFileUploading,
chunking: supportsChunking,
deleteFileCors: supportsDeleteFileCors,
deleteFileCorsXdr: supportsDeleteFileXdr,
deleteFileCorsXhr: supportsDeleteFileCorsXhr,
dialogElement: !!window.HTMLDialogElement,
fileDrop: supportsFileDrop,
folderDrop: supportsFolderDrop,
folderSelection: supportsFolderSelection,
imagePreviews: supportsImagePreviews,
imageValidation: supportsImagePreviews,
itemSizeValidation: supportsAjaxFileUploading,
pause: supportsChunking,
progressBar: supportsUploadProgress,
resume: supportsResume,
scaling: supportsImagePreviews && supportsUploadingBlobs,
tiffPreviews: qq.safari(),
unlimitedScaledImageSize: !qq.ios(),
uploading: supportsUploading,
uploadCors: supportsUploadCors,
uploadCustomHeaders: supportsAjaxFileUploading,
uploadNonMultipart: supportsAjaxFileUploading,
uploadViaPaste: supportsUploadViaPaste
};
}();
qq.isGenericPromise = function(maybePromise) {
"use strict";
return !!(maybePromise && maybePromise.then && qq.isFunction(maybePromise.then));
};
qq.Promise = function() {
"use strict";
var successArgs, failureArgs, successCallbacks = [], failureCallbacks = [], doneCallbacks = [], state = 0;
qq.extend(this, {
then: function(onSuccess, onFailure) {
if (state === 0) {
if (onSuccess) {
successCallbacks.push(onSuccess);
}
if (onFailure) {
failureCallbacks.push(onFailure);
}
} else if (state === -1) {
onFailure && onFailure.apply(null, failureArgs);
} else if (onSuccess) {
onSuccess.apply(null, successArgs);
}
return this;
},
done: function(callback) {
if (state === 0) {
doneCallbacks.push(callback);
} else {
callback.apply(null, failureArgs === undefined ? successArgs : failureArgs);
}
return this;
},
success: function() {
state = 1;
successArgs = arguments;
if (successCallbacks.length) {
qq.each(successCallbacks, function(idx, callback) {
callback.apply(null, successArgs);
});
}
if (doneCallbacks.length) {
qq.each(doneCallbacks, function(idx, callback) {
callback.apply(null, successArgs);
});
}
return this;
},
failure: function() {
state = -1;
failureArgs = arguments;
if (failureCallbacks.length) {
qq.each(failureCallbacks, function(idx, callback) {
callback.apply(null, failureArgs);
});
}
if (doneCallbacks.length) {
qq.each(doneCallbacks, function(idx, callback) {
callback.apply(null, failureArgs);
});
}
return this;
}
});
};
qq.BlobProxy = function(referenceBlob, onCreate) {
"use strict";
qq.extend(this, {
referenceBlob: referenceBlob,
create: function() {
return onCreate(referenceBlob);
}
});
};
qq.UploadButton = function(o) {
"use strict";
var self = this, disposeSupport = new qq.DisposeSupport(), options = {
acceptFiles: null,
element: null,
focusClass: "qq-upload-button-focus",
folders: false,
hoverClass: "qq-upload-button-hover",
ios8BrowserCrashWorkaround: false,
multiple: false,
name: "qqfile",
onChange: function(input) {},
title: null
}, input, buttonId;
qq.extend(options, o);
buttonId = qq.getUniqueId();
function createInput() {
var input = document.createElement("input");
input.setAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME, buttonId);
input.setAttribute("title", options.title);
self.setMultiple(options.multiple, input);
if (options.folders && qq.supportedFeatures.folderSelection) {
input.setAttribute("webkitdirectory", "");
}
if (options.acceptFiles) {
input.setAttribute("accept", options.acceptFiles);
}
input.setAttribute("type", "file");
input.setAttribute("name", options.name);
qq(input).css({
position: "absolute",
right: 0,
top: 0,
fontFamily: "Arial",
fontSize: qq.ie() && !qq.ie8() ? "3500px" : "118px",
margin: 0,
padding: 0,
cursor: "pointer",
opacity: 0
});
!qq.ie7() && qq(input).css({
height: "100%"
});
options.element.appendChild(input);
disposeSupport.attach(input, "change", function() {
options.onChange(input);
});
disposeSupport.attach(input, "mouseover", function() {
qq(options.element).addClass(options.hoverClass);
});
disposeSupport.attach(input, "mouseout", function() {
qq(options.element).removeClass(options.hoverClass);
});
disposeSupport.attach(input, "focus", function() {
qq(options.element).addClass(options.focusClass);
});
disposeSupport.attach(input, "blur", function() {
qq(options.element).removeClass(options.focusClass);
});
return input;
}
qq(options.element).css({
position: "relative",
overflow: "hidden",
direction: "ltr"
});
qq.extend(this, {
getInput: function() {
return input;
},
getButtonId: function() {
return buttonId;
},
setMultiple: function(isMultiple, optInput) {
var input = optInput || this.getInput();
if (options.ios8BrowserCrashWorkaround && qq.ios8() && (qq.iosChrome() || qq.iosSafariWebView())) {
input.setAttribute("multiple", "");
} else {
if (isMultiple) {
input.setAttribute("multiple", "");
} else {
input.removeAttribute("multiple");
}
}
},
setAcceptFiles: function(acceptFiles) {
if (acceptFiles !== options.acceptFiles) {
input.setAttribute("accept", acceptFiles);
}
},
reset: function() {
if (input.parentNode) {
qq(input).remove();
}
qq(options.element).removeClass(options.focusClass);
input = null;
input = createInput();
}
});
input = createInput();
};
qq.UploadButton.BUTTON_ID_ATTR_NAME = "qq-button-id";
qq.UploadData = function(uploaderProxy) {
"use strict";
var data = [], byUuid = {}, byStatus = {}, byProxyGroupId = {}, byBatchId = {};
function getDataByIds(idOrIds) {
if (qq.isArray(idOrIds)) {
var entries = [];
qq.each(idOrIds, function(idx, id) {
entries.push(data[id]);
});
return entries;
}
return data[idOrIds];
}
function getDataByUuids(uuids) {
if (qq.isArray(uuids)) {
var entries = [];
qq.each(uuids, function(idx, uuid) {
entries.push(data[byUuid[uuid]]);
});
return entries;
}
return data[byUuid[uuids]];
}
function getDataByStatus(status) {
var statusResults = [], statuses = [].concat(status);
qq.each(statuses, function(index, statusEnum) {
var statusResultIndexes = byStatus[statusEnum];
if (statusResultIndexes !== undefined) {
qq.each(statusResultIndexes, function(i, dataIndex) {
statusResults.push(data[dataIndex]);
});
}
});
return statusResults;
}
qq.extend(this, {
addFile: function(spec) {
var status = spec.status || qq.status.SUBMITTING, id = data.push({
name: spec.name,
originalName: spec.name,
uuid: spec.uuid,
size: spec.size == null ? -1 : spec.size,
status: status
}) - 1;
if (spec.batchId) {
data[id].batchId = spec.batchId;
if (byBatchId[spec.batchId] === undefined) {
byBatchId[spec.batchId] = [];
}
byBatchId[spec.batchId].push(id);
}
if (spec.proxyGroupId) {
data[id].proxyGroupId = spec.proxyGroupId;
if (byProxyGroupId[spec.proxyGroupId] === undefined) {
byProxyGroupId[spec.proxyGroupId] = [];
}
byProxyGroupId[spec.proxyGroupId].push(id);
}
data[id].id = id;
byUuid[spec.uuid] = id;
if (byStatus[status] === undefined) {
byStatus[status] = [];
}
byStatus[status].push(id);
uploaderProxy.onStatusChange(id, null, status);
return id;
},
retrieve: function(optionalFilter) {
if (qq.isObject(optionalFilter) && data.length) {
if (optionalFilter.id !== undefined) {
return getDataByIds(optionalFilter.id);
} else if (optionalFilter.uuid !== undefined) {
return getDataByUuids(optionalFilter.uuid);
} else if (optionalFilter.status) {
return getDataByStatus(optionalFilter.status);
}
} else {
return qq.extend([], data, true);
}
},
reset: function() {
data = [];
byUuid = {};
byStatus = {};
byBatchId = {};
},
setStatus: function(id, newStatus) {
var oldStatus = data[id].status, byStatusOldStatusIndex = qq.indexOf(byStatus[oldStatus], id);
byStatus[oldStatus].splice(byStatusOldStatusIndex, 1);
data[id].status = newStatus;
if (byStatus[newStatus] === undefined) {
byStatus[newStatus] = [];
}
byStatus[newStatus].push(id);
uploaderProxy.onStatusChange(id, oldStatus, newStatus);
},
uuidChanged: function(id, newUuid) {
var oldUuid = data[id].uuid;
data[id].uuid = newUuid;
byUuid[newUuid] = id;
delete byUuid[oldUuid];
},
updateName: function(id, newName) {
data[id].name = newName;
},
updateSize: function(id, newSize) {
data[id].size = newSize;
},
setParentId: function(targetId, parentId) {
data[targetId].parentId = parentId;
},
getIdsInProxyGroup: function(id) {
var proxyGroupId = data[id].proxyGroupId;
if (proxyGroupId) {
return byProxyGroupId[proxyGroupId];
}
return [];
},
getIdsInBatch: function(id) {
var batchId = data[id].batchId;
return byBatchId[batchId];
}
});
};
qq.status = {
SUBMITTING: "submitting",
SUBMITTED: "submitted",
REJECTED: "rejected",
QUEUED: "queued",
CANCELED: "canceled",
PAUSED: "paused",
UPLOADING: "uploading",
UPLOAD_RETRYING: "retrying upload",
UPLOAD_SUCCESSFUL: "upload successful",
UPLOAD_FAILED: "upload failed",
DELETE_FAILED: "delete failed",
DELETING: "deleting",
DELETED: "deleted"
};
(function() {
"use strict";
qq.basePublicApi = {
addBlobs: function(blobDataOrArray, params, endpoint) {
this.addFiles(blobDataOrArray, params, endpoint);
},
addInitialFiles: function(cannedFileList) {
var self = this;
qq.each(cannedFileList, function(index, cannedFile) {
self._addCannedFile(cannedFile);
});
},
addFiles: function(data, params, endpoint) {
this._maybeHandleIos8SafariWorkaround();
var batchId = this._storedIds.length === 0 ? qq.getUniqueId() : this._currentBatchId, processBlob = qq.bind(function(blob) {
this._handleNewFile({
blob: blob,
name: this._options.blobs.defaultName
}, batchId, verifiedFiles);
}, this), processBlobData = qq.bind(function(blobData) {
this._handleNewFile(blobData, batchId, verifiedFiles);
}, this), processCanvas = qq.bind(function(canvas) {
var blob = qq.canvasToBlob(canvas);
this._handleNewFile({
blob: blob,
name: this._options.blobs.defaultName + ".png"
}, batchId, verifiedFiles);
}, this), processCanvasData = qq.bind(function(canvasData) {
var normalizedQuality = canvasData.quality && canvasData.quality / 100, blob = qq.canvasToBlob(canvasData.canvas, canvasData.type, normalizedQuality);
this._handleNewFile({
blob: blob,
name: canvasData.name
}, batchId, verifiedFiles);
}, this), processFileOrInput = qq.bind(function(fileOrInput) {
if (qq.isInput(fileOrInput) && qq.supportedFeatures.ajaxUploading) {
var files = Array.prototype.slice.call(fileOrInput.files), self = this;
qq.each(files, function(idx, file) {
self._handleNewFile(file, batchId, verifiedFiles);
});
} else {
this._handleNewFile(fileOrInput, batchId, verifiedFiles);
}
}, this), normalizeData = function() {
if (qq.isFileList(data)) {
data = Array.prototype.slice.call(data);
}
data = [].concat(data);
}, self = this, verifiedFiles = [];
this._currentBatchId = batchId;
if (data) {
normalizeData();
qq.each(data, function(idx, fileContainer) {
if (qq.isFileOrInput(fileContainer)) {
processFileOrInput(fileContainer);
} else if (qq.isBlob(fileContainer)) {
processBlob(fileContainer);
} else if (qq.isObject(fileContainer)) {
if (fileContainer.blob && fileContainer.name) {
processBlobData(fileContainer);
} else if (fileContainer.canvas && fileContainer.name) {
processCanvasData(fileContainer);
}
} else if (fileContainer.tagName && fileContainer.tagName.toLowerCase() === "canvas") {
processCanvas(fileContainer);
} else {
self.log(fileContainer + " is not a valid file container! Ignoring!", "warn");
}
});
this.log("Received " + verifiedFiles.length + " files.");
this._prepareItemsForUpload(verifiedFiles, params, endpoint);
}
},
cancel: function(id) {
this._handler.cancel(id);
},
cancelAll: function() {
var storedIdsCopy = [], self = this;
qq.extend(storedIdsCopy, this._storedIds);
qq.each(storedIdsCopy, function(idx, storedFileId) {
self.cancel(storedFileId);
});
this._handler.cancelAll();
},
clearStoredFiles: function() {
this._storedIds = [];
},
continueUpload: function(id) {
var uploadData = this._uploadData.retrieve({
id: id
});
if (!qq.supportedFeatures.pause || !this._options.chunking.enabled) {
return false;
}
if (uploadData.status === qq.status.PAUSED) {
this.log(qq.format("Paused file ID {} ({}) will be continued. Not paused.", id, this.getName(id)));
this._uploadFile(id);
return true;
} else {
this.log(qq.format("Ignoring continue for file ID {} ({}). Not paused.", id, this.getName(id)), "error");
}
return false;
},
deleteFile: function(id) {
return this._onSubmitDelete(id);
},
doesExist: function(fileOrBlobId) {
return this._handler.isValid(fileOrBlobId);
},
drawThumbnail: function(fileId, imgOrCanvas, maxSize, fromServer, customResizeFunction) {
var promiseToReturn = new qq.Promise(), fileOrUrl, options;
if (this._imageGenerator) {
fileOrUrl = this._thumbnailUrls[fileId];
options = {
customResizeFunction: customResizeFunction,
maxSize: maxSize > 0 ? maxSize : null,
scale: maxSize > 0
};
if (!fromServer && qq.supportedFeatures.imagePreviews) {
fileOrUrl = this.getFile(fileId);
}
if (fileOrUrl == null) {
promiseToReturn.failure({
container: imgOrCanvas,
error: "File or URL not found."
});
} else {
this._imageGenerator.generate(fileOrUrl, imgOrCanvas, options).then(function success(modifiedContainer) {
promiseToReturn.success(modifiedContainer);
}, function failure(container, reason) {
promiseToReturn.failure({
container: container,
error: reason || "Problem generating thumbnail"
});
});
}
} else {
promiseToReturn.failure({
container: imgOrCanvas,
error: "Missing image generator module"
});
}
return promiseToReturn;
},
getButton: function(fileId) {
return this._getButton(this._buttonIdsForFileIds[fileId]);
},
getEndpoint: function(fileId) {
return this._endpointStore.get(fileId);
},
getFile: function(fileOrBlobId) {
return this._handler.getFile(fileOrBlobId) || null;
},
getInProgress: function() {
return this._uploadData.retrieve({
status: [ qq.status.UPLOADING, qq.status.UPLOAD_RETRYING, qq.status.QUEUED ]
}).length;
},
getName: function(id) {
return this._uploadData.retrieve({
id: id
}).name;
},
getParentId: function(id) {
var uploadDataEntry = this.getUploads({
id: id
}), parentId = null;
if (uploadDataEntry) {
if (uploadDataEntry.parentId !== undefined) {
parentId = uploadDataEntry.parentId;
}
}
return parentId;
},
getResumableFilesData: function() {
return this._handler.getResumableFilesData();
},
getSize: function(id) {
return this._uploadData.retrieve({
id: id
}).size;
},
getNetUploads: function() {
return this._netUploaded;
},
getRemainingAllowedItems: function() {
var allowedItems = this._currentItemLimit;
if (allowedItems > 0) {
return allowedItems - this._netUploadedOrQueued;
}
return null;
},
getUploads: function(optionalFilter) {
return this._uploadData.retrieve(optionalFilter);
},
getUuid: function(id) {
return this._uploadData.retrieve({
id: id
}).uuid;
},
log: function(str, level) {
if (this._options.debug && (!level || level === "info")) {
qq.log("[Fine Uploader " + qq.version + "] " + str);
} else if (level && level !== "info") {
qq.log("[Fine Uploader " + qq.version + "] " + str, level);
}
},
pauseUpload: function(id) {
var uploadData = this._uploadData.retrieve({
id: id
});
if (!qq.supportedFeatures.pause || !this._options.chunking.enabled) {
return false;
}
if (qq.indexOf([ qq.status.UPLOADING, qq.status.UPLOAD_RETRYING ], uploadData.status) >= 0) {
if (this._handler.pause(id)) {
this._uploadData.setStatus(id, qq.status.PAUSED);
return true;
} else {
this.log(qq.format("Unable to pause file ID {} ({}).", id, this.getName(id)), "error");
}
} else {
this.log(qq.format("Ignoring pause for file ID {} ({}). Not in progress.", id, this.getName(id)), "error");
}
return false;
},
reset: function() {
this.log("Resetting uploader...");
this._handler.reset();
this._storedIds = [];
this._autoRetries = [];
this._retryTimeouts = [];
this._preventRetries = [];
this._thumbnailUrls = [];
qq.each(this._buttons, function(idx, button) {
button.reset();
});
this._paramsStore.reset();
this._endpointStore.reset();
this._netUploadedOrQueued = 0;
this._netUploaded = 0;
this._uploadData.reset();
this._buttonIdsForFileIds = [];
this._pasteHandler && this._pasteHandler.reset();
this._options.session.refreshOnReset && this._refreshSessionData();
this._succeededSinceLastAllComplete = [];
this._failedSinceLastAllComplete = [];
this._totalProgress && this._totalProgress.reset();
},
retry: function(id) {
return this._manualRetry(id);
},
scaleImage: function(id, specs) {
var self = this;
return qq.Scaler.prototype.scaleImage(id, specs, {
log: qq.bind(self.log, self),
getFile: qq.bind(self.getFile, self),
uploadData: self._uploadData
});
},
setCustomHeaders: function(headers, id) {
this._customHeadersStore.set(headers, id);
},
setDeleteFileCustomHeaders: function(headers, id) {
this._deleteFileCustomHeadersStore.set(headers, id);
},
setDeleteFileEndpoint: function(endpoint, id) {
this._deleteFileEndpointStore.set(endpoint, id);
},
setDeleteFileParams: function(params, id) {
this._deleteFileParamsStore.set(params, id);
},
setEndpoint: function(endpoint, id) {
this._endpointStore.set(endpoint, id);
},
setForm: function(elementOrId) {
this._updateFormSupportAndParams(elementOrId);
},
setItemLimit: function(newItemLimit) {
this._currentItemLimit = newItemLimit;
},
setName: function(id, newName) {
this._uploadData.updateName(id, newName);
},
setParams: function(params, id) {
this._paramsStore.set(params, id);
},
setUuid: function(id, newUuid) {
return this._uploadData.uuidChanged(id, newUuid);
},
uploadStoredFiles: function() {
if (this._storedIds.length === 0) {
this._itemError("noFilesError");
} else {
this._uploadStoredFiles();
}
}
};
qq.basePrivateApi = {
_addCannedFile: function(sessionData) {
var id = this._uploadData.addFile({
uuid: sessionData.uuid,
name: sessionData.name,
size: sessionData.size,
status: qq.status.UPLOAD_SUCCESSFUL
});
sessionData.deleteFileEndpoint && this.setDeleteFileEndpoint(sessionData.deleteFileEndpoint, id);
sessionData.deleteFileParams && this.setDeleteFileParams(sessionData.deleteFileParams, id);
if (sessionData.thumbnailUrl) {
this._thumbnailUrls[id] = sessionData.thumbnailUrl;
}
this._netUploaded++;
this._netUploadedOrQueued++;
return id;
},
_annotateWithButtonId: function(file, associatedInput) {
if (qq.isFile(file)) {
file.qqButtonId = this._getButtonId(associatedInput);
}
},
_batchError: function(message) {
this._options.callbacks.onError(null, null, message, undefined);
},
_createDeleteHandler: function() {
var self = this;
return new qq.DeleteFileAjaxRequester({
method: this._options.deleteFile.method.toUpperCase(),
maxConnections: this._options.maxConnections,
uuidParamName: this._options.request.uuidName,
customHeaders: this._deleteFileCustomHeadersStore,
paramsStore: this._deleteFileParamsStore,
endpointStore: this._deleteFileEndpointStore,
cors: this._options.cors,
log: qq.bind(self.log, self),
onDelete: function(id) {
self._onDelete(id);
self._options.callbacks.onDelete(id);
},
onDeleteComplete: function(id, xhrOrXdr, isError) {
self._onDeleteComplete(id, xhrOrXdr, isError);
self._options.callbacks.onDeleteComplete(id, xhrOrXdr, isError);
}
});
},
_createPasteHandler: function() {
var self = this;
return new qq.PasteSupport({
targetElement: this._options.paste.targetElement,
callbacks: {
log: qq.bind(self.log, self),
pasteReceived: function(blob) {
self._handleCheckedCallback({
name: "onPasteReceived",
callback: qq.bind(self._options.callbacks.onPasteReceived, self, blob),
onSuccess: qq.bind(self._handlePasteSuccess, self, blob),
identifier: "pasted image"
});
}
}
});
},
_createStore: function(initialValue, _readOnlyValues_) {
var store = {}, catchall = initialValue, perIdReadOnlyValues = {}, readOnlyValues = _readOnlyValues_, copy = function(orig) {
if (qq.isObject(orig)) {
return qq.extend({}, orig);
}
return orig;
}, getReadOnlyValues = function() {
if (qq.isFunction(readOnlyValues)) {
return readOnlyValues();
}
return readOnlyValues;
}, includeReadOnlyValues = function(id, existing) {
if (readOnlyValues && qq.isObject(existing)) {
qq.extend(existing, getReadOnlyValues());
}
if (perIdReadOnlyValues[id]) {
qq.extend(existing, perIdReadOnlyValues[id]);
}
};
return {
set: function(val, id) {
if (id == null) {
store = {};
catchall = copy(val);
} else {
store[id] = copy(val);
}
},
get: function(id) {
var values;
if (id != null && store[id]) {
values = store[id];
} else {
values = copy(catchall);
}
includeReadOnlyValues(id, values);
return copy(values);
},
addReadOnly: function(id, values) {
if (qq.isObject(store)) {
if (id === null) {
if (qq.isFunction(values)) {
readOnlyValues = values;
} else {
readOnlyValues = readOnlyValues || {};
qq.extend(readOnlyValues, values);
}
} else {
perIdReadOnlyValues[id] = perIdReadOnlyValues[id] || {};
qq.extend(perIdReadOnlyValues[id], values);
}
}
},
remove: function(fileId) {
return delete store[fileId];
},
reset: function() {
store = {};
perIdReadOnlyValues = {};
catchall = initialValue;
}
};
},
_createUploadDataTracker: function() {
var self = this;
return new qq.UploadData({
getName: function(id) {
return self.getName(id);
},
getUuid: function(id) {
return self.getUuid(id);
},
getSize: function(id) {
return self.getSize(id);
},
onStatusChange: function(id, oldStatus, newStatus) {
self._onUploadStatusChange(id, oldStatus, newStatus);
self._options.callbacks.onStatusChange(id, oldStatus, newStatus);
self._maybeAllComplete(id, newStatus);
if (self._totalProgress) {
setTimeout(function() {
self._totalProgress.onStatusChange(id, oldStatus, newStatus);
}, 0);
}
}
});
},
_createUploadButton: function(spec) {
var self = this, acceptFiles = spec.accept || this._options.validation.acceptFiles, allowedExtensions = spec.allowedExtensions || this._options.validation.allowedExtensions, button;
function allowMultiple() {
if (qq.supportedFeatures.ajaxUploading) {
if (self._options.workarounds.iosEmptyVideos && qq.ios() && !qq.ios6() && self._isAllowedExtension(allowedExtensions, ".mov")) {
return false;
}
if (spec.multiple === undefined) {
return self._options.multiple;
}
return spec.multiple;
}
return false;
}
button = new qq.UploadButton({
acceptFiles: acceptFiles,
element: spec.element,
focusClass: this._options.classes.buttonFocus,
folders: spec.folders,
hoverClass: this._options.classes.buttonHover,
ios8BrowserCrashWorkaround: this._options.workarounds.ios8BrowserCrash,
multiple: allowMultiple(),
name: this._options.request.inputName,
onChange: function(input) {
self._onInputChange(input);
},
title: spec.title == null ? this._options.text.fileInputTitle : spec.title
});
this._disposeSupport.addDisposer(function() {
button.dispose();
});
self._buttons.push(button);
return button;
},
_createUploadHandler: function(additionalOptions, namespace) {
var self = this, lastOnProgress = {}, options = {
debug: this._options.debug,
maxConnections: this._options.maxConnections,
cors: this._options.cors,
paramsStore: this._paramsStore,
endpointStore: this._endpointStore,
chunking: this._options.chunking,
resume: this._options.resume,
blobs: this._options.blobs,
log: qq.bind(self.log, self),
preventRetryParam: this._options.retry.preventRetryResponseProperty,
onProgress: function(id, name, loaded, total) {
if (loaded < 0 || total < 0) {
return;
}
if (lastOnProgress[id]) {
if (lastOnProgress[id].loaded !== loaded || lastOnProgress[id].total !== total) {
self._onProgress(id, name, loaded, total);
self._options.callbacks.onProgress(id, name, loaded, total);
}
} else {
self._onProgress(id, name, loaded, total);
self._options.callbacks.onProgress(id, name, loaded, total);
}
lastOnProgress[id] = {
loaded: loaded,
total: total
};
},
onComplete: function(id, name, result, xhr) {
delete lastOnProgress[id];
var status = self.getUploads({
id: id
}).status, retVal;
if (status === qq.status.UPLOAD_SUCCESSFUL || status === qq.status.UPLOAD_FAILED) {
return;
}
retVal = self._onComplete(id, name, result, xhr);
if (retVal instanceof qq.Promise) {
retVal.done(function() {
self._options.callbacks.onComplete(id, name, result, xhr);
});
} else {
self._options.callbacks.onComplete(id, name, result, xhr);
}
},
onCancel: function(id, name, cancelFinalizationEffort) {
var promise = new qq.Promise();
self._handleCheckedCallback({
name: "onCancel",
callback: qq.bind(self._options.callbacks.onCancel, self, id, name),
onFailure: promise.failure,
onSuccess: function() {
cancelFinalizationEffort.then(function() {
self._onCancel(id, name);
});
promise.success();
},
identifier: id
});
return promise;
},
onUploadPrep: qq.bind(this._onUploadPrep, this),
onUpload: function(id, name) {
self._onUpload(id, name);
self._options.callbacks.onUpload(id, name);
},
onUploadChunk: function(id, name, chunkData) {
self._onUploadChunk(id, chunkData);
self._options.callbacks.onUploadChunk(id, name, chunkData);
},
onUploadChunkSuccess: function(id, chunkData, result, xhr) {
self._options.callbacks.onUploadChunkSuccess.apply(self, arguments);
},
onResume: function(id, name, chunkData) {
return self._options.callbacks.onResume(id, name, chunkData);
},
onAutoRetry: function(id, name, responseJSON, xhr) {
return self._onAutoRetry.apply(self, arguments);
},
onUuidChanged: function(id, newUuid) {
self.log("Server requested UUID change from '" + self.getUuid(id) + "' to '" + newUuid + "'");
self.setUuid(id, newUuid);
},
getName: qq.bind(self.getName, self),
getUuid: qq.bind(self.getUuid, self),
getSize: qq.bind(self.getSize, self),
setSize: qq.bind(self._setSize, self),
getDataByUuid: function(uuid) {
return self.getUploads({
uuid: uuid
});
},
isQueued: function(id) {
var status = self.getUploads({
id: id
}).status;
return status === qq.status.QUEUED || status === qq.status.SUBMITTED || status === qq.status.UPLOAD_RETRYING || status === qq.status.PAUSED;
},
getIdsInProxyGroup: self._uploadData.getIdsInProxyGroup,
getIdsInBatch: self._uploadData.getIdsInBatch
};
qq.each(this._options.request, function(prop, val) {
options[prop] = val;
});
options.customHeaders = this._customHeadersStore;
if (additionalOptions) {
qq.each(additionalOptions, function(key, val) {
options[key] = val;
});
}
return new qq.UploadHandlerController(options, namespace);
},
_fileOrBlobRejected: function(id) {
this._netUploadedOrQueued--;
this._uploadData.setStatus(id, qq.status.REJECTED);
},
_formatSize: function(bytes) {
var i = -1;
do {
bytes = bytes / 1e3;
i++;
} while (bytes > 999);
return Math.max(bytes, .1).toFixed(1) + this._options.text.sizeSymbols[i];
},
_generateExtraButtonSpecs: function() {
var self = this;
this._extraButtonSpecs = {};
qq.each(this._options.extraButtons, function(idx, extraButtonOptionEntry) {
var multiple = extraButtonOptionEntry.multiple, validation = qq.extend({}, self._options.validation, true), extraButtonSpec = qq.extend({}, extraButtonOptionEntry);
if (multiple === undefined) {
multiple = self._options.multiple;
}
if (extraButtonSpec.validation) {
qq.extend(validation, extraButtonOptionEntry.validation, true);
}
qq.extend(extraButtonSpec, {
multiple: multiple,
validation: validation
}, true);
self._initExtraButton(extraButtonSpec);
});
},
_getButton: function(buttonId) {
var extraButtonsSpec = this._extraButtonSpecs[buttonId];
if (extraButtonsSpec) {
return extraButtonsSpec.element;
} else if (buttonId === this._defaultButtonId) {
return this._options.button;
}
},
_getButtonId: function(buttonOrFileInputOrFile) {
var inputs, fileInput, fileBlobOrInput = buttonOrFileInputOrFile;
if (fileBlobOrInput instanceof qq.BlobProxy) {
fileBlobOrInput = fileBlobOrInput.referenceBlob;
}
if (fileBlobOrInput && !qq.isBlob(fileBlobOrInput)) {
if (qq.isFile(fileBlobOrInput)) {
return fileBlobOrInput.qqButtonId;
} else if (fileBlobOrInput.tagName.toLowerCase() === "input" && fileBlobOrInput.type.toLowerCase() === "file") {
return fileBlobOrInput.getAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME);
}
inputs = fileBlobOrInput.getElementsByTagName("input");
qq.each(inputs, function(idx, input) {
if (input.getAttribute("type") === "file") {
fileInput = input;
return false;
}
});
if (fileInput) {
return fileInput.getAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME);
}
}
},
_getNotFinished: function() {
return this._uploadData.retrieve({
status: [ qq.status.UPLOADING, qq.status.UPLOAD_RETRYING, qq.status.QUEUED, qq.status.SUBMITTING, qq.status.SUBMITTED, qq.status.PAUSED ]
}).length;
},
_getValidationBase: function(buttonId) {
var extraButtonSpec = this._extraButtonSpecs[buttonId];
return extraButtonSpec ? extraButtonSpec.validation : this._options.validation;
},
_getValidationDescriptor: function(fileWrapper) {
if (fileWrapper.file instanceof qq.BlobProxy) {
return {
name: qq.getFilename(fileWrapper.file.referenceBlob),
size: fileWrapper.file.referenceBlob.size
};
}
return {
name: this.getUploads({
id: fileWrapper.id
}).name,
size: this.getUploads({
id: fileWrapper.id
}).size
};
},
_getValidationDescriptors: function(fileWrappers) {
var self = this, fileDescriptors = [];
qq.each(fileWrappers, function(idx, fileWrapper) {
fileDescriptors.push(self._getValidationDescriptor(fileWrapper));
});
return fileDescriptors;
},
_handleCameraAccess: function() {
if (this._options.camera.ios && qq.ios()) {
var acceptIosCamera = "image/*;capture=camera", button = this._options.camera.button, buttonId = button ? this._getButtonId(button) : this._defaultButtonId, optionRoot = this._options;
if (buttonId && buttonId !== this._defaultButtonId) {
optionRoot = this._extraButtonSpecs[buttonId];
}
optionRoot.multiple = false;
if (optionRoot.validation.acceptFiles === null) {
optionRoot.validation.acceptFiles = acceptIosCamera;
} else {
optionRoot.validation.acceptFiles += "," + acceptIosCamera;
}
qq.each(this._buttons, function(idx, button) {
if (button.getButtonId() === buttonId) {
button.setMultiple(optionRoot.multiple);
button.setAcceptFiles(optionRoot.acceptFiles);
return false;
}
});
}
},
_handleCheckedCallback: function(details) {
var self = this, callbackRetVal = details.callback();
if (qq.isGenericPromise(callbackRetVal)) {
this.log(details.name + " - waiting for " + details.name + " promise to be fulfilled for " + details.identifier);
return callbackRetVal.then(function(successParam) {
self.log(details.name + " promise success for " + details.identifier);
details.onSuccess(successParam);
}, function() {
if (details.onFailure) {
self.log(details.name + " promise failure for " + details.identifier);
details.onFailure();
} else {
self.log(details.name + " promise failure for " + details.identifier);
}
});
}
if (callbackRetVal !== false) {
details.onSuccess(callbackRetVal);
} else {
if (details.onFailure) {
this.log(details.name + " - return value was 'false' for " + details.identifier + ". Invoking failure callback.");
details.onFailure();
} else {
this.log(details.name + " - return value was 'false' for " + details.identifier + ". Will not proceed.");
}
}
return callbackRetVal;
},
_handleNewFile: function(file, batchId, newFileWrapperList) {
var self = this, uuid = qq.getUniqueId(), size = -1, name = qq.getFilename(file), actualFile = file.blob || file, handler = this._customNewFileHandler ? this._customNewFileHandler : qq.bind(self._handleNewFileGeneric, self);
if (!qq.isInput(actualFile) && actualFile.size >= 0) {
size = actualFile.size;
}
handler(actualFile, name, uuid, size, newFileWrapperList, batchId, this._options.request.uuidName, {
uploadData: self._uploadData,
paramsStore: self._paramsStore,
addFileToHandler: function(id, file) {
self._handler.add(id, file);
self._netUploadedOrQueued++;
self._trackButton(id);
}
});
},
_handleNewFileGeneric: function(file, name, uuid, size, fileList, batchId) {
var id = this._uploadData.addFile({
uuid: uuid,
name: name,
size: size,
batchId: batchId
});
this._handler.add(id, file);
this._trackButton(id);
this._netUploadedOrQueued++;
fileList.push({
id: id,
file: file
});
},
_handlePasteSuccess: function(blob, extSuppliedName) {
var extension = blob.type.split("/")[1], name = extSuppliedName;
if (name == null) {
name = this._options.paste.defaultName;
}
name += "." + extension;
this.addFiles({
name: name,
blob: blob
});
},
_initExtraButton: function(spec) {
var button = this._createUploadButton({
accept: spec.validation.acceptFiles,
allowedExtensions: spec.validation.allowedExtensions,
element: spec.element,
folders: spec.folders,
multiple: spec.multiple,
title: spec.fileInputTitle
});
this._extraButtonSpecs[button.getButtonId()] = spec;
},
_initFormSupportAndParams: function() {
this._formSupport = qq.FormSupport && new qq.FormSupport(this._options.form, qq.bind(this.uploadStoredFiles, this), qq.bind(this.log, this));
if (this._formSupport && this._formSupport.attachedToForm) {
this._paramsStore = this._createStore(this._options.request.params, this._formSupport.getFormInputsAsObject);
this._options.autoUpload = this._formSupport.newAutoUpload;
if (this._formSupport.newEndpoint) {
this._options.request.endpoint = this._formSupport.newEndpoint;
}
} else {
this._paramsStore = this._createStore(this._options.request.params);
}
},
_isDeletePossible: function() {
if (!qq.DeleteFileAjaxRequester || !this._options.deleteFile.enabled) {
return false;
}
if (this._options.cors.expected) {
if (qq.supportedFeatures.deleteFileCorsXhr) {
return true;
}
if (qq.supportedFeatures.deleteFileCorsXdr && this._options.cors.allowXdr) {
return true;
}
return false;
}
return true;
},
_isAllowedExtension: function(allowed, fileName) {
var valid = false;
if (!allowed.length) {
return true;
}
qq.each(allowed, function(idx, allowedExt) {
if (qq.isString(allowedExt)) {
var extRegex = new RegExp("\\." + allowedExt + "$", "i");
if (fileName.match(extRegex) != null) {
valid = true;
return false;
}
}
});
return valid;
},
_itemError: function(code, maybeNameOrNames, item) {
var message = this._options.messages[code], allowedExtensions = [], names = [].concat(maybeNameOrNames), name = names[0], buttonId = this._getButtonId(item), validationBase = this._getValidationBase(buttonId), extensionsForMessage, placeholderMatch;
function r(name, replacement) {
message = message.replace(name, replacement);
}
qq.each(validationBase.allowedExtensions, function(idx, allowedExtension) {
if (qq.isString(allowedExtension)) {
allowedExtensions.push(allowedExtension);
}
});
extensionsForMessage = allowedExtensions.join(", ").toLowerCase();
r("{file}", this._options.formatFileName(name));
r("{extensions}", extensionsForMessage);
r("{sizeLimit}", this._formatSize(validationBase.sizeLimit));
r("{minSizeLimit}", this._formatSize(validationBase.minSizeLimit));
placeholderMatch = message.match(/(\{\w+\})/g);
if (placeholderMatch !== null) {
qq.each(placeholderMatch, function(idx, placeholder) {
r(placeholder, names[idx]);
});
}
this._options.callbacks.onError(null, name, message, undefined);
return message;
},
_manualRetry: function(id, callback) {
if (this._onBeforeManualRetry(id)) {
this._netUploadedOrQueued++;
this._uploadData.setStatus(id, qq.status.UPLOAD_RETRYING);
if (callback) {
callback(id);
} else {
this._handler.retry(id);
}
return true;
}
},
_maybeAllComplete: function(id, status) {
var self = this, notFinished = this._getNotFinished();
if (status === qq.status.UPLOAD_SUCCESSFUL) {
this._succeededSinceLastAllComplete.push(id);
} else if (status === qq.status.UPLOAD_FAILED) {
this._failedSinceLastAllComplete.push(id);
}
if (notFinished === 0 && (this._succeededSinceLastAllComplete.length || this._failedSinceLastAllComplete.length)) {
setTimeout(function() {
self._onAllComplete(self._succeededSinceLastAllComplete, self._failedSinceLastAllComplete);
}, 0);
}
},
_maybeHandleIos8SafariWorkaround: function() {
var self = this;
if (this._options.workarounds.ios8SafariUploads && qq.ios800() && qq.iosSafari()) {
setTimeout(function() {
window.alert(self._options.messages.unsupportedBrowserIos8Safari);
}, 0);
throw new qq.Error(this._options.messages.unsupportedBrowserIos8Safari);
}
},
_maybeParseAndSendUploadError: function(id, name, response, xhr) {
if (!response.success) {
if (xhr && xhr.status !== 200 && !response.error) {
this._options.callbacks.onError(id, name, "XHR returned response code " + xhr.status, xhr);
} else {
var errorReason = response.error ? response.error : this._options.text.defaultResponseError;
this._options.callbacks.onError(id, name, errorReason, xhr);
}
}
},
_maybeProcessNextItemAfterOnValidateCallback: function(validItem, items, index, params, endpoint) {
var self = this;
if (items.length > index) {
if (validItem || !this._options.validation.stopOnFirstInvalidFile) {
setTimeout(function() {
var validationDescriptor = self._getValidationDescriptor(items[index]), buttonId = self._getButtonId(items[index].file), button = self._getButton(buttonId);
self._handleCheckedCallback({
name: "onValidate",
callback: qq.bind(self._options.callbacks.onValidate, self, validationDescriptor, button),
onSuccess: qq.bind(self._onValidateCallbackSuccess, self, items, index, params, endpoint),
onFailure: qq.bind(self._onValidateCallbackFailure, self, items, index, params, endpoint),
identifier: "Item '" + validationDescriptor.name + "', size: " + validationDescriptor.size
});
}, 0);
} else if (!validItem) {
for (;index < items.length; index++) {
self._fileOrBlobRejected(items[index].id);
}
}
}
},
_onAllComplete: function(successful, failed) {
this._totalProgress && this._totalProgress.onAllComplete(successful, failed, this._preventRetries);
this._options.callbacks.onAllComplete(qq.extend([], successful), qq.extend([], failed));
this._succeededSinceLastAllComplete = [];
this._failedSinceLastAllComplete = [];
},
_onAutoRetry: function(id, name, responseJSON, xhr, callback) {
var self = this;
self._preventRetries[id] = responseJSON[self._options.retry.preventRetryResponseProperty];
if (self._shouldAutoRetry(id, name, responseJSON)) {
self._maybeParseAndSendUploadError.apply(self, arguments);
self._options.callbacks.onAutoRetry(id, name, self._autoRetries[id]);
self._onBeforeAutoRetry(id, name);
self._retryTimeouts[id] = setTimeout(function() {
self.log("Retrying " + name + "...");
self._uploadData.setStatus(id, qq.status.UPLOAD_RETRYING);
if (callback) {
callback(id);
} else {
self._handler.retry(id);
}
}, self._options.retry.autoAttemptDelay * 1e3);
return true;
}
},
_onBeforeAutoRetry: function(id, name) {
this.log("Waiting " + this._options.retry.autoAttemptDelay + " seconds before retrying " + name + "...");
},
_onBeforeManualRetry: function(id) {
var itemLimit = this._currentItemLimit, fileName;
if (this._preventRetries[id]) {
this.log("Retries are forbidden for id " + id, "warn");
return false;
} else if (this._handler.isValid(id)) {
fileName = this.getName(id);
if (this._options.callbacks.onManualRetry(id, fileName) === false) {
return false;
}
if (itemLimit > 0 && this._netUploadedOrQueued + 1 > itemLimit) {
this._itemError("retryFailTooManyItems");
return false;
}
this.log("Retrying upload for '" + fileName + "' (id: " + id + ")...");
return true;
} else {
this.log("'" + id + "' is not a valid file ID", "error");
return false;
}
},
_onCancel: function(id, name) {
this._netUploadedOrQueued--;
clearTimeout(this._retryTimeouts[id]);
var storedItemIndex = qq.indexOf(this._storedIds, id);
if (!this._options.autoUpload && storedItemIndex >= 0) {
this._storedIds.splice(storedItemIndex, 1);
}
this._uploadData.setStatus(id, qq.status.CANCELED);
},
_onComplete: function(id, name, result, xhr) {
if (!result.success) {
this._netUploadedOrQueued--;
this._uploadData.setStatus(id, qq.status.UPLOAD_FAILED);
if (result[this._options.retry.preventRetryResponseProperty] === true) {
this._preventRetries[id] = true;
}
} else {
if (result.thumbnailUrl) {
this._thumbnailUrls[id] = result.thumbnailUrl;
}
this._netUploaded++;
this._uploadData.setStatus(id, qq.status.UPLOAD_SUCCESSFUL);
}
this._maybeParseAndSendUploadError(id, name, result, xhr);
return result.success ? true : false;
},
_onDelete: function(id) {
this._uploadData.setStatus(id, qq.status.DELETING);
},
_onDeleteComplete: function(id, xhrOrXdr, isError) {
var name = this.getName(id);
if (isError) {
this._uploadData.setStatus(id, qq.status.DELETE_FAILED);
this.log("Delete request for '" + name + "' has failed.", "error");
if (xhrOrXdr.withCredentials === undefined) {
this._options.callbacks.onError(id, name, "Delete request failed", xhrOrXdr);
} else {
this._options.callbacks.onError(id, name, "Delete request failed with response code " + xhrOrXdr.status, xhrOrXdr);
}
} else {
this._netUploadedOrQueued--;
this._netUploaded--;
this._handler.expunge(id);
this._uploadData.setStatus(id, qq.status.DELETED);
this.log("Delete request for '" + name + "' has succeeded.");
}
},
_onInputChange: function(input) {
var fileIndex;
if (qq.supportedFeatures.ajaxUploading) {
for (fileIndex = 0; fileIndex < input.files.length; fileIndex++) {
this._annotateWithButtonId(input.files[fileIndex], input);
}
this.addFiles(input.files);
} else if (input.value.length > 0) {
this.addFiles(input);
}
qq.each(this._buttons, function(idx, button) {
button.reset();
});
},
_onProgress: function(id, name, loaded, total) {
this._totalProgress && this._totalProgress.onIndividualProgress(id, loaded, total);
},
_onSubmit: function(id, name) {},
_onSubmitCallbackSuccess: function(id, name) {
this._onSubmit.apply(this, arguments);
this._uploadData.setStatus(id, qq.status.SUBMITTED);
this._onSubmitted.apply(this, arguments);
if (this._options.autoUpload) {
this._options.callbacks.onSubmitted.apply(this, arguments);
this._uploadFile(id);
} else {
this._storeForLater(id);
this._options.callbacks.onSubmitted.apply(this, arguments);
}
},
_onSubmitDelete: function(id, onSuccessCallback, additionalMandatedParams) {
var uuid = this.getUuid(id), adjustedOnSuccessCallback;
if (onSuccessCallback) {
adjustedOnSuccessCallback = qq.bind(onSuccessCallback, this, id, uuid, additionalMandatedParams);
}
if (this._isDeletePossible()) {
this._handleCheckedCallback({
name: "onSubmitDelete",
callback: qq.bind(this._options.callbacks.onSubmitDelete, this, id),
onSuccess: adjustedOnSuccessCallback || qq.bind(this._deleteHandler.sendDelete, this, id, uuid, additionalMandatedParams),
identifier: id
});
return true;
} else {
this.log("Delete request ignored for ID " + id + ", delete feature is disabled or request not possible " + "due to CORS on a user agent that does not support pre-flighting.", "warn");
return false;
}
},
_onSubmitted: function(id) {},
_onTotalProgress: function(loaded, total) {
this._options.callbacks.onTotalProgress(loaded, total);
},
_onUploadPrep: function(id) {},
_onUpload: function(id, name) {
this._uploadData.setStatus(id, qq.status.UPLOADING);
},
_onUploadChunk: function(id, chunkData) {},
_onUploadStatusChange: function(id, oldStatus, newStatus) {
if (newStatus === qq.status.PAUSED) {
clearTimeout(this._retryTimeouts[id]);
}
},
_onValidateBatchCallbackFailure: function(fileWrappers) {
var self = this;
qq.each(fileWrappers, function(idx, fileWrapper) {
self._fileOrBlobRejected(fileWrapper.id);
});
},
_onValidateBatchCallbackSuccess: function(validationDescriptors, items, params, endpoint, button) {
var errorMessage, itemLimit = this._currentItemLimit, proposedNetFilesUploadedOrQueued = this._netUploadedOrQueued;
if (itemLimit === 0 || proposedNetFilesUploadedOrQueued <= itemLimit) {
if (items.length > 0) {
this._handleCheckedCallback({
name: "onValidate",
callback: qq.bind(this._options.callbacks.onValidate, this, validationDescriptors[0], button),
onSuccess: qq.bind(this._onValidateCallbackSuccess, this, items, 0, params, endpoint),
onFailure: qq.bind(this._onValidateCallbackFailure, this, items, 0, params, endpoint),
identifier: "Item '" + items[0].file.name + "', size: " + items[0].file.size
});
} else {
this._itemError("noFilesError");
}
} else {
this._onValidateBatchCallbackFailure(items);
errorMessage = this._options.messages.tooManyItemsError.replace(/\{netItems\}/g, proposedNetFilesUploadedOrQueued).replace(/\{itemLimit\}/g, itemLimit);
this._batchError(errorMessage);
}
},
_onValidateCallbackFailure: function(items, index, params, endpoint) {
var nextIndex = index + 1;
this._fileOrBlobRejected(items[index].id, items[index].file.name);
this._maybeProcessNextItemAfterOnValidateCallback(false, items, nextIndex, params, endpoint);
},
_onValidateCallbackSuccess: function(items, index, params, endpoint) {
var self = this, nextIndex = index + 1, validationDescriptor = this._getValidationDescriptor(items[index]);
this._validateFileOrBlobData(items[index], validationDescriptor).then(function() {
self._upload(items[index].id, params, endpoint);
self._maybeProcessNextItemAfterOnValidateCallback(true, items, nextIndex, params, endpoint);
}, function() {
self._maybeProcessNextItemAfterOnValidateCallback(false, items, nextIndex, params, endpoint);
});
},
_prepareItemsForUpload: function(items, params, endpoint) {
if (items.length === 0) {
this._itemError("noFilesError");
return;
}
var validationDescriptors = this._getValidationDescriptors(items), buttonId = this._getButtonId(items[0].file), button = this._getButton(buttonId);
this._handleCheckedCallback({
name: "onValidateBatch",
callback: qq.bind(this._options.callbacks.onValidateBatch, this, validationDescriptors, button),
onSuccess: qq.bind(this._onValidateBatchCallbackSuccess, this, validationDescriptors, items, params, endpoint, button),
onFailure: qq.bind(this._onValidateBatchCallbackFailure, this, items),
identifier: "batch validation"
});
},
_preventLeaveInProgress: function() {
var self = this;
this._disposeSupport.attach(window, "beforeunload", function(e) {
if (self.getInProgress()) {
e = e || window.event;
e.returnValue = self._options.messages.onLeave;
return self._options.messages.onLeave;
}
});
},
_refreshSessionData: function() {
var self = this, options = this._options.session;
if (qq.Session && this._options.session.endpoint != null) {
if (!this._session) {
qq.extend(options, {
cors: this._options.cors
});
options.log = qq.bind(this.log, this);
options.addFileRecord = qq.bind(this._addCannedFile, this);
this._session = new qq.Session(options);
}
setTimeout(function() {
self._session.refresh().then(function(response, xhrOrXdr) {
self._sessionRequestComplete();
self._options.callbacks.onSessionRequestComplete(response, true, xhrOrXdr);
}, function(response, xhrOrXdr) {
self._options.callbacks.onSessionRequestComplete(response, false, xhrOrXdr);
});
}, 0);
}
},
_sessionRequestComplete: function() {},
_setSize: function(id, newSize) {
this._uploadData.updateSize(id, newSize);
this._totalProgress && this._totalProgress.onNewSize(id);
},
_shouldAutoRetry: function(id, name, responseJSON) {
var uploadData = this._uploadData.retrieve({
id: id
});
if (!this._preventRetries[id] && this._options.retry.enableAuto && uploadData.status !== qq.status.PAUSED) {
if (this._autoRetries[id] === undefined) {
this._autoRetries[id] = 0;
}
if (this._autoRetries[id] < this._options.retry.maxAutoAttempts) {
this._autoRetries[id] += 1;
return true;
}
}
return false;
},
_storeForLater: function(id) {
this._storedIds.push(id);
},
_trackButton: function(id) {
var buttonId;
if (qq.supportedFeatures.ajaxUploading) {
buttonId = this._handler.getFile(id).qqButtonId;
} else {
buttonId = this._getButtonId(this._handler.getInput(id));
}
if (buttonId) {
this._buttonIdsForFileIds[id] = buttonId;
}
},
_updateFormSupportAndParams: function(formElementOrId) {
this._options.form.element = formElementOrId;
this._formSupport = qq.FormSupport && new qq.FormSupport(this._options.form, qq.bind(this.uploadStoredFiles, this), qq.bind(this.log, this));
if (this._formSupport && this._formSupport.attachedToForm) {
this._paramsStore.addReadOnly(null, this._formSupport.getFormInputsAsObject);
this._options.autoUpload = this._formSupport.newAutoUpload;
if (this._formSupport.newEndpoint) {
this.setEndpoint(this._formSupport.newEndpoint);
}
}
},
_upload: function(id, params, endpoint) {
var name = this.getName(id);
if (params) {
this.setParams(params, id);
}
if (endpoint) {
this.setEndpoint(endpoint, id);
}
this._handleCheckedCallback({
name: "onSubmit",
callback: qq.bind(this._options.callbacks.onSubmit, this, id, name),
onSuccess: qq.bind(this._onSubmitCallbackSuccess, this, id, name),
onFailure: qq.bind(this._fileOrBlobRejected, this, id, name),
identifier: id
});
},
_uploadFile: function(id) {
if (!this._handler.upload(id)) {
this._uploadData.setStatus(id, qq.status.QUEUED);
}
},
_uploadStoredFiles: function() {
var idToUpload, stillSubmitting, self = this;
while (this._storedIds.length) {
idToUpload = this._storedIds.shift();
this._uploadFile(idToUpload);
}
stillSubmitting = this.getUploads({
status: qq.status.SUBMITTING
}).length;
if (stillSubmitting) {
qq.log("Still waiting for " + stillSubmitting + " files to clear submit queue. Will re-parse stored IDs array shortly.");
setTimeout(function() {
self._uploadStoredFiles();
}, 1e3);
}
},
_validateFileOrBlobData: function(fileWrapper, validationDescriptor) {
var self = this, file = function() {
if (fileWrapper.file instanceof qq.BlobProxy) {
return fileWrapper.file.referenceBlob;
}
return fileWrapper.file;
}(), name = validationDescriptor.name, size = validationDescriptor.size, buttonId = this._getButtonId(fileWrapper.file), validationBase = this._getValidationBase(buttonId), validityChecker = new qq.Promise();
validityChecker.then(function() {}, function() {
self._fileOrBlobRejected(fileWrapper.id, name);
});
if (qq.isFileOrInput(file) && !this._isAllowedExtension(validationBase.allowedExtensions, name)) {
this._itemError("typeError", name, file);
return validityChecker.failure();
}
if (size === 0) {
this._itemError("emptyError", name, file);
return validityChecker.failure();
}
if (size > 0 && validationBase.sizeLimit && size > validationBase.sizeLimit) {
this._itemError("sizeError", name, file);
return validityChecker.failure();
}
if (size > 0 && size < validationBase.minSizeLimit) {
this._itemError("minSizeError", name, file);
return validityChecker.failure();
}
if (qq.ImageValidation && qq.supportedFeatures.imagePreviews && qq.isFile(file)) {
new qq.ImageValidation(file, qq.bind(self.log, self)).validate(validationBase.image).then(validityChecker.success, function(errorCode) {
self._itemError(errorCode + "ImageError", name, file);
validityChecker.failure();
});
} else {
validityChecker.success();
}
return validityChecker;
},
_wrapCallbacks: function() {
var self, safeCallback, prop;
self = this;
safeCallback = function(name, callback, args) {
var errorMsg;
try {
return callback.apply(self, args);
} catch (exception) {
errorMsg = exception.message || exception.toString();
self.log("Caught exception in '" + name + "' callback - " + errorMsg, "error");
}
};
for (prop in this._options.callbacks) {
(function() {
var callbackName, callbackFunc;
callbackName = prop;
callbackFunc = self._options.callbacks[callbackName];
self._options.callbacks[callbackName] = function() {
return safeCallback(callbackName, callbackFunc, arguments);
};
})();
}
}
};
})();
(function() {
"use strict";
qq.FineUploaderBasic = function(o) {
var self = this;
this._options = {
debug: false,
button: null,
multiple: true,
maxConnections: 3,
disableCancelForFormUploads: false,
autoUpload: true,
request: {
customHeaders: {},
endpoint: "/server/upload",
filenameParam: "qqfilename",
forceMultipart: true,
inputName: "qqfile",
method: "POST",
params: {},
paramsInBody: true,
totalFileSizeName: "qqtotalfilesize",
uuidName: "qquuid"
},
validation: {
allowedExtensions: [],
sizeLimit: 0,
minSizeLimit: 0,
itemLimit: 0,
stopOnFirstInvalidFile: true,
acceptFiles: null,
image: {
maxHeight: 0,
maxWidth: 0,
minHeight: 0,
minWidth: 0
}
},
callbacks: {
onSubmit: function(id, name) {},
onSubmitted: function(id, name) {},
onComplete: function(id, name, responseJSON, maybeXhr) {},
onAllComplete: function(successful, failed) {},
onCancel: function(id, name) {},
onUpload: function(id, name) {},
onUploadChunk: function(id, name, chunkData) {},
onUploadChunkSuccess: function(id, chunkData, responseJSON, xhr) {},
onResume: function(id, fileName, chunkData) {},
onProgress: function(id, name, loaded, total) {},
onTotalProgress: function(loaded, total) {},
onError: function(id, name, reason, maybeXhrOrXdr) {},
onAutoRetry: function(id, name, attemptNumber) {},
onManualRetry: function(id, name) {},
onValidateBatch: function(fileOrBlobData) {},
onValidate: function(fileOrBlobData) {},
onSubmitDelete: function(id) {},
onDelete: function(id) {},
onDeleteComplete: function(id, xhrOrXdr, isError) {},
onPasteReceived: function(blob) {},
onStatusChange: function(id, oldStatus, newStatus) {},
onSessionRequestComplete: function(response, success, xhrOrXdr) {}
},
messages: {
typeError: "{file} has an invalid extension. Valid extension(s): {extensions}.",
sizeError: "{file} is too large, maximum file size is {sizeLimit}.",
minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.",
emptyError: "{file} is empty, please select files again without it.",
noFilesError: "No files to upload.",
tooManyItemsError: "Too many items ({netItems}) would be uploaded. Item limit is {itemLimit}.",
maxHeightImageError: "Image is too tall.",
maxWidthImageError: "Image is too wide.",
minHeightImageError: "Image is not tall enough.",
minWidthImageError: "Image is not wide enough.",
retryFailTooManyItems: "Retry failed - you have reached your file limit.",
onLeave: "The files are being uploaded, if you leave now the upload will be canceled.",
unsupportedBrowserIos8Safari: "Unrecoverable error - this browser does not permit file uploading of any kind due to serious bugs in iOS8 Safari. Please use iOS8 Chrome until Apple fixes these issues."
},
retry: {
enableAuto: false,
maxAutoAttempts: 3,
autoAttemptDelay: 5,
preventRetryResponseProperty: "preventRetry"
},
classes: {
buttonHover: "qq-upload-button-hover",
buttonFocus: "qq-upload-button-focus"
},
chunking: {
enabled: false,
concurrent: {
enabled: false
},
mandatory: false,
paramNames: {
partIndex: "qqpartindex",
partByteOffset: "qqpartbyteoffset",
chunkSize: "qqchunksize",
totalFileSize: "qqtotalfilesize",
totalParts: "qqtotalparts"
},
partSize: 2e6,
success: {
endpoint: null
}
},
resume: {
enabled: false,
recordsExpireIn: 7,
paramNames: {
resuming: "qqresume"
}
},
formatFileName: function(fileOrBlobName) {
return fileOrBlobName;
},
text: {
defaultResponseError: "Upload failure reason unknown",
fileInputTitle: "file input",
sizeSymbols: [ "kB", "MB", "GB", "TB", "PB", "EB" ]
},
deleteFile: {
enabled: false,
method: "DELETE",
endpoint: "/server/upload",
customHeaders: {},
params: {}
},
cors: {
expected: false,
sendCredentials: false,
allowXdr: false
},
blobs: {
defaultName: "misc_data"
},
paste: {
targetElement: null,
defaultName: "pasted_image"
},
camera: {
ios: false,
button: null
},
extraButtons: [],
session: {
endpoint: null,
params: {},
customHeaders: {},
refreshOnReset: true
},
form: {
element: "qq-form",
autoUpload: false,
interceptSubmit: true
},
scaling: {
customResizer: null,
sendOriginal: true,
orient: true,
defaultType: null,
defaultQuality: 80,
failureText: "Failed to scale",
includeExif: false,
sizes: []
},
workarounds: {
iosEmptyVideos: true,
ios8SafariUploads: true,
ios8BrowserCrash: false
}
};
qq.extend(this._options, o, true);
this._buttons = [];
this._extraButtonSpecs = {};
this._buttonIdsForFileIds = [];
this._wrapCallbacks();
this._disposeSupport = new qq.DisposeSupport();
this._storedIds = [];
this._autoRetries = [];
this._retryTimeouts = [];
this._preventRetries = [];
this._thumbnailUrls = [];
this._netUploadedOrQueued = 0;
this._netUploaded = 0;
this._uploadData = this._createUploadDataTracker();
this._initFormSupportAndParams();
this._customHeadersStore = this._createStore(this._options.request.customHeaders);
this._deleteFileCustomHeadersStore = this._createStore(this._options.deleteFile.customHeaders);
this._deleteFileParamsStore = this._createStore(this._options.deleteFile.params);
this._endpointStore = this._createStore(this._options.request.endpoint);
this._deleteFileEndpointStore = this._createStore(this._options.deleteFile.endpoint);
this._handler = this._createUploadHandler();
this._deleteHandler = qq.DeleteFileAjaxRequester && this._createDeleteHandler();
if (this._options.button) {
this._defaultButtonId = this._createUploadButton({
element: this._options.button,
title: this._options.text.fileInputTitle
}).getButtonId();
}
this._generateExtraButtonSpecs();
this._handleCameraAccess();
if (this._options.paste.targetElement) {
if (qq.PasteSupport) {
this._pasteHandler = this._createPasteHandler();
} else {
this.log("Paste support module not found", "error");
}
}
this._preventLeaveInProgress();
this._imageGenerator = qq.ImageGenerator && new qq.ImageGenerator(qq.bind(this.log, this));
this._refreshSessionData();
this._succeededSinceLastAllComplete = [];
this._failedSinceLastAllComplete = [];
this._scaler = qq.Scaler && new qq.Scaler(this._options.scaling, qq.bind(this.log, this)) || {};
if (this._scaler.enabled) {
this._customNewFileHandler = qq.bind(this._scaler.handleNewFile, this._scaler);
}
if (qq.TotalProgress && qq.supportedFeatures.progressBar) {
this._totalProgress = new qq.TotalProgress(qq.bind(this._onTotalProgress, this), function(id) {
var entry = self._uploadData.retrieve({
id: id
});
return entry && entry.size || 0;
});
}
this._currentItemLimit = this._options.validation.itemLimit;
};
qq.FineUploaderBasic.prototype = qq.basePublicApi;
qq.extend(qq.FineUploaderBasic.prototype, qq.basePrivateApi);
})();
qq.AjaxRequester = function(o) {
"use strict";
var log, shouldParamsBeInQueryString, queue = [], requestData = {}, options = {
acceptHeader: null,
validMethods: [ "PATCH", "POST", "PUT" ],
method: "POST",
contentType: "application/x-www-form-urlencoded",
maxConnections: 3,
customHeaders: {},
endpointStore: {},
paramsStore: {},
mandatedParams: {},
allowXRequestedWithAndCacheControl: true,
successfulResponseCodes: {
DELETE: [ 200, 202, 204 ],
PATCH: [ 200, 201, 202, 203, 204 ],
POST: [ 200, 201, 202, 203, 204 ],
PUT: [ 200, 201, 202, 203, 204 ],
GET: [ 200 ]
},
cors: {
expected: false,
sendCredentials: false
},
log: function(str, level) {},
onSend: function(id) {},
onComplete: function(id, xhrOrXdr, isError) {},
onProgress: null
};
qq.extend(options, o);
log = options.log;
if (qq.indexOf(options.validMethods, options.method) < 0) {
throw new Error("'" + options.method + "' is not a supported method for this type of request!");
}
function isSimpleMethod() {
return qq.indexOf([ "GET", "POST", "HEAD" ], options.method) >= 0;
}
function containsNonSimpleHeaders(headers) {
var containsNonSimple = false;
qq.each(containsNonSimple, function(idx, header) {
if (qq.indexOf([ "Accept", "Accept-Language", "Content-Language", "Content-Type" ], header) < 0) {
containsNonSimple = true;
return false;
}
});
return containsNonSimple;
}
function isXdr(xhr) {
return options.cors.expected && xhr.withCredentials === undefined;
}
function getCorsAjaxTransport() {
var xhrOrXdr;
if (window.XMLHttpRequest || window.ActiveXObject) {
xhrOrXdr = qq.createXhrInstance();
if (xhrOrXdr.withCredentials === undefined) {
xhrOrXdr = new XDomainRequest();
xhrOrXdr.onload = function() {};
xhrOrXdr.onerror = function() {};
xhrOrXdr.ontimeout = function() {};
xhrOrXdr.onprogress = function() {};
}
}
return xhrOrXdr;
}
function getXhrOrXdr(id, suppliedXhr) {
var xhrOrXdr = requestData[id].xhr;
if (!xhrOrXdr) {
if (suppliedXhr) {
xhrOrXdr = suppliedXhr;
} else {
if (options.cors.expected) {
xhrOrXdr = getCorsAjaxTransport();
} else {
xhrOrXdr = qq.createXhrInstance();
}
}
requestData[id].xhr = xhrOrXdr;
}
return xhrOrXdr;
}
function dequeue(id) {
var i = qq.indexOf(queue, id), max = options.maxConnections, nextId;
delete requestData[id];
queue.splice(i, 1);
if (queue.length >= max && i < max) {
nextId = queue[max - 1];
sendRequest(nextId);
}
}
function onComplete(id, xdrError) {
var xhr = getXhrOrXdr(id), method = options.method, isError = xdrError === true;
dequeue(id);
if (isError) {
log(method + " request for " + id + " has failed", "error");
} else if (!isXdr(xhr) && !isResponseSuccessful(xhr.status)) {
isError = true;
log(method + " request for " + id + " has failed - response code " + xhr.status, "error");
}
options.onComplete(id, xhr, isError);
}
function getParams(id) {
var onDemandParams = requestData[id].additionalParams, mandatedParams = options.mandatedParams, params;
if (options.paramsStore.get) {
params = options.paramsStore.get(id);
}
if (onDemandParams) {
qq.each(onDemandParams, function(name, val) {
params = params || {};
params[name] = val;
});
}
if (mandatedParams) {
qq.each(mandatedParams, function(name, val) {
params = params || {};
params[name] = val;
});
}
return params;
}
function sendRequest(id, optXhr) {
var xhr = getXhrOrXdr(id, optXhr), method = options.method, params = getParams(id), payload = requestData[id].payload, url;
options.onSend(id);
url = createUrl(id, params, requestData[id].additionalQueryParams);
if (isXdr(xhr)) {
xhr.onload = getXdrLoadHandler(id);
xhr.onerror = getXdrErrorHandler(id);
} else {
xhr.onreadystatechange = getXhrReadyStateChangeHandler(id);
}
registerForUploadProgress(id);
xhr.open(method, url, true);
if (options.cors.expected && options.cors.sendCredentials && !isXdr(xhr)) {
xhr.withCredentials = true;
}
setHeaders(id);
log("Sending " + method + " request for " + id);
if (payload) {
xhr.send(payload);
} else if (shouldParamsBeInQueryString || !params) {
xhr.send();
} else if (params && options.contentType && options.contentType.toLowerCase().indexOf("application/x-www-form-urlencoded") >= 0) {
xhr.send(qq.obj2url(params, ""));
} else if (params && options.contentType && options.contentType.toLowerCase().indexOf("application/json") >= 0) {
xhr.send(JSON.stringify(params));
} else {
xhr.send(params);
}
return xhr;
}
function createUrl(id, params, additionalQueryParams) {
var endpoint = options.endpointStore.get(id), addToPath = requestData[id].addToPath;
if (addToPath != undefined) {
endpoint += "/" + addToPath;
}
if (shouldParamsBeInQueryString && params) {
endpoint = qq.obj2url(params, endpoint);
}
if (additionalQueryParams) {
endpoint = qq.obj2url(additionalQueryParams, endpoint);
}
return endpoint;
}
function getXhrReadyStateChangeHandler(id) {
return function() {
if (getXhrOrXdr(id).readyState === 4) {
onComplete(id);
}
};
}
function registerForUploadProgress(id) {
var onProgress = options.onProgress;
if (onProgress) {
getXhrOrXdr(id).upload.onprogress = function(e) {
if (e.lengthComputable) {
onProgress(id, e.loaded, e.total);
}
};
}
}
function getXdrLoadHandler(id) {
return function() {
onComplete(id);
};
}
function getXdrErrorHandler(id) {
return function() {
onComplete(id, true);
};
}
function setHeaders(id) {
var xhr = getXhrOrXdr(id), customHeaders = options.customHeaders, onDemandHeaders = requestData[id].additionalHeaders || {}, method = options.method, allHeaders = {};
if (!isXdr(xhr)) {
options.acceptHeader && xhr.setRequestHeader("Accept", options.acceptHeader);
if (options.allowXRequestedWithAndCacheControl) {
if (!options.cors.expected || (!isSimpleMethod() || containsNonSimpleHeaders(customHeaders))) {
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("Cache-Control", "no-cache");
}
}
if (options.contentType && (method === "POST" || method === "PUT")) {
xhr.setRequestHeader("Content-Type", options.contentType);
}
qq.extend(allHeaders, qq.isFunction(customHeaders) ? customHeaders(id) : customHeaders);
qq.extend(allHeaders, onDemandHeaders);
qq.each(allHeaders, function(name, val) {
xhr.setRequestHeader(name, val);
});
}
}
function isResponseSuccessful(responseCode) {
return qq.indexOf(options.successfulResponseCodes[options.method], responseCode) >= 0;
}
function prepareToSend(id, optXhr, addToPath, additionalParams, additionalQueryParams, additionalHeaders, payload) {
requestData[id] = {
addToPath: addToPath,
additionalParams: additionalParams,
additionalQueryParams: additionalQueryParams,
additionalHeaders: additionalHeaders,
payload: payload
};
var len = queue.push(id);
if (len <= options.maxConnections) {
return sendRequest(id, optXhr);
}
}
shouldParamsBeInQueryString = options.method === "GET" || options.method === "DELETE";
qq.extend(this, {
initTransport: function(id) {
var path, params, headers, payload, cacheBuster, additionalQueryParams;
return {
withPath: function(appendToPath) {
path = appendToPath;
return this;
},
withParams: function(additionalParams) {
params = additionalParams;
return this;
},
withQueryParams: function(_additionalQueryParams_) {
additionalQueryParams = _additionalQueryParams_;
return this;
},
withHeaders: function(additionalHeaders) {
headers = additionalHeaders;
return this;
},
withPayload: function(thePayload) {
payload = thePayload;
return this;
},
withCacheBuster: function() {
cacheBuster = true;
return this;
},
send: function(optXhr) {
if (cacheBuster && qq.indexOf([ "GET", "DELETE" ], options.method) >= 0) {
params.qqtimestamp = new Date().getTime();
}
return prepareToSend(id, optXhr, path, params, additionalQueryParams, headers, payload);
}
};
},
canceled: function(id) {
dequeue(id);
}
});
};
qq.UploadHandler = function(spec) {
"use strict";
var proxy = spec.proxy, fileState = {}, onCancel = proxy.onCancel, getName = proxy.getName;
qq.extend(this, {
add: function(id, fileItem) {
fileState[id] = fileItem;
fileState[id].temp = {};
},
cancel: function(id) {
var self = this, cancelFinalizationEffort = new qq.Promise(), onCancelRetVal = onCancel(id, getName(id), cancelFinalizationEffort);
onCancelRetVal.then(function() {
if (self.isValid(id)) {
fileState[id].canceled = true;
self.expunge(id);
}
cancelFinalizationEffort.success();
});
},
expunge: function(id) {
delete fileState[id];
},
getThirdPartyFileId: function(id) {
return fileState[id].key;
},
isValid: function(id) {
return fileState[id] !== undefined;
},
reset: function() {
fileState = {};
},
_getFileState: function(id) {
return fileState[id];
},
_setThirdPartyFileId: function(id, thirdPartyFileId) {
fileState[id].key = thirdPartyFileId;
},
_wasCanceled: function(id) {
return !!fileState[id].canceled;
}
});
};
qq.UploadHandlerController = function(o, namespace) {
"use strict";
var controller = this, chunkingPossible = false, concurrentChunkingPossible = false, chunking, preventRetryResponse, log, handler, options = {
paramsStore: {},
maxConnections: 3,
chunking: {
enabled: false,
multiple: {
enabled: false
}
},
log: function(str, level) {},
onProgress: function(id, fileName, loaded, total) {},
onComplete: function(id, fileName, response, xhr) {},
onCancel: function(id, fileName) {},
onUploadPrep: function(id) {},
onUpload: function(id, fileName) {},
onUploadChunk: function(id, fileName, chunkData) {},
onUploadChunkSuccess: function(id, chunkData, response, xhr) {},
onAutoRetry: function(id, fileName, response, xhr) {},
onResume: function(id, fileName, chunkData) {},
onUuidChanged: function(id, newUuid) {},
getName: function(id) {},
setSize: function(id, newSize) {},
isQueued: function(id) {},
getIdsInProxyGroup: function(id) {},
getIdsInBatch: function(id) {}
}, chunked = {
done: function(id, chunkIdx, response, xhr) {
var chunkData = handler._getChunkData(id, chunkIdx);
handler._getFileState(id).attemptingResume = false;
delete handler._getFileState(id).temp.chunkProgress[chunkIdx];
handler._getFileState(id).loaded += chunkData.size;
options.onUploadChunkSuccess(id, handler._getChunkDataForCallback(chunkData), response, xhr);
},
finalize: function(id) {
var size = options.getSize(id), name = options.getName(id);
log("All chunks have been uploaded for " + id + " - finalizing....");
handler.finalizeChunks(id).then(function(response, xhr) {
log("Finalize successful for " + id);
var normaizedResponse = upload.normalizeResponse(response, true);
options.onProgress(id, name, size, size);
handler._maybeDeletePersistedChunkData(id);
upload.cleanup(id, normaizedResponse, xhr);
}, function(response, xhr) {
var normaizedResponse = upload.normalizeResponse(response, false);
log("Problem finalizing chunks for file ID " + id + " - " + normaizedResponse.error, "error");
if (normaizedResponse.reset) {
chunked.reset(id);
}
if (!options.onAutoRetry(id, name, normaizedResponse, xhr)) {
upload.cleanup(id, normaizedResponse, xhr);
}
});
},
hasMoreParts: function(id) {
return !!handler._getFileState(id).chunking.remaining.length;
},
nextPart: function(id) {
var nextIdx = handler._getFileState(id).chunking.remaining.shift();
if (nextIdx >= handler._getTotalChunks(id)) {
nextIdx = null;
}
return nextIdx;
},
reset: function(id) {
log("Server or callback has ordered chunking effort to be restarted on next attempt for item ID " + id, "error");
handler._maybeDeletePersistedChunkData(id);
handler.reevaluateChunking(id);
handler._getFileState(id).loaded = 0;
},
sendNext: function(id) {
var size = options.getSize(id), name = options.getName(id), chunkIdx = chunked.nextPart(id), chunkData = handler._getChunkData(id, chunkIdx), resuming = handler._getFileState(id).attemptingResume, inProgressChunks = handler._getFileState(id).chunking.inProgress || [];
if (handler._getFileState(id).loaded == null) {
handler._getFileState(id).loaded = 0;
}
if (resuming && options.onResume(id, name, chunkData) === false) {
chunked.reset(id);
chunkIdx = chunked.nextPart(id);
chunkData = handler._getChunkData(id, chunkIdx);
resuming = false;
}
if (chunkIdx == null && inProgressChunks.length === 0) {
chunked.finalize(id);
} else {
log(qq.format("Sending chunked upload request for item {}.{}, bytes {}-{} of {}.", id, chunkIdx, chunkData.start + 1, chunkData.end, size));
options.onUploadChunk(id, name, handler._getChunkDataForCallback(chunkData));
inProgressChunks.push(chunkIdx);
handler._getFileState(id).chunking.inProgress = inProgressChunks;
if (concurrentChunkingPossible) {
connectionManager.open(id, chunkIdx);
}
if (concurrentChunkingPossible && connectionManager.available() && handler._getFileState(id).chunking.remaining.length) {
chunked.sendNext(id);
}
handler.uploadChunk(id, chunkIdx, resuming).then(function success(response, xhr) {
log("Chunked upload request succeeded for " + id + ", chunk " + chunkIdx);
handler.clearCachedChunk(id, chunkIdx);
var inProgressChunks = handler._getFileState(id).chunking.inProgress || [], responseToReport = upload.normalizeResponse(response, true), inProgressChunkIdx = qq.indexOf(inProgressChunks, chunkIdx);
log(qq.format("Chunk {} for file {} uploaded successfully.", chunkIdx, id));
chunked.done(id, chunkIdx, responseToReport, xhr);
if (inProgressChunkIdx >= 0) {
inProgressChunks.splice(inProgressChunkIdx, 1);
}
handler._maybePersistChunkedState(id);
if (!chunked.hasMoreParts(id) && inProgressChunks.length === 0) {
chunked.finalize(id);
} else if (chunked.hasMoreParts(id)) {
chunked.sendNext(id);
} else {
log(qq.format("File ID {} has no more chunks to send and these chunk indexes are still marked as in-progress: {}", id, JSON.stringify(inProgressChunks)));
}
}, function failure(response, xhr) {
log("Chunked upload request failed for " + id + ", chunk " + chunkIdx);
handler.clearCachedChunk(id, chunkIdx);
var responseToReport = upload.normalizeResponse(response, false), inProgressIdx;
if (responseToReport.reset) {
chunked.reset(id);
} else {
inProgressIdx = qq.indexOf(handler._getFileState(id).chunking.inProgress, chunkIdx);
if (inProgressIdx >= 0) {
handler._getFileState(id).chunking.inProgress.splice(inProgressIdx, 1);
handler._getFileState(id).chunking.remaining.unshift(chunkIdx);
}
}
if (!handler._getFileState(id).temp.ignoreFailure) {
if (concurrentChunkingPossible) {
handler._getFileState(id).temp.ignoreFailure = true;
log(qq.format("Going to attempt to abort these chunks: {}. These are currently in-progress: {}.", JSON.stringify(Object.keys(handler._getXhrs(id))), JSON.stringify(handler._getFileState(id).chunking.inProgress)));
qq.each(handler._getXhrs(id), function(ckid, ckXhr) {
log(qq.format("Attempting to abort file {}.{}. XHR readyState {}. ", id, ckid, ckXhr.readyState));
ckXhr.abort();
ckXhr._cancelled = true;
});
handler.moveInProgressToRemaining(id);
connectionManager.free(id, true);
}
if (!options.onAutoRetry(id, name, responseToReport, xhr)) {
upload.cleanup(id, responseToReport, xhr);
}
}
}).done(function() {
handler.clearXhr(id, chunkIdx);
});
}
}
}, connectionManager = {
_open: [],
_openChunks: {},
_waiting: [],
available: function() {
var max = options.maxConnections, openChunkEntriesCount = 0, openChunksCount = 0;
qq.each(connectionManager._openChunks, function(fileId, openChunkIndexes) {
openChunkEntriesCount++;
openChunksCount += openChunkIndexes.length;
});
return max - (connectionManager._open.length - openChunkEntriesCount + openChunksCount);
},
free: function(id, dontAllowNext) {
var allowNext = !dontAllowNext, waitingIndex = qq.indexOf(connectionManager._waiting, id), connectionsIndex = qq.indexOf(connectionManager._open, id), nextId;
delete connectionManager._openChunks[id];
if (upload.getProxyOrBlob(id) instanceof qq.BlobProxy) {
log("Generated blob upload has ended for " + id + ", disposing generated blob.");
delete handler._getFileState(id).file;
}
if (waitingIndex >= 0) {
connectionManager._waiting.splice(waitingIndex, 1);
} else if (allowNext && connectionsIndex >= 0) {
connectionManager._open.splice(connectionsIndex, 1);
nextId = connectionManager._waiting.shift();
if (nextId >= 0) {
connectionManager._open.push(nextId);
upload.start(nextId);
}
}
},
getWaitingOrConnected: function() {
var waitingOrConnected = [];
qq.each(connectionManager._openChunks, function(fileId, chunks) {
if (chunks && chunks.length) {
waitingOrConnected.push(parseInt(fileId));
}
});
qq.each(connectionManager._open, function(idx, fileId) {
if (!connectionManager._openChunks[fileId]) {
waitingOrConnected.push(parseInt(fileId));
}
});
waitingOrConnected = waitingOrConnected.concat(connectionManager._waiting);
return waitingOrConnected;
},
isUsingConnection: function(id) {
return qq.indexOf(connectionManager._open, id) >= 0;
},
open: function(id, chunkIdx) {
if (chunkIdx == null) {
connectionManager._waiting.push(id);
}
if (connectionManager.available()) {
if (chunkIdx == null) {
connectionManager._waiting.pop();
connectionManager._open.push(id);
} else {
(function() {
var openChunksEntry = connectionManager._openChunks[id] || [];
openChunksEntry.push(chunkIdx);
connectionManager._openChunks[id] = openChunksEntry;
})();
}
return true;
}
return false;
},
reset: function() {
connectionManager._waiting = [];
connectionManager._open = [];
}
}, simple = {
send: function(id, name) {
handler._getFileState(id).loaded = 0;
log("Sending simple upload request for " + id);
handler.uploadFile(id).then(function(response, optXhr) {
log("Simple upload request succeeded for " + id);
var responseToReport = upload.normalizeResponse(response, true), size = options.getSize(id);
options.onProgress(id, name, size, size);
upload.maybeNewUuid(id, responseToReport);
upload.cleanup(id, responseToReport, optXhr);
}, function(response, optXhr) {
log("Simple upload request failed for " + id);
var responseToReport = upload.normalizeResponse(response, false);
if (!options.onAutoRetry(id, name, responseToReport, optXhr)) {
upload.cleanup(id, responseToReport, optXhr);
}
});
}
}, upload = {
cancel: function(id) {
log("Cancelling " + id);
options.paramsStore.remove(id);
connectionManager.free(id);
},
cleanup: function(id, response, optXhr) {
var name = options.getName(id);
options.onComplete(id, name, response, optXhr);
if (handler._getFileState(id)) {
handler._clearXhrs && handler._clearXhrs(id);
}
connectionManager.free(id);
},
getProxyOrBlob: function(id) {
return handler.getProxy && handler.getProxy(id) || handler.getFile && handler.getFile(id);
},
initHandler: function() {
var handlerType = namespace ? qq[namespace] : qq.traditional, handlerModuleSubtype = qq.supportedFeatures.ajaxUploading ? "Xhr" : "Form";
handler = new handlerType[handlerModuleSubtype + "UploadHandler"](options, {
getDataByUuid: options.getDataByUuid,
getName: options.getName,
getSize: options.getSize,
getUuid: options.getUuid,
log: log,
onCancel: options.onCancel,
onProgress: options.onProgress,
onUuidChanged: options.onUuidChanged
});
if (handler._removeExpiredChunkingRecords) {
handler._removeExpiredChunkingRecords();
}
},
isDeferredEligibleForUpload: function(id) {
return options.isQueued(id);
},
maybeDefer: function(id, blob) {
if (blob && !handler.getFile(id) && blob instanceof qq.BlobProxy) {
options.onUploadPrep(id);
log("Attempting to generate a blob on-demand for " + id);
blob.create().then(function(generatedBlob) {
log("Generated an on-demand blob for " + id);
handler.updateBlob(id, generatedBlob);
options.setSize(id, generatedBlob.size);
handler.reevaluateChunking(id);
upload.maybeSendDeferredFiles(id);
}, function(errorMessage) {
var errorResponse = {};
if (errorMessage) {
errorResponse.error = errorMessage;
}
log(qq.format("Failed to generate blob for ID {}. Error message: {}.", id, errorMessage), "error");
options.onComplete(id, options.getName(id), qq.extend(errorResponse, preventRetryResponse), null);
upload.maybeSendDeferredFiles(id);
connectionManager.free(id);
});
} else {
return upload.maybeSendDeferredFiles(id);
}
return false;
},
maybeSendDeferredFiles: function(id) {
var idsInGroup = options.getIdsInProxyGroup(id), uploadedThisId = false;
if (idsInGroup && idsInGroup.length) {
log("Maybe ready to upload proxy group file " + id);
qq.each(idsInGroup, function(idx, idInGroup) {
if (upload.isDeferredEligibleForUpload(idInGroup) && !!handler.getFile(idInGroup)) {
uploadedThisId = idInGroup === id;
upload.now(idInGroup);
} else if (upload.isDeferredEligibleForUpload(idInGroup)) {
return false;
}
});
} else {
uploadedThisId = true;
upload.now(id);
}
return uploadedThisId;
},
maybeNewUuid: function(id, response) {
if (response.newUuid !== undefined) {
options.onUuidChanged(id, response.newUuid);
}
},
normalizeResponse: function(originalResponse, successful) {
var response = originalResponse;
if (!qq.isObject(originalResponse)) {
response = {};
if (qq.isString(originalResponse) && !successful) {
response.error = originalResponse;
}
}
response.success = successful;
return response;
},
now: function(id) {
var name = options.getName(id);
if (!controller.isValid(id)) {
throw new qq.Error(id + " is not a valid file ID to upload!");
}
options.onUpload(id, name);
if (chunkingPossible && handler._shouldChunkThisFile(id)) {
chunked.sendNext(id);
} else {
simple.send(id, name);
}
},
start: function(id) {
var blobToUpload = upload.getProxyOrBlob(id);
if (blobToUpload) {
return upload.maybeDefer(id, blobToUpload);
} else {
upload.now(id);
return true;
}
}
};
qq.extend(this, {
add: function(id, file) {
handler.add.apply(this, arguments);
},
upload: function(id) {
if (connectionManager.open(id)) {
return upload.start(id);
}
return false;
},
retry: function(id) {
if (concurrentChunkingPossible) {
handler._getFileState(id).temp.ignoreFailure = false;
}
if (connectionManager.isUsingConnection(id)) {
return upload.start(id);
} else {
return controller.upload(id);
}
},
cancel: function(id) {
var cancelRetVal = handler.cancel(id);
if (qq.isGenericPromise(cancelRetVal)) {
cancelRetVal.then(function() {
upload.cancel(id);
});
} else if (cancelRetVal !== false) {
upload.cancel(id);
}
},
cancelAll: function() {
var waitingOrConnected = connectionManager.getWaitingOrConnected(), i;
if (waitingOrConnected.length) {
for (i = waitingOrConnected.length - 1; i >= 0; i--) {
controller.cancel(waitingOrConnected[i]);
}
}
connectionManager.reset();
},
getFile: function(id) {
if (handler.getProxy && handler.getProxy(id)) {
return handler.getProxy(id).referenceBlob;
}
return handler.getFile && handler.getFile(id);
},
isProxied: function(id) {
return !!(handler.getProxy && handler.getProxy(id));
},
getInput: function(id) {
if (handler.getInput) {
return handler.getInput(id);
}
},
reset: function() {
log("Resetting upload handler");
controller.cancelAll();
connectionManager.reset();
handler.reset();
},
expunge: function(id) {
if (controller.isValid(id)) {
return handler.expunge(id);
}
},
isValid: function(id) {
return handler.isValid(id);
},
getResumableFilesData: function() {
if (handler.getResumableFilesData) {
return handler.getResumableFilesData();
}
return [];
},
getThirdPartyFileId: function(id) {
if (controller.isValid(id)) {
return handler.getThirdPartyFileId(id);
}
},
pause: function(id) {
if (controller.isResumable(id) && handler.pause && controller.isValid(id) && handler.pause(id)) {
connectionManager.free(id);
handler.moveInProgressToRemaining(id);
return true;
}
return false;
},
isResumable: function(id) {
return !!handler.isResumable && handler.isResumable(id);
}
});
qq.extend(options, o);
log = options.log;
chunkingPossible = options.chunking.enabled && qq.supportedFeatures.chunking;
concurrentChunkingPossible = chunkingPossible && options.chunking.concurrent.enabled;
preventRetryResponse = function() {
var response = {};
response[options.preventRetryParam] = true;
return response;
}();
upload.initHandler();
};
qq.FormUploadHandler = function(spec) {
"use strict";
var options = spec.options, handler = this, proxy = spec.proxy, formHandlerInstanceId = qq.getUniqueId(), onloadCallbacks = {}, detachLoadEvents = {}, postMessageCallbackTimers = {}, isCors = options.isCors, inputName = options.inputName, getUuid = proxy.getUuid, log = proxy.log, corsMessageReceiver = new qq.WindowReceiveMessage({
log: log
});
function expungeFile(id) {
delete detachLoadEvents[id];
if (isCors) {
clearTimeout(postMessageCallbackTimers[id]);
delete postMessageCallbackTimers[id];
corsMessageReceiver.stopReceivingMessages(id);
}
var iframe = document.getElementById(handler._getIframeName(id));
if (iframe) {
iframe.setAttribute("src", "javascript:false;");
qq(iframe).remove();
}
}
function getFileIdForIframeName(iframeName) {
return iframeName.split("_")[0];
}
function initIframeForUpload(name) {
var iframe = qq.toElement("<iframe src='javascript:false;' name='" + name + "' />");
iframe.setAttribute("id", name);
iframe.style.display = "none";
document.body.appendChild(iframe);
return iframe;
}
function registerPostMessageCallback(iframe, callback) {
var iframeName = iframe.id, fileId = getFileIdForIframeName(iframeName), uuid = getUuid(fileId);
onloadCallbacks[uuid] = callback;
detachLoadEvents[fileId] = qq(iframe).attach("load", function() {
if (handler.getInput(fileId)) {
log("Received iframe load event for CORS upload request (iframe name " + iframeName + ")");
postMessageCallbackTimers[iframeName] = setTimeout(function() {
var errorMessage = "No valid message received from loaded iframe for iframe name " + iframeName;
log(errorMessage, "error");
callback({
error: errorMessage
});
}, 1e3);
}
});
corsMessageReceiver.receiveMessage(iframeName, function(message) {
log("Received the following window message: '" + message + "'");
var fileId = getFileIdForIframeName(iframeName), response = handler._parseJsonResponse(message), uuid = response.uuid, onloadCallback;
if (uuid && onloadCallbacks[uuid]) {
log("Handling response for iframe name " + iframeName);
clearTimeout(postMessageCallbackTimers[iframeName]);
delete postMessageCallbackTimers[iframeName];
handler._detachLoadEvent(iframeName);
onloadCallback = onloadCallbacks[uuid];
delete onloadCallbacks[uuid];
corsMessageReceiver.stopReceivingMessages(iframeName);
onloadCallback(response);
} else if (!uuid) {
log("'" + message + "' does not contain a UUID - ignoring.");
}
});
}
qq.extend(this, new qq.UploadHandler(spec));
qq.override(this, function(super_) {
return {
add: function(id, fileInput) {
super_.add(id, {
input: fileInput
});
fileInput.setAttribute("name", inputName);
if (fileInput.parentNode) {
qq(fileInput).remove();
}
},
expunge: function(id) {
expungeFile(id);
super_.expunge(id);
},
isValid: function(id) {
return super_.isValid(id) && handler._getFileState(id).input !== undefined;
}
};
});
qq.extend(this, {
getInput: function(id) {
return handler._getFileState(id).input;
},
_attachLoadEvent: function(iframe, callback) {
var responseDescriptor;
if (isCors) {
registerPostMessageCallback(iframe, callback);
} else {
detachLoadEvents[iframe.id] = qq(iframe).attach("load", function() {
log("Received response for " + iframe.id);
if (!iframe.parentNode) {
return;
}
try {
if (iframe.contentDocument && iframe.contentDocument.body && iframe.contentDocument.body.innerHTML == "false") {
return;
}
} catch (error) {
log("Error when attempting to access iframe during handling of upload response (" + error.message + ")", "error");
responseDescriptor = {
success: false
};
}
callback(responseDescriptor);
});
}
},
_createIframe: function(id) {
var iframeName = handler._getIframeName(id);
return initIframeForUpload(iframeName);
},
_detachLoadEvent: function(id) {
if (detachLoadEvents[id] !== undefined) {
detachLoadEvents[id]();
delete detachLoadEvents[id];
}
},
_getIframeName: function(fileId) {
return fileId + "_" + formHandlerInstanceId;
},
_initFormForUpload: function(spec) {
var method = spec.method, endpoint = spec.endpoint, params = spec.params, paramsInBody = spec.paramsInBody, targetName = spec.targetName, form = qq.toElement("<form method='" + method + "' enctype='multipart/form-data'></form>"), url = endpoint;
if (paramsInBody) {
qq.obj2Inputs(params, form);
} else {
url = qq.obj2url(params, endpoint);
}
form.setAttribute("action", url);
form.setAttribute("target", targetName);
form.style.display = "none";
document.body.appendChild(form);
return form;
},
_parseJsonResponse: function(innerHtmlOrMessage) {
var response = {};
try {
response = qq.parseJson(innerHtmlOrMessage);
} catch (error) {
log("Error when attempting to parse iframe upload response (" + error.message + ")", "error");
}
return response;
}
});
};
qq.XhrUploadHandler = function(spec) {
"use strict";
var handler = this, namespace = spec.options.namespace, proxy = spec.proxy, chunking = spec.options.chunking, resume = spec.options.resume, chunkFiles = chunking && spec.options.chunking.enabled && qq.supportedFeatures.chunking, resumeEnabled = resume && spec.options.resume.enabled && chunkFiles && qq.supportedFeatures.resume, getName = proxy.getName, getSize = proxy.getSize, getUuid = proxy.getUuid, getEndpoint = proxy.getEndpoint, getDataByUuid = proxy.getDataByUuid, onUuidChanged = proxy.onUuidChanged, onProgress = proxy.onProgress, log = proxy.log;
function abort(id) {
qq.each(handler._getXhrs(id), function(xhrId, xhr) {
var ajaxRequester = handler._getAjaxRequester(id, xhrId);
xhr.onreadystatechange = null;
xhr.upload.onprogress = null;
xhr.abort();
ajaxRequester && ajaxRequester.canceled && ajaxRequester.canceled(id);
});
}
qq.extend(this, new qq.UploadHandler(spec));
qq.override(this, function(super_) {
return {
add: function(id, blobOrProxy) {
if (qq.isFile(blobOrProxy) || qq.isBlob(blobOrProxy)) {
super_.add(id, {
file: blobOrProxy
});
} else if (blobOrProxy instanceof qq.BlobProxy) {
super_.add(id, {
proxy: blobOrProxy
});
} else {
throw new Error("Passed obj is not a File, Blob, or proxy");
}
handler._initTempState(id);
resumeEnabled && handler._maybePrepareForResume(id);
},
expunge: function(id) {
abort(id);
handler._maybeDeletePersistedChunkData(id);
handler._clearXhrs(id);
super_.expunge(id);
}
};
});
qq.extend(this, {
clearCachedChunk: function(id, chunkIdx) {
delete handler._getFileState(id).temp.cachedChunks[chunkIdx];
},
clearXhr: function(id, chunkIdx) {
var tempState = handler._getFileState(id).temp;
if (tempState.xhrs) {
delete tempState.xhrs[chunkIdx];
}
if (tempState.ajaxRequesters) {
delete tempState.ajaxRequesters[chunkIdx];
}
},
finalizeChunks: function(id, responseParser) {
var lastChunkIdx = handler._getTotalChunks(id) - 1, xhr = handler._getXhr(id, lastChunkIdx);
if (responseParser) {
return new qq.Promise().success(responseParser(xhr), xhr);
}
return new qq.Promise().success({}, xhr);
},
getFile: function(id) {
return handler.isValid(id) && handler._getFileState(id).file;
},
getProxy: function(id) {
return handler.isValid(id) && handler._getFileState(id).proxy;
},
getResumableFilesData: function() {
var resumableFilesData = [];
handler._iterateResumeRecords(function(key, uploadData) {
handler.moveInProgressToRemaining(null, uploadData.chunking.inProgress, uploadData.chunking.remaining);
var data = {
name: uploadData.name,
remaining: uploadData.chunking.remaining,
size: uploadData.size,
uuid: uploadData.uuid
};
if (uploadData.key) {
data.key = uploadData.key;
}
resumableFilesData.push(data);
});
return resumableFilesData;
},
isResumable: function(id) {
return !!chunking && handler.isValid(id) && !handler._getFileState(id).notResumable;
},
moveInProgressToRemaining: function(id, optInProgress, optRemaining) {
var inProgress = optInProgress || handler._getFileState(id).chunking.inProgress, remaining = optRemaining || handler._getFileState(id).chunking.remaining;
if (inProgress) {
log(qq.format("Moving these chunks from in-progress {}, to remaining.", JSON.stringify(inProgress)));
inProgress.reverse();
qq.each(inProgress, function(idx, chunkIdx) {
remaining.unshift(chunkIdx);
});
inProgress.length = 0;
}
},
pause: function(id) {
if (handler.isValid(id)) {
log(qq.format("Aborting XHR upload for {} '{}' due to pause instruction.", id, getName(id)));
handler._getFileState(id).paused = true;
abort(id);
return true;
}
},
reevaluateChunking: function(id) {
if (chunking && handler.isValid(id)) {
var state = handler._getFileState(id), totalChunks, i;
delete state.chunking;
state.chunking = {};
totalChunks = handler._getTotalChunks(id);
if (totalChunks > 1 || chunking.mandatory) {
state.chunking.enabled = true;
state.chunking.parts = totalChunks;
state.chunking.remaining = [];
for (i = 0; i < totalChunks; i++) {
state.chunking.remaining.push(i);
}
handler._initTempState(id);
} else {
state.chunking.enabled = false;
}
}
},
updateBlob: function(id, newBlob) {
if (handler.isValid(id)) {
handler._getFileState(id).file = newBlob;
}
},
_clearXhrs: function(id) {
var tempState = handler._getFileState(id).temp;
qq.each(tempState.ajaxRequesters, function(chunkId) {
delete tempState.ajaxRequesters[chunkId];
});
qq.each(tempState.xhrs, function(chunkId) {
delete tempState.xhrs[chunkId];
});
},
_createXhr: function(id, optChunkIdx) {
return handler._registerXhr(id, optChunkIdx, qq.createXhrInstance());
},
_getAjaxRequester: function(id, optChunkIdx) {
var chunkIdx = optChunkIdx == null ? -1 : optChunkIdx;
return handler._getFileState(id).temp.ajaxRequesters[chunkIdx];
},
_getChunkData: function(id, chunkIndex) {
var chunkSize = chunking.partSize, fileSize = getSize(id), fileOrBlob = handler.getFile(id), startBytes = chunkSize * chunkIndex, endBytes = startBytes + chunkSize >= fileSize ? fileSize : startBytes + chunkSize, totalChunks = handler._getTotalChunks(id), cachedChunks = this._getFileState(id).temp.cachedChunks, blob = cachedChunks[chunkIndex] || qq.sliceBlob(fileOrBlob, startBytes, endBytes);
cachedChunks[chunkIndex] = blob;
return {
part: chunkIndex,
start: startBytes,
end: endBytes,
count: totalChunks,
blob: blob,
size: endBytes - startBytes
};
},
_getChunkDataForCallback: function(chunkData) {
return {
partIndex: chunkData.part,
startByte: chunkData.start + 1,
endByte: chunkData.end,
totalParts: chunkData.count
};
},
_getLocalStorageId: function(id) {
var formatVersion = "5.0", name = getName(id), size = getSize(id), chunkSize = chunking.partSize, endpoint = getEndpoint(id);
return qq.format("qq{}resume{}-{}-{}-{}-{}", namespace, formatVersion, name, size, chunkSize, endpoint);
},
_getMimeType: function(id) {
return handler.getFile(id).type;
},
_getPersistableData: function(id) {
return handler._getFileState(id).chunking;
},
_getTotalChunks: function(id) {
if (chunking) {
var fileSize = getSize(id), chunkSize = chunking.partSize;
return Math.ceil(fileSize / chunkSize);
}
},
_getXhr: function(id, optChunkIdx) {
var chunkIdx = optChunkIdx == null ? -1 : optChunkIdx;
return handler._getFileState(id).temp.xhrs[chunkIdx];
},
_getXhrs: function(id) {
return handler._getFileState(id).temp.xhrs;
},
_iterateResumeRecords: function(callback) {
if (resumeEnabled) {
qq.each(localStorage, function(key, item) {
if (key.indexOf(qq.format("qq{}resume", namespace)) === 0) {
var uploadData = JSON.parse(item);
callback(key, uploadData);
}
});
}
},
_initTempState: function(id) {
handler._getFileState(id).temp = {
ajaxRequesters: {},
chunkProgress: {},
xhrs: {},
cachedChunks: {}
};
},
_markNotResumable: function(id) {
handler._getFileState(id).notResumable = true;
},
_maybeDeletePersistedChunkData: function(id) {
var localStorageId;
if (resumeEnabled && handler.isResumable(id)) {
localStorageId = handler._getLocalStorageId(id);
if (localStorageId && localStorage.getItem(localStorageId)) {
localStorage.removeItem(localStorageId);
return true;
}
}
return false;
},
_maybePrepareForResume: function(id) {
var state = handler._getFileState(id), localStorageId, persistedData;
if (resumeEnabled && state.key === undefined) {
localStorageId = handler._getLocalStorageId(id);
persistedData = localStorage.getItem(localStorageId);
if (persistedData) {
persistedData = JSON.parse(persistedData);
if (getDataByUuid(persistedData.uuid)) {
handler._markNotResumable(id);
} else {
log(qq.format("Identified file with ID {} and name of {} as resumable.", id, getName(id)));
onUuidChanged(id, persistedData.uuid);
state.key = persistedData.key;
state.chunking = persistedData.chunking;
state.loaded = persistedData.loaded;
state.attemptingResume = true;
handler.moveInProgressToRemaining(id);
}
}
}
},
_maybePersistChunkedState: function(id) {
var state = handler._getFileState(id), localStorageId, persistedData;
if (resumeEnabled && handler.isResumable(id)) {
localStorageId = handler._getLocalStorageId(id);
persistedData = {
name: getName(id),
size: getSize(id),
uuid: getUuid(id),
key: state.key,
chunking: state.chunking,
loaded: state.loaded,
lastUpdated: Date.now()
};
try {
localStorage.setItem(localStorageId, JSON.stringify(persistedData));
} catch (error) {
log(qq.format("Unable to save resume data for '{}' due to error: '{}'.", id, error.toString()), "warn");
}
}
},
_registerProgressHandler: function(id, chunkIdx, chunkSize) {
var xhr = handler._getXhr(id, chunkIdx), name = getName(id), progressCalculator = {
simple: function(loaded, total) {
var fileSize = getSize(id);
if (loaded === total) {
onProgress(id, name, fileSize, fileSize);
} else {
onProgress(id, name, loaded >= fileSize ? fileSize - 1 : loaded, fileSize);
}
},
chunked: function(loaded, total) {
var chunkProgress = handler._getFileState(id).temp.chunkProgress, totalSuccessfullyLoadedForFile = handler._getFileState(id).loaded, loadedForRequest = loaded, totalForRequest = total, totalFileSize = getSize(id), estActualChunkLoaded = loadedForRequest - (totalForRequest - chunkSize), totalLoadedForFile = totalSuccessfullyLoadedForFile;
chunkProgress[chunkIdx] = estActualChunkLoaded;
qq.each(chunkProgress, function(chunkIdx, chunkLoaded) {
totalLoadedForFile += chunkLoaded;
});
onProgress(id, name, totalLoadedForFile, totalFileSize);
}
};
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var type = chunkSize == null ? "simple" : "chunked";
progressCalculator[type](e.loaded, e.total);
}
};
},
_registerXhr: function(id, optChunkIdx, xhr, optAjaxRequester) {
var xhrsId = optChunkIdx == null ? -1 : optChunkIdx, tempState = handler._getFileState(id).temp;
tempState.xhrs = tempState.xhrs || {};
tempState.ajaxRequesters = tempState.ajaxRequesters || {};
tempState.xhrs[xhrsId] = xhr;
if (optAjaxRequester) {
tempState.ajaxRequesters[xhrsId] = optAjaxRequester;
}
return xhr;
},
_removeExpiredChunkingRecords: function() {
var expirationDays = resume.recordsExpireIn;
handler._iterateResumeRecords(function(key, uploadData) {
var expirationDate = new Date(uploadData.lastUpdated);
expirationDate.setDate(expirationDate.getDate() + expirationDays);
if (expirationDate.getTime() <= Date.now()) {
log("Removing expired resume record with key " + key);
localStorage.removeItem(key);
}
});
},
_shouldChunkThisFile: function(id) {
var state = handler._getFileState(id);
if (!state.chunking) {
handler.reevaluateChunking(id);
}
return state.chunking.enabled;
}
});
};
qq.DeleteFileAjaxRequester = function(o) {
"use strict";
var requester, options = {
method: "DELETE",
uuidParamName: "qquuid",
endpointStore: {},
maxConnections: 3,
customHeaders: function(id) {
return {};
},
paramsStore: {},
cors: {
expected: false,
sendCredentials: false
},
log: function(str, level) {},
onDelete: function(id) {},
onDeleteComplete: function(id, xhrOrXdr, isError) {}
};
qq.extend(options, o);
function getMandatedParams() {
if (options.method.toUpperCase() === "POST") {
return {
_method: "DELETE"
};
}
return {};
}
requester = qq.extend(this, new qq.AjaxRequester({
acceptHeader: "application/json",
validMethods: [ "POST", "DELETE" ],
method: options.method,
endpointStore: options.endpointStore,
paramsStore: options.paramsStore,
mandatedParams: getMandatedParams(),
maxConnections: options.maxConnections,
customHeaders: function(id) {
return options.customHeaders.get(id);
},
log: options.log,
onSend: options.onDelete,
onComplete: options.onDeleteComplete,
cors: options.cors
}));
qq.extend(this, {
sendDelete: function(id, uuid, additionalMandatedParams) {
var additionalOptions = additionalMandatedParams || {};
options.log("Submitting delete file request for " + id);
if (options.method === "DELETE") {
requester.initTransport(id).withPath(uuid).withParams(additionalOptions).send();
} else {
additionalOptions[options.uuidParamName] = uuid;
requester.initTransport(id).withParams(additionalOptions).send();
}
}
});
};
(function() {
function detectSubsampling(img) {
var iw = img.naturalWidth, ih = img.naturalHeight, canvas = document.createElement("canvas"), ctx;
if (iw * ih > 1024 * 1024) {
canvas.width = canvas.height = 1;
ctx = canvas.getContext("2d");
ctx.drawImage(img, -iw + 1, 0);
return ctx.getImageData(0, 0, 1, 1).data[3] === 0;
} else {
return false;
}
}
function detectVerticalSquash(img, iw, ih) {
var canvas = document.createElement("canvas"), sy = 0, ey = ih, py = ih, ctx, data, alpha, ratio;
canvas.width = 1;
canvas.height = ih;
ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
data = ctx.getImageData(0, 0, 1, ih).data;
while (py > sy) {
alpha = data[(py - 1) * 4 + 3];
if (alpha === 0) {
ey = py;
} else {
sy = py;
}
py = ey + sy >> 1;
}
ratio = py / ih;
return ratio === 0 ? 1 : ratio;
}
function renderImageToDataURL(img, blob, options, doSquash) {
var canvas = document.createElement("canvas"), mime = options.mime || "image/jpeg", promise = new qq.Promise();
renderImageToCanvas(img, blob, canvas, options, doSquash).then(function() {
promise.success(canvas.toDataURL(mime, options.quality || .8));
});
return promise;
}
function maybeCalculateDownsampledDimensions(spec) {
var maxPixels = 5241e3;
if (!qq.ios()) {
throw new qq.Error("Downsampled dimensions can only be reliably calculated for iOS!");
}
if (spec.origHeight * spec.origWidth > maxPixels) {
return {
newHeight: Math.round(Math.sqrt(maxPixels * (spec.origHeight / spec.origWidth))),
newWidth: Math.round(Math.sqrt(maxPixels * (spec.origWidth / spec.origHeight)))
};
}
}
function renderImageToCanvas(img, blob, canvas, options, doSquash) {
var iw = img.naturalWidth, ih = img.naturalHeight, width = options.width, height = options.height, ctx = canvas.getContext("2d"), promise = new qq.Promise(), modifiedDimensions;
ctx.save();
if (options.resize) {
return renderImageToCanvasWithCustomResizer({
blob: blob,
canvas: canvas,
image: img,
imageHeight: ih,
imageWidth: iw,
orientation: options.orientation,
resize: options.resize,
targetHeight: height,
targetWidth: width
});
}
if (!qq.supportedFeatures.unlimitedScaledImageSize) {
modifiedDimensions = maybeCalculateDownsampledDimensions({
origWidth: width,
origHeight: height
});
if (modifiedDimensions) {
qq.log(qq.format("Had to reduce dimensions due to device limitations from {}w / {}h to {}w / {}h", width, height, modifiedDimensions.newWidth, modifiedDimensions.newHeight), "warn");
width = modifiedDimensions.newWidth;
height = modifiedDimensions.newHeight;
}
}
transformCoordinate(canvas, width, height, options.orientation);
if (qq.ios()) {
(function() {
if (detectSubsampling(img)) {
iw /= 2;
ih /= 2;
}
var d = 1024, tmpCanvas = document.createElement("canvas"), vertSquashRatio = doSquash ? detectVerticalSquash(img, iw, ih) : 1, dw = Math.ceil(d * width / iw), dh = Math.ceil(d * height / ih / vertSquashRatio), sy = 0, dy = 0, tmpCtx, sx, dx;
tmpCanvas.width = tmpCanvas.height = d;
tmpCtx = tmpCanvas.getContext("2d");
while (sy < ih) {
sx = 0;
dx = 0;
while (sx < iw) {
tmpCtx.clearRect(0, 0, d, d);
tmpCtx.drawImage(img, -sx, -sy);
ctx.drawImage(tmpCanvas, 0, 0, d, d, dx, dy, dw, dh);
sx += d;
dx += dw;
}
sy += d;
dy += dh;
}
ctx.restore();
tmpCanvas = tmpCtx = null;
})();
} else {
ctx.drawImage(img, 0, 0, width, height);
}
canvas.qqImageRendered && canvas.qqImageRendered();
promise.success();
return promise;
}
function renderImageToCanvasWithCustomResizer(resizeInfo) {
var blob = resizeInfo.blob, image = resizeInfo.image, imageHeight = resizeInfo.imageHeight, imageWidth = resizeInfo.imageWidth, orientation = resizeInfo.orientation, promise = new qq.Promise(), resize = resizeInfo.resize, sourceCanvas = document.createElement("canvas"), sourceCanvasContext = sourceCanvas.getContext("2d"), targetCanvas = resizeInfo.canvas, targetHeight = resizeInfo.targetHeight, targetWidth = resizeInfo.targetWidth;
transformCoordinate(sourceCanvas, imageWidth, imageHeight, orientation);
targetCanvas.height = targetHeight;
targetCanvas.width = targetWidth;
sourceCanvasContext.drawImage(image, 0, 0);
resize({
blob: blob,
height: targetHeight,
image: image,
sourceCanvas: sourceCanvas,
targetCanvas: targetCanvas,
width: targetWidth
}).then(function success() {
targetCanvas.qqImageRendered && targetCanvas.qqImageRendered();
promise.success();
}, promise.failure);
return promise;
}
function transformCoordinate(canvas, width, height, orientation) {
switch (orientation) {
case 5:
case 6:
case 7:
case 8:
canvas.width = height;
canvas.height = width;
break;
default:
canvas.width = width;
canvas.height = height;
}
var ctx = canvas.getContext("2d");
switch (orientation) {
case 2:
ctx.translate(width, 0);
ctx.scale(-1, 1);
break;
case 3:
ctx.translate(width, height);
ctx.rotate(Math.PI);
break;
case 4:
ctx.translate(0, height);
ctx.scale(1, -1);
break;
case 5:
ctx.rotate(.5 * Math.PI);
ctx.scale(1, -1);
break;
case 6:
ctx.rotate(.5 * Math.PI);
ctx.translate(0, -height);
break;
case 7:
ctx.rotate(.5 * Math.PI);
ctx.translate(width, -height);
ctx.scale(-1, 1);
break;
case 8:
ctx.rotate(-.5 * Math.PI);
ctx.translate(-width, 0);
break;
default:
break;
}
}
function MegaPixImage(srcImage, errorCallback) {
var self = this;
if (window.Blob && srcImage instanceof Blob) {
(function() {
var img = new Image(), URL = window.URL && window.URL.createObjectURL ? window.URL : window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL : null;
if (!URL) {
throw Error("No createObjectURL function found to create blob url");
}
img.src = URL.createObjectURL(srcImage);
self.blob = srcImage;
srcImage = img;
})();
}
if (!srcImage.naturalWidth && !srcImage.naturalHeight) {
srcImage.onload = function() {
var listeners = self.imageLoadListeners;
if (listeners) {
self.imageLoadListeners = null;
setTimeout(function() {
for (var i = 0, len = listeners.length; i < len; i++) {
listeners[i]();
}
}, 0);
}
};
srcImage.onerror = errorCallback;
this.imageLoadListeners = [];
}
this.srcImage = srcImage;
}
MegaPixImage.prototype.render = function(target, options) {
options = options || {};
var self = this, imgWidth = this.srcImage.naturalWidth, imgHeight = this.srcImage.naturalHeight, width = options.width, height = options.height, maxWidth = options.maxWidth, maxHeight = options.maxHeight, doSquash = !this.blob || this.blob.type === "image/jpeg", tagName = target.tagName.toLowerCase(), opt;
if (this.imageLoadListeners) {
this.imageLoadListeners.push(function() {
self.render(target, options);
});
return;
}
if (width && !height) {
height = imgHeight * width / imgWidth << 0;
} else if (height && !width) {
width = imgWidth * height / imgHeight << 0;
} else {
width = imgWidth;
height = imgHeight;
}
if (maxWidth && width > maxWidth) {
width = maxWidth;
height = imgHeight * width / imgWidth << 0;
}
if (maxHeight && height > maxHeight) {
height = maxHeight;
width = imgWidth * height / imgHeight << 0;
}
opt = {
width: width,
height: height
}, qq.each(options, function(optionsKey, optionsValue) {
opt[optionsKey] = optionsValue;
});
if (tagName === "img") {
(function() {
var oldTargetSrc = target.src;
renderImageToDataURL(self.srcImage, self.blob, opt, doSquash).then(function(dataUri) {
target.src = dataUri;
oldTargetSrc === target.src && target.onload();
});
})();
} else if (tagName === "canvas") {
renderImageToCanvas(this.srcImage, this.blob, target, opt, doSquash);
}
if (typeof this.onrender === "function") {
this.onrender(target);
}
};
qq.MegaPixImage = MegaPixImage;
})();
qq.ImageGenerator = function(log) {
"use strict";
function isImg(el) {
return el.tagName.toLowerCase() === "img";
}
function isCanvas(el) {
return el.tagName.toLowerCase() === "canvas";
}
function isImgCorsSupported() {
return new Image().crossOrigin !== undefined;
}
function isCanvasSupported() {
var canvas = document.createElement("canvas");
return canvas.getContext && canvas.getContext("2d");
}
function determineMimeOfFileName(nameWithPath) {
var pathSegments = nameWithPath.split("/"), name = pathSegments[pathSegments.length - 1].split("?")[0], extension = qq.getExtension(name);
extension = extension && extension.toLowerCase();
switch (extension) {
case "jpeg":
case "jpg":
return "image/jpeg";
case "png":
return "image/png";
case "bmp":
return "image/bmp";
case "gif":
return "image/gif";
case "tiff":
case "tif":
return "image/tiff";
}
}
function isCrossOrigin(url) {
var targetAnchor = document.createElement("a"), targetProtocol, targetHostname, targetPort;
targetAnchor.href = url;
targetProtocol = targetAnchor.protocol;
targetPort = targetAnchor.port;
targetHostname = targetAnchor.hostname;
if (targetProtocol.toLowerCase() !== window.location.protocol.toLowerCase()) {
return true;
}
if (targetHostname.toLowerCase() !== window.location.hostname.toLowerCase()) {
return true;
}
if (targetPort !== window.location.port && !qq.ie()) {
return true;
}
return false;
}
function registerImgLoadListeners(img, promise) {
img.onload = function() {
img.onload = null;
img.onerror = null;
promise.success(img);
};
img.onerror = function() {
img.onload = null;
img.onerror = null;
log("Problem drawing thumbnail!", "error");
promise.failure(img, "Problem drawing thumbnail!");
};
}
function registerCanvasDrawImageListener(canvas, promise) {
canvas.qqImageRendered = function() {
promise.success(canvas);
};
}
function registerThumbnailRenderedListener(imgOrCanvas, promise) {
var registered = isImg(imgOrCanvas) || isCanvas(imgOrCanvas);
if (isImg(imgOrCanvas)) {
registerImgLoadListeners(imgOrCanvas, promise);
} else if (isCanvas(imgOrCanvas)) {
registerCanvasDrawImageListener(imgOrCanvas, promise);
} else {
promise.failure(imgOrCanvas);
log(qq.format("Element container of type {} is not supported!", imgOrCanvas.tagName), "error");
}
return registered;
}
function draw(fileOrBlob, container, options) {
var drawPreview = new qq.Promise(), identifier = new qq.Identify(fileOrBlob, log), maxSize = options.maxSize, orient = options.orient == null ? true : options.orient, megapixErrorHandler = function() {
container.onerror = null;
container.onload = null;
log("Could not render preview, file may be too large!", "error");
drawPreview.failure(container, "Browser cannot render image!");
};
identifier.isPreviewable().then(function(mime) {
var dummyExif = {
parse: function() {
return new qq.Promise().success();
}
}, exif = orient ? new qq.Exif(fileOrBlob, log) : dummyExif, mpImg = new qq.MegaPixImage(fileOrBlob, megapixErrorHandler);
if (registerThumbnailRenderedListener(container, drawPreview)) {
exif.parse().then(function(exif) {
var orientation = exif && exif.Orientation;
mpImg.render(container, {
maxWidth: maxSize,
maxHeight: maxSize,
orientation: orientation,
mime: mime,
resize: options.customResizeFunction
});
}, function(failureMsg) {
log(qq.format("EXIF data could not be parsed ({}). Assuming orientation = 1.", failureMsg));
mpImg.render(container, {
maxWidth: maxSize,
maxHeight: maxSize,
mime: mime,
resize: options.customResizeFunction
});
});
}
}, function() {
log("Not previewable");
drawPreview.failure(container, "Not previewable");
});
return drawPreview;
}
function drawOnCanvasOrImgFromUrl(url, canvasOrImg, draw, maxSize, customResizeFunction) {
var tempImg = new Image(), tempImgRender = new qq.Promise();
registerThumbnailRenderedListener(tempImg, tempImgRender);
if (isCrossOrigin(url)) {
tempImg.crossOrigin = "anonymous";
}
tempImg.src = url;
tempImgRender.then(function rendered() {
registerThumbnailRenderedListener(canvasOrImg, draw);
var mpImg = new qq.MegaPixImage(tempImg);
mpImg.render(canvasOrImg, {
maxWidth: maxSize,
maxHeight: maxSize,
mime: determineMimeOfFileName(url),
resize: customResizeFunction
});
}, draw.failure);
}
function drawOnImgFromUrlWithCssScaling(url, img, draw, maxSize) {
registerThumbnailRenderedListener(img, draw);
qq(img).css({
maxWidth: maxSize + "px",
maxHeight: maxSize + "px"
});
img.src = url;
}
function drawFromUrl(url, container, options) {
var draw = new qq.Promise(), scale = options.scale, maxSize = scale ? options.maxSize : null;
if (scale && isImg(container)) {
if (isCanvasSupported()) {
if (isCrossOrigin(url) && !isImgCorsSupported()) {
drawOnImgFromUrlWithCssScaling(url, container, draw, maxSize);
} else {
drawOnCanvasOrImgFromUrl(url, container, draw, maxSize);
}
} else {
drawOnImgFromUrlWithCssScaling(url, container, draw, maxSize);
}
} else if (isCanvas(container)) {
drawOnCanvasOrImgFromUrl(url, container, draw, maxSize);
} else if (registerThumbnailRenderedListener(container, draw)) {
container.src = url;
}
return draw;
}
qq.extend(this, {
generate: function(fileBlobOrUrl, container, options) {
if (qq.isString(fileBlobOrUrl)) {
log("Attempting to update thumbnail based on server response.");
return drawFromUrl(fileBlobOrUrl, container, options || {});
} else {
log("Attempting to draw client-side image preview.");
return draw(fileBlobOrUrl, container, options || {});
}
}
});
this._testing = {};
this._testing.isImg = isImg;
this._testing.isCanvas = isCanvas;
this._testing.isCrossOrigin = isCrossOrigin;
this._testing.determineMimeOfFileName = determineMimeOfFileName;
};
qq.Exif = function(fileOrBlob, log) {
"use strict";
var TAG_IDS = [ 274 ], TAG_INFO = {
274: {
name: "Orientation",
bytes: 2
}
};
function parseLittleEndian(hex) {
var result = 0, pow = 0;
while (hex.length > 0) {
result += parseInt(hex.substring(0, 2), 16) * Math.pow(2, pow);
hex = hex.substring(2, hex.length);
pow += 8;
}
return result;
}
function seekToApp1(offset, promise) {
var theOffset = offset, thePromise = promise;
if (theOffset === undefined) {
theOffset = 2;
thePromise = new qq.Promise();
}
qq.readBlobToHex(fileOrBlob, theOffset, 4).then(function(hex) {
var match = /^ffe([0-9])/.exec(hex), segmentLength;
if (match) {
if (match[1] !== "1") {
segmentLength = parseInt(hex.slice(4, 8), 16);
seekToApp1(theOffset + segmentLength + 2, thePromise);
} else {
thePromise.success(theOffset);
}
} else {
thePromise.failure("No EXIF header to be found!");
}
});
return thePromise;
}
function getApp1Offset() {
var promise = new qq.Promise();
qq.readBlobToHex(fileOrBlob, 0, 6).then(function(hex) {
if (hex.indexOf("ffd8") !== 0) {
promise.failure("Not a valid JPEG!");
} else {
seekToApp1().then(function(offset) {
promise.success(offset);
}, function(error) {
promise.failure(error);
});
}
});
return promise;
}
function isLittleEndian(app1Start) {
var promise = new qq.Promise();
qq.readBlobToHex(fileOrBlob, app1Start + 10, 2).then(function(hex) {
promise.success(hex === "4949");
});
return promise;
}
function getDirEntryCount(app1Start, littleEndian) {
var promise = new qq.Promise();
qq.readBlobToHex(fileOrBlob, app1Start + 18, 2).then(function(hex) {
if (littleEndian) {
return promise.success(parseLittleEndian(hex));
} else {
promise.success(parseInt(hex, 16));
}
});
return promise;
}
function getIfd(app1Start, dirEntries) {
var offset = app1Start + 20, bytes = dirEntries * 12;
return qq.readBlobToHex(fileOrBlob, offset, bytes);
}
function getDirEntries(ifdHex) {
var entries = [], offset = 0;
while (offset + 24 <= ifdHex.length) {
entries.push(ifdHex.slice(offset, offset + 24));
offset += 24;
}
return entries;
}
function getTagValues(littleEndian, dirEntries) {
var TAG_VAL_OFFSET = 16, tagsToFind = qq.extend([], TAG_IDS), vals = {};
qq.each(dirEntries, function(idx, entry) {
var idHex = entry.slice(0, 4), id = littleEndian ? parseLittleEndian(idHex) : parseInt(idHex, 16), tagsToFindIdx = tagsToFind.indexOf(id), tagValHex, tagName, tagValLength;
if (tagsToFindIdx >= 0) {
tagName = TAG_INFO[id].name;
tagValLength = TAG_INFO[id].bytes;
tagValHex = entry.slice(TAG_VAL_OFFSET, TAG_VAL_OFFSET + tagValLength * 2);
vals[tagName] = littleEndian ? parseLittleEndian(tagValHex) : parseInt(tagValHex, 16);
tagsToFind.splice(tagsToFindIdx, 1);
}
if (tagsToFind.length === 0) {
return false;
}
});
return vals;
}
qq.extend(this, {
parse: function() {
var parser = new qq.Promise(), onParseFailure = function(message) {
log(qq.format("EXIF header parse failed: '{}' ", message));
parser.failure(message);
};
getApp1Offset().then(function(app1Offset) {
log(qq.format("Moving forward with EXIF header parsing for '{}'", fileOrBlob.name === undefined ? "blob" : fileOrBlob.name));
isLittleEndian(app1Offset).then(function(littleEndian) {
log(qq.format("EXIF Byte order is {} endian", littleEndian ? "little" : "big"));
getDirEntryCount(app1Offset, littleEndian).then(function(dirEntryCount) {
log(qq.format("Found {} APP1 directory entries", dirEntryCount));
getIfd(app1Offset, dirEntryCount).then(function(ifdHex) {
var dirEntries = getDirEntries(ifdHex), tagValues = getTagValues(littleEndian, dirEntries);
log("Successfully parsed some EXIF tags");
parser.success(tagValues);
}, onParseFailure);
}, onParseFailure);
}, onParseFailure);
}, onParseFailure);
return parser;
}
});
this._testing = {};
this._testing.parseLittleEndian = parseLittleEndian;
};
qq.Identify = function(fileOrBlob, log) {
"use strict";
function isIdentifiable(magicBytes, questionableBytes) {
var identifiable = false, magicBytesEntries = [].concat(magicBytes);
qq.each(magicBytesEntries, function(idx, magicBytesArrayEntry) {
if (questionableBytes.indexOf(magicBytesArrayEntry) === 0) {
identifiable = true;
return false;
}
});
return identifiable;
}
qq.extend(this, {
isPreviewable: function() {
var self = this, identifier = new qq.Promise(), previewable = false, name = fileOrBlob.name === undefined ? "blob" : fileOrBlob.name;
log(qq.format("Attempting to determine if {} can be rendered in this browser", name));
log("First pass: check type attribute of blob object.");
if (this.isPreviewableSync()) {
log("Second pass: check for magic bytes in file header.");
qq.readBlobToHex(fileOrBlob, 0, 4).then(function(hex) {
qq.each(self.PREVIEWABLE_MIME_TYPES, function(mime, bytes) {
if (isIdentifiable(bytes, hex)) {
if (mime !== "image/tiff" || qq.supportedFeatures.tiffPreviews) {
previewable = true;
identifier.success(mime);
}
return false;
}
});
log(qq.format("'{}' is {} able to be rendered in this browser", name, previewable ? "" : "NOT"));
if (!previewable) {
identifier.failure();
}
}, function() {
log("Error reading file w/ name '" + name + "'. Not able to be rendered in this browser.");
identifier.failure();
});
} else {
identifier.failure();
}
return identifier;
},
isPreviewableSync: function() {
var fileMime = fileOrBlob.type, isRecognizedImage = qq.indexOf(Object.keys(this.PREVIEWABLE_MIME_TYPES), fileMime) >= 0, previewable = false, name = fileOrBlob.name === undefined ? "blob" : fileOrBlob.name;
if (isRecognizedImage) {
if (fileMime === "image/tiff") {
previewable = qq.supportedFeatures.tiffPreviews;
} else {
previewable = true;
}
}
!previewable && log(name + " is not previewable in this browser per the blob's type attr");
return previewable;
}
});
};
qq.Identify.prototype.PREVIEWABLE_MIME_TYPES = {
"image/jpeg": "ffd8ff",
"image/gif": "474946",
"image/png": "89504e",
"image/bmp": "424d",
"image/tiff": [ "49492a00", "4d4d002a" ]
};
qq.Identify = function(fileOrBlob, log) {
"use strict";
function isIdentifiable(magicBytes, questionableBytes) {
var identifiable = false, magicBytesEntries = [].concat(magicBytes);
qq.each(magicBytesEntries, function(idx, magicBytesArrayEntry) {
if (questionableBytes.indexOf(magicBytesArrayEntry) === 0) {
identifiable = true;
return false;
}
});
return identifiable;
}
qq.extend(this, {
isPreviewable: function() {
var self = this, identifier = new qq.Promise(), previewable = false, name = fileOrBlob.name === undefined ? "blob" : fileOrBlob.name;
log(qq.format("Attempting to determine if {} can be rendered in this browser", name));
log("First pass: check type attribute of blob object.");
if (this.isPreviewableSync()) {
log("Second pass: check for magic bytes in file header.");
qq.readBlobToHex(fileOrBlob, 0, 4).then(function(hex) {
qq.each(self.PREVIEWABLE_MIME_TYPES, function(mime, bytes) {
if (isIdentifiable(bytes, hex)) {
if (mime !== "image/tiff" || qq.supportedFeatures.tiffPreviews) {
previewable = true;
identifier.success(mime);
}
return false;
}
});
log(qq.format("'{}' is {} able to be rendered in this browser", name, previewable ? "" : "NOT"));
if (!previewable) {
identifier.failure();
}
}, function() {
log("Error reading file w/ name '" + name + "'. Not able to be rendered in this browser.");
identifier.failure();
});
} else {
identifier.failure();
}
return identifier;
},
isPreviewableSync: function() {
var fileMime = fileOrBlob.type, isRecognizedImage = qq.indexOf(Object.keys(this.PREVIEWABLE_MIME_TYPES), fileMime) >= 0, previewable = false, name = fileOrBlob.name === undefined ? "blob" : fileOrBlob.name;
if (isRecognizedImage) {
if (fileMime === "image/tiff") {
previewable = qq.supportedFeatures.tiffPreviews;
} else {
previewable = true;
}
}
!previewable && log(name + " is not previewable in this browser per the blob's type attr");
return previewable;
}
});
};
qq.Identify.prototype.PREVIEWABLE_MIME_TYPES = {
"image/jpeg": "ffd8ff",
"image/gif": "474946",
"image/png": "89504e",
"image/bmp": "424d",
"image/tiff": [ "49492a00", "4d4d002a" ]
};
qq.ImageValidation = function(blob, log) {
"use strict";
function hasNonZeroLimits(limits) {
var atLeastOne = false;
qq.each(limits, function(limit, value) {
if (value > 0) {
atLeastOne = true;
return false;
}
});
return atLeastOne;
}
function getWidthHeight() {
var sizeDetermination = new qq.Promise();
new qq.Identify(blob, log).isPreviewable().then(function() {
var image = new Image(), url = window.URL && window.URL.createObjectURL ? window.URL : window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL : null;
if (url) {
image.onerror = function() {
log("Cannot determine dimensions for image. May be too large.", "error");
sizeDetermination.failure();
};
image.onload = function() {
sizeDetermination.success({
width: this.width,
height: this.height
});
};
image.src = url.createObjectURL(blob);
} else {
log("No createObjectURL function available to generate image URL!", "error");
sizeDetermination.failure();
}
}, sizeDetermination.failure);
return sizeDetermination;
}
function getFailingLimit(limits, dimensions) {
var failingLimit;
qq.each(limits, function(limitName, limitValue) {
if (limitValue > 0) {
var limitMatcher = /(max|min)(Width|Height)/.exec(limitName), dimensionPropName = limitMatcher[2].charAt(0).toLowerCase() + limitMatcher[2].slice(1), actualValue = dimensions[dimensionPropName];
switch (limitMatcher[1]) {
case "min":
if (actualValue < limitValue) {
failingLimit = limitName;
return false;
}
break;
case "max":
if (actualValue > limitValue) {
failingLimit = limitName;
return false;
}
break;
}
}
});
return failingLimit;
}
this.validate = function(limits) {
var validationEffort = new qq.Promise();
log("Attempting to validate image.");
if (hasNonZeroLimits(limits)) {
getWidthHeight().then(function(dimensions) {
var failingLimit = getFailingLimit(limits, dimensions);
if (failingLimit) {
validationEffort.failure(failingLimit);
} else {
validationEffort.success();
}
}, validationEffort.success);
} else {
validationEffort.success();
}
return validationEffort;
};
};
qq.Session = function(spec) {
"use strict";
var options = {
endpoint: null,
params: {},
customHeaders: {},
cors: {},
addFileRecord: function(sessionData) {},
log: function(message, level) {}
};
qq.extend(options, spec, true);
function isJsonResponseValid(response) {
if (qq.isArray(response)) {
return true;
}
options.log("Session response is not an array.", "error");
}
function handleFileItems(fileItems, success, xhrOrXdr, promise) {
var someItemsIgnored = false;
success = success && isJsonResponseValid(fileItems);
if (success) {
qq.each(fileItems, function(idx, fileItem) {
if (fileItem.uuid == null) {
someItemsIgnored = true;
options.log(qq.format("Session response item {} did not include a valid UUID - ignoring.", idx), "error");
} else if (fileItem.name == null) {
someItemsIgnored = true;
options.log(qq.format("Session response item {} did not include a valid name - ignoring.", idx), "error");
} else {
try {
options.addFileRecord(fileItem);
return true;
} catch (err) {
someItemsIgnored = true;
options.log(err.message, "error");
}
}
return false;
});
}
promise[success && !someItemsIgnored ? "success" : "failure"](fileItems, xhrOrXdr);
}
this.refresh = function() {
var refreshEffort = new qq.Promise(), refreshCompleteCallback = function(response, success, xhrOrXdr) {
handleFileItems(response, success, xhrOrXdr, refreshEffort);
}, requesterOptions = qq.extend({}, options), requester = new qq.SessionAjaxRequester(qq.extend(requesterOptions, {
onComplete: refreshCompleteCallback
}));
requester.queryServer();
return refreshEffort;
};
};
qq.SessionAjaxRequester = function(spec) {
"use strict";
var requester, options = {
endpoint: null,
customHeaders: {},
params: {},
cors: {
expected: false,
sendCredentials: false
},
onComplete: function(response, success, xhrOrXdr) {},
log: function(str, level) {}
};
qq.extend(options, spec);
function onComplete(id, xhrOrXdr, isError) {
var response = null;
if (xhrOrXdr.responseText != null) {
try {
response = qq.parseJson(xhrOrXdr.responseText);
} catch (err) {
options.log("Problem parsing session response: " + err.message, "error");
isError = true;
}
}
options.onComplete(response, !isError, xhrOrXdr);
}
requester = qq.extend(this, new qq.AjaxRequester({
acceptHeader: "application/json",
validMethods: [ "GET" ],
method: "GET",
endpointStore: {
get: function() {
return options.endpoint;
}
},
customHeaders: options.customHeaders,
log: options.log,
onComplete: onComplete,
cors: options.cors
}));
qq.extend(this, {
queryServer: function() {
var params = qq.extend({}, options.params);
options.log("Session query request.");
requester.initTransport("sessionRefresh").withParams(params).withCacheBuster().send();
}
});
};
qq.Scaler = function(spec, log) {
"use strict";
var self = this, customResizeFunction = spec.customResizer, includeOriginal = spec.sendOriginal, orient = spec.orient, defaultType = spec.defaultType, defaultQuality = spec.defaultQuality / 100, failedToScaleText = spec.failureText, includeExif = spec.includeExif, sizes = this._getSortedSizes(spec.sizes);
qq.extend(this, {
enabled: qq.supportedFeatures.scaling && sizes.length > 0,
getFileRecords: function(originalFileUuid, originalFileName, originalBlobOrBlobData) {
var self = this, records = [], originalBlob = originalBlobOrBlobData.blob ? originalBlobOrBlobData.blob : originalBlobOrBlobData, identifier = new qq.Identify(originalBlob, log);
if (identifier.isPreviewableSync()) {
qq.each(sizes, function(idx, sizeRecord) {
var outputType = self._determineOutputType({
defaultType: defaultType,
requestedType: sizeRecord.type,
refType: originalBlob.type
});
records.push({
uuid: qq.getUniqueId(),
name: self._getName(originalFileName, {
name: sizeRecord.name,
type: outputType,
refType: originalBlob.type
}),
blob: new qq.BlobProxy(originalBlob, qq.bind(self._generateScaledImage, self, {
customResizeFunction: customResizeFunction,
maxSize: sizeRecord.maxSize,
orient: orient,
type: outputType,
quality: defaultQuality,
failedText: failedToScaleText,
includeExif: includeExif,
log: log
}))
});
});
records.push({
uuid: originalFileUuid,
name: originalFileName,
size: originalBlob.size,
blob: includeOriginal ? originalBlob : null
});
} else {
records.push({
uuid: originalFileUuid,
name: originalFileName,
size: originalBlob.size,
blob: originalBlob
});
}
return records;
},
handleNewFile: function(file, name, uuid, size, fileList, batchId, uuidParamName, api) {
var self = this, buttonId = file.qqButtonId || file.blob && file.blob.qqButtonId, scaledIds = [], originalId = null, addFileToHandler = api.addFileToHandler, uploadData = api.uploadData, paramsStore = api.paramsStore, proxyGroupId = qq.getUniqueId();
qq.each(self.getFileRecords(uuid, name, file), function(idx, record) {
var blobSize = record.size, id;
if (record.blob instanceof qq.BlobProxy) {
blobSize = -1;
}
id = uploadData.addFile({
uuid: record.uuid,
name: record.name,
size: blobSize,
batchId: batchId,
proxyGroupId: proxyGroupId
});
if (record.blob instanceof qq.BlobProxy) {
scaledIds.push(id);
} else {
originalId = id;
}
if (record.blob) {
addFileToHandler(id, record.blob);
fileList.push({
id: id,
file: record.blob
});
} else {
uploadData.setStatus(id, qq.status.REJECTED);
}
});
if (originalId !== null) {
qq.each(scaledIds, function(idx, scaledId) {
var params = {
qqparentuuid: uploadData.retrieve({
id: originalId
}).uuid,
qqparentsize: uploadData.retrieve({
id: originalId
}).size
};
params[uuidParamName] = uploadData.retrieve({
id: scaledId
}).uuid;
uploadData.setParentId(scaledId, originalId);
paramsStore.addReadOnly(scaledId, params);
});
if (scaledIds.length) {
(function() {
var param = {};
param[uuidParamName] = uploadData.retrieve({
id: originalId
}).uuid;
paramsStore.addReadOnly(originalId, param);
})();
}
}
}
});
};
qq.extend(qq.Scaler.prototype, {
scaleImage: function(id, specs, api) {
"use strict";
if (!qq.supportedFeatures.scaling) {
throw new qq.Error("Scaling is not supported in this browser!");
}
var scalingEffort = new qq.Promise(), log = api.log, file = api.getFile(id), uploadData = api.uploadData.retrieve({
id: id
}), name = uploadData && uploadData.name, uuid = uploadData && uploadData.uuid, scalingOptions = {
customResizer: specs.customResizer,
sendOriginal: false,
orient: specs.orient,
defaultType: specs.type || null,
defaultQuality: specs.quality,
failedToScaleText: "Unable to scale",
sizes: [ {
name: "",
maxSize: specs.maxSize
} ]
}, scaler = new qq.Scaler(scalingOptions, log);
if (!qq.Scaler || !qq.supportedFeatures.imagePreviews || !file) {
scalingEffort.failure();
log("Could not generate requested scaled image for " + id + ". " + "Scaling is either not possible in this browser, or the file could not be located.", "error");
} else {
qq.bind(function() {
var record = scaler.getFileRecords(uuid, name, file)[0];
if (record && record.blob instanceof qq.BlobProxy) {
record.blob.create().then(scalingEffort.success, scalingEffort.failure);
} else {
log(id + " is not a scalable image!", "error");
scalingEffort.failure();
}
}, this)();
}
return scalingEffort;
},
_determineOutputType: function(spec) {
"use strict";
var requestedType = spec.requestedType, defaultType = spec.defaultType, referenceType = spec.refType;
if (!defaultType && !requestedType) {
if (referenceType !== "image/jpeg") {
return "image/png";
}
return referenceType;
}
if (!requestedType) {
return defaultType;
}
if (qq.indexOf(Object.keys(qq.Identify.prototype.PREVIEWABLE_MIME_TYPES), requestedType) >= 0) {
if (requestedType === "image/tiff") {
return qq.supportedFeatures.tiffPreviews ? requestedType : defaultType;
}
return requestedType;
}
return defaultType;
},
_getName: function(originalName, scaledVersionProperties) {
"use strict";
var startOfExt = originalName.lastIndexOf("."), versionType = scaledVersionProperties.type || "image/png", referenceType = scaledVersionProperties.refType, scaledName = "", scaledExt = qq.getExtension(originalName), nameAppendage = "";
if (scaledVersionProperties.name && scaledVersionProperties.name.trim().length) {
nameAppendage = " (" + scaledVersionProperties.name + ")";
}
if (startOfExt >= 0) {
scaledName = originalName.substr(0, startOfExt);
if (referenceType !== versionType) {
scaledExt = versionType.split("/")[1];
}
scaledName += nameAppendage + "." + scaledExt;
} else {
scaledName = originalName + nameAppendage;
}
return scaledName;
},
_getSortedSizes: function(sizes) {
"use strict";
sizes = qq.extend([], sizes);
return sizes.sort(function(a, b) {
if (a.maxSize > b.maxSize) {
return 1;
}
if (a.maxSize < b.maxSize) {
return -1;
}
return 0;
});
},
_generateScaledImage: function(spec, sourceFile) {
"use strict";
var self = this, customResizeFunction = spec.customResizeFunction, log = spec.log, maxSize = spec.maxSize, orient = spec.orient, type = spec.type, quality = spec.quality, failedText = spec.failedText, includeExif = spec.includeExif && sourceFile.type === "image/jpeg" && type === "image/jpeg", scalingEffort = new qq.Promise(), imageGenerator = new qq.ImageGenerator(log), canvas = document.createElement("canvas");
log("Attempting to generate scaled version for " + sourceFile.name);
imageGenerator.generate(sourceFile, canvas, {
maxSize: maxSize,
orient: orient,
customResizeFunction: customResizeFunction
}).then(function() {
var scaledImageDataUri = canvas.toDataURL(type, quality), signalSuccess = function() {
log("Success generating scaled version for " + sourceFile.name);
var blob = qq.dataUriToBlob(scaledImageDataUri);
scalingEffort.success(blob);
};
if (includeExif) {
self._insertExifHeader(sourceFile, scaledImageDataUri, log).then(function(scaledImageDataUriWithExif) {
scaledImageDataUri = scaledImageDataUriWithExif;
signalSuccess();
}, function() {
log("Problem inserting EXIF header into scaled image. Using scaled image w/out EXIF data.", "error");
signalSuccess();
});
} else {
signalSuccess();
}
}, function() {
log("Failed attempt to generate scaled version for " + sourceFile.name, "error");
scalingEffort.failure(failedText);
});
return scalingEffort;
},
_insertExifHeader: function(originalImage, scaledImageDataUri, log) {
"use strict";
var reader = new FileReader(), insertionEffort = new qq.Promise(), originalImageDataUri = "";
reader.onload = function() {
originalImageDataUri = reader.result;
insertionEffort.success(qq.ExifRestorer.restore(originalImageDataUri, scaledImageDataUri));
};
reader.onerror = function() {
log("Problem reading " + originalImage.name + " during attempt to transfer EXIF data to scaled version.", "error");
insertionEffort.failure();
};
reader.readAsDataURL(originalImage);
return insertionEffort;
},
_dataUriToBlob: function(dataUri) {
"use strict";
var byteString, mimeString, arrayBuffer, intArray;
if (dataUri.split(",")[0].indexOf("base64") >= 0) {
byteString = atob(dataUri.split(",")[1]);
} else {
byteString = decodeURI(dataUri.split(",")[1]);
}
mimeString = dataUri.split(",")[0].split(":")[1].split(";")[0];
arrayBuffer = new ArrayBuffer(byteString.length);
intArray = new Uint8Array(arrayBuffer);
qq.each(byteString, function(idx, character) {
intArray[idx] = character.charCodeAt(0);
});
return this._createBlob(arrayBuffer, mimeString);
},
_createBlob: function(data, mime) {
"use strict";
var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder, blobBuilder = BlobBuilder && new BlobBuilder();
if (blobBuilder) {
blobBuilder.append(data);
return blobBuilder.getBlob(mime);
} else {
return new Blob([ data ], {
type: mime
});
}
}
});
qq.ExifRestorer = function() {
var ExifRestorer = {};
ExifRestorer.KEY_STR = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv" + "wxyz0123456789+/" + "=";
ExifRestorer.encode64 = function(input) {
var output = "", chr1, chr2, chr3 = "", enc1, enc2, enc3, enc4 = "", i = 0;
do {
chr1 = input[i++];
chr2 = input[i++];
chr3 = input[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 + this.KEY_STR.charAt(enc1) + this.KEY_STR.charAt(enc2) + this.KEY_STR.charAt(enc3) + this.KEY_STR.charAt(enc4);
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return output;
};
ExifRestorer.restore = function(origFileBase64, resizedFileBase64) {
var expectedBase64Header = "data:image/jpeg;base64,";
if (!origFileBase64.match(expectedBase64Header)) {
return resizedFileBase64;
}
var rawImage = this.decode64(origFileBase64.replace(expectedBase64Header, ""));
var segments = this.slice2Segments(rawImage);
var image = this.exifManipulation(resizedFileBase64, segments);
return expectedBase64Header + this.encode64(image);
};
ExifRestorer.exifManipulation = function(resizedFileBase64, segments) {
var exifArray = this.getExifArray(segments), newImageArray = this.insertExif(resizedFileBase64, exifArray), aBuffer = new Uint8Array(newImageArray);
return aBuffer;
};
ExifRestorer.getExifArray = function(segments) {
var seg;
for (var x = 0; x < segments.length; x++) {
seg = segments[x];
if (seg[0] == 255 & seg[1] == 225) {
return seg;
}
}
return [];
};
ExifRestorer.insertExif = function(resizedFileBase64, exifArray) {
var imageData = resizedFileBase64.replace("data:image/jpeg;base64,", ""), buf = this.decode64(imageData), separatePoint = buf.indexOf(255, 3), mae = buf.slice(0, separatePoint), ato = buf.slice(separatePoint), array = mae;
array = array.concat(exifArray);
array = array.concat(ato);
return array;
};
ExifRestorer.slice2Segments = function(rawImageArray) {
var head = 0, segments = [];
while (1) {
if (rawImageArray[head] == 255 & rawImageArray[head + 1] == 218) {
break;
}
if (rawImageArray[head] == 255 & rawImageArray[head + 1] == 216) {
head += 2;
} else {
var length = rawImageArray[head + 2] * 256 + rawImageArray[head + 3], endPoint = head + length + 2, seg = rawImageArray.slice(head, endPoint);
segments.push(seg);
head = endPoint;
}
if (head > rawImageArray.length) {
break;
}
}
return segments;
};
ExifRestorer.decode64 = function(input) {
var output = "", chr1, chr2, chr3 = "", enc1, enc2, enc3, enc4 = "", i = 0, buf = [];
var base64test = /[^A-Za-z0-9\+\/\=]/g;
if (base64test.exec(input)) {
throw new Error("There were invalid base64 characters in the input text. " + "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='");
}
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
do {
enc1 = this.KEY_STR.indexOf(input.charAt(i++));
enc2 = this.KEY_STR.indexOf(input.charAt(i++));
enc3 = this.KEY_STR.indexOf(input.charAt(i++));
enc4 = this.KEY_STR.indexOf(input.charAt(i++));
chr1 = enc1 << 2 | enc2 >> 4;
chr2 = (enc2 & 15) << 4 | enc3 >> 2;
chr3 = (enc3 & 3) << 6 | enc4;
buf.push(chr1);
if (enc3 != 64) {
buf.push(chr2);
}
if (enc4 != 64) {
buf.push(chr3);
}
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return buf;
};
return ExifRestorer;
}();
qq.TotalProgress = function(callback, getSize) {
"use strict";
var perFileProgress = {}, totalLoaded = 0, totalSize = 0, lastLoadedSent = -1, lastTotalSent = -1, callbackProxy = function(loaded, total) {
if (loaded !== lastLoadedSent || total !== lastTotalSent) {
callback(loaded, total);
}
lastLoadedSent = loaded;
lastTotalSent = total;
}, noRetryableFiles = function(failed, retryable) {
var none = true;
qq.each(failed, function(idx, failedId) {
if (qq.indexOf(retryable, failedId) >= 0) {
none = false;
return false;
}
});
return none;
}, onCancel = function(id) {
updateTotalProgress(id, -1, -1);
delete perFileProgress[id];
}, onAllComplete = function(successful, failed, retryable) {
if (failed.length === 0 || noRetryableFiles(failed, retryable)) {
callbackProxy(totalSize, totalSize);
this.reset();
}
}, onNew = function(id) {
var size = getSize(id);
if (size > 0) {
updateTotalProgress(id, 0, size);
perFileProgress[id] = {
loaded: 0,
total: size
};
}
}, updateTotalProgress = function(id, newLoaded, newTotal) {
var oldLoaded = perFileProgress[id] ? perFileProgress[id].loaded : 0, oldTotal = perFileProgress[id] ? perFileProgress[id].total : 0;
if (newLoaded === -1 && newTotal === -1) {
totalLoaded -= oldLoaded;
totalSize -= oldTotal;
} else {
if (newLoaded) {
totalLoaded += newLoaded - oldLoaded;
}
if (newTotal) {
totalSize += newTotal - oldTotal;
}
}
callbackProxy(totalLoaded, totalSize);
};
qq.extend(this, {
onAllComplete: onAllComplete,
onStatusChange: function(id, oldStatus, newStatus) {
if (newStatus === qq.status.CANCELED || newStatus === qq.status.REJECTED) {
onCancel(id);
} else if (newStatus === qq.status.SUBMITTING) {
onNew(id);
}
},
onIndividualProgress: function(id, loaded, total) {
updateTotalProgress(id, loaded, total);
perFileProgress[id] = {
loaded: loaded,
total: total
};
},
onNewSize: function(id) {
onNew(id);
},
reset: function() {
perFileProgress = {};
totalLoaded = 0;
totalSize = 0;
}
});
};
qq.PasteSupport = function(o) {
"use strict";
var options, detachPasteHandler;
options = {
targetElement: null,
callbacks: {
log: function(message, level) {},
pasteReceived: function(blob) {}
}
};
function isImage(item) {
return item.type && item.type.indexOf("image/") === 0;
}
function registerPasteHandler() {
detachPasteHandler = qq(options.targetElement).attach("paste", function(event) {
var clipboardData = event.clipboardData;
if (clipboardData) {
qq.each(clipboardData.items, function(idx, item) {
if (isImage(item)) {
var blob = item.getAsFile();
options.callbacks.pasteReceived(blob);
}
});
}
});
}
function unregisterPasteHandler() {
if (detachPasteHandler) {
detachPasteHandler();
}
}
qq.extend(options, o);
registerPasteHandler();
qq.extend(this, {
reset: function() {
unregisterPasteHandler();
}
});
};
qq.FormSupport = function(options, startUpload, log) {
"use strict";
var self = this, interceptSubmit = options.interceptSubmit, formEl = options.element, autoUpload = options.autoUpload;
qq.extend(this, {
newEndpoint: null,
newAutoUpload: autoUpload,
attachedToForm: false,
getFormInputsAsObject: function() {
if (formEl == null) {
return null;
}
return self._form2Obj(formEl);
}
});
function determineNewEndpoint(formEl) {
if (formEl.getAttribute("action")) {
self.newEndpoint = formEl.getAttribute("action");
}
}
function validateForm(formEl, nativeSubmit) {
if (formEl.checkValidity && !formEl.checkValidity()) {
log("Form did not pass validation checks - will not upload.", "error");
nativeSubmit();
} else {
return true;
}
}
function maybeUploadOnSubmit(formEl) {
var nativeSubmit = formEl.submit;
qq(formEl).attach("submit", function(event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
validateForm(formEl, nativeSubmit) && startUpload();
});
formEl.submit = function() {
validateForm(formEl, nativeSubmit) && startUpload();
};
}
function determineFormEl(formEl) {
if (formEl) {
if (qq.isString(formEl)) {
formEl = document.getElementById(formEl);
}
if (formEl) {
log("Attaching to form element.");
determineNewEndpoint(formEl);
interceptSubmit && maybeUploadOnSubmit(formEl);
}
}
return formEl;
}
formEl = determineFormEl(formEl);
this.attachedToForm = !!formEl;
};
qq.extend(qq.FormSupport.prototype, {
_form2Obj: function(form) {
"use strict";
var obj = {}, notIrrelevantType = function(type) {
var irrelevantTypes = [ "button", "image", "reset", "submit" ];
return qq.indexOf(irrelevantTypes, type.toLowerCase()) < 0;
}, radioOrCheckbox = function(type) {
return qq.indexOf([ "checkbox", "radio" ], type.toLowerCase()) >= 0;
}, ignoreValue = function(el) {
if (radioOrCheckbox(el.type) && !el.checked) {
return true;
}
return el.disabled && el.type.toLowerCase() !== "hidden";
}, selectValue = function(select) {
var value = null;
qq.each(qq(select).children(), function(idx, child) {
if (child.tagName.toLowerCase() === "option" && child.selected) {
value = child.value;
return false;
}
});
return value;
};
qq.each(form.elements, function(idx, el) {
if ((qq.isInput(el, true) || el.tagName.toLowerCase() === "textarea") && notIrrelevantType(el.type) && !ignoreValue(el)) {
obj[el.name] = el.value;
} else if (el.tagName.toLowerCase() === "select" && !ignoreValue(el)) {
var value = selectValue(el);
if (value !== null) {
obj[el.name] = value;
}
}
});
return obj;
}
});
qq.CryptoJS = function(Math, undefined) {
var C = {};
var C_lib = C.lib = {};
var Base = C_lib.Base = function() {
function F() {}
return {
extend: function(overrides) {
F.prototype = this;
var subtype = new F();
if (overrides) {
subtype.mixIn(overrides);
}
if (!subtype.hasOwnProperty("init")) {
subtype.init = function() {
subtype.$super.init.apply(this, arguments);
};
}
subtype.init.prototype = subtype;
subtype.$super = this;
return subtype;
},
create: function() {
var instance = this.extend();
instance.init.apply(instance, arguments);
return instance;
},
init: function() {},
mixIn: function(properties) {
for (var propertyName in properties) {
if (properties.hasOwnProperty(propertyName)) {
this[propertyName] = properties[propertyName];
}
}
if (properties.hasOwnProperty("toString")) {
this.toString = properties.toString;
}
},
clone: function() {
return this.init.prototype.extend(this);
}
};
}();
var WordArray = C_lib.WordArray = Base.extend({
init: function(words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 4;
}
},
toString: function(encoder) {
return (encoder || Hex).stringify(this);
},
concat: function(wordArray) {
var thisWords = this.words;
var thatWords = wordArray.words;
var thisSigBytes = this.sigBytes;
var thatSigBytes = wordArray.sigBytes;
this.clamp();
if (thisSigBytes % 4) {
for (var i = 0; i < thatSigBytes; i++) {
var thatByte = thatWords[i >>> 2] >>> 24 - i % 4 * 8 & 255;
thisWords[thisSigBytes + i >>> 2] |= thatByte << 24 - (thisSigBytes + i) % 4 * 8;
}
} else if (thatWords.length > 65535) {
for (var i = 0; i < thatSigBytes; i += 4) {
thisWords[thisSigBytes + i >>> 2] = thatWords[i >>> 2];
}
} else {
thisWords.push.apply(thisWords, thatWords);
}
this.sigBytes += thatSigBytes;
return this;
},
clamp: function() {
var words = this.words;
var sigBytes = this.sigBytes;
words[sigBytes >>> 2] &= 4294967295 << 32 - sigBytes % 4 * 8;
words.length = Math.ceil(sigBytes / 4);
},
clone: function() {
var clone = Base.clone.call(this);
clone.words = this.words.slice(0);
return clone;
},
random: function(nBytes) {
var words = [];
for (var i = 0; i < nBytes; i += 4) {
words.push(Math.random() * 4294967296 | 0);
}
return new WordArray.init(words, nBytes);
}
});
var C_enc = C.enc = {};
var Hex = C_enc.Hex = {
stringify: function(wordArray) {
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
var hexChars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = words[i >>> 2] >>> 24 - i % 4 * 8 & 255;
hexChars.push((bite >>> 4).toString(16));
hexChars.push((bite & 15).toString(16));
}
return hexChars.join("");
},
parse: function(hexStr) {
var hexStrLength = hexStr.length;
var words = [];
for (var i = 0; i < hexStrLength; i += 2) {
words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << 24 - i % 8 * 4;
}
return new WordArray.init(words, hexStrLength / 2);
}
};
var Latin1 = C_enc.Latin1 = {
stringify: function(wordArray) {
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
var latin1Chars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = words[i >>> 2] >>> 24 - i % 4 * 8 & 255;
latin1Chars.push(String.fromCharCode(bite));
}
return latin1Chars.join("");
},
parse: function(latin1Str) {
var latin1StrLength = latin1Str.length;
var words = [];
for (var i = 0; i < latin1StrLength; i++) {
words[i >>> 2] |= (latin1Str.charCodeAt(i) & 255) << 24 - i % 4 * 8;
}
return new WordArray.init(words, latin1StrLength);
}
};
var Utf8 = C_enc.Utf8 = {
stringify: function(wordArray) {
try {
return decodeURIComponent(escape(Latin1.stringify(wordArray)));
} catch (e) {
throw new Error("Malformed UTF-8 data");
}
},
parse: function(utf8Str) {
return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
}
};
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
reset: function() {
this._data = new WordArray.init();
this._nDataBytes = 0;
},
_append: function(data) {
if (typeof data == "string") {
data = Utf8.parse(data);
}
this._data.concat(data);
this._nDataBytes += data.sigBytes;
},
_process: function(doFlush) {
var data = this._data;
var dataWords = data.words;
var dataSigBytes = data.sigBytes;
var blockSize = this.blockSize;
var blockSizeBytes = blockSize * 4;
var nBlocksReady = dataSigBytes / blockSizeBytes;
if (doFlush) {
nBlocksReady = Math.ceil(nBlocksReady);
} else {
nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
}
var nWordsReady = nBlocksReady * blockSize;
var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
if (nWordsReady) {
for (var offset = 0; offset < nWordsReady; offset += blockSize) {
this._doProcessBlock(dataWords, offset);
}
var processedWords = dataWords.splice(0, nWordsReady);
data.sigBytes -= nBytesReady;
}
return new WordArray.init(processedWords, nBytesReady);
},
clone: function() {
var clone = Base.clone.call(this);
clone._data = this._data.clone();
return clone;
},
_minBufferSize: 0
});
var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
cfg: Base.extend(),
init: function(cfg) {
this.cfg = this.cfg.extend(cfg);
this.reset();
},
reset: function() {
BufferedBlockAlgorithm.reset.call(this);
this._doReset();
},
update: function(messageUpdate) {
this._append(messageUpdate);
this._process();
return this;
},
finalize: function(messageUpdate) {
if (messageUpdate) {
this._append(messageUpdate);
}
var hash = this._doFinalize();
return hash;
},
blockSize: 512 / 32,
_createHelper: function(hasher) {
return function(message, cfg) {
return new hasher.init(cfg).finalize(message);
};
},
_createHmacHelper: function(hasher) {
return function(message, key) {
return new C_algo.HMAC.init(hasher, key).finalize(message);
};
}
});
var C_algo = C.algo = {};
return C;
}(Math);
(function() {
var C = qq.CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
var Base64 = C_enc.Base64 = {
stringify: function(wordArray) {
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
var map = this._map;
wordArray.clamp();
var base64Chars = [];
for (var i = 0; i < sigBytes; i += 3) {
var byte1 = words[i >>> 2] >>> 24 - i % 4 * 8 & 255;
var byte2 = words[i + 1 >>> 2] >>> 24 - (i + 1) % 4 * 8 & 255;
var byte3 = words[i + 2 >>> 2] >>> 24 - (i + 2) % 4 * 8 & 255;
var triplet = byte1 << 16 | byte2 << 8 | byte3;
for (var j = 0; j < 4 && i + j * .75 < sigBytes; j++) {
base64Chars.push(map.charAt(triplet >>> 6 * (3 - j) & 63));
}
}
var paddingChar = map.charAt(64);
if (paddingChar) {
while (base64Chars.length % 4) {
base64Chars.push(paddingChar);
}
}
return base64Chars.join("");
},
parse: function(base64Str) {
var base64StrLength = base64Str.length;
var map = this._map;
var paddingChar = map.charAt(64);
if (paddingChar) {
var paddingIndex = base64Str.indexOf(paddingChar);
if (paddingIndex != -1) {
base64StrLength = paddingIndex;
}
}
var words = [];
var nBytes = 0;
for (var i = 0; i < base64StrLength; i++) {
if (i % 4) {
var bits1 = map.indexOf(base64Str.charAt(i - 1)) << i % 4 * 2;
var bits2 = map.indexOf(base64Str.charAt(i)) >>> 6 - i % 4 * 2;
words[nBytes >>> 2] |= (bits1 | bits2) << 24 - nBytes % 4 * 8;
nBytes++;
}
}
return WordArray.create(words, nBytes);
},
_map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
};
})();
(function() {
var C = qq.CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var C_algo = C.algo;
var HMAC = C_algo.HMAC = Base.extend({
init: function(hasher, key) {
hasher = this._hasher = new hasher.init();
if (typeof key == "string") {
key = Utf8.parse(key);
}
var hasherBlockSize = hasher.blockSize;
var hasherBlockSizeBytes = hasherBlockSize * 4;
if (key.sigBytes > hasherBlockSizeBytes) {
key = hasher.finalize(key);
}
key.clamp();
var oKey = this._oKey = key.clone();
var iKey = this._iKey = key.clone();
var oKeyWords = oKey.words;
var iKeyWords = iKey.words;
for (var i = 0; i < hasherBlockSize; i++) {
oKeyWords[i] ^= 1549556828;
iKeyWords[i] ^= 909522486;
}
oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
this.reset();
},
reset: function() {
var hasher = this._hasher;
hasher.reset();
hasher.update(this._iKey);
},
update: function(messageUpdate) {
this._hasher.update(messageUpdate);
return this;
},
finalize: function(messageUpdate) {
var hasher = this._hasher;
var innerHash = hasher.finalize(messageUpdate);
hasher.reset();
var hmac = hasher.finalize(this._oKey.clone().concat(innerHash));
return hmac;
}
});
})();
(function() {
var C = qq.CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
var W = [];
var SHA1 = C_algo.SHA1 = Hasher.extend({
_doReset: function() {
this._hash = new WordArray.init([ 1732584193, 4023233417, 2562383102, 271733878, 3285377520 ]);
},
_doProcessBlock: function(M, offset) {
var H = this._hash.words;
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
for (var i = 0; i < 80; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
W[i] = n << 1 | n >>> 31;
}
var t = (a << 5 | a >>> 27) + e + W[i];
if (i < 20) {
t += (b & c | ~b & d) + 1518500249;
} else if (i < 40) {
t += (b ^ c ^ d) + 1859775393;
} else if (i < 60) {
t += (b & c | b & d | c & d) - 1894007588;
} else {
t += (b ^ c ^ d) - 899497514;
}
e = d;
d = c;
c = b << 30 | b >>> 2;
b = a;
a = t;
}
H[0] = H[0] + a | 0;
H[1] = H[1] + b | 0;
H[2] = H[2] + c | 0;
H[3] = H[3] + d | 0;
H[4] = H[4] + e | 0;
},
_doFinalize: function() {
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
dataWords[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
dataWords[(nBitsLeft + 64 >>> 9 << 4) + 14] = Math.floor(nBitsTotal / 4294967296);
dataWords[(nBitsLeft + 64 >>> 9 << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
this._process();
return this._hash;
},
clone: function() {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
C.SHA1 = Hasher._createHelper(SHA1);
C.HmacSHA1 = Hasher._createHmacHelper(SHA1);
})();
(function(Math) {
var C = qq.CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
var H = [];
var K = [];
(function() {
function isPrime(n) {
var sqrtN = Math.sqrt(n);
for (var factor = 2; factor <= sqrtN; factor++) {
if (!(n % factor)) {
return false;
}
}
return true;
}
function getFractionalBits(n) {
return (n - (n | 0)) * 4294967296 | 0;
}
var n = 2;
var nPrime = 0;
while (nPrime < 64) {
if (isPrime(n)) {
if (nPrime < 8) {
H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
}
K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
nPrime++;
}
n++;
}
})();
var W = [];
var SHA256 = C_algo.SHA256 = Hasher.extend({
_doReset: function() {
this._hash = new WordArray.init(H.slice(0));
},
_doProcessBlock: function(M, offset) {
var H = this._hash.words;
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
var f = H[5];
var g = H[6];
var h = H[7];
for (var i = 0; i < 64; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var gamma0x = W[i - 15];
var gamma0 = (gamma0x << 25 | gamma0x >>> 7) ^ (gamma0x << 14 | gamma0x >>> 18) ^ gamma0x >>> 3;
var gamma1x = W[i - 2];
var gamma1 = (gamma1x << 15 | gamma1x >>> 17) ^ (gamma1x << 13 | gamma1x >>> 19) ^ gamma1x >>> 10;
W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
}
var ch = e & f ^ ~e & g;
var maj = a & b ^ a & c ^ b & c;
var sigma0 = (a << 30 | a >>> 2) ^ (a << 19 | a >>> 13) ^ (a << 10 | a >>> 22);
var sigma1 = (e << 26 | e >>> 6) ^ (e << 21 | e >>> 11) ^ (e << 7 | e >>> 25);
var t1 = h + sigma1 + ch + K[i] + W[i];
var t2 = sigma0 + maj;
h = g;
g = f;
f = e;
e = d + t1 | 0;
d = c;
c = b;
b = a;
a = t1 + t2 | 0;
}
H[0] = H[0] + a | 0;
H[1] = H[1] + b | 0;
H[2] = H[2] + c | 0;
H[3] = H[3] + d | 0;
H[4] = H[4] + e | 0;
H[5] = H[5] + f | 0;
H[6] = H[6] + g | 0;
H[7] = H[7] + h | 0;
},
_doFinalize: function() {
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
dataWords[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
dataWords[(nBitsLeft + 64 >>> 9 << 4) + 14] = Math.floor(nBitsTotal / 4294967296);
dataWords[(nBitsLeft + 64 >>> 9 << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
this._process();
return this._hash;
},
clone: function() {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
C.SHA256 = Hasher._createHelper(SHA256);
C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
})(Math);
(function() {
if (typeof ArrayBuffer != "function") {
return;
}
var C = qq.CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var superInit = WordArray.init;
var subInit = WordArray.init = function(typedArray) {
if (typedArray instanceof ArrayBuffer) {
typedArray = new Uint8Array(typedArray);
}
if (typedArray instanceof Int8Array || typedArray instanceof Uint8ClampedArray || typedArray instanceof Int16Array || typedArray instanceof Uint16Array || typedArray instanceof Int32Array || typedArray instanceof Uint32Array || typedArray instanceof Float32Array || typedArray instanceof Float64Array) {
typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
}
if (typedArray instanceof Uint8Array) {
var typedArrayByteLength = typedArray.byteLength;
var words = [];
for (var i = 0; i < typedArrayByteLength; i++) {
words[i >>> 2] |= typedArray[i] << 24 - i % 4 * 8;
}
superInit.call(this, words, typedArrayByteLength);
} else {
superInit.apply(this, arguments);
}
};
subInit.prototype = WordArray;
})();
qq.s3 = qq.s3 || {};
qq.s3.util = qq.s3.util || function() {
"use strict";
return {
ALGORITHM_PARAM_NAME: "x-amz-algorithm",
AWS_PARAM_PREFIX: "x-amz-meta-",
CREDENTIAL_PARAM_NAME: "x-amz-credential",
DATE_PARAM_NAME: "x-amz-date",
REDUCED_REDUNDANCY_PARAM_NAME: "x-amz-storage-class",
REDUCED_REDUNDANCY_PARAM_VALUE: "REDUCED_REDUNDANCY",
SERVER_SIDE_ENCRYPTION_PARAM_NAME: "x-amz-server-side-encryption",
SERVER_SIDE_ENCRYPTION_PARAM_VALUE: "AES256",
SESSION_TOKEN_PARAM_NAME: "x-amz-security-token",
V4_ALGORITHM_PARAM_VALUE: "AWS4-HMAC-SHA256",
V4_SIGNATURE_PARAM_NAME: "x-amz-signature",
CASE_SENSITIVE_PARAM_NAMES: [ "Cache-Control", "Content-Disposition", "Content-Encoding", "Content-MD5" ],
UNSIGNABLE_REST_HEADER_NAMES: [ "Cache-Control", "Content-Disposition", "Content-Encoding", "Content-MD5" ],
UNPREFIXED_PARAM_NAMES: [ "Cache-Control", "Content-Disposition", "Content-Encoding", "Content-MD5", "x-amz-server-side-encryption-customer-algorithm", "x-amz-server-side-encryption-customer-key", "x-amz-server-side-encryption-customer-key-MD5" ],
getBucket: function(endpoint) {
var patterns = [ /^(?:https?:\/\/)?([a-z0-9.\-_]+)\.s3(?:-[a-z0-9\-]+)?\.amazonaws\.com/i, /^(?:https?:\/\/)?s3(?:-[a-z0-9\-]+)?\.amazonaws\.com\/([a-z0-9.\-_]+)/i, /^(?:https?:\/\/)?([a-z0-9.\-_]+)/i ], bucket;
qq.each(patterns, function(idx, pattern) {
var match = pattern.exec(endpoint);
if (match) {
bucket = match[1];
return false;
}
});
return bucket;
},
_getPrefixedParamName: function(name) {
if (qq.indexOf(qq.s3.util.UNPREFIXED_PARAM_NAMES, name) >= 0) {
return name;
}
return qq.s3.util.AWS_PARAM_PREFIX + name;
},
getPolicy: function(spec) {
var policy = {}, conditions = [], bucket = spec.bucket, date = spec.date, drift = spec.clockDrift, key = spec.key, accessKey = spec.accessKey, acl = spec.acl, type = spec.type, expectedStatus = spec.expectedStatus, sessionToken = spec.sessionToken, params = spec.params, successRedirectUrl = qq.s3.util.getSuccessRedirectAbsoluteUrl(spec.successRedirectUrl), minFileSize = spec.minFileSize, maxFileSize = spec.maxFileSize, reducedRedundancy = spec.reducedRedundancy, region = spec.region, serverSideEncryption = spec.serverSideEncryption, signatureVersion = spec.signatureVersion;
policy.expiration = qq.s3.util.getPolicyExpirationDate(date, drift);
conditions.push({
acl: acl
});
conditions.push({
bucket: bucket
});
if (type) {
conditions.push({
"Content-Type": type
});
}
if (expectedStatus) {
conditions.push({
success_action_status: expectedStatus.toString()
});
}
if (successRedirectUrl) {
conditions.push({
success_action_redirect: successRedirectUrl
});
}
if (reducedRedundancy) {
conditions.push({});
conditions[conditions.length - 1][qq.s3.util.REDUCED_REDUNDANCY_PARAM_NAME] = qq.s3.util.REDUCED_REDUNDANCY_PARAM_VALUE;
}
if (sessionToken) {
conditions.push({});
conditions[conditions.length - 1][qq.s3.util.SESSION_TOKEN_PARAM_NAME] = sessionToken;
}
if (serverSideEncryption) {
conditions.push({});
conditions[conditions.length - 1][qq.s3.util.SERVER_SIDE_ENCRYPTION_PARAM_NAME] = qq.s3.util.SERVER_SIDE_ENCRYPTION_PARAM_VALUE;
}
if (signatureVersion === 2) {
conditions.push({
key: key
});
} else if (signatureVersion === 4) {
conditions.push({});
conditions[conditions.length - 1][qq.s3.util.ALGORITHM_PARAM_NAME] = qq.s3.util.V4_ALGORITHM_PARAM_VALUE;
conditions.push({});
conditions[conditions.length - 1].key = key;
conditions.push({});
conditions[conditions.length - 1][qq.s3.util.CREDENTIAL_PARAM_NAME] = qq.s3.util.getV4CredentialsString({
date: date,
key: accessKey,
region: region
});
conditions.push({});
conditions[conditions.length - 1][qq.s3.util.DATE_PARAM_NAME] = qq.s3.util.getV4PolicyDate(date, drift);
}
qq.each(params, function(name, val) {
var awsParamName = qq.s3.util._getPrefixedParamName(name), param = {};
if (qq.indexOf(qq.s3.util.UNPREFIXED_PARAM_NAMES, awsParamName) >= 0) {
param[awsParamName] = val;
} else {
param[awsParamName] = encodeURIComponent(val);
}
conditions.push(param);
});
policy.conditions = conditions;
qq.s3.util.enforceSizeLimits(policy, minFileSize, maxFileSize);
return policy;
},
refreshPolicyCredentials: function(policy, newSessionToken) {
var sessionTokenFound = false;
qq.each(policy.conditions, function(oldCondIdx, oldCondObj) {
qq.each(oldCondObj, function(oldCondName, oldCondVal) {
if (oldCondName === qq.s3.util.SESSION_TOKEN_PARAM_NAME) {
oldCondObj[oldCondName] = newSessionToken;
sessionTokenFound = true;
}
});
});
if (!sessionTokenFound) {
policy.conditions.push({});
policy.conditions[policy.conditions.length - 1][qq.s3.util.SESSION_TOKEN_PARAM_NAME] = newSessionToken;
}
},
generateAwsParams: function(spec, signPolicyCallback) {
var awsParams = {}, customParams = spec.params, promise = new qq.Promise(), sessionToken = spec.sessionToken, drift = spec.clockDrift, type = spec.type, key = spec.key, accessKey = spec.accessKey, acl = spec.acl, expectedStatus = spec.expectedStatus, successRedirectUrl = qq.s3.util.getSuccessRedirectAbsoluteUrl(spec.successRedirectUrl), reducedRedundancy = spec.reducedRedundancy, region = spec.region, serverSideEncryption = spec.serverSideEncryption, signatureVersion = spec.signatureVersion, now = new Date(), log = spec.log, policyJson;
spec.date = now;
policyJson = qq.s3.util.getPolicy(spec);
awsParams.key = key;
if (type) {
awsParams["Content-Type"] = type;
}
if (expectedStatus) {
awsParams.success_action_status = expectedStatus;
}
if (successRedirectUrl) {
awsParams.success_action_redirect = successRedirectUrl;
}
if (reducedRedundancy) {
awsParams[qq.s3.util.REDUCED_REDUNDANCY_PARAM_NAME] = qq.s3.util.REDUCED_REDUNDANCY_PARAM_VALUE;
}
if (serverSideEncryption) {
awsParams[qq.s3.util.SERVER_SIDE_ENCRYPTION_PARAM_NAME] = qq.s3.util.SERVER_SIDE_ENCRYPTION_PARAM_VALUE;
}
if (sessionToken) {
awsParams[qq.s3.util.SESSION_TOKEN_PARAM_NAME] = sessionToken;
}
awsParams.acl = acl;
qq.each(customParams, function(name, val) {
var awsParamName = qq.s3.util._getPrefixedParamName(name);
if (qq.indexOf(qq.s3.util.UNPREFIXED_PARAM_NAMES, awsParamName) >= 0) {
awsParams[awsParamName] = val;
} else {
awsParams[awsParamName] = encodeURIComponent(val);
}
});
if (signatureVersion === 2) {
awsParams.AWSAccessKeyId = accessKey;
} else if (signatureVersion === 4) {
awsParams[qq.s3.util.ALGORITHM_PARAM_NAME] = qq.s3.util.V4_ALGORITHM_PARAM_VALUE;
awsParams[qq.s3.util.CREDENTIAL_PARAM_NAME] = qq.s3.util.getV4CredentialsString({
date: now,
key: accessKey,
region: region
});
awsParams[qq.s3.util.DATE_PARAM_NAME] = qq.s3.util.getV4PolicyDate(now, drift);
}
signPolicyCallback(policyJson).then(function(policyAndSignature, updatedAccessKey, updatedSessionToken) {
awsParams.policy = policyAndSignature.policy;
if (spec.signatureVersion === 2) {
awsParams.signature = policyAndSignature.signature;
if (updatedAccessKey) {
awsParams.AWSAccessKeyId = updatedAccessKey;
}
} else if (spec.signatureVersion === 4) {
awsParams[qq.s3.util.V4_SIGNATURE_PARAM_NAME] = policyAndSignature.signature;
}
if (updatedSessionToken) {
awsParams[qq.s3.util.SESSION_TOKEN_PARAM_NAME] = updatedSessionToken;
}
promise.success(awsParams);
}, function(errorMessage) {
errorMessage = errorMessage || "Can't continue further with request to S3 as we did not receive " + "a valid signature and policy from the server.";
log("Policy signing failed. " + errorMessage, "error");
promise.failure(errorMessage);
});
return promise;
},
enforceSizeLimits: function(policy, minSize, maxSize) {
var adjustedMinSize = minSize < 0 ? 0 : minSize, adjustedMaxSize = maxSize <= 0 ? 9007199254740992 : maxSize;
if (minSize > 0 || maxSize > 0) {
policy.conditions.push([ "content-length-range", adjustedMinSize.toString(), adjustedMaxSize.toString() ]);
}
},
getPolicyExpirationDate: function(date, drift) {
var adjustedDate = new Date(date.getTime() + drift);
return qq.s3.util.getPolicyDate(adjustedDate, 5);
},
getCredentialsDate: function(date) {
return date.getUTCFullYear() + "" + ("0" + (date.getUTCMonth() + 1)).slice(-2) + ("0" + date.getUTCDate()).slice(-2);
},
getPolicyDate: function(date, _minutesToAdd_) {
var minutesToAdd = _minutesToAdd_ || 0, pad, r;
date.setMinutes(date.getMinutes() + (minutesToAdd || 0));
if (Date.prototype.toISOString) {
return date.toISOString();
} else {
pad = function(number) {
r = String(number);
if (r.length === 1) {
r = "0" + r;
}
return r;
};
return date.getUTCFullYear() + "-" + pad(date.getUTCMonth() + 1) + "-" + pad(date.getUTCDate()) + "T" + pad(date.getUTCHours()) + ":" + pad(date.getUTCMinutes()) + ":" + pad(date.getUTCSeconds()) + "." + String((date.getUTCMilliseconds() / 1e3).toFixed(3)).slice(2, 5) + "Z";
}
},
parseIframeResponse: function(iframe) {
var doc = iframe.contentDocument || iframe.contentWindow.document, queryString = doc.location.search, match = /bucket=(.+)&key=(.+)&etag=(.+)/.exec(queryString);
if (match) {
return {
bucket: match[1],
key: match[2],
etag: match[3].replace(/%22/g, "")
};
}
},
getSuccessRedirectAbsoluteUrl: function(successRedirectUrl) {
if (successRedirectUrl) {
var targetAnchorContainer = document.createElement("div"), targetAnchor;
if (qq.ie7()) {
targetAnchorContainer.innerHTML = "<a href='" + successRedirectUrl + "'></a>";
targetAnchor = targetAnchorContainer.firstChild;
return targetAnchor.href;
} else {
targetAnchor = document.createElement("a");
targetAnchor.href = successRedirectUrl;
targetAnchor.href = targetAnchor.href;
return targetAnchor.href;
}
}
},
getV4CredentialsString: function(spec) {
return spec.key + "/" + qq.s3.util.getCredentialsDate(spec.date) + "/" + spec.region + "/s3/aws4_request";
},
getV4PolicyDate: function(date, drift) {
var adjustedDate = new Date(date.getTime() + drift);
return qq.s3.util.getCredentialsDate(adjustedDate) + "T" + ("0" + adjustedDate.getUTCHours()).slice(-2) + ("0" + adjustedDate.getUTCMinutes()).slice(-2) + ("0" + adjustedDate.getUTCSeconds()).slice(-2) + "Z";
},
encodeQueryStringParam: function(param) {
var percentEncoded = encodeURIComponent(param);
percentEncoded = percentEncoded.replace(/[!'()]/g, escape);
percentEncoded = percentEncoded.replace(/\*/g, "%2A");
return percentEncoded.replace(/%20/g, "+");
}
};
}();
(function() {
"use strict";
qq.nonTraditionalBasePublicApi = {
setUploadSuccessParams: function(params, id) {
this._uploadSuccessParamsStore.set(params, id);
},
setUploadSuccessEndpoint: function(endpoint, id) {
this._uploadSuccessEndpointStore.set(endpoint, id);
}
};
qq.nonTraditionalBasePrivateApi = {
_onComplete: function(id, name, result, xhr) {
var success = result.success ? true : false, self = this, onCompleteArgs = arguments, successEndpoint = this._uploadSuccessEndpointStore.get(id), successCustomHeaders = this._options.uploadSuccess.customHeaders, successMethod = this._options.uploadSuccess.method, cors = this._options.cors, promise = new qq.Promise(), uploadSuccessParams = this._uploadSuccessParamsStore.get(id), fileParams = this._paramsStore.get(id), onSuccessFromServer = function(successRequestResult) {
delete self._failedSuccessRequestCallbacks[id];
qq.extend(result, successRequestResult);
qq.FineUploaderBasic.prototype._onComplete.apply(self, onCompleteArgs);
promise.success(successRequestResult);
}, onFailureFromServer = function(successRequestResult) {
var callback = submitSuccessRequest;
qq.extend(result, successRequestResult);
if (result && result.reset) {
callback = null;
}
if (!callback) {
delete self._failedSuccessRequestCallbacks[id];
} else {
self._failedSuccessRequestCallbacks[id] = callback;
}
if (!self._onAutoRetry(id, name, result, xhr, callback)) {
qq.FineUploaderBasic.prototype._onComplete.apply(self, onCompleteArgs);
promise.failure(successRequestResult);
}
}, submitSuccessRequest, successAjaxRequester;
if (success && successEndpoint) {
successAjaxRequester = new qq.UploadSuccessAjaxRequester({
endpoint: successEndpoint,
method: successMethod,
customHeaders: successCustomHeaders,
cors: cors,
log: qq.bind(this.log, this)
});
qq.extend(uploadSuccessParams, self._getEndpointSpecificParams(id, result, xhr), true);
fileParams && qq.extend(uploadSuccessParams, fileParams, true);
submitSuccessRequest = qq.bind(function() {
successAjaxRequester.sendSuccessRequest(id, uploadSuccessParams).then(onSuccessFromServer, onFailureFromServer);
}, self);
submitSuccessRequest();
return promise;
}
return qq.FineUploaderBasic.prototype._onComplete.apply(this, arguments);
},
_manualRetry: function(id) {
var successRequestCallback = this._failedSuccessRequestCallbacks[id];
return qq.FineUploaderBasic.prototype._manualRetry.call(this, id, successRequestCallback);
}
};
})();
(function() {
"use strict";
qq.s3.FineUploaderBasic = function(o) {
var options = {
request: {
accessKey: null,
clockDrift: 0
},
objectProperties: {
acl: "private",
bucket: qq.bind(function(id) {
return qq.s3.util.getBucket(this.getEndpoint(id));
}, this),
host: qq.bind(function(id) {
return /(?:http|https):\/\/(.+)(?:\/.+)?/.exec(this._endpointStore.get(id))[1];
}, this),
key: "uuid",
reducedRedundancy: false,
region: "us-east-1",
serverSideEncryption: false
},
credentials: {
accessKey: null,
secretKey: null,
expiration: null,
sessionToken: null
},
signature: {
customHeaders: {},
endpoint: null,
version: 2
},
uploadSuccess: {
endpoint: null,
method: "POST",
params: {},
customHeaders: {}
},
iframeSupport: {
localBlankPagePath: null
},
chunking: {
partSize: 5242880
},
cors: {
allowXdr: true
},
callbacks: {
onCredentialsExpired: function() {}
}
};
qq.extend(options, o, true);
if (!this.setCredentials(options.credentials, true)) {
this._currentCredentials.accessKey = options.request.accessKey;
}
this._aclStore = this._createStore(options.objectProperties.acl);
qq.FineUploaderBasic.call(this, options);
this._uploadSuccessParamsStore = this._createStore(this._options.uploadSuccess.params);
this._uploadSuccessEndpointStore = this._createStore(this._options.uploadSuccess.endpoint);
this._failedSuccessRequestCallbacks = {};
this._cannedKeys = {};
this._cannedBuckets = {};
this._buckets = {};
this._hosts = {};
};
qq.extend(qq.s3.FineUploaderBasic.prototype, qq.basePublicApi);
qq.extend(qq.s3.FineUploaderBasic.prototype, qq.basePrivateApi);
qq.extend(qq.s3.FineUploaderBasic.prototype, qq.nonTraditionalBasePublicApi);
qq.extend(qq.s3.FineUploaderBasic.prototype, qq.nonTraditionalBasePrivateApi);
qq.extend(qq.s3.FineUploaderBasic.prototype, {
getBucket: function(id) {
if (this._cannedBuckets[id] == null) {
return this._buckets[id];
}
return this._cannedBuckets[id];
},
getKey: function(id) {
if (this._cannedKeys[id] == null) {
return this._handler.getThirdPartyFileId(id);
}
return this._cannedKeys[id];
},
reset: function() {
qq.FineUploaderBasic.prototype.reset.call(this);
this._failedSuccessRequestCallbacks = [];
this._buckets = {};
this._hosts = {};
},
setCredentials: function(credentials, ignoreEmpty) {
if (credentials && credentials.secretKey) {
if (!credentials.accessKey) {
throw new qq.Error("Invalid credentials: no accessKey");
} else if (!credentials.expiration) {
throw new qq.Error("Invalid credentials: no expiration");
} else {
this._currentCredentials = qq.extend({}, credentials);
if (qq.isString(credentials.expiration)) {
this._currentCredentials.expiration = new Date(credentials.expiration);
}
}
return true;
} else if (!ignoreEmpty) {
throw new qq.Error("Invalid credentials parameter!");
} else {
this._currentCredentials = {};
}
},
setAcl: function(acl, id) {
this._aclStore.set(acl, id);
},
_createUploadHandler: function() {
var self = this, additionalOptions = {
aclStore: this._aclStore,
getBucket: qq.bind(this._determineBucket, this),
getHost: qq.bind(this._determineHost, this),
getKeyName: qq.bind(this._determineKeyName, this),
iframeSupport: this._options.iframeSupport,
objectProperties: this._options.objectProperties,
signature: this._options.signature,
clockDrift: this._options.request.clockDrift,
validation: {
minSizeLimit: this._options.validation.minSizeLimit,
maxSizeLimit: this._options.validation.sizeLimit
}
};
qq.override(this._endpointStore, function(super_) {
return {
get: function(id) {
var endpoint = super_.get(id);
if (endpoint.indexOf("http") < 0) {
return "http://" + endpoint;
}
return endpoint;
}
};
});
qq.override(this._paramsStore, function(super_) {
return {
get: function(id) {
var oldParams = super_.get(id), modifiedParams = {};
qq.each(oldParams, function(name, val) {
var paramName = name;
if (qq.indexOf(qq.s3.util.CASE_SENSITIVE_PARAM_NAMES, paramName) < 0) {
paramName = paramName.toLowerCase();
}
modifiedParams[paramName] = qq.isFunction(val) ? val() : val;
});
return modifiedParams;
}
};
});
additionalOptions.signature.credentialsProvider = {
get: function() {
return self._currentCredentials;
},
onExpired: function() {
var updateCredentials = new qq.Promise(), callbackRetVal = self._options.callbacks.onCredentialsExpired();
if (qq.isGenericPromise(callbackRetVal)) {
callbackRetVal.then(function(credentials) {
try {
self.setCredentials(credentials);
updateCredentials.success();
} catch (error) {
self.log("Invalid credentials returned from onCredentialsExpired callback! (" + error.message + ")", "error");
updateCredentials.failure("onCredentialsExpired did not return valid credentials.");
}
}, function(errorMsg) {
self.log("onCredentialsExpired callback indicated failure! (" + errorMsg + ")", "error");
updateCredentials.failure("onCredentialsExpired callback failed.");
});
} else {
self.log("onCredentialsExpired callback did not return a promise!", "error");
updateCredentials.failure("Unexpected return value for onCredentialsExpired.");
}
return updateCredentials;
}
};
return qq.FineUploaderBasic.prototype._createUploadHandler.call(this, additionalOptions, "s3");
},
_determineObjectPropertyValue: function(id, property) {
var maybe = this._options.objectProperties[property], promise = new qq.Promise(), self = this;
if (qq.isFunction(maybe)) {
maybe = maybe(id);
if (qq.isGenericPromise(maybe)) {
promise = maybe;
} else {
promise.success(maybe);
}
} else if (qq.isString(maybe)) {
promise.success(maybe);
}
promise.then(function success(value) {
self["_" + property + "s"][id] = value;
}, function failure(errorMsg) {
qq.log("Problem determining " + property + " for ID " + id + " (" + errorMsg + ")", "error");
});
return promise;
},
_determineBucket: function(id) {
return this._determineObjectPropertyValue(id, "bucket");
},
_determineHost: function(id) {
return this._determineObjectPropertyValue(id, "host");
},
_determineKeyName: function(id, filename) {
var promise = new qq.Promise(), keynameLogic = this._options.objectProperties.key, extension = qq.getExtension(filename), onGetKeynameFailure = promise.failure, onGetKeynameSuccess = function(keyname, extension) {
var keynameToUse = keyname;
if (extension !== undefined) {
keynameToUse += "." + extension;
}
promise.success(keynameToUse);
};
switch (keynameLogic) {
case "uuid":
onGetKeynameSuccess(this.getUuid(id), extension);
break;
case "filename":
onGetKeynameSuccess(filename);
break;
default:
if (qq.isFunction(keynameLogic)) {
this._handleKeynameFunction(keynameLogic, id, onGetKeynameSuccess, onGetKeynameFailure);
} else {
this.log(keynameLogic + " is not a valid value for the s3.keyname option!", "error");
onGetKeynameFailure();
}
}
return promise;
},
_handleKeynameFunction: function(keynameFunc, id, successCallback, failureCallback) {
var self = this, onSuccess = function(keyname) {
successCallback(keyname);
}, onFailure = function(reason) {
self.log(qq.format("Failed to retrieve key name for {}. Reason: {}", id, reason || "null"), "error");
failureCallback(reason);
}, keyname = keynameFunc.call(this, id);
if (qq.isGenericPromise(keyname)) {
keyname.then(onSuccess, onFailure);
} else if (keyname == null) {
onFailure();
} else {
onSuccess(keyname);
}
},
_getEndpointSpecificParams: function(id, response, maybeXhr) {
var params = {
key: this.getKey(id),
uuid: this.getUuid(id),
name: this.getName(id),
bucket: this.getBucket(id)
};
if (maybeXhr && maybeXhr.getResponseHeader("ETag")) {
params.etag = maybeXhr.getResponseHeader("ETag");
} else if (response.etag) {
params.etag = response.etag;
}
return params;
},
_onSubmitDelete: function(id, onSuccessCallback) {
var additionalMandatedParams = {
key: this.getKey(id),
bucket: this.getBucket(id)
};
return qq.FineUploaderBasic.prototype._onSubmitDelete.call(this, id, onSuccessCallback, additionalMandatedParams);
},
_addCannedFile: function(sessionData) {
var id;
if (sessionData.s3Key == null) {
throw new qq.Error("Did not find s3Key property in server session response. This is required!");
} else {
id = qq.FineUploaderBasic.prototype._addCannedFile.apply(this, arguments);
this._cannedKeys[id] = sessionData.s3Key;
this._cannedBuckets[id] = sessionData.s3Bucket;
}
return id;
}
});
})();
if (!window.Uint8ClampedArray) {
window.Uint8ClampedArray = function() {};
}
qq.s3.RequestSigner = function(o) {
"use strict";
var requester, thisSignatureRequester = this, pendingSignatures = {}, options = {
expectingPolicy: false,
method: "POST",
signatureSpec: {
drift: 0,
credentialsProvider: {},
endpoint: null,
customHeaders: {},
version: 2
},
maxConnections: 3,
endpointStore: {},
paramsStore: {},
cors: {
expected: false,
sendCredentials: false
},
log: function(str, level) {}
}, credentialsProvider, generateHeaders = function(signatureConstructor, signature, promise) {
var headers = signatureConstructor.getHeaders();
if (options.signatureSpec.version === 4) {
headers.Authorization = qq.s3.util.V4_ALGORITHM_PARAM_VALUE + " Credential=" + options.signatureSpec.credentialsProvider.get().accessKey + "/" + qq.s3.util.getCredentialsDate(signatureConstructor.getRequestDate()) + "/" + options.signatureSpec.region + "/" + "s3/aws4_request," + "SignedHeaders=" + signatureConstructor.getSignedHeaders() + "," + "Signature=" + signature;
} else {
headers.Authorization = "AWS " + options.signatureSpec.credentialsProvider.get().accessKey + ":" + signature;
}
promise.success(headers, signatureConstructor.getEndOfUrl());
}, v2 = {
getStringToSign: function(signatureSpec) {
return qq.format("{}\n{}\n{}\n\n{}/{}/{}", signatureSpec.method, signatureSpec.contentMd5 || "", signatureSpec.contentType || "", signatureSpec.headersStr || "\n", signatureSpec.bucket, signatureSpec.endOfUrl);
},
signApiRequest: function(signatureConstructor, headersStr, signatureEffort) {
var headersWordArray = qq.CryptoJS.enc.Utf8.parse(headersStr), headersHmacSha1 = qq.CryptoJS.HmacSHA1(headersWordArray, credentialsProvider.get().secretKey), headersHmacSha1Base64 = qq.CryptoJS.enc.Base64.stringify(headersHmacSha1);
generateHeaders(signatureConstructor, headersHmacSha1Base64, signatureEffort);
},
signPolicy: function(policy, signatureEffort, updatedAccessKey, updatedSessionToken) {
var policyStr = JSON.stringify(policy), policyWordArray = qq.CryptoJS.enc.Utf8.parse(policyStr), base64Policy = qq.CryptoJS.enc.Base64.stringify(policyWordArray), policyHmacSha1 = qq.CryptoJS.HmacSHA1(base64Policy, credentialsProvider.get().secretKey), policyHmacSha1Base64 = qq.CryptoJS.enc.Base64.stringify(policyHmacSha1);
signatureEffort.success({
policy: base64Policy,
signature: policyHmacSha1Base64
}, updatedAccessKey, updatedSessionToken);
}
}, v4 = {
getCanonicalQueryString: function(endOfUri) {
var queryParamIdx = endOfUri.indexOf("?"), canonicalQueryString = "", encodedQueryParams, encodedQueryParamNames, queryStrings;
if (queryParamIdx >= 0) {
encodedQueryParams = {};
queryStrings = endOfUri.substr(queryParamIdx + 1).split("&");
qq.each(queryStrings, function(idx, queryString) {
var nameAndVal = queryString.split("="), paramVal = nameAndVal[1];
if (paramVal == null) {
paramVal = "";
}
encodedQueryParams[encodeURIComponent(nameAndVal[0])] = encodeURIComponent(paramVal);
});
encodedQueryParamNames = Object.keys(encodedQueryParams).sort();
encodedQueryParamNames.forEach(function(encodedQueryParamName, idx) {
canonicalQueryString += encodedQueryParamName + "=" + encodedQueryParams[encodedQueryParamName];
if (idx < encodedQueryParamNames.length - 1) {
canonicalQueryString += "&";
}
});
}
return canonicalQueryString;
},
getCanonicalRequest: function(signatureSpec) {
return qq.format("{}\n{}\n{}\n{}\n{}\n{}", signatureSpec.method, v4.getCanonicalUri(signatureSpec.endOfUrl), v4.getCanonicalQueryString(signatureSpec.endOfUrl), signatureSpec.headersStr || "\n", v4.getSignedHeaders(signatureSpec.headerNames), signatureSpec.hashedContent);
},
getCanonicalUri: function(endOfUri) {
var path = endOfUri, queryParamIdx = endOfUri.indexOf("?");
if (queryParamIdx > 0) {
path = endOfUri.substr(0, queryParamIdx);
}
return escape("/" + decodeURIComponent(path));
},
getEncodedHashedPayload: function(body) {
var promise = new qq.Promise(), reader;
if (qq.isBlob(body)) {
reader = new FileReader();
reader.onloadend = function(e) {
if (e.target.readyState === FileReader.DONE) {
if (e.target.error) {
promise.failure(e.target.error);
} else {
var wordArray = qq.CryptoJS.lib.WordArray.create(e.target.result);
promise.success(qq.CryptoJS.SHA256(wordArray).toString());
}
}
};
reader.readAsArrayBuffer(body);
} else {
body = body || "";
promise.success(qq.CryptoJS.SHA256(body).toString());
}
return promise;
},
getScope: function(date, region) {
return qq.s3.util.getCredentialsDate(date) + "/" + region + "/s3/aws4_request";
},
getStringToSign: function(signatureSpec) {
var canonicalRequest = v4.getCanonicalRequest(signatureSpec), date = qq.s3.util.getV4PolicyDate(signatureSpec.date, signatureSpec.drift), hashedRequest = qq.CryptoJS.SHA256(canonicalRequest).toString(), scope = v4.getScope(signatureSpec.date, options.signatureSpec.region), stringToSignTemplate = "AWS4-HMAC-SHA256\n{}\n{}\n{}";
return {
hashed: qq.format(stringToSignTemplate, date, scope, hashedRequest),
raw: qq.format(stringToSignTemplate, date, scope, canonicalRequest)
};
},
getSignedHeaders: function(headerNames) {
var signedHeaders = "";
headerNames.forEach(function(headerName, idx) {
signedHeaders += headerName.toLowerCase();
if (idx < headerNames.length - 1) {
signedHeaders += ";";
}
});
return signedHeaders;
},
signApiRequest: function(signatureConstructor, headersStr, signatureEffort) {
var secretKey = credentialsProvider.get().secretKey, headersPattern = /.+\n.+\n(\d+)\/(.+)\/s3\/.+\n(.+)/, matches = headersPattern.exec(headersStr), dateKey, dateRegionKey, dateRegionServiceKey, signingKey;
dateKey = qq.CryptoJS.HmacSHA256(matches[1], "AWS4" + secretKey);
dateRegionKey = qq.CryptoJS.HmacSHA256(matches[2], dateKey);
dateRegionServiceKey = qq.CryptoJS.HmacSHA256("s3", dateRegionKey);
signingKey = qq.CryptoJS.HmacSHA256("aws4_request", dateRegionServiceKey);
generateHeaders(signatureConstructor, qq.CryptoJS.HmacSHA256(headersStr, signingKey), signatureEffort);
},
signPolicy: function(policy, signatureEffort, updatedAccessKey, updatedSessionToken) {
var policyStr = JSON.stringify(policy), policyWordArray = qq.CryptoJS.enc.Utf8.parse(policyStr), base64Policy = qq.CryptoJS.enc.Base64.stringify(policyWordArray), secretKey = credentialsProvider.get().secretKey, credentialPattern = /.+\/(.+)\/(.+)\/s3\/aws4_request/, credentialCondition = function() {
var credential = null;
qq.each(policy.conditions, function(key, condition) {
var val = condition["x-amz-credential"];
if (val) {
credential = val;
return false;
}
});
return credential;
}(), matches, dateKey, dateRegionKey, dateRegionServiceKey, signingKey;
matches = credentialPattern.exec(credentialCondition);
dateKey = qq.CryptoJS.HmacSHA256(matches[1], "AWS4" + secretKey);
dateRegionKey = qq.CryptoJS.HmacSHA256(matches[2], dateKey);
dateRegionServiceKey = qq.CryptoJS.HmacSHA256("s3", dateRegionKey);
signingKey = qq.CryptoJS.HmacSHA256("aws4_request", dateRegionServiceKey);
signatureEffort.success({
policy: base64Policy,
signature: qq.CryptoJS.HmacSHA256(base64Policy, signingKey).toString()
}, updatedAccessKey, updatedSessionToken);
}
};
qq.extend(options, o, true);
credentialsProvider = options.signatureSpec.credentialsProvider;
function handleSignatureReceived(id, xhrOrXdr, isError) {
var responseJson = xhrOrXdr.responseText, pendingSignatureData = pendingSignatures[id], promise = pendingSignatureData.promise, signatureConstructor = pendingSignatureData.signatureConstructor, errorMessage, response;
delete pendingSignatures[id];
if (responseJson) {
try {
response = qq.parseJson(responseJson);
} catch (error) {
options.log("Error attempting to parse signature response: " + error, "error");
}
}
if (response && response.invalid) {
isError = true;
errorMessage = "Invalid policy document or request headers!";
} else if (response) {
if (options.expectingPolicy && !response.policy) {
isError = true;
errorMessage = "Response does not include the base64 encoded policy!";
} else if (!response.signature) {
isError = true;
errorMessage = "Response does not include the signature!";
}
} else {
isError = true;
errorMessage = "Received an empty or invalid response from the server!";
}
if (isError) {
if (errorMessage) {
options.log(errorMessage, "error");
}
promise.failure(errorMessage);
} else if (signatureConstructor) {
generateHeaders(signatureConstructor, response.signature, promise);
} else {
promise.success(response);
}
}
function getStringToSignArtifacts(id, version, requestInfo) {
var promise = new qq.Promise(), method = "POST", headerNames = [], headersStr = "", now = new Date(), endOfUrl, signatureSpec, toSign, generateStringToSign = function(requestInfo) {
var contentMd5, headerIndexesToRemove = [];
qq.each(requestInfo.headers, function(name) {
headerNames.push(name);
});
headerNames.sort();
qq.each(headerNames, function(idx, headerName) {
if (qq.indexOf(qq.s3.util.UNSIGNABLE_REST_HEADER_NAMES, headerName) < 0) {
headersStr += headerName.toLowerCase() + ":" + requestInfo.headers[headerName].trim() + "\n";
} else if (headerName === "Content-MD5") {
contentMd5 = requestInfo.headers[headerName];
} else {
headerIndexesToRemove.unshift(idx);
}
});
qq.each(headerIndexesToRemove, function(idx, headerIdx) {
headerNames.splice(headerIdx, 1);
});
signatureSpec = {
bucket: requestInfo.bucket,
contentMd5: contentMd5,
contentType: requestInfo.contentType,
date: now,
drift: options.signatureSpec.drift,
endOfUrl: endOfUrl,
hashedContent: requestInfo.hashedContent,
headerNames: headerNames,
headersStr: headersStr,
method: method
};
toSign = version === 2 ? v2.getStringToSign(signatureSpec) : v4.getStringToSign(signatureSpec);
return {
date: now,
endOfUrl: endOfUrl,
signedHeaders: version === 4 ? v4.getSignedHeaders(signatureSpec.headerNames) : null,
toSign: version === 4 ? toSign.hashed : toSign,
toSignRaw: version === 4 ? toSign.raw : toSign
};
};
switch (requestInfo.type) {
case thisSignatureRequester.REQUEST_TYPE.MULTIPART_ABORT:
method = "DELETE";
endOfUrl = qq.format("uploadId={}", requestInfo.uploadId);
break;
case thisSignatureRequester.REQUEST_TYPE.MULTIPART_INITIATE:
endOfUrl = "uploads";
break;
case thisSignatureRequester.REQUEST_TYPE.MULTIPART_COMPLETE:
endOfUrl = qq.format("uploadId={}", requestInfo.uploadId);
break;
case thisSignatureRequester.REQUEST_TYPE.MULTIPART_UPLOAD:
method = "PUT";
endOfUrl = qq.format("partNumber={}&uploadId={}", requestInfo.partNum, requestInfo.uploadId);
break;
}
endOfUrl = requestInfo.key + "?" + endOfUrl;
if (version === 4) {
v4.getEncodedHashedPayload(requestInfo.content).then(function(hashedContent) {
requestInfo.headers["x-amz-content-sha256"] = hashedContent;
requestInfo.headers.Host = requestInfo.host;
requestInfo.headers["x-amz-date"] = qq.s3.util.getV4PolicyDate(now, options.signatureSpec.drift);
requestInfo.hashedContent = hashedContent;
promise.success(generateStringToSign(requestInfo));
});
} else {
promise.success(generateStringToSign(requestInfo));
}
return promise;
}
function determineSignatureClientSide(id, toBeSigned, signatureEffort, updatedAccessKey, updatedSessionToken) {
var updatedHeaders;
if (toBeSigned.signatureConstructor) {
if (updatedSessionToken) {
updatedHeaders = toBeSigned.signatureConstructor.getHeaders();
updatedHeaders[qq.s3.util.SESSION_TOKEN_PARAM_NAME] = updatedSessionToken;
toBeSigned.signatureConstructor.withHeaders(updatedHeaders);
}
toBeSigned.signatureConstructor.getToSign(id).then(function(signatureArtifacts) {
signApiRequest(toBeSigned.signatureConstructor, signatureArtifacts.stringToSign, signatureEffort);
});
} else {
updatedSessionToken && qq.s3.util.refreshPolicyCredentials(toBeSigned, updatedSessionToken);
signPolicy(toBeSigned, signatureEffort, updatedAccessKey, updatedSessionToken);
}
}
function signPolicy(policy, signatureEffort, updatedAccessKey, updatedSessionToken) {
if (options.signatureSpec.version === 4) {
v4.signPolicy(policy, signatureEffort, updatedAccessKey, updatedSessionToken);
} else {
v2.signPolicy(policy, signatureEffort, updatedAccessKey, updatedSessionToken);
}
}
function signApiRequest(signatureConstructor, headersStr, signatureEffort) {
if (options.signatureSpec.version === 4) {
v4.signApiRequest(signatureConstructor, headersStr, signatureEffort);
} else {
v2.signApiRequest(signatureConstructor, headersStr, signatureEffort);
}
}
requester = qq.extend(this, new qq.AjaxRequester({
acceptHeader: "application/json",
method: options.method,
contentType: "application/json; charset=utf-8",
endpointStore: {
get: function() {
return options.signatureSpec.endpoint;
}
},
paramsStore: options.paramsStore,
maxConnections: options.maxConnections,
customHeaders: options.signatureSpec.customHeaders,
log: options.log,
onComplete: handleSignatureReceived,
cors: options.cors
}));
qq.extend(this, {
getSignature: function(id, toBeSigned) {
var params = toBeSigned, signatureConstructor = toBeSigned.signatureConstructor, signatureEffort = new qq.Promise(), queryParams;
if (options.signatureSpec.version === 4) {
queryParams = {
v4: true
};
}
if (credentialsProvider.get().secretKey && qq.CryptoJS) {
if (credentialsProvider.get().expiration.getTime() > Date.now()) {
determineSignatureClientSide(id, toBeSigned, signatureEffort);
} else {
credentialsProvider.onExpired().then(function() {
determineSignatureClientSide(id, toBeSigned, signatureEffort, credentialsProvider.get().accessKey, credentialsProvider.get().sessionToken);
}, function(errorMsg) {
options.log("Attempt to update expired credentials apparently failed! Unable to sign request. ", "error");
signatureEffort.failure("Unable to sign request - expired credentials.");
});
}
} else {
options.log("Submitting S3 signature request for " + id);
if (signatureConstructor) {
signatureConstructor.getToSign(id).then(function(signatureArtifacts) {
params = {
headers: signatureArtifacts.stringToSignRaw
};
requester.initTransport(id).withParams(params).withQueryParams(queryParams).send();
});
} else {
requester.initTransport(id).withParams(params).withQueryParams(queryParams).send();
}
pendingSignatures[id] = {
promise: signatureEffort,
signatureConstructor: signatureConstructor
};
}
return signatureEffort;
},
constructStringToSign: function(type, bucket, host, key) {
var headers = {}, uploadId, content, contentType, partNum, artifacts;
return {
withHeaders: function(theHeaders) {
headers = theHeaders;
return this;
},
withUploadId: function(theUploadId) {
uploadId = theUploadId;
return this;
},
withContent: function(theContent) {
content = theContent;
return this;
},
withContentType: function(theContentType) {
contentType = theContentType;
return this;
},
withPartNum: function(thePartNum) {
partNum = thePartNum;
return this;
},
getToSign: function(id) {
var sessionToken = credentialsProvider.get().sessionToken, promise = new qq.Promise(), adjustedDate = new Date(Date.now() + options.signatureSpec.drift);
headers["x-amz-date"] = adjustedDate.toUTCString();
if (sessionToken) {
headers[qq.s3.util.SESSION_TOKEN_PARAM_NAME] = sessionToken;
}
getStringToSignArtifacts(id, options.signatureSpec.version, {
bucket: bucket,
content: content,
contentType: contentType,
headers: headers,
host: host,
key: key,
partNum: partNum,
type: type,
uploadId: uploadId
}).then(function(_artifacts_) {
artifacts = _artifacts_;
promise.success({
headers: function() {
if (contentType) {
headers["Content-Type"] = contentType;
}
delete headers.Host;
return headers;
}(),
date: artifacts.date,
endOfUrl: artifacts.endOfUrl,
signedHeaders: artifacts.signedHeaders,
stringToSign: artifacts.toSign,
stringToSignRaw: artifacts.toSignRaw
});
});
return promise;
},
getHeaders: function() {
return qq.extend({}, headers);
},
getEndOfUrl: function() {
return artifacts && artifacts.endOfUrl;
},
getRequestDate: function() {
return artifacts && artifacts.date;
},
getSignedHeaders: function() {
return artifacts && artifacts.signedHeaders;
}
};
}
});
};
qq.s3.RequestSigner.prototype.REQUEST_TYPE = {
MULTIPART_INITIATE: "multipart_initiate",
MULTIPART_COMPLETE: "multipart_complete",
MULTIPART_ABORT: "multipart_abort",
MULTIPART_UPLOAD: "multipart_upload"
};
qq.UploadSuccessAjaxRequester = function(o) {
"use strict";
var requester, pendingRequests = [], options = {
method: "POST",
endpoint: null,
maxConnections: 3,
customHeaders: {},
paramsStore: {},
cors: {
expected: false,
sendCredentials: false
},
log: function(str, level) {}
};
qq.extend(options, o);
function handleSuccessResponse(id, xhrOrXdr, isError) {
var promise = pendingRequests[id], responseJson = xhrOrXdr.responseText, successIndicator = {
success: true
}, failureIndicator = {
success: false
}, parsedResponse;
delete pendingRequests[id];
options.log(qq.format("Received the following response body to an upload success request for id {}: {}", id, responseJson));
try {
parsedResponse = qq.parseJson(responseJson);
if (isError || parsedResponse && (parsedResponse.error || parsedResponse.success === false)) {
options.log("Upload success request was rejected by the server.", "error");
promise.failure(qq.extend(parsedResponse, failureIndicator));
} else {
options.log("Upload success was acknowledged by the server.");
promise.success(qq.extend(parsedResponse, successIndicator));
}
} catch (error) {
if (isError) {
options.log(qq.format("Your server indicated failure in its upload success request response for id {}!", id), "error");
promise.failure(failureIndicator);
} else {
options.log("Upload success was acknowledged by the server.");
promise.success(successIndicator);
}
}
}
requester = qq.extend(this, new qq.AjaxRequester({
acceptHeader: "application/json",
method: options.method,
endpointStore: {
get: function() {
return options.endpoint;
}
},
paramsStore: options.paramsStore,
maxConnections: options.maxConnections,
customHeaders: options.customHeaders,
log: options.log,
onComplete: handleSuccessResponse,
cors: options.cors
}));
qq.extend(this, {
sendSuccessRequest: function(id, spec) {
var promise = new qq.Promise();
options.log("Submitting upload success request/notification for " + id);
requester.initTransport(id).withParams(spec).send();
pendingRequests[id] = promise;
return promise;
}
});
};
qq.s3.InitiateMultipartAjaxRequester = function(o) {
"use strict";
var requester, pendingInitiateRequests = {}, options = {
filenameParam: "qqfilename",
method: "POST",
endpointStore: null,
paramsStore: null,
signatureSpec: null,
aclStore: null,
reducedRedundancy: false,
serverSideEncryption: false,
maxConnections: 3,
getContentType: function(id) {},
getBucket: function(id) {},
getHost: function(id) {},
getKey: function(id) {},
getName: function(id) {},
log: function(str, level) {}
}, getSignatureAjaxRequester;
qq.extend(options, o);
getSignatureAjaxRequester = new qq.s3.RequestSigner({
endpointStore: options.endpointStore,
signatureSpec: options.signatureSpec,
cors: options.cors,
log: options.log
});
function getHeaders(id) {
var bucket = options.getBucket(id), host = options.getHost(id), headers = {}, promise = new qq.Promise(), key = options.getKey(id), signatureConstructor;
headers["x-amz-acl"] = options.aclStore.get(id);
if (options.reducedRedundancy) {
headers[qq.s3.util.REDUCED_REDUNDANCY_PARAM_NAME] = qq.s3.util.REDUCED_REDUNDANCY_PARAM_VALUE;
}
if (options.serverSideEncryption) {
headers[qq.s3.util.SERVER_SIDE_ENCRYPTION_PARAM_NAME] = qq.s3.util.SERVER_SIDE_ENCRYPTION_PARAM_VALUE;
}
headers[qq.s3.util.AWS_PARAM_PREFIX + options.filenameParam] = encodeURIComponent(options.getName(id));
qq.each(options.paramsStore.get(id), function(name, val) {
if (qq.indexOf(qq.s3.util.UNPREFIXED_PARAM_NAMES, name) >= 0) {
headers[name] = val;
} else {
headers[qq.s3.util.AWS_PARAM_PREFIX + name] = encodeURIComponent(val);
}
});
signatureConstructor = getSignatureAjaxRequester.constructStringToSign(getSignatureAjaxRequester.REQUEST_TYPE.MULTIPART_INITIATE, bucket, host, key).withContentType(options.getContentType(id)).withHeaders(headers);
getSignatureAjaxRequester.getSignature(id, {
signatureConstructor: signatureConstructor
}).then(promise.success, promise.failure);
return promise;
}
function handleInitiateRequestComplete(id, xhr, isError) {
var promise = pendingInitiateRequests[id], domParser = new DOMParser(), responseDoc = domParser.parseFromString(xhr.responseText, "application/xml"), uploadIdElements, messageElements, uploadId, errorMessage, status;
delete pendingInitiateRequests[id];
if (isError) {
status = xhr.status;
messageElements = responseDoc.getElementsByTagName("Message");
if (messageElements.length > 0) {
errorMessage = messageElements[0].textContent;
}
} else {
uploadIdElements = responseDoc.getElementsByTagName("UploadId");
if (uploadIdElements.length > 0) {
uploadId = uploadIdElements[0].textContent;
} else {
errorMessage = "Upload ID missing from request";
}
}
if (uploadId === undefined) {
if (errorMessage) {
options.log(qq.format("Specific problem detected initiating multipart upload request for {}: '{}'.", id, errorMessage), "error");
} else {
options.log(qq.format("Unexplained error with initiate multipart upload request for {}. Status code {}.", id, status), "error");
}
promise.failure("Problem initiating upload request.", xhr);
} else {
options.log(qq.format("Initiate multipart upload request successful for {}. Upload ID is {}", id, uploadId));
promise.success(uploadId, xhr);
}
}
requester = qq.extend(this, new qq.AjaxRequester({
method: options.method,
contentType: null,
endpointStore: options.endpointStore,
maxConnections: options.maxConnections,
allowXRequestedWithAndCacheControl: false,
log: options.log,
onComplete: handleInitiateRequestComplete,
successfulResponseCodes: {
POST: [ 200 ]
}
}));
qq.extend(this, {
send: function(id) {
var promise = new qq.Promise();
getHeaders(id).then(function(headers, endOfUrl) {
options.log("Submitting S3 initiate multipart upload request for " + id);
pendingInitiateRequests[id] = promise;
requester.initTransport(id).withPath(endOfUrl).withHeaders(headers).send();
}, promise.failure);
return promise;
}
});
};
qq.s3.CompleteMultipartAjaxRequester = function(o) {
"use strict";
var requester, pendingCompleteRequests = {}, options = {
method: "POST",
contentType: "text/xml",
endpointStore: null,
signatureSpec: null,
maxConnections: 3,
getBucket: function(id) {},
getHost: function(id) {},
getKey: function(id) {},
log: function(str, level) {}
}, getSignatureAjaxRequester;
qq.extend(options, o);
getSignatureAjaxRequester = new qq.s3.RequestSigner({
endpointStore: options.endpointStore,
signatureSpec: options.signatureSpec,
cors: options.cors,
log: options.log
});
function getHeaders(id, uploadId, body) {
var headers = {}, promise = new qq.Promise(), bucket = options.getBucket(id), host = options.getHost(id), signatureConstructor = getSignatureAjaxRequester.constructStringToSign(getSignatureAjaxRequester.REQUEST_TYPE.MULTIPART_COMPLETE, bucket, host, options.getKey(id)).withUploadId(uploadId).withContent(body).withContentType("application/xml; charset=UTF-8");
getSignatureAjaxRequester.getSignature(id, {
signatureConstructor: signatureConstructor
}).then(promise.success, promise.failure);
return promise;
}
function handleCompleteRequestComplete(id, xhr, isError) {
var promise = pendingCompleteRequests[id], domParser = new DOMParser(), bucket = options.getBucket(id), key = options.getKey(id), responseDoc = domParser.parseFromString(xhr.responseText, "application/xml"), bucketEls = responseDoc.getElementsByTagName("Bucket"), keyEls = responseDoc.getElementsByTagName("Key");
delete pendingCompleteRequests[id];
options.log(qq.format("Complete response status {}, body = {}", xhr.status, xhr.responseText));
if (isError) {
options.log(qq.format("Complete Multipart Upload request for {} failed with status {}.", id, xhr.status), "error");
} else {
if (bucketEls.length && keyEls.length) {
if (bucketEls[0].textContent !== bucket) {
isError = true;
options.log(qq.format("Wrong bucket in response to Complete Multipart Upload request for {}.", id), "error");
}
} else {
isError = true;
options.log(qq.format("Missing bucket and/or key in response to Complete Multipart Upload request for {}.", id), "error");
}
}
if (isError) {
promise.failure("Problem combining the file parts!", xhr);
} else {
promise.success({}, xhr);
}
}
function getCompleteRequestBody(etagEntries) {
var doc = document.implementation.createDocument(null, "CompleteMultipartUpload", null);
etagEntries.sort(function(a, b) {
return a.part - b.part;
});
qq.each(etagEntries, function(idx, etagEntry) {
var part = etagEntry.part, etag = etagEntry.etag, partEl = doc.createElement("Part"), partNumEl = doc.createElement("PartNumber"), partNumTextEl = doc.createTextNode(part), etagTextEl = doc.createTextNode(etag), etagEl = doc.createElement("ETag");
etagEl.appendChild(etagTextEl);
partNumEl.appendChild(partNumTextEl);
partEl.appendChild(partNumEl);
partEl.appendChild(etagEl);
qq(doc).children()[0].appendChild(partEl);
});
return new XMLSerializer().serializeToString(doc);
}
requester = qq.extend(this, new qq.AjaxRequester({
method: options.method,
contentType: "application/xml; charset=UTF-8",
endpointStore: options.endpointStore,
maxConnections: options.maxConnections,
allowXRequestedWithAndCacheControl: false,
log: options.log,
onComplete: handleCompleteRequestComplete,
successfulResponseCodes: {
POST: [ 200 ]
}
}));
qq.extend(this, {
send: function(id, uploadId, etagEntries) {
var promise = new qq.Promise(), body = getCompleteRequestBody(etagEntries);
getHeaders(id, uploadId, body).then(function(headers, endOfUrl) {
options.log("Submitting S3 complete multipart upload request for " + id);
pendingCompleteRequests[id] = promise;
delete headers["Content-Type"];
requester.initTransport(id).withPath(endOfUrl).withHeaders(headers).withPayload(body).send();
}, promise.failure);
return promise;
}
});
};
qq.s3.AbortMultipartAjaxRequester = function(o) {
"use strict";
var requester, options = {
method: "DELETE",
endpointStore: null,
signatureSpec: null,
maxConnections: 3,
getBucket: function(id) {},
getHost: function(id) {},
getKey: function(id) {},
log: function(str, level) {}
}, getSignatureAjaxRequester;
qq.extend(options, o);
getSignatureAjaxRequester = new qq.s3.RequestSigner({
endpointStore: options.endpointStore,
signatureSpec: options.signatureSpec,
cors: options.cors,
log: options.log
});
function getHeaders(id, uploadId) {
var headers = {}, promise = new qq.Promise(), bucket = options.getBucket(id), host = options.getHost(id), signatureConstructor = getSignatureAjaxRequester.constructStringToSign(getSignatureAjaxRequester.REQUEST_TYPE.MULTIPART_ABORT, bucket, host, options.getKey(id)).withUploadId(uploadId);
getSignatureAjaxRequester.getSignature(id, {
signatureConstructor: signatureConstructor
}).then(promise.success, promise.failure);
return promise;
}
function handleAbortRequestComplete(id, xhr, isError) {
var domParser = new DOMParser(), responseDoc = domParser.parseFromString(xhr.responseText, "application/xml"), errorEls = responseDoc.getElementsByTagName("Error"), awsErrorMsg;
options.log(qq.format("Abort response status {}, body = {}", xhr.status, xhr.responseText));
if (isError) {
options.log(qq.format("Abort Multipart Upload request for {} failed with status {}.", id, xhr.status), "error");
} else {
if (errorEls.length) {
isError = true;
awsErrorMsg = responseDoc.getElementsByTagName("Message")[0].textContent;
options.log(qq.format("Failed to Abort Multipart Upload request for {}. Error: {}", id, awsErrorMsg), "error");
} else {
options.log(qq.format("Abort MPU request succeeded for file ID {}.", id));
}
}
}
requester = qq.extend(this, new qq.AjaxRequester({
validMethods: [ "DELETE" ],
method: options.method,
contentType: null,
endpointStore: options.endpointStore,
maxConnections: options.maxConnections,
allowXRequestedWithAndCacheControl: false,
log: options.log,
onComplete: handleAbortRequestComplete,
successfulResponseCodes: {
DELETE: [ 204 ]
}
}));
qq.extend(this, {
send: function(id, uploadId) {
getHeaders(id, uploadId).then(function(headers, endOfUrl) {
options.log("Submitting S3 Abort multipart upload request for " + id);
requester.initTransport(id).withPath(endOfUrl).withHeaders(headers).send();
});
}
});
};
qq.s3.XhrUploadHandler = function(spec, proxy) {
"use strict";
var getName = proxy.getName, log = proxy.log, clockDrift = spec.clockDrift, expectedStatus = 200, onGetBucket = spec.getBucket, onGetHost = spec.getHost, onGetKeyName = spec.getKeyName, filenameParam = spec.filenameParam, paramsStore = spec.paramsStore, endpointStore = spec.endpointStore, aclStore = spec.aclStore, reducedRedundancy = spec.objectProperties.reducedRedundancy, region = spec.objectProperties.region, serverSideEncryption = spec.objectProperties.serverSideEncryption, validation = spec.validation, signature = qq.extend({
region: region,
drift: clockDrift
}, spec.signature), handler = this, credentialsProvider = spec.signature.credentialsProvider, chunked = {
combine: function(id) {
var uploadId = handler._getPersistableData(id).uploadId, etagMap = handler._getPersistableData(id).etags, result = new qq.Promise();
requesters.completeMultipart.send(id, uploadId, etagMap).then(result.success, function failure(reason, xhr) {
result.failure(upload.done(id, xhr).response, xhr);
});
return result;
},
done: function(id, xhr, chunkIdx) {
var response = upload.response.parse(id, xhr), etag;
if (response.success) {
etag = xhr.getResponseHeader("ETag");
if (!handler._getPersistableData(id).etags) {
handler._getPersistableData(id).etags = [];
}
handler._getPersistableData(id).etags.push({
part: chunkIdx + 1,
etag: etag
});
}
},
initHeaders: function(id, chunkIdx, blob) {
var headers = {}, bucket = upload.bucket.getName(id), host = upload.host.getName(id), key = upload.key.urlSafe(id), promise = new qq.Promise(), signatureConstructor = requesters.restSignature.constructStringToSign(requesters.restSignature.REQUEST_TYPE.MULTIPART_UPLOAD, bucket, host, key).withPartNum(chunkIdx + 1).withContent(blob).withUploadId(handler._getPersistableData(id).uploadId);
requesters.restSignature.getSignature(id + "." + chunkIdx, {
signatureConstructor: signatureConstructor
}).then(promise.success, promise.failure);
return promise;
},
put: function(id, chunkIdx) {
var xhr = handler._createXhr(id, chunkIdx), chunkData = handler._getChunkData(id, chunkIdx), domain = spec.endpointStore.get(id), promise = new qq.Promise();
chunked.initHeaders(id, chunkIdx, chunkData.blob).then(function(headers, endOfUrl) {
if (xhr._cancelled) {
log(qq.format("Upload of item {}.{} cancelled. Upload will not start after successful signature request.", id, chunkIdx));
promise.failure({
error: "Chunk upload cancelled"
});
} else {
var url = domain + "/" + endOfUrl;
handler._registerProgressHandler(id, chunkIdx, chunkData.size);
upload.track(id, xhr, chunkIdx).then(promise.success, promise.failure);
xhr.open("PUT", url, true);
qq.each(headers, function(name, val) {
xhr.setRequestHeader(name, val);
});
xhr.send(chunkData.blob);
}
}, function() {
promise.failure({
error: "Problem signing the chunk!"
}, xhr);
});
return promise;
},
send: function(id, chunkIdx) {
var promise = new qq.Promise();
chunked.setup(id).then(function() {
chunked.put(id, chunkIdx).then(promise.success, promise.failure);
}, function(errorMessage, xhr) {
promise.failure({
error: errorMessage
}, xhr);
});
return promise;
},
setup: function(id) {
var promise = new qq.Promise(), uploadId = handler._getPersistableData(id).uploadId, uploadIdPromise = new qq.Promise();
if (!uploadId) {
handler._getPersistableData(id).uploadId = uploadIdPromise;
requesters.initiateMultipart.send(id).then(function(uploadId) {
handler._getPersistableData(id).uploadId = uploadId;
uploadIdPromise.success(uploadId);
promise.success(uploadId);
}, function(errorMsg, xhr) {
handler._getPersistableData(id).uploadId = null;
promise.failure(errorMsg, xhr);
uploadIdPromise.failure(errorMsg, xhr);
});
} else if (uploadId instanceof qq.Promise) {
uploadId.then(function(uploadId) {
promise.success(uploadId);
});
} else {
promise.success(uploadId);
}
return promise;
}
}, requesters = {
abortMultipart: new qq.s3.AbortMultipartAjaxRequester({
endpointStore: endpointStore,
signatureSpec: signature,
cors: spec.cors,
log: log,
getBucket: function(id) {
return upload.bucket.getName(id);
},
getHost: function(id) {
return upload.host.getName(id);
},
getKey: function(id) {
return upload.key.urlSafe(id);
}
}),
completeMultipart: new qq.s3.CompleteMultipartAjaxRequester({
endpointStore: endpointStore,
signatureSpec: signature,
cors: spec.cors,
log: log,
getBucket: function(id) {
return upload.bucket.getName(id);
},
getHost: function(id) {
return upload.host.getName(id);
},
getKey: function(id) {
return upload.key.urlSafe(id);
}
}),
initiateMultipart: new qq.s3.InitiateMultipartAjaxRequester({
filenameParam: filenameParam,
endpointStore: endpointStore,
paramsStore: paramsStore,
signatureSpec: signature,
aclStore: aclStore,
reducedRedundancy: reducedRedundancy,
serverSideEncryption: serverSideEncryption,
cors: spec.cors,
log: log,
getContentType: function(id) {
return handler._getMimeType(id);
},
getBucket: function(id) {
return upload.bucket.getName(id);
},
getHost: function(id) {
return upload.host.getName(id);
},
getKey: function(id) {
return upload.key.urlSafe(id);
},
getName: function(id) {
return getName(id);
}
}),
policySignature: new qq.s3.RequestSigner({
expectingPolicy: true,
signatureSpec: signature,
cors: spec.cors,
log: log
}),
restSignature: new qq.s3.RequestSigner({
endpointStore: endpointStore,
signatureSpec: signature,
cors: spec.cors,
log: log
})
}, simple = {
initParams: function(id) {
var customParams = paramsStore.get(id);
customParams[filenameParam] = getName(id);
return qq.s3.util.generateAwsParams({
endpoint: endpointStore.get(id),
clockDrift: clockDrift,
params: customParams,
type: handler._getMimeType(id),
bucket: upload.bucket.getName(id),
key: handler.getThirdPartyFileId(id),
accessKey: credentialsProvider.get().accessKey,
sessionToken: credentialsProvider.get().sessionToken,
acl: aclStore.get(id),
expectedStatus: expectedStatus,
minFileSize: validation.minSizeLimit,
maxFileSize: validation.maxSizeLimit,
reducedRedundancy: reducedRedundancy,
region: region,
serverSideEncryption: serverSideEncryption,
signatureVersion: signature.version,
log: log
}, qq.bind(requesters.policySignature.getSignature, this, id));
},
send: function(id) {
var promise = new qq.Promise(), xhr = handler._createXhr(id), fileOrBlob = handler.getFile(id);
handler._registerProgressHandler(id);
upload.track(id, xhr).then(promise.success, promise.failure);
simple.setup(id, xhr, fileOrBlob).then(function(toSend) {
log("Sending upload request for " + id);
xhr.send(toSend);
}, promise.failure);
return promise;
},
setup: function(id, xhr, fileOrBlob) {
var formData = new FormData(), endpoint = endpointStore.get(id), url = endpoint, promise = new qq.Promise();
simple.initParams(id).then(function(awsParams) {
xhr.open("POST", url, true);
qq.obj2FormData(awsParams, formData);
formData.append("file", fileOrBlob);
promise.success(formData);
}, function(errorMessage) {
promise.failure({
error: errorMessage
});
});
return promise;
}
}, upload = {
bucket: {
promise: function(id) {
var promise = new qq.Promise(), cachedBucket = handler._getFileState(id).bucket;
if (cachedBucket) {
promise.success(cachedBucket);
} else {
onGetBucket(id).then(function(bucket) {
handler._getFileState(id).bucket = bucket;
promise.success(bucket);
}, promise.failure);
}
return promise;
},
getName: function(id) {
return handler._getFileState(id).bucket;
}
},
host: {
promise: function(id) {
var promise = new qq.Promise(), cachedHost = handler._getFileState(id).host;
if (cachedHost) {
promise.success(cachedHost);
} else {
onGetHost(id).then(function(host) {
handler._getFileState(id).host = host;
promise.success(host);
}, promise.failure);
}
return promise;
},
getName: function(id) {
return handler._getFileState(id).host;
}
},
done: function(id, xhr) {
var response = upload.response.parse(id, xhr), isError = response.success !== true;
if (isError && upload.response.shouldReset(response.code)) {
log("This is an unrecoverable error, we must restart the upload entirely on the next retry attempt.", "error");
response.reset = true;
}
return {
success: !isError,
response: response
};
},
key: {
promise: function(id) {
var promise = new qq.Promise(), key = handler.getThirdPartyFileId(id);
if (key == null) {
handler._setThirdPartyFileId(id, promise);
onGetKeyName(id, getName(id)).then(function(keyName) {
handler._setThirdPartyFileId(id, keyName);
promise.success(keyName);
}, function(errorReason) {
handler._setThirdPartyFileId(id, null);
promise.failure(errorReason);
});
} else if (qq.isGenericPromise(key)) {
key.then(promise.success, promise.failure);
} else {
promise.success(key);
}
return promise;
},
urlSafe: function(id) {
var encodedKey = encodeURIComponent(handler.getThirdPartyFileId(id));
return encodedKey.replace(/%2F/g, "/");
}
},
response: {
parse: function(id, xhr) {
var response = {}, parsedErrorProps;
try {
log(qq.format("Received response status {} with body: {}", xhr.status, xhr.responseText));
if (xhr.status === expectedStatus) {
response.success = true;
} else {
parsedErrorProps = upload.response.parseError(xhr.responseText);
if (parsedErrorProps) {
response.error = parsedErrorProps.message;
response.code = parsedErrorProps.code;
}
}
} catch (error) {
log("Error when attempting to parse xhr response text (" + error.message + ")", "error");
}
return response;
},
parseError: function(awsResponseXml) {
var parser = new DOMParser(), parsedDoc = parser.parseFromString(awsResponseXml, "application/xml"), errorEls = parsedDoc.getElementsByTagName("Error"), errorDetails = {}, codeEls, messageEls;
if (errorEls.length) {
codeEls = parsedDoc.getElementsByTagName("Code");
messageEls = parsedDoc.getElementsByTagName("Message");
if (messageEls.length) {
errorDetails.message = messageEls[0].textContent;
}
if (codeEls.length) {
errorDetails.code = codeEls[0].textContent;
}
return errorDetails;
}
},
shouldReset: function(errorCode) {
return errorCode === "EntityTooSmall" || errorCode === "InvalidPart" || errorCode === "InvalidPartOrder" || errorCode === "NoSuchUpload";
}
},
start: function(id, optChunkIdx) {
var promise = new qq.Promise();
upload.key.promise(id).then(function() {
upload.bucket.promise(id).then(function() {
upload.host.promise(id).then(function() {
if (optChunkIdx == null) {
simple.send(id).then(promise.success, promise.failure);
} else {
chunked.send(id, optChunkIdx).then(promise.success, promise.failure);
}
});
});
}, function(errorReason) {
promise.failure({
error: errorReason
});
});
return promise;
},
track: function(id, xhr, optChunkIdx) {
var promise = new qq.Promise();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
var result;
if (optChunkIdx == null) {
result = upload.done(id, xhr);
promise[result.success ? "success" : "failure"](result.response, xhr);
} else {
chunked.done(id, xhr, optChunkIdx);
result = upload.done(id, xhr);
promise[result.success ? "success" : "failure"](result.response, xhr);
}
}
};
return promise;
}
};
qq.extend(this, {
uploadChunk: upload.start,
uploadFile: upload.start
});
qq.extend(this, new qq.XhrUploadHandler({
options: qq.extend({
namespace: "s3"
}, spec),
proxy: qq.extend({
getEndpoint: spec.endpointStore.get
}, proxy)
}));
qq.override(this, function(super_) {
return {
expunge: function(id) {
var uploadId = handler._getPersistableData(id) && handler._getPersistableData(id).uploadId, existedInLocalStorage = handler._maybeDeletePersistedChunkData(id);
if (uploadId !== undefined && existedInLocalStorage) {
requesters.abortMultipart.send(id, uploadId);
}
super_.expunge(id);
},
finalizeChunks: function(id) {
return chunked.combine(id);
},
_getLocalStorageId: function(id) {
var baseStorageId = super_._getLocalStorageId(id), bucketName = upload.bucket.getName(id);
return baseStorageId + "-" + bucketName;
}
};
});
};
qq.s3.FormUploadHandler = function(options, proxy) {
"use strict";
var handler = this, clockDrift = options.clockDrift, onUuidChanged = proxy.onUuidChanged, getName = proxy.getName, getUuid = proxy.getUuid, log = proxy.log, onGetBucket = options.getBucket, onGetKeyName = options.getKeyName, filenameParam = options.filenameParam, paramsStore = options.paramsStore, endpointStore = options.endpointStore, aclStore = options.aclStore, reducedRedundancy = options.objectProperties.reducedRedundancy, region = options.objectProperties.region, serverSideEncryption = options.objectProperties.serverSideEncryption, validation = options.validation, signature = options.signature, successRedirectUrl = options.iframeSupport.localBlankPagePath, credentialsProvider = options.signature.credentialsProvider, getSignatureAjaxRequester = new qq.s3.RequestSigner({
signatureSpec: signature,
cors: options.cors,
log: log
});
if (successRedirectUrl === undefined) {
throw new Error("successRedirectEndpoint MUST be defined if you intend to use browsers that do not support the File API!");
}
function isValidResponse(id, iframe) {
var response, endpoint = options.endpointStore.get(id), bucket = handler._getFileState(id).bucket, doc, innerHtml, responseData;
try {
doc = iframe.contentDocument || iframe.contentWindow.document;
innerHtml = doc.body.innerHTML;
responseData = qq.s3.util.parseIframeResponse(iframe);
if (responseData.bucket === bucket && responseData.key === qq.s3.util.encodeQueryStringParam(handler.getThirdPartyFileId(id))) {
return true;
}
log("Response from AWS included an unexpected bucket or key name.", "error");
} catch (error) {
log("Error when attempting to parse form upload response (" + error.message + ")", "error");
}
return false;
}
function generateAwsParams(id) {
var customParams = paramsStore.get(id);
customParams[filenameParam] = getName(id);
return qq.s3.util.generateAwsParams({
endpoint: endpointStore.get(id),
clockDrift: clockDrift,
params: customParams,
bucket: handler._getFileState(id).bucket,
key: handler.getThirdPartyFileId(id),
accessKey: credentialsProvider.get().accessKey,
sessionToken: credentialsProvider.get().sessionToken,
acl: aclStore.get(id),
minFileSize: validation.minSizeLimit,
maxFileSize: validation.maxSizeLimit,
successRedirectUrl: successRedirectUrl,
reducedRedundancy: reducedRedundancy,
region: region,
serverSideEncryption: serverSideEncryption,
signatureVersion: signature.version,
log: log
}, qq.bind(getSignatureAjaxRequester.getSignature, this, id));
}
function createForm(id, iframe) {
var promise = new qq.Promise(), method = "POST", endpoint = options.endpointStore.get(id), fileName = getName(id);
generateAwsParams(id).then(function(params) {
var form = handler._initFormForUpload({
method: method,
endpoint: endpoint,
params: params,
paramsInBody: true,
targetName: iframe.name
});
promise.success(form);
}, function(errorMessage) {
promise.failure(errorMessage);
handleFinishedUpload(id, iframe, fileName, {
error: errorMessage
});
});
return promise;
}
function handleUpload(id) {
var iframe = handler._createIframe(id), input = handler.getInput(id), promise = new qq.Promise();
createForm(id, iframe).then(function(form) {
form.appendChild(input);
handler._attachLoadEvent(iframe, function(response) {
log("iframe loaded");
if (response) {
if (response.success === false) {
log("Amazon likely rejected the upload request", "error");
promise.failure(response);
}
} else {
response = {};
response.success = isValidResponse(id, iframe);
if (response.success === false) {
log("A success response was received by Amazon, but it was invalid in some way.", "error");
promise.failure(response);
} else {
qq.extend(response, qq.s3.util.parseIframeResponse(iframe));
promise.success(response);
}
}
handleFinishedUpload(id, iframe);
});
log("Sending upload request for " + id);
form.submit();
qq(form).remove();
}, promise.failure);
return promise;
}
function handleFinishedUpload(id, iframe) {
handler._detachLoadEvent(id);
iframe && qq(iframe).remove();
}
qq.extend(this, new qq.FormUploadHandler({
options: {
isCors: false,
inputName: "file"
},
proxy: {
onCancel: options.onCancel,
onUuidChanged: onUuidChanged,
getName: getName,
getUuid: getUuid,
log: log
}
}));
qq.extend(this, {
uploadFile: function(id) {
var name = getName(id), promise = new qq.Promise();
if (handler.getThirdPartyFileId(id)) {
if (handler._getFileState(id).bucket) {
handleUpload(id).then(promise.success, promise.failure);
} else {
onGetBucket(id).then(function(bucket) {
handler._getFileState(id).bucket = bucket;
handleUpload(id).then(promise.success, promise.failure);
});
}
} else {
onGetKeyName(id, name).then(function(key) {
onGetBucket(id).then(function(bucket) {
handler._getFileState(id).bucket = bucket;
handler._setThirdPartyFileId(id, key);
handleUpload(id).then(promise.success, promise.failure);
}, function(errorReason) {
promise.failure({
error: errorReason
});
});
}, function(errorReason) {
promise.failure({
error: errorReason
});
});
}
return promise;
}
});
};
})(window);
//# sourceMappingURL=s3.fine-uploader.core.js.map
|
'use strict';
if (typeof module !== 'undefined' && typeof exports !== 'undefined' && module.exports === exports) {
module.exports = 'ngParallax';
}
angular.module('ngParallax',[]);
angular.module('ngParallax').directive('ngParallax', [
'$timeout',
function ($window, $timeout) {
return {
restrict: 'AE',
scope:{
pattern: '=',
speed: '='
},
link: function(scope, elem, attr) {
window.mobileAndTabletcheck = function() {
if( navigator.userAgent.match(/Android/i)
|| navigator.userAgent.match(/webOS/i)
|| navigator.userAgent.match(/iPhone/i)
|| navigator.userAgent.match(/iPad/i)
|| navigator.userAgent.match(/iPod/i)
|| navigator.userAgent.match(/BlackBerry/i)
|| navigator.userAgent.match(/Windows Phone/i)
){
return true
}
else{
return false;
}
}
var bgObj = elem[0];
bgObj.style.backgroundRepeat = "repeat";
bgObj.style.backgroundAttachment = "fixed";
bgObj.style.height = "100%";
bgObj.style.margin = "0 auto"
bgObj.style.position = "relative"
bgObj.style.background = "url(" + scope.pattern + ")"
bgObj.style.backgroundAttachment = 'fixed';
var isMobile = window.mobileAndTabletcheck();
function execute(){
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
var speed = (scrollTop / scope.speed);
if(isMobile){
speed = speed * .10
}
if(speed == 0){
bgObj.style.backgroundPosition = '0% '+ 0 + '%';
}
else{
bgObj.style.backgroundPosition = '0% '+ speed + '%';
}
};
// for mobile
window.document.addEventListener("touchmove", function(){
execute();
})
// for browsers
window.document.addEventListener("scroll", function() {
execute();
});
execute();
},
};
}
]);
|
// Copyright 2010 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
goog.provide('goog.ui.SplitBehaviorTest');
goog.setTestOnly('goog.ui.SplitBehaviorTest');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.events');
goog.require('goog.events.Event');
goog.require('goog.testing.jsunit');
goog.require('goog.ui.Component');
goog.require('goog.ui.CustomButton');
goog.require('goog.ui.Menu');
goog.require('goog.ui.MenuButton');
goog.require('goog.ui.MenuItem');
goog.require('goog.ui.SplitBehavior');
goog.require('goog.ui.decorate');
var splitbehavior;
var button;
var menuValues;
var menu;
var menuButton;
var splitDiv;
function setUp() {
splitDiv = document.getElementById('split');
button = new goog.ui.CustomButton('text');
menu = new goog.ui.Menu();
menuValues = ['a', 'b', 'c'];
goog.array.forEach(
menuValues, function(val) { menu.addItem(new goog.ui.MenuItem(val)); });
menuButton = new goog.ui.MenuButton('text', menu);
splitbehavior = new goog.ui.SplitBehavior(button, menuButton);
}
function tearDown() {
button.dispose();
menu.dispose();
menuButton.dispose();
splitbehavior.dispose();
goog.dom.removeChildren(splitDiv);
splitDiv.className = '';
}
function testRender() {
assertEquals(
'no elements in doc with goog-split-behavior class', 0,
goog.dom
.getElementsByTagNameAndClass(
goog.dom.TagName.DIV, 'goog-split-behavior')
.length);
splitbehavior.render(splitDiv);
assertEquals('two childs are rendered', 2, splitDiv.childNodes.length);
assertEquals(
'one element in doc with goog-split-behavior class', 1,
goog.dom
.getElementsByTagNameAndClass(
goog.dom.TagName.DIV, 'goog-split-behavior')
.length);
assertEquals(
'one goog-custom-button', 1,
goog.dom
.getElementsByTagNameAndClass(
goog.dom.TagName.DIV, 'goog-custom-button', splitDiv)
.length);
assertEquals(
'one goog-menu-button', 1,
goog.dom
.getElementsByTagNameAndClass(
goog.dom.TagName.DIV, 'goog-menu-button', splitDiv)
.length);
}
function testDecorate() {
var decorateDiv = goog.dom.createDom(
goog.dom.TagName.DIV, 'goog-split-behavior',
goog.dom.createDom(goog.dom.TagName.DIV, 'goog-custom-button'),
goog.dom.createDom(goog.dom.TagName.DIV, 'goog-menu-button'));
goog.dom.appendChild(splitDiv, decorateDiv);
var split = goog.ui.decorate(decorateDiv);
assertNotNull(split);
assertTrue(
'instance of SplitBehavior', split.constructor == goog.ui.SplitBehavior);
assertNotNull(split.first_);
assertTrue(
'instance of CustomButton',
split.first_.constructor == goog.ui.CustomButton);
assertNotNull(split.second_);
assertTrue(
'instance of MenuButton',
split.second_.constructor == goog.ui.MenuButton);
}
function testBehaviorDefault() {
splitbehavior.render(splitDiv);
assertEquals('original caption is "text"', 'text', button.getCaption());
var menuItem = menuButton.getMenu().getChildAt(0);
var type = goog.ui.Component.EventType.ACTION;
goog.events.dispatchEvent(menuButton, new goog.events.Event(type, menuItem));
assertEquals('caption is updated to "a"', 'a', button.getCaption());
}
function testBehaviorCustomEvent() {
splitbehavior.render(splitDiv);
assertEquals('original caption is "text"', 'text', button.getCaption());
var type = goog.ui.Component.EventType.ENTER;
splitbehavior.setEventType(type);
var menuItem = menuButton.getMenu().getChildAt(0);
goog.events.dispatchEvent(menuButton, new goog.events.Event(type, menuItem));
assertEquals('caption is updated to "a"', 'a', button.getCaption());
}
function testBehaviorCustomHandler() {
splitbehavior.render(splitDiv);
var called = false;
splitbehavior.setHandler(function() { called = true; });
goog.events.dispatchEvent(menuButton, goog.ui.Component.EventType.ACTION);
assertTrue('custom handler is called', called);
}
function testSetActive() {
splitbehavior.render(splitDiv, false);
assertEquals('original caption is "text"', 'text', button.getCaption());
var menuItem = menuButton.getMenu().getChildAt(0);
var type = goog.ui.Component.EventType.ACTION;
goog.events.dispatchEvent(menuButton, new goog.events.Event(type, menuItem));
assertEquals('caption remains "text"', 'text', button.getCaption());
splitbehavior.setActive(true);
goog.events.dispatchEvent(menuButton, new goog.events.Event(type, menuItem));
assertEquals('caption is updated to "a"', 'a', button.getCaption());
}
function testDispose() {
goog.dispose(splitbehavior);
assertTrue(splitbehavior.isDisposed());
assertTrue(splitbehavior.first_.isDisposed());
assertTrue(splitbehavior.second_.isDisposed());
}
function testDisposeNoControls() {
splitbehavior.setDisposeControls(false);
goog.dispose(splitbehavior);
assertTrue(splitbehavior.isDisposed());
assertFalse(splitbehavior.first_.isDisposed());
assertFalse(splitbehavior.second_.isDisposed());
}
function testDisposeFirstAndNotSecondControl() {
splitbehavior.setDisposeControls(true, false);
goog.dispose(splitbehavior);
assertTrue(splitbehavior.isDisposed());
assertTrue(splitbehavior.first_.isDisposed());
assertFalse(splitbehavior.second_.isDisposed());
}
|
var validator = require('../validator')
, format = require('util').format;
function test(options) {
var args = options.args || [];
args.unshift(null);
if (options.valid) {
options.valid.forEach(function (valid) {
args[0] = valid;
if (!validator[options.validator].apply(validator, args)) {
var warning = format('validator.%s(%s) failed but should have passed',
options.validator, args.join(', '));
throw new Error(warning);
}
});
}
if (options.invalid) {
options.invalid.forEach(function (invalid) {
args[0] = invalid;
if (validator[options.validator].apply(validator, args)) {
var warning = format('validator.%s(%s) passed but should have failed',
options.validator, args.join(', '));
throw new Error(warning);
}
});
}
}
describe('Validators', function () {
it('should validate email addresses', function () {
test({
validator: 'isEmail'
, valid: [
'foo@bar.com'
, 'x@x.x'
, 'foo@bar.com.au'
, 'foo+bar@bar.com'
, 'hans.müller@test.com'
, 'hans@müller.com'
, 'test|123@müller.com'
]
, invalid: [
'invalidemail@'
, 'invalid.com'
, '@invalid.com'
]
});
});
it('should validate URLs', function () {
test({
validator: 'isURL'
, valid: [
'foobar.com'
, 'www.foobar.com'
, 'foobar.com/'
, 'valid.au'
, 'http://www.foobar.com/'
, 'https://www.foobar.com/'
, 'ftp://www.foobar.com/'
, 'http://www.foobar.com/~foobar'
, 'http://user:pass@www.foobar.com/'
, 'http://127.0.0.1/'
, 'http://10.0.0.0/'
, 'http://189.123.14.13/'
, 'http://duckduckgo.com/?q=%2F'
, 'http://foobar.com/t$-_.+!*\'(),'
, 'http://localhost:3000/'
, 'http://foobar.com/?foo=bar#baz=qux'
, 'http://foobar.com?foo=bar'
, 'http://foobar.com#baz=qux'
]
, invalid: [
'xyz://foobar.com'
, 'invalid/'
, 'invalid.x'
, 'invalid.'
, '.com'
, 'http://com/'
, 'http://300.0.0.1/'
, 'mailto:foo@bar.com'
, 'rtmp://foobar.com'
]
});
});
it('should validate URLs with custom protocols', function () {
test({
validator: 'isURL'
, args: [{
protocols: [ 'rtmp' ]
}]
, valid: [
, 'rtmp://foobar.com'
]
, invalid: [
'http://foobar.com'
]
});
});
it('should validate URLs that do not have a TLD', function () {
test({
validator: 'isURL'
, args: [{
require_tld: false
}]
, valid: [
, 'http://foobar.com/'
, 'http://foobar/'
, 'foobar/'
, 'foobar'
]
, invalid: [
'foobar.'
]
});
});
it('should let users specify whether URLs require a protocol', function () {
test({
validator: 'isURL'
, args: [{
require_protocol: true
}]
, valid: [
, 'http://foobar.com/'
, 'http://localhost/'
]
, invalid: [
'foobar.com'
, 'foobar'
]
});
});
it('should validate IP addresses', function () {
test({
validator: 'isIP'
, valid: [
'127.0.0.1'
, '0.0.0.0'
, '255.255.255.255'
, '1.2.3.4'
, '::1'
, '2001:db8:0000:1:1:1:1:1'
]
, invalid: [
'abc'
, '256.0.0.0'
, '0.0.0.256'
]
});
test({
validator: 'isIP'
, args: [ 4 ]
, valid: [
'127.0.0.1'
, '0.0.0.0'
, '255.255.255.255'
, '1.2.3.4'
]
, invalid: [
'::1'
, '2001:db8:0000:1:1:1:1:1'
]
});
test({
validator: 'isIP'
, args: [ 6 ]
, valid: [
'::1'
, '2001:db8:0000:1:1:1:1:1'
]
, invalid: [
'127.0.0.1'
, '0.0.0.0'
, '255.255.255.255'
, '1.2.3.4'
]
});
test({
validator: 'isIP'
, args: [ 10 ]
, valid: [
]
, invalid: [
'127.0.0.1'
, '0.0.0.0'
, '255.255.255.255'
, '1.2.3.4'
, '::1'
, '2001:db8:0000:1:1:1:1:1'
]
});
});
it('should validate alpha strings', function () {
test({
validator: 'isAlpha'
, valid: [
'abc'
, 'ABC'
, 'FoObar'
]
, invalid: [
'abc1'
, ' foo '
, ''
]
});
});
it('should validate alphanumeric strings', function () {
test({
validator: 'isAlphanumeric'
, valid: [
'abc123'
, 'ABC11'
]
, invalid: [
'abc '
, 'foo!!'
]
});
});
it('should validate numeric strings', function () {
test({
validator: 'isNumeric'
, valid: [
'123'
, '00123'
, '-00123'
, '0'
, '-0'
]
, invalid: [
'123.123'
, ' '
, '.'
]
});
});
it('should validate lowercase strings', function () {
test({
validator: 'isLowercase'
, valid: [
'abc'
, 'abc123'
, 'this is lowercase.'
, 'très über'
]
, invalid: [
'fooBar'
, '123A'
]
});
});
it('should validate uppercase strings', function () {
test({
validator: 'isUppercase'
, valid: [
'ABC'
, 'ABC123'
, 'ALL CAPS IS FUN.'
, ' .'
]
, invalid: [
'fooBar'
, '123abc'
]
});
});
it('should validate integers', function () {
test({
validator: 'isInt'
, valid: [
'13'
, '123'
, '0'
, '123'
, '-0'
]
, invalid: [
'01'
, '-01'
, '000'
, '100e10'
, '123.123'
, ' '
, ''
]
});
});
it('should validate floats', function () {
test({
validator: 'isFloat'
, valid: [
'123'
, '123.'
, '123.123'
, '-123.123'
, '-0.123'
, '0.123'
, '.0'
, '01.123'
, '-0.22250738585072011e-307'
]
, invalid: [
'-.123'
, ' '
, ''
, 'foo'
]
});
});
it('should validate hexadecimal strings', function () {
test({
validator: 'isHexadecimal'
, valid: [
'deadBEEF'
, 'ff0044'
]
, invalid: [
'abcdefg'
, ''
, '..'
]
});
});
it('should validate hexadecimal color strings', function () {
test({
validator: 'isHexColor'
, valid: [
'#ff0034'
, '#CCCCCC'
, 'fff'
, '#f00'
]
, invalid: [
'#ff'
, 'fff0'
, '#ff12FG'
]
});
});
it('should validate null strings', function () {
test({
validator: 'isNull'
, valid: [
''
, NaN
, []
, undefined
, null
]
, invalid: [
, ' '
, 'foo'
]
});
});
it('should validate strings against an expected value', function () {
test({ validator: 'equals', args: ['abc'], valid: ['abc'], invalid: ['Abc', '123'] });
});
it('should validate strings contain another string', function () {
test({ validator: 'contains', args: ['foo'], valid: ['foo', 'foobar', 'bazfoo'],
invalid: ['bar', 'fobar'] });
});
it('should validate strings against a pattern', function () {
test({ validator: 'matches', args: [/abc/], valid: ['abc', 'abcdef', '123abc'],
invalid: ['acb', 'Abc'] });
test({ validator: 'matches', args: ['abc'], valid: ['abc', 'abcdef', '123abc'],
invalid: ['acb', 'Abc'] });
test({ validator: 'matches', args: ['abc', 'i'], valid: ['abc', 'abcdef', '123abc', 'AbC'],
invalid: ['acb'] });
});
it('should validate strings by length', function () {
test({ validator: 'isLength', args: [2], valid: ['abc', 'de', 'abcd'], invalid: [ '', 'a' ] });
test({ validator: 'isLength', args: [2, 3], valid: ['abc', 'de'], invalid: [ '', 'a', 'abcd' ] });
});
it('should validate UUIDs', function () {
test({
validator: 'isUUID'
, valid: [
'A987FBC9-4BED-3078-CF07-9141BA07C9F3'
, 'A987FBC9-4BED-4078-8F07-9141BA07C9F3'
, 'A987FBC9-4BED-5078-AF07-9141BA07C9F3'
]
, invalid: [
''
, 'xxxA987FBC9-4BED-3078-CF07-9141BA07C9F3'
, 'A987FBC9-4BED-3078-CF07-9141BA07C9F3xxx'
, 'A987FBC94BED3078CF079141BA07C9F3'
, '934859'
, '987FBC9-4BED-3078-CF07A-9141BA07C9F3'
, 'AAAAAAAA-1111-1111-AAAG-111111111111'
]
});
test({
validator: 'isUUID'
, args: [ 3 ]
, valid: [
'A987FBC9-4BED-3078-CF07-9141BA07C9F3'
]
, invalid: [
''
, 'xxxA987FBC9-4BED-3078-CF07-9141BA07C9F3'
, '934859'
, 'AAAAAAAA-1111-1111-AAAG-111111111111'
, 'A987FBC9-4BED-4078-8F07-9141BA07C9F3'
, 'A987FBC9-4BED-5078-AF07-9141BA07C9F3'
]
});
test({
validator: 'isUUID'
, args: [ 4 ]
, valid: [
'713ae7e3-cb32-45f9-adcb-7c4fa86b90c1'
, '625e63f3-58f5-40b7-83a1-a72ad31acffb'
, '57b73598-8764-4ad0-a76a-679bb6640eb1'
, '9c858901-8a57-4791-81fe-4c455b099bc9'
]
, invalid: [
''
, 'xxxA987FBC9-4BED-3078-CF07-9141BA07C9F3'
, '934859'
, 'AAAAAAAA-1111-1111-AAAG-111111111111'
, 'A987FBC9-4BED-5078-AF07-9141BA07C9F3'
, 'A987FBC9-4BED-3078-CF07-9141BA07C9F3'
]
});
test({
validator: 'isUUID'
, args: [ 5 ]
, valid: [
'987FBC97-4BED-5078-AF07-9141BA07C9F3'
, '987FBC97-4BED-5078-BF07-9141BA07C9F3'
, '987FBC97-4BED-5078-8F07-9141BA07C9F3'
, '987FBC97-4BED-5078-9F07-9141BA07C9F3'
]
, invalid: [
''
, 'xxxA987FBC9-4BED-3078-CF07-9141BA07C9F3'
, '934859'
, 'AAAAAAAA-1111-1111-AAAG-111111111111'
, '9c858901-8a57-4791-81fe-4c455b099bc9'
, 'A987FBC9-4BED-3078-CF07-9141BA07C9F3'
]
});
});
it('should validate a string that is in another string or array', function () {
test({ validator: 'isIn', args: ['foobar'], valid: ['foo', 'bar', 'foobar', ''],
invalid: ['foobarbaz', 'barfoo'] });
test({ validator: 'isIn', args: [['foo', 'bar']], valid: ['foo', 'bar'],
invalid: ['foobar', 'barfoo', ''] });
test({ validator: 'isIn', args: [[1, 2, 3]], valid: ['1', '2', '3'],
invalid: ['4', ''] });
test({ validator: 'isIn', invalid: ['foo', ''] });
});
it('should validate dates', function () {
test({
validator: 'isDate'
, valid: [
'2011-08-04'
, '04. 08. 2011.'
, '08/04/2011'
, '2011.08.04'
, '4. 8. 2011. GMT'
, '2011-08-04 12:00'
]
, invalid: [
'foo'
, '2011-foo-04'
, 'GMT'
]
});
});
it('should validate dates against a start date', function () {
test({ validator: 'isAfter', args: ['2011-08-03'],
valid: [ '2011-08-04', new Date(2011, 8, 10) ],
invalid: [ '2010-07-02', '2011-08-03', new Date(0), 'foo'] });
test({ validator: 'isAfter',
valid: [ '2100-08-04', new Date(Date.now() + 86400000) ],
invalid: [ '2010-07-02', new Date(0) ] });
});
it('should validate dates against an end date', function () {
test({ validator: 'isBefore', args: ['08/04/2011'],
valid: [ '2010-07-02', '2010-08-04', new Date(0) ],
invalid: [ '08/04/2011', new Date(2011, 9, 10) ] });
test({ validator: 'isBefore', args: [ new Date(2011, 7, 4) ],
valid: [ '2010-07-02', '2010-08-04', new Date(0) ],
invalid: [ '08/04/2011', new Date(2011, 9, 10) ] });
test({ validator: 'isBefore',
valid: [ '2000-08-04', new Date(0), new Date(Date.now() - 86400000) ],
invalid: [ '2100-07-02', new Date(2017, 10, 10) ] });
});
it('should validate that integer strings are divisible by a number', function () {
test({
validator: 'isDivisibleBy'
, args: [ 2 ]
, valid: [ '2', '4', '100', '1000' ]
, invalid: [
'1'
, '2.5'
, '101'
, 'foo'
, ''
]
});
});
it('should validate credit cards', function () {
test({
validator: 'isCreditCard'
, valid: [
'375556917985515'
, '36050234196908'
, '4716461583322103'
, '4716-2210-5188-5662'
, '4929 7226 5379 7141'
, '5398228707871527'
]
, invalid: [
'foo'
, 'foo'
, '5398228707871528'
]
});
});
it('should validate ISBNs', function () {
test({
validator: 'isISBN'
, args: [ 10 ]
, valid: [
'3836221195', '3-8362-2119-5', '3 8362 2119 5'
, '1617290858', '1-61729-085-8', '1 61729 085-8'
, '0007269706', '0-00-726970-6', '0 00 726970 6'
, '3423214120', '3-423-21412-0', '3 423 21412 0'
, '340101319X', '3-401-01319-X', '3 401 01319 X'
]
, invalid: [
'3423214121', '3-423-21412-1', '3 423 21412 1'
, '978-3836221191', '9783836221191',
, '123456789a', 'foo', ''
]
});
test({
validator: 'isISBN'
, args: [ 13 ]
, valid: [
'9783836221191', '978-3-8362-2119-1', '978 3 8362 2119 1'
, '9783401013190', '978-3401013190', '978 3401013190'
, '9784873113685', '978-4-87311-368-5', '978 4 87311 368 5'
]
, invalid: [
'9783836221190', '978-3-8362-2119-0', '978 3 8362 2119 0'
, '3836221195', '3-8362-2119-5', '3 8362 2119 5'
, '01234567890ab', 'foo', ''
]
});
test({
validator: 'isISBN'
, valid: [
'340101319X'
, '9784873113685'
]
, invalid: [
'3423214121'
, '9783836221190'
]
});
test({
validator: 'isISBN'
, args: [ 'foo' ]
, invalid: [
'340101319X'
, '9784873113685'
]
});
});
it('should validate JSON', function () {
test({
validator: 'isJSON'
, valid: [
'{ "key": "value" }'
]
, invalid: [
'{ key: "value" }'
, { "key": "value" }
, { key: 'value' }
, '{ \'key\': \'value\' }'
]
});
});
});
|
/**
* Disallows space after keyword.
*
* Types: `Array` or `Boolean`
*
* Values: Array of quoted keywords or `true` to disallow spaces after all possible keywords.
*
* #### Example
*
* ```js
* "disallowSpaceAfterKeywords": [
* "if",
* "else",
* "for",
* "while",
* "do",
* "switch",
* "try",
* "catch"
* ]
* ```
*
* ##### Valid
*
* ```js
* if(x > y) {
* y++;
* }
* ```
*
* ##### Invalid
*
* ```js
* if (x > y) {
* y++;
* }
* ```
*/
var assert = require('assert');
var defaultKeywords = require('../utils').spacedKeywords;
module.exports = function() {};
module.exports.prototype = {
configure: function(keywords) {
assert(
Array.isArray(keywords) || keywords === true,
this.getOptionName() + ' option requires array or true value'
);
if (keywords === true) {
keywords = defaultKeywords;
}
this._keywords = keywords;
},
getOptionName: function() {
return 'disallowSpaceAfterKeywords';
},
check: function(file, errors) {
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {
var nextToken = file.getNextToken(token);
// Make an exception if the next token is also a keyword (a space would be required).
if (nextToken.type === 'Keyword') {
return;
}
errors.assert.noWhitespaceBetween({
token: token,
nextToken: nextToken
});
});
}
};
|
class C<+T, -U> {}
function f<+T, -U>() {}
type T<+T, -U> = {};
|
/**
* @fileoverview Tests for api.
* @author Gyandeep Singh
* @copyright 2015 Gyandeep Singh. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict";
var assert = require("chai").assert,
api = require("../../lib/api");
describe("api", function() {
it("should have RuleTester exposed", function() {
assert.isFunction(api.RuleTester);
});
it("should have CLIEngine exposed", function() {
assert.isFunction(api.CLIEngine);
});
it("should have linter exposed", function() {
assert.isObject(api.linter);
});
it("should have SourceCode exposed", function() {
assert.isFunction(api.SourceCode);
});
});
|
/*
* jquery.inputmask.phone.extensions.js
* http://github.com/RobinHerbots/jquery.inputmask
* Copyright (c) 2010 - 2014 Robin Herbots
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
* Version: 3.1.13
*/
!function(a){"function"==typeof define&&define.amd?define(["jquery","./jquery.inputmask"],a):a(jQuery)}(function(a){return a.extend(a.inputmask.defaults.aliases,{phone:{url:"phone-codes/phone-codes.js",mask:function(b){b.definitions={p:{validator:function(){return!1},cardinality:1},"#":{validator:"[0-9]",cardinality:1}};var c=[];return a.ajax({url:b.url,async:!1,dataType:"json",success:function(a){c=a}}),c.splice(0,0,"+pp(pp)pppppppp"),c},nojumps:!0,nojumpsThreshold:1},phonebe:{url:"phone-codes/phone-be.js",mask:function(b){b.definitions={p:{validator:function(){return!1},cardinality:1},"#":{validator:"[0-9]",cardinality:1}};var c=[];return a.ajax({url:b.url,async:!1,dataType:"json",success:function(a){c=a}}),c.splice(0,0,"+32(pp)pppppppp"),c},nojumps:!0,nojumpsThreshold:4}}),a.fn.inputmask});
|
/** @jsx React.DOM */
/* jshint node: true, browser: true, newcap: false */
/**
* The Flocks library module.
*
* @module Flocks
* @main Flocks
*/
// if it's in a <script> it's defined already
// otherwise assume commonjs
if (typeof React === 'undefined') {
var React = require('react');
}
// wrap the remainder
(function() {
'use strict';
var initialized = false,
updateBlocks = 0,
dirty = false,
tagtype = undefined,
handler = function() { return true; },
finalizer = function() { return true; },
prevFCtx = {},
nextFCtx = {},
flocks2_ctxs = { flocks2context: React.PropTypes.object };
function flocksLog(Level, Message) {
if (typeof Level === 'string') {
if (member(Level, ['warn','debug','error','log','info','exception','assert'])) {
console[Level]('Flocks2 [' + Level + '] ' + Message.toString());
} else {
console.log('Flocks2 [Unknown level] ' + Message.toString());
}
} else if (nextFCtx.flocks_config === undefined) {
console.log('Flocks2 pre-config [' + Level.toString() + '] ' + Message.toString());
} else if (nextFCtx.flocks_config.log_level >= Level) {
console.log('Flocks2 [' + Level.toString() + '] ' + Message.toString());
}
}
function enforceString(On, Label) {
Label = Label || 'Argument must be a string';
if (typeof On !== 'string') {
throw Label;
}
}
function isArray(maybeArray) {
return (Object.prototype.toString.call(maybeArray) === '[object Array]');
}
function isNonArrayObject(maybeArray) {
if (typeof maybeArray !== 'object') { return false; }
if (Object.prototype.toString.call(maybeArray) === '[object Array]') { return false; }
return true;
}
function setByKey(Key, MaybeValue) {
enforceString(Key, "Flocks2 set/2 must take a string for its key");
nextFCtx[Key] = MaybeValue;
flocksLog(1, " - Flocks2 setByKey \"" + Key + "\"");
attemptUpdate();
}
function setByPath(Key, MaybeValue) { flocksLog(0, ' - Flocks2 setByPath stub' ); attemptUpdate(); }
function setByObject(Key, MaybeValue) { flocksLog(0, ' - Flocks2 setByObject stub'); attemptUpdate(); }
function set(Key, MaybeValue) {
flocksLog(3, ' - Flocks2 multi-set');
if (typeof Key === 'string') { setByKey(Key, MaybeValue); }
else if (isArray(Key)) { setByPath(Key, MaybeValue); }
else if (isNonArrayObject(Key)) { setByObject(Key); }
else { throw 'Flocks2 set/1,2 key must be a string or an array'; }
}
function clone(obj, loglabel) {
flocksLog(3, ' + Flocks2 cloning ' + (loglabel? loglabel : JSON.stringify(obj).substring(0,100) ) );
if ((null === obj) || ('object' != typeof obj)) { return obj; }
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) { copy[attr] = obj[attr]; }
}
return copy;
}
// ... lol
function member(Item, Array) {
return (!!(~( Array.indexOf(Item) )));
}
function attemptUpdate() {
flocksLog(3, ' - Flocks2 attempting update');
dirty = true;
if (!(initialized)) {
flocksLog(1, ' x Flocks2 skipped update: root is not initialized');
return null;
}
if (updateBlocks) {
flocksLog(1, ' x Flocks2 skipped update: lock count updateBlocks is non-zero');
return null;
}
/* whargarbl see issue #9 https://github.com/StoneCypher/flocks.js/issues/9
if (deepCompare(nextFCtx, prevFCtx)) {
flocksLog(2, ' x Flocks2 skipped update: no update to state');
return true;
}
*/
if (!(handler(nextFCtx))) {
flocksLog(0, ' ! Flocks2 rolling back update: handler rejected propset');
nextFCtx = prevFCtx;
dirty = false;
return null;
}
prevFCtx = nextFCtx;
flocksLog(3, ' - Flocks2 update passed');
React.render( React.createFactory(tagtype)( { flocks2context: nextFCtx } ), document.body );
dirty = false;
flocksLog(3, ' - Flocks2 update complete; finalizing');
finalizer();
return true;
}
function create(iFlocksConfig, iFlocksData) {
var FlocksConfig = iFlocksConfig || {},
FlocksData = iFlocksData || {},
target = FlocksConfig.target || document.body,
stub = function() { window.alert('whargarbl stub'); attemptUpdate(); },
updater = { get: stub, set: set, override: stub, clear: stub, update: stub, lock: stub, unlock: stub };
FlocksConfig.log_level = FlocksConfig.log_level || -1;
tagtype = FlocksConfig.control;
FlocksData.flocks_config = FlocksConfig;
nextFCtx = FlocksData;
flocksLog(1, 'Flocks2 root creation begins');
if (!(tagtype)) { throw 'Flocks2 fatal error: must provide a control in create/2 FlocksConfig'; }
if (FlocksConfig.handler) { handler = FlocksConfig.handler; flocksLog(3, ' - Flocks2 handler assigned' ); }
if (FlocksConfig.finalizer) { finalizer = FlocksConfig.finalizer; flocksLog(3, ' - Flocks2 finalizer assigned'); }
if (FlocksConfig.preventAutoContext) {
flocksLog(2, ' - Flocks2 skipping auto-context');
} else {
flocksLog(2, ' - Flocks2 engaging auto-context');
this.fctx = clone(nextFCtx);
}
flocksLog(3, 'Flocks2 creation finished; initializing');
initialized = true;
attemptUpdate();
flocksLog(3, 'Flocks2 expose updater');
this.fupd = updater;
this.fset = updater.set;
flocksLog(3, 'Flocks2 initialization finished');
return updater;
}
var Mixin = {
contextTypes : flocks2_ctxs,
childContextTypes : flocks2_ctxs,
componentWillMount: function() {
flocksLog(1, ' - Flocks2 component will mount: ' + this.constructor.displayName);
flocksLog(3, typeof this.props.flocks2context === 'undefined'? ' - No F2 Context Prop' : ' - F2 Context Prop found');
flocksLog(3, typeof this.context.flocks2context === 'undefined'? ' - No F2 Context' : ' - F2 Context found');
if (this.props.flocks2context) {
this.context.flocks2context = this.props.flocks2context;
}
this.fset = function(X,Y) { set(X,Y); };
this.fctx = this.context.flocks2context;
},
getChildContext: function() {
return this.context;
}
};
var exports = {
member : Mixin,
create : create,
clone : clone,
isArray : isArray,
isNonArrayObject : isNonArrayObject,
enforceString : enforceString,
/*
enforceArray : enforceArray,
enforceNonArrayObject : enforceNonArrayObject,
member : member
*/
};
if (typeof module !== 'undefined') {
module.exports = exports;
} else {
window.flocksjs2 = exports;
}
}());
|
'use strict';
module.exports = require('./lib/weak')(require('./plain'));
|
(function () {
"use strict";
var root = this,
$ = root.jQuery;
if(typeof root.GOVUK === 'undefined') { root.GOVUK = {}; }
// Stick elements to top of screen when you scroll past, documentation is in the README.md
var sticky = {
_hasScrolled: false,
_scrollTimeout: false,
init: function(){
var $els = $('.js-stick-at-top-when-scrolling');
if($els.length > 0){
sticky.$els = $els;
if(sticky._scrollTimeout === false) {
$(root).scroll(sticky.onScroll);
sticky._scrollTimeout = root.setInterval(sticky.checkScroll, 50);
}
$(root).resize(sticky.onResize);
}
if(root.GOVUK.stopScrollingAtFooter){
$els.each(function(i,el){
var $img = $(el).find('img');
if($img.length > 0){
var image = new Image();
image.onload = function(){
root.GOVUK.stopScrollingAtFooter.addEl($(el), $(el).outerHeight());
};
image.src = $img.attr('src');
} else {
root.GOVUK.stopScrollingAtFooter.addEl($(el), $(el).outerHeight());
}
});
}
},
onScroll: function(){
sticky._hasScrolled = true;
},
checkScroll: function(){
if(sticky._hasScrolled === true){
sticky._hasScrolled = false;
var windowVerticalPosition = $(root).scrollTop();
sticky.$els.each(function(i, el){
var $el = $(el),
scrolledFrom = $el.data('scrolled-from');
if (scrolledFrom && windowVerticalPosition < scrolledFrom){
sticky.release($el);
} else if($(root).width() > 768 && windowVerticalPosition >= $el.offset().top) {
sticky.stick($el);
}
});
}
},
stick: function($el){
if (!$el.hasClass('content-fixed')) {
$el.data('scrolled-from', $el.offset().top);
var height = Math.max($el.height(), 1);
$el.before('<div class="shim" style="width: '+ $el.width() + 'px; height: ' + height + 'px"> </div>');
$el.css('width', $el.width() + "px").addClass('content-fixed');
}
},
release: function($el){
if($el.hasClass('content-fixed')){
$el.data('scrolled-from', false);
$el.removeClass('content-fixed').css('width', '');
$el.siblings('.shim').remove();
}
}
};
root.GOVUK.stickAtTopWhenScrolling = sticky;
}).call(this);
|
"use strict";
var path = require('path');
var fs = require('fs');
var optimist = require('optimist');
/**
* The command line interface for interacting with the Protractor runner.
* It takes care of parsing command line options.
*
* Values from command line options override values from the config.
*/
var args = [];
process.argv.slice(2).forEach(function (arg) {
var flag = arg.split('=')[0];
switch (flag) {
case 'debug':
args.push('--nodeDebug');
args.push('true');
break;
case '-d':
case '--debug':
case '--debug-brk':
args.push('--v8Debug');
args.push('true');
break;
default:
args.push(arg);
break;
}
});
optimist
.usage('Usage: protractor [configFile] [options]\n' +
'configFile defaults to protractor.conf.js\n' +
'The [options] object will override values from the config file.\n' +
'See the reference config for a full list of options.')
.describe('help', 'Print Protractor help menu')
.describe('version', 'Print Protractor version')
.describe('browser', 'Browsername, e.g. chrome or firefox')
.describe('seleniumAddress', 'A running selenium address to use')
.describe('seleniumSessionId', 'Attaching an existing session id')
.describe('seleniumServerJar', 'Location of the standalone selenium jar file')
.describe('seleniumPort', 'Optional port for the selenium standalone server')
.describe('baseUrl', 'URL to prepend to all relative paths')
.describe('rootElement', 'Element housing ng-app, if not html or body')
.describe('specs', 'Comma-separated list of files to test')
.describe('exclude', 'Comma-separated list of files to exclude')
.describe('verbose', 'Print full spec names')
.describe('stackTrace', 'Print stack trace on error')
.describe('params', 'Param object to be passed to the tests')
.describe('framework', 'Test framework to use: jasmine, mocha, or custom')
.describe('resultJsonOutputFile', 'Path to save JSON test result')
.describe('troubleshoot', 'Turn on troubleshooting output')
.describe('elementExplorer', 'Interactively test Protractor commands')
.describe('debuggerServerPort', 'Start a debugger server at specified port instead of repl')
.alias('browser', 'capabilities.browserName')
.alias('name', 'capabilities.name')
.alias('platform', 'capabilities.platform')
.alias('platform-version', 'capabilities.version')
.alias('tags', 'capabilities.tags')
.alias('build', 'capabilities.build')
.alias('grep', 'jasmineNodeOpts.grep')
.alias('invert-grep', 'jasmineNodeOpts.invertGrep')
.alias('explorer', 'elementExplorer')
.string('capabilities.tunnel-identifier')
.check(function (arg) {
if (arg._.length > 1) {
throw 'Error: more than one config file specified';
}
});
var argv = optimist.parse(args);
if (argv.help) {
optimist.showHelp();
process.exit(0);
}
if (argv.version) {
console.log('Version ' + require(path.join(__dirname, '../package.json')).version);
process.exit(0);
}
// WebDriver capabilities properties require dot notation, but optimist parses
// that into an object. Re-flatten it.
function flattenObject(obj, prefix, out) {
prefix = prefix || '';
out = out || {};
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
typeof obj[prop] === 'object' ?
flattenObject(obj[prop], prefix + prop + '.', out) :
out[prefix + prop] = obj[prop];
}
}
return out;
}
;
if (argv.capabilities) {
argv.capabilities = flattenObject(argv.capabilities);
}
/**
* Helper to resolve comma separated lists of file pattern strings relative to
* the cwd.
*
* @private
* @param {Array} list
*/
function processFilePatterns_(list) {
return list.split(',').map(function (spec) {
return path.resolve(process.cwd(), spec);
});
}
;
if (argv.specs) {
argv.specs = processFilePatterns_(argv.specs);
}
if (argv.exclude) {
argv.exclude = processFilePatterns_(argv.exclude);
}
// Use default configuration, if it exists.
var configFile = argv._[0];
if (!configFile) {
if (fs.existsSync('./protractor.conf.js')) {
configFile = './protractor.conf.js';
}
}
if (!configFile && !argv.elementExplorer && args.length < 3) {
console.log('**you must either specify a configuration file ' +
'or at least 3 options. See below for the options:\n');
optimist.showHelp();
process.exit(1);
}
// Run the launcher
var launcher = require('./launcher');
launcher.init(configFile, argv);
|
"use strict";
var t = function t() {
return 5 + 5;
};
|
'use strict';
var enhanceError = require('./enhanceError');
/**
* Create an Error with the specified message, config, error code, request and response.
*
* @param {string} message The error message.
* @param {Object} config The config.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [request] The request.
* @param {Object} [response] The response.
* @returns {Error} The created error.
*/
module.exports = function createError(message, config, code, request, response) {
var error = new Error(message);
return enhanceError(error, config, code, request, response);
};
|
"use strict";
function nextOdd(n) {
return isEven(n) ? n + 1 : n + 2;
}
var isOdd = (function (isEven) {
return function (n) {
return !isEven(n);
};
})(isEven);
|
jQuery.webshims.register("form-number-date-ui",function(c,f,n,k,v,g){var o=f.triggerInlineForm,r=Modernizr.inputtypes,s=function(){var c={"padding-box":"innerWidth","border-box":"outerWidth","content-box":"width"},a=Modernizr.prefixed&&Modernizr.prefixed("boxSizing");return function(b,h){var f,i,g;i="width";a&&(i=c[b.css(a)]||i);f=b[i]();i="width"==i;if(f){var l=parseInt(h.css("marginLeft"),10)||0,p=h.outerWidth();(g=parseInt(b.css("marginRight"),10)||0)&&b.css("marginRight",0);l<=-1*p?(h.css("marginRight",
Math.floor(Math.abs(p+l)+g)),b.css("paddingRight",(parseInt(b.css("paddingRight"),10)||0)+Math.abs(l)),i&&b.css("width",Math.floor(f+l))):(h.css("marginRight",g),b.css("width",Math.floor(f-l-p)))}}}(),t={dateFormat:"yy-mm-dd"},w=c([]),q,j=function(d,a){c("input",d).add(a.filter("input")).each(function(){var b=c.prop(this,"type");if(j[b]&&!f.data(this,"shadowData"))j[b](c(this))})},x=function(d,a){if(g.lazyDate){var b=c.data(d[0],"setDateLazyTimer");b&&clearTimeout(b);c.data(d[0],"setDateLazyTimer",
setTimeout(function(){d.datepicker("setDate",a);c.removeData(d[0],"setDateLazyTimer");d=null},0))}else d.datepicker("setDate",a)};if(g.lazyDate===v)try{g.lazyDate=c.browser.msie&&9>f.browserVersion||500>c(n).width()&&500>c(n).height()}catch(z){}var u={tabindex:1,tabIndex:1,title:1,"aria-required":1,"aria-invalid":1};if(!g.copyAttrs)g.copyAttrs={};f.extendUNDEFProp(g.copyAttrs,u);j.common=function(d,a,b){Modernizr.formvalidation&&d.bind("firstinvalid",function(b){(f.fromSubmit||!q)&&d.unbind("invalid.replacedwidgetbubble").bind("invalid.replacedwidgetbubble",
function(c){!b.isInvalidUIPrevented()&&!c.isDefaultPrevented()&&(f.validityAlert.showFor(b.target),b.preventDefault(),c.preventDefault());d.unbind("invalid.replacedwidgetbubble")})});var h,m,i=c("input, span.ui-slider-handle",a),j=d[0].attributes;for(h in g.copyAttrs)if((m=j[h])&&m.specified)u[h]&&i[0]?i.attr(h,m.nodeValue):a[0].setAttribute(h,m.nodeValue);m=d.attr("id");h=g.calculateWidth?{css:{marginRight:d.css("marginRight"),marginLeft:d.css("marginLeft")},outerWidth:d.outerWidth()}:{};h.label=
m?c('label[for="'+m+'"]',d[0].form):w;m=f.getID(h.label);a.addClass(d[0].className);f.addShadowDom(d,a,{data:b||{},shadowFocusElement:c("input.input-datetime-local-date, span.ui-slider-handle",a)[0],shadowChilds:i});d.after(a).hide();d[0].form&&c(d[0].form).bind("reset",function(b){b.originalEvent&&!b.isDefaultPrevented()&&setTimeout(function(){d.prop("value",d.prop("value"))},0)});1==a.length&&!c("*",a)[0]&&(a.attr("aria-labelledby",m),h.label.bind("click",function(){a.focus();return!1}));return h};
Modernizr.formvalidation&&["input","form"].forEach(function(c){var a=f.defineNodeNameProperty(c,"checkValidity",{prop:{value:function(){q=!0;var b=a.prop._supvalue.apply(this,arguments);q=!1;return b}}})});if(!r.date||g.replaceUI){var y=function(d,a,b,h){var m,i,j=function(){l.dpDiv.unbind("mousedown.webshimsmousedownhandler");i=m=!1},l=a.bind("focusin",function(){j();l.dpDiv.unbind("mousedown.webshimsmousedownhandler").bind("mousedown.webshimsmousedownhandler",function(){m=!0})}).bind("focusout blur",
function(b){m&&(i=!0,b.stopImmediatePropagation())}).datepicker(c.extend({onClose:function(){i&&k.activeElement!==a[0]?(j(),a.trigger("focusout"),a.triggerHandler("blur")):j()}},t,g.datepicker,d.data("datepicker"))).bind("change",b).data("datepicker");l.dpDiv.addClass("input-date-datepicker-control");h&&f.triggerDomUpdate(h[0]);["disabled","min","max","value","step"].forEach(function(b){var c=d.prop(b);""!==c&&("disabled"!=b||!c)&&d.prop(b,c)});return l};j.date=function(d){if(c.fn.datepicker){var a=
c('<input class="input-date" type="text" />'),b=this.common(d,a,j.date.attrs),h=y(d,a,function(b){j.date.blockAttr=!0;var h;if(g.lazyDate){var f=c.data(a[0],"setDateLazyTimer");f&&(clearTimeout(f),c.removeData(a[0],"setDateLazyTimer"))}try{h=(h=c.datepicker.parseDate(a.datepicker("option","dateFormat"),a.prop("value")))?c.datepicker.formatDate("yy-mm-dd",h):a.prop("value")}catch(l){h=a.prop("value")}d.prop("value",h);j.date.blockAttr=!1;b.stopImmediatePropagation();o(d[0],"input");o(d[0],"change")});
b.css&&(a.css(b.css),b.outerWidth&&a.outerWidth(b.outerWidth),h.trigger[0]&&s(a,h.trigger))}};j.date.attrs={disabled:function(d,a,b){c.prop(a,"disabled",!!b)},min:function(d,a,b){try{b=c.datepicker.parseDate("yy-mm-dd",b)}catch(h){b=!1}b&&c(a).datepicker("option","minDate",b)},max:function(d,a,b){try{b=c.datepicker.parseDate("yy-mm-dd",b)}catch(h){b=!1}b&&c(a).datepicker("option","maxDate",b)},value:function(d,a,b){if(!j.date.blockAttr){try{var h=c.datepicker.parseDate("yy-mm-dd",b)}catch(f){h=!1}h?
x(c(a),h):c.prop(a,"value",b)}}}}if(!r.range||g.replaceUI)j.range=function(d){if(c.fn.slider){var a=c('<span class="input-range"><span class="ui-slider-handle" role="slider" tabindex="0" /></span>'),b=this.common(d,a,j.range.attrs);c("span",a).attr("aria-labelledby",b.label.attr("id"));b.label.bind("click",function(){c("span",a).focus();return!1});b.css&&(a.css(b.css),b.outerWidth&&a.outerWidth(b.outerWidth));a.slider(c.extend({},g.slider,d.data("slider"),{slide:function(b,c){if(b.originalEvent)j.range.blockAttr=
!0,d.prop("value",c.value),j.range.blockAttr=!1,o(d[0],"input"),o(d[0],"change")}}));["disabled","min","max","step","value"].forEach(function(b){var a=d.attr(b),f;"value"==b&&!a&&(f=d.getShadowElement())&&(a=(c(f).slider("option","max")-c(f).slider("option","min"))/2);null!=a&&d.attr(b,a)})}},j.range.attrs={disabled:function(d,a,b){b=!!b;c(a).slider("option","disabled",b);c("span",a).attr({"aria-disabled":b+"",tabindex:b?"-1":"0"})},min:function(d,a,b){b=b?1*b||0:0;c(a).slider("option","min",b);c("span",
a).attr({"aria-valuemin":b})},max:function(d,a,b){b=b||0===b?1*b||100:100;c(a).slider("option","max",b);c("span",a).attr({"aria-valuemax":b})},value:function(d,a,b){b=c(d).prop("valueAsNumber");isNaN(b)||(j.range.blockAttr||c(a).slider("option","value",b),c("span",a).attr({"aria-valuenow":b,"aria-valuetext":b}))},step:function(d,a,b){b=b&&c.trim(b)?1*b||1:1;c(a).slider("option","step",b)}};if(!f.bugs.valueAsNumberSet&&(g.replaceUI||!Modernizr.inputtypes.date||!Modernizr.inputtypes.range))n=function(){f.data(this,
"hasShadow")&&c.prop(this,"value",c.prop(this,"value"))},f.onNodeNamesPropertyModify("input","valueAsNumber",n),f.onNodeNamesPropertyModify("input","valueAsDate",n);c.each(["disabled","min","max","value","step"],function(c,a){f.onNodeNamesPropertyModify("input",a,function(b){var c=f.data(this,"shadowData");if(c&&c.data&&c.data[a]&&c.nativeElement===this)c.data[a](this,c.shadowElement,b)})});if(!g.availabeLangs)g.availabeLangs="af ar ar-DZ az bg bs ca cs da de el en-AU en-GB en-NZ eo es et eu fa fi fo fr fr-CH gl he hr hu hy id is it ja ko kz lt lv ml ms nl no pl pt-BR rm ro ru sk sl sq sr sr-SR sv ta th tr uk vi zh-CN zh-HK zh-TW".split(" ");
n=function(){c.datepicker&&(f.activeLang({langObj:c.datepicker.regional,module:"form-number-date-ui",callback:function(d){c("input.hasDatepicker").filter(".input-date, .input-datetime-local-date").datepicker("option",c.extend(t,d,g.datepicker))}}),c(k).unbind("jquery-uiReady.langchange input-widgetsReady.langchange"))};c(k).bind("jquery-uiReady.langchange input-widgetsReady.langchange",n);n();(function(){var d=function(){var b={};return function(a){return a in b?b[a]:b[a]=c('<input type="'+a+'" />')[0].type===
a}}();if(!d("number")){var a=f.cfg["forms-ext"],b=f.inputTypes,h=function(a,d,e){e=e||{};if(!("type"in e))e.type=c.prop(a,"type");if(!("step"in e))e.step=f.getStep(a,e.type);if(!("valueAsNumber"in e))e.valueAsNumber=b[e.type].asNumber(c.prop(a,"value"));var h="any"==e.step?b[e.type].step*b[e.type].stepScaleFactor:e.step;f.addMinMaxNumberToCache("min",c(a),e);f.addMinMaxNumberToCache("max",c(a),e);if(isNaN(e.valueAsNumber))e.valueAsNumber=b[e.type].stepBase||0;if("any"!==e.step&&(a=Math.round(1E7*
((e.valueAsNumber-(e.minAsnumber||0))%e.step))/1E7)&&Math.abs(a)!=e.step)e.valueAsNumber-=a;a=e.valueAsNumber+h*d;return a=!isNaN(e.minAsNumber)&&a<e.minAsNumber?e.valueAsNumber*d<e.minAsNumber?e.minAsNumber:isNaN(e.maxAsNumber)?e.valueAsNumber:e.maxAsNumber:!isNaN(e.maxAsNumber)&&a>e.maxAsNumber?e.valueAsNumber*d>e.maxAsNumber?e.maxAsNumber:isNaN(e.minAsNumber)?e.valueAsNumber:e.minAsNumber:Math.round(1E7*a)/1E7};f.modules["form-number-date-ui"].getNextStep=h;var j=function(a,d,e){if(!a.disabled&&
!a.readOnly&&!c(e).hasClass("step-controls")&&(c.prop(a,"value",b[d].numberToString(h(a,c(e).hasClass("step-up")?1:-1,{type:d}))),c(a).unbind("blur.stepeventshim"),o(a,"input"),k.activeElement)){if(k.activeElement!==a)try{a.focus()}catch(f){}setTimeout(function(){if(k.activeElement!==a)try{a.focus()}catch(b){}c(a).one("blur.stepeventshim",function(){o(a,"change")})},0)}};if(a.stepArrows){var g={set:function(){var a=f.data(this,"step-controls");if(a)a[this.disabled||this.readonly?"addClass":"removeClass"]("disabled-step-control")}};
f.onNodeNamesPropertyModify("input","disabled",g);f.onNodeNamesPropertyModify("input","readonly",c.extend({},g))}var n={38:1,40:-1};f.addReady(function(g,i){a.stepArrows&&c("input",g).add(i.filter("input")).each(function(){var e=c.prop(this,"type");if(b[e]&&b[e].asNumber&&a.stepArrows&&!(!0!==a.stepArrows&&!a.stepArrows[e]||d(e)||c(g).hasClass("has-step-controls"))){var g=this,i=c('<span class="step-controls" unselectable="on"><span class="step-up" /><span class="step-down" /></span>').insertAfter(g).bind("selectstart dragstart",
function(){return!1}).bind("mousedown mousepress",function(a){j(g,e,a.target);return!1}).bind("mousepressstart mousepressend",function(a){c(a.target)["mousepressstart"==a.type?"addClass":"removeClass"]("mousepress-ui")}),l=function(a,d){if(!g.disabled&&!g.readOnly)return c.prop(g,"value",b[e].numberToString(h(g,d,{type:e}))),o(g,"input"),!1},k=c(g).addClass("has-step-controls").attr({readonly:g.readOnly,disabled:g.disabled,autocomplete:"off",role:"spinbutton"}).bind(c.browser.msie?"keydown":"keypress",
function(a){if(!g.disabled&&!g.readOnly&&n[a.keyCode])return c.prop(g,"value",b[e].numberToString(h(g,n[a.keyCode],{type:e}))),o(g,"input"),!1});c.fn.mwheelIntent?k.add(i).bind("mwheelIntent",l):k.bind("focus",function(){k.add(i).unbind(".mwhellwebshims").bind("mousewheel.mwhellwebshims",l)}).bind("blur",function(){c(g).add(i).unbind(".mwhellwebshims")});f.data(g,"step-controls",i);a.calculateWidth&&(s(k,i),i.css("marginTop",(k.outerHeight()-i.outerHeight())/2))}})})}})();f.addReady(function(d,a){c(k).bind("jquery-uiReady.initinputui input-widgetsReady.initinputui",
function(){(c.datepicker||c.fn.slider)&&j(d,a);c.datepicker&&c.fn.slider?c(k).unbind(".initinputui"):f.modules["input-widgets"].src||f.warn('jQuery UI Widget factory is already included, but not datepicker or slider. configure src of $.webshims.modules["input-widgets"].src')})})});
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'toolbar', 'gl', {
toolbarCollapse: 'Contraer a barra de ferramentas',
toolbarExpand: 'Expandir a barra de ferramentas',
toolbarGroups: {
document: 'Documento',
clipboard: 'Portapapeis/desfacer',
editing: 'Edición',
forms: 'Formularios',
basicstyles: 'Estilos básicos',
paragraph: 'Paragrafo',
links: 'Ligazóns',
insert: 'Inserir',
styles: 'Estilos',
colors: 'Cores',
tools: 'Ferramentas'
},
toolbars: 'Barras de ferramentas do editor'
});
|
/**
* Controllers
*
* By default, Sails inspects your controllers, models, and configuration and binds
* certain routes automatically. These dynamically generated routes are called blueprints.
*
* These settings are for the global configuration of controllers & blueprint routes.
* You may also override these settings on a per-controller basis by defining a '_config'
* key in any of your controller files, and assigning it an object, e.g.:
* {
* // ...
* _config: { blueprints: { rest: false } }
* // ...
* }
*
* For more information on configuring controllers and blueprints, check out:
* http://sailsjs.org/#documentation
*/
module.exports.controllers = {
/**
* NOTE:
* A lot of the configuration options below affect so-called "CRUD methods",
* or your controllers' `find`, `create`, `update`, and `destroy` actions.
*
* It's important to realize that, even if you haven't defined these yourself, as long as
* a model exists with the same name as the controller, Sails will respond with built-in CRUD
* logic in the form of a JSON API, including support for sort, pagination, and filtering.
*/
blueprints: {
/**
* `actions`
*
* Action blueprints speed up backend development and shorten the development workflow by
* eliminating the need to manually bind routes.
* When enabled, GET, POST, PUT, and DELETE routes will be generated for every one of a controller's actions.
*
* If an `index` action exists, additional naked routes will be created for it.
* Finally, all `actions` blueprints support an optional path parameter, `id`, for convenience.
*
* For example, assume we have an EmailController with actions `send` and `index`.
* With `actions` enabled, the following blueprint routes would be bound at runtime:
*
* `EmailController.index`
* :::::::::::::::::::::::::::::::::::::::::::::::::::::::
* `GET /email/:id?` `GET /email/index/:id?`
* `POST /email/:id?` `POST /email/index/:id?`
* `PUT /email/:id?` `PUT /email/index/:id?`
* `DELETE /email/:id?` `DELETE /email/index/:id?`
*
* `EmailController.send`
* :::::::::::::::::::::::::::::::::::::::::::::::::::::::
* `GET /email/send/:id?`
* `POST /email/send/:id?`
* `PUT /email/send/:id?`
* `DELETE /email/send/:id?`
*
*
* `actions` are enabled by default, and are OK for production-- however,
* you must take great care not to inadvertently expose unsafe controller logic to GET requests.
*/
actions: true,
/**
* `rest`
*
* REST blueprints are the automatically generated routes Sails uses to expose
* a conventional REST API on top of a controller's `find`, `create`, `update`, and `destroy`
* actions.
*
* For example, a BoatController with `rest` enabled generates the following routes:
* :::::::::::::::::::::::::::::::::::::::::::::::::::::::
* GET /boat/:id? -> BoatController.find
* POST /boat -> BoatController.create
* PUT /boat/:id -> BoatController.update
* DELETE /boat/:id -> BoatController.destroy
*
* `rest` blueprints are enabled by default, and suitable for a production scenario.
*/
rest: true,
/**
* `shortcuts`
*
* Shortcut blueprints are simple helpers to provide access to a controller's CRUD methods
* from your browser's URL bar. When enabled, GET, POST, PUT, and DELETE routes will be generated
* for the controller's`find`, `create`, `update`, and `destroy` actions.
*
* `shortcuts` are enabled by default, but SHOULD BE DISABLED IN PRODUCTION!!!!!
*/
shortcuts: true,
/**
* `prefix`
*
* An optional mount path for all blueprint routes on a controller, including `rest`,
* `actions`, and `shortcuts`. This allows you to continue to use blueprints, even if you
* need to namespace your API methods.
*
* For example, `prefix: '/api/v2'` would make the following REST blueprint routes
* for a FooController:
*
* `GET /api/v2/foo/:id?`
* `POST /api/v2/foo`
* `PUT /api/v2/foo/:id`
* `DELETE /api/v2/foo/:id`
*
* By default, no prefix is used.
*/
prefix: '',
/**
* `pluralize`
*
* Whether to pluralize controller names in generated routes
*
* For example, REST blueprints for `FooController` with `pluralize` enabled:
* GET /foos/:id?
* POST /foos
* PUT /foos/:id?
* DELETE /foos/:id?
*/
pluralize: false
},
/**
* `jsonp`
*
* If enabled, allows built-in CRUD methods to support JSONP for cross-domain requests.
*
* Example usage (REST blueprint + UserController):
* `GET /user?name=ciaran&limit=10&callback=receiveJSONPResponse`
*
* Defaults to false.
*/
jsonp: false,
/**
* `expectIntegerId`
*
* If enabled, built-in CRUD methods will only accept valid integers as an :id parameter.
*
* i.e. trigger built-in API if requests look like:
* `GET /user/8`
* but not like:
* `GET /user/a8j4g9jsd9ga4ghjasdha`
*
* Defaults to false.
*/
expectIntegerId: false
};
|
/* global expect, describe, it */
describe('Object.setPrototypeOf(o, p)', function () {
'use strict';
it('changes prototype to regular objects', function () {
var obj = { a: 123 };
expect(obj).to.be.an.instanceOf(Object);
// sham requires assignment to work cross browser
obj = Object.setPrototypeOf(obj, null);
expect(obj).not.to.be.an.instanceOf(Object);
expect(obj.a).to.equal(123);
});
it('changes prototype to null objects', function () {
var obj = Object.create(null);
obj.a = 456;
expect(obj).not.to.be.an.instanceOf(Object);
expect(obj.a).to.equal(456);
// sham requires assignment to work cross browser
obj = Object.setPrototypeOf(obj, {});
expect(obj).to.be.an.instanceOf(Object);
expect(obj.a).to.equal(456);
});
});
|
/*globals describe, it, before, beforeEach, afterEach */
/*jshint expr:true*/
var should = require('should'),
sinon = require('sinon'),
Promise = require('bluebird'),
rewire = require('rewire'),
// Thing we're testing
pagination = rewire('../../server/models/base/pagination');
// To stop jshint complaining
should.equal(true, true);
describe('pagination', function () {
var sandbox,
paginationUtils;
beforeEach(function () {
sandbox = sinon.sandbox.create();
});
afterEach(function () {
sandbox.restore();
});
describe('paginationUtils', function () {
before(function () {
paginationUtils = pagination.__get__('paginationUtils');
});
describe('formatResponse', function () {
var formatResponse;
before(function () {
formatResponse = paginationUtils.formatResponse;
});
it('returns correct pagination object for single page', function () {
formatResponse(5, {limit: 10, page: 1}).should.eql({
limit: 10,
next: null,
page: 1,
pages: 1,
prev: null,
total: 5
});
});
it('returns correct pagination object for first page of many', function () {
formatResponse(44, {limit: 5, page: 1}).should.eql({
limit: 5,
next: 2,
page: 1,
pages: 9,
prev: null,
total: 44
});
});
it('returns correct pagination object for middle page of many', function () {
formatResponse(44, {limit: 5, page: 9}).should.eql({
limit: 5,
next: null,
page: 9,
pages: 9,
prev: 8,
total: 44
});
});
it('returns correct pagination object for last page of many', function () {
formatResponse(44, {limit: 5, page: 3}).should.eql({
limit: 5,
next: 4,
page: 3,
pages: 9,
prev: 2,
total: 44
});
});
it('returns correct pagination object when page not set', function () {
formatResponse(5, {limit: 10}).should.eql({
limit: 10,
next: null,
page: 1,
pages: 1,
prev: null,
total: 5
});
});
it('returns correct pagination object for limit all', function () {
formatResponse(5, {limit: 'all'}).should.eql({
limit: 'all',
next: null,
page: 1,
pages: 1,
prev: null,
total: 5
});
});
});
describe('parseOptions', function () {
var parseOptions;
before(function () {
parseOptions = paginationUtils.parseOptions;
});
it('should use defaults if no options are passed', function () {
parseOptions().should.eql({
limit: 15,
page: 1
});
});
it('should accept numbers for limit and page', function () {
parseOptions({
limit: 10,
page: 2
}).should.eql({
limit: 10,
page: 2
});
});
it('should use defaults if bad options are passed', function () {
parseOptions({
limit: 'thelma',
page: 'louise'
}).should.eql({
limit: 15,
page: 1
});
});
it('should permit all for limit', function () {
parseOptions({
limit: 'all'
}).should.eql({
limit: 'all',
page: 1
});
});
});
describe('query', function () {
var query,
collection = {};
before(function () {
query = paginationUtils.query;
});
beforeEach(function () {
collection.query = sandbox.stub().returns(collection);
});
it('should add query options if limit is set', function () {
query(collection, {limit: 5, page: 1});
collection.query.calledTwice.should.be.true;
collection.query.firstCall.calledWith('limit', 5).should.be.true;
collection.query.secondCall.calledWith('offset', 0).should.be.true;
});
it('should not add query options if limit is not set', function () {
query(collection, {page: 1});
collection.query.called.should.be.false;
});
});
});
describe('fetchPage', function () {
var model, bookshelf, on, mockQuery, fetch, colQuery;
before(function () {
paginationUtils = pagination.__get__('paginationUtils');
});
beforeEach(function () {
// Stub paginationUtils
paginationUtils.parseOptions = sandbox.stub();
paginationUtils.query = sandbox.stub();
paginationUtils.formatResponse = sandbox.stub().returns({});
// Mock out bookshelf model
mockQuery = {
clone: sandbox.stub(),
count: sandbox.stub()
};
mockQuery.clone.returns(mockQuery);
mockQuery.count.returns([{aggregate: 1}]);
fetch = sandbox.stub().returns(Promise.resolve({}));
colQuery = sandbox.stub();
on = function () { return this; };
on = sandbox.spy(on);
model = function () {};
model.prototype.constructor = {
collection: sandbox.stub().returns({
on: on,
fetch: fetch,
query: colQuery
})
};
model.prototype.query = sandbox.stub();
model.prototype.resetQuery = sandbox.stub();
model.prototype.query.returns(mockQuery);
bookshelf = {Model: model};
pagination(bookshelf);
});
it('extends Model with fetchPage', function () {
bookshelf.Model.prototype.should.have.ownProperty('fetchPage');
bookshelf.Model.prototype.fetchPage.should.be.a.Function;
});
it('fetchPage calls all paginationUtils and methods', function (done) {
paginationUtils.parseOptions.returns({});
bookshelf.Model.prototype.fetchPage().then(function () {
sinon.assert.callOrder(
paginationUtils.parseOptions,
model.prototype.constructor.collection,
model.prototype.query,
mockQuery.clone,
mockQuery.count,
model.prototype.query,
mockQuery.clone,
paginationUtils.query,
on,
on,
fetch,
paginationUtils.formatResponse
);
paginationUtils.parseOptions.calledOnce.should.be.true;
paginationUtils.parseOptions.calledWith(undefined).should.be.true;
paginationUtils.query.calledOnce.should.be.true;
paginationUtils.formatResponse.calledOnce.should.be.true;
model.prototype.constructor.collection.calledOnce.should.be.true;
model.prototype.constructor.collection.calledWith().should.be.true;
model.prototype.query.calledTwice.should.be.true;
model.prototype.query.firstCall.calledWith().should.be.true;
model.prototype.query.secondCall.calledWith().should.be.true;
mockQuery.clone.calledTwice.should.be.true;
mockQuery.clone.firstCall.calledWith().should.be.true;
mockQuery.clone.secondCall.calledWith().should.be.true;
mockQuery.count.calledOnce.should.be.true;
mockQuery.count.calledWith().should.be.true;
on.calledTwice.should.be.true;
on.firstCall.calledWith('fetching').should.be.true;
on.secondCall.calledWith('fetched').should.be.true;
fetch.calledOnce.should.be.true;
fetch.calledWith({}).should.be.true;
done();
}).catch(done);
});
it('fetchPage calls all paginationUtils and methods when order set', function (done) {
var orderOptions = {order: {id: 'DESC'}};
paginationUtils.parseOptions.returns(orderOptions);
bookshelf.Model.prototype.fetchPage(orderOptions).then(function () {
sinon.assert.callOrder(
paginationUtils.parseOptions,
model.prototype.constructor.collection,
model.prototype.query,
mockQuery.clone,
mockQuery.count,
model.prototype.query,
mockQuery.clone,
paginationUtils.query,
colQuery,
on,
on,
fetch,
paginationUtils.formatResponse
);
paginationUtils.parseOptions.calledOnce.should.be.true;
paginationUtils.parseOptions.calledWith(orderOptions).should.be.true;
paginationUtils.query.calledOnce.should.be.true;
paginationUtils.formatResponse.calledOnce.should.be.true;
model.prototype.constructor.collection.calledOnce.should.be.true;
model.prototype.constructor.collection.calledWith().should.be.true;
model.prototype.query.calledTwice.should.be.true;
model.prototype.query.firstCall.calledWith().should.be.true;
model.prototype.query.secondCall.calledWith().should.be.true;
mockQuery.clone.calledTwice.should.be.true;
mockQuery.clone.firstCall.calledWith().should.be.true;
mockQuery.clone.secondCall.calledWith().should.be.true;
mockQuery.count.calledOnce.should.be.true;
mockQuery.count.calledWith().should.be.true;
colQuery.calledOnce.should.be.true;
colQuery.calledWith('orderBy', 'undefined.id', 'DESC').should.be.true;
on.calledTwice.should.be.true;
on.firstCall.calledWith('fetching').should.be.true;
on.secondCall.calledWith('fetched').should.be.true;
fetch.calledOnce.should.be.true;
fetch.calledWith(orderOptions).should.be.true;
done();
}).catch(done);
});
it('fetchPage returns expected response', function (done) {
paginationUtils.parseOptions.returns({});
bookshelf.Model.prototype.fetchPage().then(function (result) {
result.should.have.ownProperty('collection');
result.should.have.ownProperty('pagination');
result.collection.should.be.an.Object;
result.pagination.should.be.an.Object;
done();
});
});
});
});
|
/* ============================================================
* bootstrap-dropdown.js v2.0.0
* http://twitter.github.com/bootstrap/javascript.html#dropdowns
* ============================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============================================================ */
!function( $ ){
"use strict"
/* DROPDOWN CLASS DEFINITION
* ========================= */
var toggle = '[data-toggle="dropdown"]'
, Dropdown = function ( element ) {
var $el = $(element).on('click.dropdown.data-api', this.toggle)
$('html').on('click.dropdown.data-api', function () {
$el.parent().removeClass('open')
})
}
Dropdown.prototype = {
constructor: Dropdown
, toggle: function ( e ) {
var $this = $(this)
, selector = $this.attr('data-target')
, $parent
, isActive
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
}
$parent = $(selector)
$parent.length || ($parent = $this.parent())
isActive = $parent.hasClass('open')
clearMenus()
!isActive && $parent.toggleClass('open')
return false
}
}
function clearMenus() {
$(toggle).parent().removeClass('open')
}
/* DROPDOWN PLUGIN DEFINITION
* ========================== */
$.fn.dropdown = function ( option ) {
return this.each(function () {
var $this = $(this)
, data = $this.data('dropdown')
if (!data) $this.data('dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
$.fn.dropdown.Constructor = Dropdown
/* APPLY TO STANDARD DROPDOWN ELEMENTS
* =================================== */
$(function () {
$('html').on('click.dropdown.data-api', clearMenus)
$('body').on('click.dropdown.data-api', toggle, Dropdown.prototype.toggle)
})
}( window.jQuery )
|
/*
* File: AutoFill.js
* Version: 1.1.2
* CVS: $Id$
* Description: AutoFill for DataTables
* Author: Allan Jardine (www.sprymedia.co.uk)
* Created: Mon 6 Sep 2010 16:54:41 BST
* Modified: $Date$ by $Author$
* Language: Javascript
* License: GPL v2 or BSD 3 point
* Project: DataTables
* Contact: www.sprymedia.co.uk/contact
*
* Copyright 2010-2011 Allan Jardine, all rights reserved.
*
* This source file is free software, under either the GPL v2 license or a
* BSD style license, available at:
* http://datatables.net/license_gpl2
* http://datatables.net/license_bsd
*
*/
/* Global scope for AutoFill */
var AutoFill;
(function($) {
/**
* AutoFill provides Excel like auto fill features for a DataTable
* @class AutoFill
* @constructor
* @param {object} DataTables settings object
* @param {object} Configuration object for AutoFill
*/
AutoFill = function( oDT, oConfig )
{
/* Santiy check that we are a new instance */
if ( !this.CLASS || this.CLASS != "AutoFill" )
{
alert( "Warning: AutoFill must be initialised with the keyword 'new'" );
return;
}
if ( !$.fn.dataTableExt.fnVersionCheck('1.7.0') )
{
alert( "Warning: AutoFill requires DataTables 1.7 or greater - www.datatables.net/download");
return;
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Public class variables
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* @namespace Settings object which contains customisable information for AutoFill instance
*/
this.s = {
/**
* @namespace Cached information about the little dragging icon (the filler)
*/
"filler": {
"height": 0,
"width": 0
},
/**
* @namespace Cached information about the border display
*/
"border": {
"width": 2
},
/**
* @namespace Store for live information for the current drag
*/
"drag": {
"startX": -1,
"startY": -1,
"startTd": null,
"endTd": null,
"dragging": false
},
/**
* @namespace Data cache for information that we need for scrolling the screen when we near
* the edges
*/
"screen": {
"interval": null,
"y": 0,
"height": 0,
"scrollTop": 0
},
/**
* @namespace Data cache for the position of the DataTables scrolling element (when scrolling
* is enabled)
*/
"scroller": {
"top": 0,
"bottom": 0
},
/**
* @namespace Information stored for each column. An array of objects
*/
"columns": []
};
/**
* @namespace Common and useful DOM elements for the class instance
*/
this.dom = {
"table": null,
"filler": null,
"borderTop": null,
"borderRight": null,
"borderBottom": null,
"borderLeft": null,
"currentTarget": null
};
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Public class methods
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Retreieve the settings object from an instance
* @method fnSettings
* @returns {object} AutoFill settings object
*/
this.fnSettings = function () {
return this.s;
};
/* Constructor logic */
this._fnInit( oDT, oConfig );
return this;
};
AutoFill.prototype = {
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Private methods (they are of course public in JS, but recommended as private)
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Initialisation
* @method _fnInit
* @param {object} oDT DataTables settings object
* @param {object} oConfig Configuration object for AutoFill
* @returns void
*/
"_fnInit": function ( oDT, oConfig )
{
var
that = this,
i, iLen;
/*
* Settings
*/
this.s.dt = oDT.fnSettings();
this.dom.table = this.s.dt.nTable;
/* Add and configure the columns */
for ( i=0, iLen=this.s.dt.aoColumns.length ; i<iLen ; i++ )
{
this._fnAddColumn( i );
}
if ( typeof oConfig != 'undefined' && typeof oConfig.aoColumnDefs != 'undefined' )
{
this._fnColumnDefs( oConfig.aoColumnDefs );
}
if ( typeof oConfig != 'undefined' && typeof oConfig.aoColumns != 'undefined' )
{
this._fnColumnsAll( oConfig.aoColumns );
}
/*
* DOM
*/
/* Auto Fill click and drag icon */
var filler = document.createElement('div');
filler.className = "AutoFill_filler";
document.body.appendChild( filler );
this.dom.filler = filler;
filler.style.display = "block";
this.s.filler.height = $(filler).height();
this.s.filler.width = $(filler).width();
filler.style.display = "none";
/* Border display - one div for each side. We can't just use a single one with a border, as
* we want the events to effectively pass through the transparent bit of the box
*/
var border;
var appender = document.body;
if ( that.s.dt.oScroll.sY !== "" )
{
that.s.dt.nTable.parentNode.style.position = "relative";
appender = that.s.dt.nTable.parentNode;
}
border = document.createElement('div');
border.className = "AutoFill_border";
appender.appendChild( border );
this.dom.borderTop = border;
border = document.createElement('div');
border.className = "AutoFill_border";
appender.appendChild( border );
this.dom.borderRight = border;
border = document.createElement('div');
border.className = "AutoFill_border";
appender.appendChild( border );
this.dom.borderBottom = border;
border = document.createElement('div');
border.className = "AutoFill_border";
appender.appendChild( border );
this.dom.borderLeft = border;
/*
* Events
*/
$(filler).mousedown( function (e) {
this.onselectstart = function() { return false; };
that._fnFillerDragStart.call( that, e );
return false;
} );
$('tbody>tr>td', this.dom.table).live( 'mouseover mouseout', function (e) {
that._fnFillerDisplay.call( that, e );
} );
},
"_fnColumnDefs": function ( aoColumnDefs )
{
var
i, j, k, iLen, jLen, kLen,
aTargets;
/* Loop over the column defs array - loop in reverse so first instace has priority */
for ( i=aoColumnDefs.length-1 ; i>=0 ; i-- )
{
/* Each column def can target multiple columns, as it is an array */
aTargets = aoColumnDefs[i].aTargets;
for ( j=0, jLen=aTargets.length ; j<jLen ; j++ )
{
if ( typeof aTargets[j] == 'number' && aTargets[j] >= 0 )
{
/* 0+ integer, left to right column counting. */
this._fnColumnOptions( aTargets[j], aoColumnDefs[i] );
}
else if ( typeof aTargets[j] == 'number' && aTargets[j] < 0 )
{
/* Negative integer, right to left column counting */
this._fnColumnOptions( this.s.dt.aoColumns.length+aTargets[j], aoColumnDefs[i] );
}
else if ( typeof aTargets[j] == 'string' )
{
/* Class name matching on TH element */
for ( k=0, kLen=this.s.dt.aoColumns.length ; k<kLen ; k++ )
{
if ( aTargets[j] == "_all" ||
this.s.dt.aoColumns[k].nTh.className.indexOf( aTargets[j] ) != -1 )
{
this._fnColumnOptions( k, aoColumnDefs[i] );
}
}
}
}
}
},
"_fnColumnsAll": function ( aoColumns )
{
for ( var i=0, iLen=this.s.dt.aoColumns.length ; i<iLen ; i++ )
{
this._fnColumnOptions( i, aoColumns[i] );
}
},
"_fnAddColumn": function ( i )
{
this.s.columns[i] = {
"enable": true,
"read": this._fnReadCell,
"write": this._fnWriteCell,
"step": this._fnStep,
"complete": null
};
},
"_fnColumnOptions": function ( i, opts )
{
if ( typeof opts.bEnable != 'undefined' )
{
this.s.columns[i].enable = opts.bEnable;
}
if ( typeof opts.fnRead != 'undefined' )
{
this.s.columns[i].read = opts.fnRead;
}
if ( typeof opts.fnWrite != 'undefined' )
{
this.s.columns[i].write = opts.fnWrite;
}
if ( typeof opts.fnStep != 'undefined' )
{
this.s.columns[i].step = opts.fnStep;
}
if ( typeof opts.fnCallback != 'undefined' )
{
this.s.columns[i].complete = opts.fnCallback;
}
},
/**
* Find out the coordinates of a given TD cell in a table
* @method _fnTargetCoords
* @param {Node} nTd
* @returns {Object} x and y properties, for the position of the cell in the tables DOM
*/
"_fnTargetCoords": function ( nTd )
{
var nTr = $(nTd).parents('tr')[0];
return {
"x": $('td', nTr).index(nTd),
"y": $('tr', nTr.parentNode).index(nTr)
};
},
/**
* Display the border around one or more cells (from start to end)
* @method _fnUpdateBorder
* @param {Node} nStart Starting cell
* @param {Node} nEnd Ending cell
* @returns void
*/
"_fnUpdateBorder": function ( nStart, nEnd )
{
var
border = this.s.border.width,
offsetStart = $(nStart).offset(),
offsetEnd = $(nEnd).offset(),
x1 = offsetStart.left - border,
x2 = offsetEnd.left + $(nEnd).outerWidth(),
y1 = offsetStart.top - border,
y2 = offsetEnd.top + $(nEnd).outerHeight(),
width = offsetEnd.left + $(nEnd).outerWidth() - offsetStart.left + (2*border),
height = offsetEnd.top + $(nEnd).outerHeight() - offsetStart.top + (2*border),
oStyle;
if ( this.s.dt.oScroll.sY !== "" )
{
/* The border elements are inside the DT scroller - so position relative to that */
var
offsetScroll = $(this.s.dt.nTable.parentNode).offset(),
scrollTop = $(this.s.dt.nTable.parentNode).scrollTop(),
scrollLeft = $(this.s.dt.nTable.parentNode).scrollLeft();
x1 -= offsetScroll.left - scrollLeft;
x2 -= offsetScroll.left - scrollLeft;
y1 -= offsetScroll.top - scrollTop;
y2 -= offsetScroll.top - scrollTop;
}
/* Top */
oStyle = this.dom.borderTop.style;
oStyle.top = y1+"px";
oStyle.left = x1+"px";
oStyle.height = this.s.border.width+"px";
oStyle.width = width+"px";
/* Bottom */
oStyle = this.dom.borderBottom.style;
oStyle.top = y2+"px";
oStyle.left = x1+"px";
oStyle.height = this.s.border.width+"px";
oStyle.width = width+"px";
/* Left */
oStyle = this.dom.borderLeft.style;
oStyle.top = y1+"px";
oStyle.left = x1+"px";
oStyle.height = height+"px";
oStyle.width = this.s.border.width+"px";
/* Right */
oStyle = this.dom.borderRight.style;
oStyle.top = y1+"px";
oStyle.left = x2+"px";
oStyle.height = height+"px";
oStyle.width = this.s.border.width+"px";
},
/**
* Mouse down event handler for starting a drag
* @method _fnFillerDragStart
* @param {Object} e Event object
* @returns void
*/
"_fnFillerDragStart": function (e)
{
var that = this;
var startingTd = this.dom.currentTarget;
this.s.drag.dragging = true;
that.dom.borderTop.style.display = "block";
that.dom.borderRight.style.display = "block";
that.dom.borderBottom.style.display = "block";
that.dom.borderLeft.style.display = "block";
var coords = this._fnTargetCoords( startingTd );
this.s.drag.startX = coords.x;
this.s.drag.startY = coords.y;
this.s.drag.startTd = startingTd;
this.s.drag.endTd = startingTd;
this._fnUpdateBorder( startingTd, startingTd );
$(document).bind('mousemove.AutoFill', function (e) {
that._fnFillerDragMove.call( that, e );
} );
$(document).bind('mouseup.AutoFill', function (e) {
that._fnFillerFinish.call( that, e );
} );
/* Scrolling information cache */
this.s.screen.y = e.pageY;
this.s.screen.height = $(window).height();
this.s.screen.scrollTop = $(document).scrollTop();
if ( this.s.dt.oScroll.sY !== "" )
{
this.s.scroller.top = $(this.s.dt.nTable.parentNode).offset().top;
this.s.scroller.bottom = this.s.scroller.top + $(this.s.dt.nTable.parentNode).height();
}
/* Scrolling handler - we set an interval (which is cancelled on mouse up) which will fire
* regularly and see if we need to do any scrolling
*/
this.s.screen.interval = setInterval( function () {
var iScrollTop = $(document).scrollTop();
var iScrollDelta = iScrollTop - that.s.screen.scrollTop;
that.s.screen.y += iScrollDelta;
if ( that.s.screen.height - that.s.screen.y + iScrollTop < 50 )
{
$('html, body').animate( {
"scrollTop": iScrollTop + 50
}, 240, 'linear' );
}
else if ( that.s.screen.y - iScrollTop < 50 )
{
$('html, body').animate( {
"scrollTop": iScrollTop - 50
}, 240, 'linear' );
}
if ( that.s.dt.oScroll.sY !== "" )
{
if ( that.s.screen.y > that.s.scroller.bottom - 50 )
{
$(that.s.dt.nTable.parentNode).animate( {
"scrollTop": $(that.s.dt.nTable.parentNode).scrollTop() + 50
}, 240, 'linear' );
}
else if ( that.s.screen.y < that.s.scroller.top + 50 )
{
$(that.s.dt.nTable.parentNode).animate( {
"scrollTop": $(that.s.dt.nTable.parentNode).scrollTop() - 50
}, 240, 'linear' );
}
}
}, 250 );
},
/**
* Mouse move event handler for during a move. See if we want to update the display based on the
* new cursor position
* @method _fnFillerDragMove
* @param {Object} e Event object
* @returns void
*/
"_fnFillerDragMove": function (e)
{
if ( e.target && e.target.nodeName.toUpperCase() == "TD" &&
e.target != this.s.drag.endTd )
{
var coords = this._fnTargetCoords( e.target );
if ( coords.x != this.s.drag.startX )
{
e.target = $('tbody>tr:eq('+coords.y+')>td:eq('+this.s.drag.startX+')', this.dom.table)[0];
coords = this._fnTargetCoords( e.target );
}
if ( coords.x == this.s.drag.startX )
{
var drag = this.s.drag;
drag.endTd = e.target;
if ( coords.y >= this.s.drag.startY )
{
this._fnUpdateBorder( drag.startTd, drag.endTd );
}
else
{
this._fnUpdateBorder( drag.endTd, drag.startTd );
}
this._fnFillerPosition( e.target );
}
}
/* Update the screen information so we can perform scrolling */
this.s.screen.y = e.pageY;
this.s.screen.scrollTop = $(document).scrollTop();
if ( this.s.dt.oScroll.sY !== "" )
{
this.s.scroller.scrollTop = $(this.s.dt.nTable.parentNode).scrollTop();
this.s.scroller.top = $(this.s.dt.nTable.parentNode).offset().top;
this.s.scroller.bottom = this.s.scroller.top + $(this.s.dt.nTable.parentNode).height();
}
},
/**
* Mouse release handler - end the drag and take action to update the cells with the needed values
* @method _fnFillerFinish
* @param {Object} e Event object
* @returns void
*/
"_fnFillerFinish": function (e)
{
var that = this;
$(document).unbind('mousemove.AutoFill');
$(document).unbind('mouseup.AutoFill');
this.dom.borderTop.style.display = "none";
this.dom.borderRight.style.display = "none";
this.dom.borderBottom.style.display = "none";
this.dom.borderLeft.style.display = "none";
this.s.drag.dragging = false;
clearInterval( this.s.screen.interval );
var coordsStart = this._fnTargetCoords( this.s.drag.startTd );
var coordsEnd = this._fnTargetCoords( this.s.drag.endTd );
var aTds = [];
var bIncrement;
if ( coordsStart.y <= coordsEnd.y )
{
bIncrement = true;
for ( i=coordsStart.y ; i<=coordsEnd.y ; i++ )
{
aTds.push( $('tbody>tr:eq('+i+')>td:eq('+coordsStart.x+')', this.dom.table)[0] );
}
}
else
{
bIncrement = false;
for ( i=coordsStart.y ; i>=coordsEnd.y ; i-- )
{
aTds.push( $('tbody>tr:eq('+i+')>td:eq('+coordsStart.x+')', this.dom.table)[0] );
}
}
var iColumn = coordsStart.x;
var bLast = false;
var aoEdited = [];
var sStart = this.s.columns[iColumn].read.call( this, this.s.drag.startTd );
var oPrepped = this._fnPrep( sStart );
for ( i=0, iLen=aTds.length ; i<iLen ; i++ )
{
if ( i==iLen-1 )
{
bLast = true;
}
var original = this.s.columns[iColumn].read.call( this, aTds[i] );
var step = this.s.columns[iColumn].step.call( this, aTds[i], oPrepped, i, bIncrement,
'SPRYMEDIA_AUTOFILL_STEPPER' );
this.s.columns[iColumn].write.call( this, aTds[i], step, bLast );
aoEdited.push( {
"td": aTds[i],
"newValue": step,
"oldValue": original
} );
}
if ( this.s.columns[iColumn].complete !== null )
{
this.s.columns[iColumn].complete.call( this, aoEdited );
}
},
/**
* Chunk a string such that it can be filled in by the stepper function
* @method _fnPrep
* @param {String} sStr String to prep
* @returns {Object} with parameters, iStart, sStr and sPostFix
*/
"_fnPrep": function ( sStr )
{
var aMatch = sStr.match(/[\d\.]+/g);
if ( !aMatch || aMatch.length === 0 )
{
return {
"iStart": 0,
"sStr": sStr,
"sPostFix": ""
};
}
var sLast = aMatch[ aMatch.length-1 ];
var num = parseInt(sLast, 10);
var regex = new RegExp( '^(.*)'+sLast+'(.*?)$' );
var decimal = sLast.match(/\./) ? "."+sLast.split('.')[1] : "";
return {
"iStart": num,
"sStr": sStr.replace(regex, "$1SPRYMEDIA_AUTOFILL_STEPPER$2"),
"sPostFix": decimal
};
},
/**
* Render a string for it's position in the table after the drag (incrememt numbers)
* @method _fnStep
* @param {Node} nTd Cell being written to
* @param {Object} oPrepped Prepared object for the stepper (from _fnPrep)
* @param {Int} iDiff Step difference
* @param {Boolean} bIncrement Increment (true) or decriment (false)
* @param {String} sToken Token to replace
* @returns {String} Rendered information
*/
"_fnStep": function ( nTd, oPrepped, iDiff, bIncrement, sToken )
{
var iReplace = bIncrement ? (oPrepped.iStart+iDiff) : (oPrepped.iStart-iDiff);
if ( isNaN(iReplace) )
{
iReplace = "";
}
return oPrepped.sStr.replace( sToken, iReplace+oPrepped.sPostFix );
},
/**
* Read informaiton from a cell, possibly using live DOM elements if suitable
* @method _fnReadCell
* @param {Node} nTd Cell to read
* @returns {String} Read value
*/
"_fnReadCell": function ( nTd )
{
var jq = $('input', nTd);
if ( jq.length > 0 )
{
return $(jq).val();
}
jq = $('select', nTd);
if ( jq.length > 0 )
{
return $(jq).val();
}
return nTd.innerHTML;
},
/**
* Write informaiton to a cell, possibly using live DOM elements if suitable
* @method _fnWriteCell
* @param {Node} nTd Cell to write
* @param {String} sVal Value to write
* @param {Boolean} bLast Flag to show if this is that last update
* @returns void
*/
"_fnWriteCell": function ( nTd, sVal, bLast )
{
var jq = $('input', nTd);
if ( jq.length > 0 )
{
$(jq).val( sVal );
return;
}
jq = $('select', nTd);
if ( jq.length > 0 )
{
$(jq).val( sVal );
return;
}
var pos = this.s.dt.oInstance.fnGetPosition( nTd );
this.s.dt.oInstance.fnUpdate( sVal, pos[0], pos[2], bLast );
},
/**
* Display the drag handle on mouse over cell
* @method _fnFillerDisplay
* @param {Object} e Event object
* @returns void
*/
"_fnFillerDisplay": function (e)
{
/* Don't display automatically when dragging */
if ( this.s.drag.dragging)
{
return;
}
/* Check that we are allowed to AutoFill this column or not */
var nTd = (e.target.nodeName.toLowerCase() == 'td') ? e.target : $(e.target).parents('td')[0];
var iX = this._fnTargetCoords(nTd).x;
if ( !this.s.columns[iX].enable )
{
return;
}
var filler = this.dom.filler;
if (e.type == 'mouseover')
{
this.dom.currentTarget = nTd;
this._fnFillerPosition( nTd );
filler.style.display = "block";
}
else if ( !e.relatedTarget || !e.relatedTarget.className.match(/AutoFill/) )
{
filler.style.display = "none";
}
},
/**
* Position the filler icon over a cell
* @method _fnFillerPosition
* @param {Node} nTd Cell to position filler icon over
* @returns void
*/
"_fnFillerPosition": function ( nTd )
{
var offset = $(nTd).offset();
var filler = this.dom.filler;
filler.style.top = (offset.top - (this.s.filler.height / 2)-1 + $(nTd).outerHeight())+"px";
filler.style.left = (offset.left - (this.s.filler.width / 2)-1 + $(nTd).outerWidth())+"px";
}
};
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Constants
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Name of this class
* @constant CLASS
* @type String
* @default AutoFill
*/
AutoFill.prototype.CLASS = "AutoFill";
/**
* AutoFill version
* @constant VERSION
* @type String
* @default 1.1.2
*/
AutoFill.VERSION = "1.1.2";
AutoFill.prototype.VERSION = AutoFill.VERSION;
})(jQuery);
|
/*
AngularJS v1.2.0
(c) 2010-2012 Google, Inc. http://angularjs.org
License: MIT
*/
(function(W,O,s){'use strict';function L(b){return function(){var a=arguments[0],c,a="["+(b?b+":":"")+a+"] http://errors.angularjs.org/undefined/"+(b?b+"/":"")+a;for(c=1;c<arguments.length;c++)a=a+(1==c?"?":"&")+"p"+(c-1)+"="+encodeURIComponent("function"==typeof arguments[c]?arguments[c].toString().replace(/ \{[\s\S]*$/,""):"undefined"==typeof arguments[c]?"undefined":"string"!=typeof arguments[c]?JSON.stringify(arguments[c]):arguments[c]);return Error(a)}}function pb(b){if(null==b||ya(b))return!1;
var a=b.length;return 1===b.nodeType&&a?!0:D(b)||J(b)||0===a||"number"===typeof a&&0<a&&a-1 in b}function q(b,a,c){var d;if(b)if(B(b))for(d in b)"prototype"!=d&&("length"!=d&&"name"!=d&&b.hasOwnProperty(d))&&a.call(c,b[d],d);else if(b.forEach&&b.forEach!==q)b.forEach(a,c);else if(pb(b))for(d=0;d<b.length;d++)a.call(c,b[d],d);else for(d in b)b.hasOwnProperty(d)&&a.call(c,b[d],d);return b}function Nb(b){var a=[],c;for(c in b)b.hasOwnProperty(c)&&a.push(c);return a.sort()}function Jc(b,a,c){for(var d=
Nb(b),e=0;e<d.length;e++)a.call(c,b[d[e]],d[e]);return d}function Ob(b){return function(a,c){b(c,a)}}function Za(){for(var b=ia.length,a;b;){b--;a=ia[b].charCodeAt(0);if(57==a)return ia[b]="A",ia.join("");if(90==a)ia[b]="0";else return ia[b]=String.fromCharCode(a+1),ia.join("")}ia.unshift("0");return ia.join("")}function Pb(b,a){a?b.$$hashKey=a:delete b.$$hashKey}function u(b){var a=b.$$hashKey;q(arguments,function(a){a!==b&&q(a,function(a,c){b[c]=a})});Pb(b,a);return b}function U(b){return parseInt(b,
10)}function Qb(b,a){return u(new (u(function(){},{prototype:b})),a)}function t(){}function za(b){return b}function aa(b){return function(){return b}}function x(b){return"undefined"==typeof b}function z(b){return"undefined"!=typeof b}function T(b){return null!=b&&"object"==typeof b}function D(b){return"string"==typeof b}function qb(b){return"number"==typeof b}function Ja(b){return"[object Date]"==Ka.apply(b)}function J(b){return"[object Array]"==Ka.apply(b)}function B(b){return"function"==typeof b}
function $a(b){return"[object RegExp]"==Ka.apply(b)}function ya(b){return b&&b.document&&b.location&&b.alert&&b.setInterval}function Kc(b){return b&&(b.nodeName||b.on&&b.find)}function Lc(b,a,c){var d=[];q(b,function(b,f,g){d.push(a.call(c,b,f,g))});return d}function ab(b,a){if(b.indexOf)return b.indexOf(a);for(var c=0;c<b.length;c++)if(a===b[c])return c;return-1}function La(b,a){var c=ab(b,a);0<=c&&b.splice(c,1);return a}function da(b,a){if(ya(b)||b&&b.$evalAsync&&b.$watch)throw Ma("cpws");if(a){if(b===
a)throw Ma("cpi");if(J(b))for(var c=a.length=0;c<b.length;c++)a.push(da(b[c]));else{c=a.$$hashKey;q(a,function(b,c){delete a[c]});for(var d in b)a[d]=da(b[d]);Pb(a,c)}}else(a=b)&&(J(b)?a=da(b,[]):Ja(b)?a=new Date(b.getTime()):$a(b)?a=RegExp(b.source):T(b)&&(a=da(b,{})));return a}function Mc(b,a){a=a||{};for(var c in b)b.hasOwnProperty(c)&&"$$"!==c.substr(0,2)&&(a[c]=b[c]);return a}function Aa(b,a){if(b===a)return!0;if(null===b||null===a)return!1;if(b!==b&&a!==a)return!0;var c=typeof b,d;if(c==typeof a&&
"object"==c)if(J(b)){if(!J(a))return!1;if((c=b.length)==a.length){for(d=0;d<c;d++)if(!Aa(b[d],a[d]))return!1;return!0}}else{if(Ja(b))return Ja(a)&&b.getTime()==a.getTime();if($a(b)&&$a(a))return b.toString()==a.toString();if(b&&b.$evalAsync&&b.$watch||a&&a.$evalAsync&&a.$watch||ya(b)||ya(a)||J(a))return!1;c={};for(d in b)if("$"!==d.charAt(0)&&!B(b[d])){if(!Aa(b[d],a[d]))return!1;c[d]=!0}for(d in a)if(!c.hasOwnProperty(d)&&"$"!==d.charAt(0)&&a[d]!==s&&!B(a[d]))return!1;return!0}return!1}function Rb(){return O.securityPolicy&&
O.securityPolicy.isActive||O.querySelector&&!(!O.querySelector("[ng-csp]")&&!O.querySelector("[data-ng-csp]"))}function rb(b,a){var c=2<arguments.length?ta.call(arguments,2):[];return!B(a)||a instanceof RegExp?a:c.length?function(){return arguments.length?a.apply(b,c.concat(ta.call(arguments,0))):a.apply(b,c)}:function(){return arguments.length?a.apply(b,arguments):a.call(b)}}function Nc(b,a){var c=a;"string"===typeof b&&"$"===b.charAt(0)?c=s:ya(a)?c="$WINDOW":a&&O===a?c="$DOCUMENT":a&&(a.$evalAsync&&
a.$watch)&&(c="$SCOPE");return c}function ma(b,a){return"undefined"===typeof b?s:JSON.stringify(b,Nc,a?" ":null)}function Sb(b){return D(b)?JSON.parse(b):b}function Na(b){b&&0!==b.length?(b=w(""+b),b=!("f"==b||"0"==b||"false"==b||"no"==b||"n"==b||"[]"==b)):b=!1;return b}function ea(b){b=y(b).clone();try{b.html("")}catch(a){}var c=y("<div>").append(b).html();try{return 3===b[0].nodeType?w(c):c.match(/^(<[^>]+>)/)[1].replace(/^<([\w\-]+)/,function(a,b){return"<"+w(b)})}catch(d){return w(c)}}function Tb(b){try{return decodeURIComponent(b)}catch(a){}}
function Ub(b){var a={},c,d;q((b||"").split("&"),function(b){b&&(c=b.split("="),d=Tb(c[0]),z(d)&&(b=z(c[1])?Tb(c[1]):!0,a[d]?J(a[d])?a[d].push(b):a[d]=[a[d],b]:a[d]=b))});return a}function Vb(b){var a=[];q(b,function(b,d){J(b)?q(b,function(b){a.push(ua(d,!0)+(!0===b?"":"="+ua(b,!0)))}):a.push(ua(d,!0)+(!0===b?"":"="+ua(b,!0)))});return a.length?a.join("&"):""}function sb(b){return ua(b,!0).replace(/%26/gi,"&").replace(/%3D/gi,"=").replace(/%2B/gi,"+")}function ua(b,a){return encodeURIComponent(b).replace(/%40/gi,
"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,a?"%20":"+")}function Oc(b,a){function c(a){a&&d.push(a)}var d=[b],e,f,g=["ng:app","ng-app","x-ng-app","data-ng-app"],h=/\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;q(g,function(a){g[a]=!0;c(O.getElementById(a));a=a.replace(":","\\:");b.querySelectorAll&&(q(b.querySelectorAll("."+a),c),q(b.querySelectorAll("."+a+"\\:"),c),q(b.querySelectorAll("["+a+"]"),c))});q(d,function(a){if(!e){var b=h.exec(" "+a.className+" ");b?(e=a,f=
(b[2]||"").replace(/\s+/g,",")):q(a.attributes,function(b){!e&&g[b.name]&&(e=a,f=b.value)})}});e&&a(e,f?[f]:[])}function Wb(b,a){var c=function(){b=y(b);if(b.injector()){var c=b[0]===O?"document":ea(b);throw Ma("btstrpd",c);}a=a||[];a.unshift(["$provide",function(a){a.value("$rootElement",b)}]);a.unshift("ng");c=Xb(a);c.invoke(["$rootScope","$rootElement","$compile","$injector","$animate",function(a,b,c,d,e){a.$apply(function(){b.data("$injector",d);c(b)(a)})}]);return c},d=/^NG_DEFER_BOOTSTRAP!/;
if(W&&!d.test(W.name))return c();W.name=W.name.replace(d,"");bb.resumeBootstrap=function(b){q(b,function(b){a.push(b)});c()}}function cb(b,a){a=a||"_";return b.replace(Pc,function(b,d){return(d?a:"")+b.toLowerCase()})}function tb(b,a,c){if(!b)throw Ma("areq",a||"?",c||"required");return b}function Oa(b,a,c){c&&J(b)&&(b=b[b.length-1]);tb(B(b),a,"not a function, got "+(b&&"object"==typeof b?b.constructor.name||"Object":typeof b));return b}function na(b,a){if("hasOwnProperty"===b)throw Ma("badname",
a);}function ub(b,a,c){if(!a)return b;a=a.split(".");for(var d,e=b,f=a.length,g=0;g<f;g++)d=a[g],b&&(b=(e=b)[d]);return!c&&B(b)?rb(e,b):b}function vb(b){if(b.startNode===b.endNode)return y(b.startNode);var a=b.startNode,c=[a];do{a=a.nextSibling;if(!a)break;c.push(a)}while(a!==b.endNode);return y(c)}function Qc(b){function a(a,b,c){return a[b]||(a[b]=c())}var c=L("$injector");return a(a(b,"angular",Object),"module",function(){var b={};return function(e,f,g){na(e,"module");f&&b.hasOwnProperty(e)&&(b[e]=
null);return a(b,e,function(){function a(c,d,e){return function(){b[e||"push"]([c,d,arguments]);return n}}if(!f)throw c("nomod",e);var b=[],d=[],l=a("$injector","invoke"),n={_invokeQueue:b,_runBlocks:d,requires:f,name:e,provider:a("$provide","provider"),factory:a("$provide","factory"),service:a("$provide","service"),value:a("$provide","value"),constant:a("$provide","constant","unshift"),animation:a("$animateProvider","register"),filter:a("$filterProvider","register"),controller:a("$controllerProvider",
"register"),directive:a("$compileProvider","directive"),config:l,run:function(a){d.push(a);return this}};g&&l(g);return n})}})}function Pa(b){return b.replace(Rc,function(a,b,d,e){return e?d.toUpperCase():d}).replace(Sc,"Moz$1")}function wb(b,a,c,d){function e(b){var e=c&&b?[this.filter(b)]:[this],m=a,k,l,n,r,p,C;if(!d||null!=b)for(;e.length;)for(k=e.shift(),l=0,n=k.length;l<n;l++)for(r=y(k[l]),m?r.triggerHandler("$destroy"):m=!m,p=0,r=(C=r.children()).length;p<r;p++)e.push(Ba(C[p]));return f.apply(this,
arguments)}var f=Ba.fn[b],f=f.$original||f;e.$original=f;Ba.fn[b]=e}function Q(b){if(b instanceof Q)return b;if(!(this instanceof Q)){if(D(b)&&"<"!=b.charAt(0))throw xb("nosel");return new Q(b)}if(D(b)){var a=O.createElement("div");a.innerHTML="<div> </div>"+b;a.removeChild(a.firstChild);yb(this,a.childNodes);y(O.createDocumentFragment()).append(this)}else yb(this,b)}function zb(b){return b.cloneNode(!0)}function Qa(b){Yb(b);var a=0;for(b=b.childNodes||[];a<b.length;a++)Qa(b[a])}function Zb(b,
a,c,d){if(z(d))throw xb("offargs");var e=ja(b,"events");ja(b,"handle")&&(x(a)?q(e,function(a,c){Ab(b,c,a);delete e[c]}):q(a.split(" "),function(a){x(c)?(Ab(b,a,e[a]),delete e[a]):La(e[a]||[],c)}))}function Yb(b,a){var c=b[db],d=Ra[c];d&&(a?delete Ra[c].data[a]:(d.handle&&(d.events.$destroy&&d.handle({},"$destroy"),Zb(b)),delete Ra[c],b[db]=s))}function ja(b,a,c){var d=b[db],d=Ra[d||-1];if(z(c))d||(b[db]=d=++Tc,d=Ra[d]={}),d[a]=c;else return d&&d[a]}function $b(b,a,c){var d=ja(b,"data"),e=z(c),f=!e&&
z(a),g=f&&!T(a);d||g||ja(b,"data",d={});if(e)d[a]=c;else if(f){if(g)return d&&d[a];u(d,a)}else return d}function Bb(b,a){return b.getAttribute?-1<(" "+(b.getAttribute("class")||"")+" ").replace(/[\n\t]/g," ").indexOf(" "+a+" "):!1}function Cb(b,a){a&&b.setAttribute&&q(a.split(" "),function(a){b.setAttribute("class",Y((" "+(b.getAttribute("class")||"")+" ").replace(/[\n\t]/g," ").replace(" "+Y(a)+" "," ")))})}function Db(b,a){if(a&&b.setAttribute){var c=(" "+(b.getAttribute("class")||"")+" ").replace(/[\n\t]/g,
" ");q(a.split(" "),function(a){a=Y(a);-1===c.indexOf(" "+a+" ")&&(c+=a+" ")});b.setAttribute("class",Y(c))}}function yb(b,a){if(a){a=a.nodeName||!z(a.length)||ya(a)?[a]:a;for(var c=0;c<a.length;c++)b.push(a[c])}}function ac(b,a){return eb(b,"$"+(a||"ngController")+"Controller")}function eb(b,a,c){b=y(b);9==b[0].nodeType&&(b=b.find("html"));for(a=J(a)?a:[a];b.length;){for(var d=0,e=a.length;d<e;d++)if((c=b.data(a[d]))!==s)return c;b=b.parent()}}function bc(b,a){var c=fb[a.toLowerCase()];return c&&
cc[b.nodeName]&&c}function Uc(b,a){var c=function(c,e){c.preventDefault||(c.preventDefault=function(){c.returnValue=!1});c.stopPropagation||(c.stopPropagation=function(){c.cancelBubble=!0});c.target||(c.target=c.srcElement||O);if(x(c.defaultPrevented)){var f=c.preventDefault;c.preventDefault=function(){c.defaultPrevented=!0;f.call(c)};c.defaultPrevented=!1}c.isDefaultPrevented=function(){return c.defaultPrevented||!1===c.returnValue};q(a[e||c.type],function(a){a.call(b,c)});8>=P?(c.preventDefault=
null,c.stopPropagation=null,c.isDefaultPrevented=null):(delete c.preventDefault,delete c.stopPropagation,delete c.isDefaultPrevented)};c.elem=b;return c}function Ca(b){var a=typeof b,c;"object"==a&&null!==b?"function"==typeof(c=b.$$hashKey)?c=b.$$hashKey():c===s&&(c=b.$$hashKey=Za()):c=b;return a+":"+c}function Sa(b){q(b,this.put,this)}function dc(b){var a,c;"function"==typeof b?(a=b.$inject)||(a=[],b.length&&(c=b.toString().replace(Vc,""),c=c.match(Wc),q(c[1].split(Xc),function(b){b.replace(Yc,function(b,
c,d){a.push(d)})})),b.$inject=a):J(b)?(c=b.length-1,Oa(b[c],"fn"),a=b.slice(0,c)):Oa(b,"fn",!0);return a}function Xb(b){function a(a){return function(b,c){if(T(b))q(b,Ob(a));else return a(b,c)}}function c(a,b){na(a,"service");if(B(b)||J(b))b=n.instantiate(b);if(!b.$get)throw Ta("pget",a);return l[a+h]=b}function d(a,b){return c(a,{$get:b})}function e(a){var b=[],c,d,f,h;q(a,function(a){if(!k.get(a)){k.put(a,!0);try{if(D(a))for(c=Ua(a),b=b.concat(e(c.requires)).concat(c._runBlocks),d=c._invokeQueue,
f=0,h=d.length;f<h;f++){var g=d[f],m=n.get(g[0]);m[g[1]].apply(m,g[2])}else B(a)?b.push(n.invoke(a)):J(a)?b.push(n.invoke(a)):Oa(a,"module")}catch(l){throw J(a)&&(a=a[a.length-1]),l.message&&(l.stack&&-1==l.stack.indexOf(l.message))&&(l=l.message+"\n"+l.stack),Ta("modulerr",a,l.stack||l.message||l);}}});return b}function f(a,b){function c(d){if(a.hasOwnProperty(d)){if(a[d]===g)throw Ta("cdep",m.join(" <- "));return a[d]}try{return m.unshift(d),a[d]=g,a[d]=b(d)}finally{m.shift()}}function d(a,b,e){var f=
[],h=dc(a),g,k,m;k=0;for(g=h.length;k<g;k++){m=h[k];if("string"!==typeof m)throw Ta("itkn",m);f.push(e&&e.hasOwnProperty(m)?e[m]:c(m))}a.$inject||(a=a[g]);switch(b?-1:f.length){case 0:return a();case 1:return a(f[0]);case 2:return a(f[0],f[1]);case 3:return a(f[0],f[1],f[2]);case 4:return a(f[0],f[1],f[2],f[3]);case 5:return a(f[0],f[1],f[2],f[3],f[4]);case 6:return a(f[0],f[1],f[2],f[3],f[4],f[5]);case 7:return a(f[0],f[1],f[2],f[3],f[4],f[5],f[6]);case 8:return a(f[0],f[1],f[2],f[3],f[4],f[5],f[6],
f[7]);case 9:return a(f[0],f[1],f[2],f[3],f[4],f[5],f[6],f[7],f[8]);case 10:return a(f[0],f[1],f[2],f[3],f[4],f[5],f[6],f[7],f[8],f[9]);default:return a.apply(b,f)}}return{invoke:d,instantiate:function(a,b){var c=function(){},e;c.prototype=(J(a)?a[a.length-1]:a).prototype;c=new c;e=d(a,c,b);return T(e)||B(e)?e:c},get:c,annotate:dc,has:function(b){return l.hasOwnProperty(b+h)||a.hasOwnProperty(b)}}}var g={},h="Provider",m=[],k=new Sa,l={$provide:{provider:a(c),factory:a(d),service:a(function(a,b){return d(a,
["$injector",function(a){return a.instantiate(b)}])}),value:a(function(a,b){return d(a,aa(b))}),constant:a(function(a,b){na(a,"constant");l[a]=b;r[a]=b}),decorator:function(a,b){var c=n.get(a+h),d=c.$get;c.$get=function(){var a=p.invoke(d,c);return p.invoke(b,null,{$delegate:a})}}}},n=l.$injector=f(l,function(){throw Ta("unpr",m.join(" <- "));}),r={},p=r.$injector=f(r,function(a){a=n.get(a+h);return p.invoke(a.$get,a)});q(e(b),function(a){p.invoke(a||t)});return p}function Zc(){var b=!0;this.disableAutoScrolling=
function(){b=!1};this.$get=["$window","$location","$rootScope",function(a,c,d){function e(a){var b=null;q(a,function(a){b||"a"!==w(a.nodeName)||(b=a)});return b}function f(){var b=c.hash(),d;b?(d=g.getElementById(b))?d.scrollIntoView():(d=e(g.getElementsByName(b)))?d.scrollIntoView():"top"===b&&a.scrollTo(0,0):a.scrollTo(0,0)}var g=a.document;b&&d.$watch(function(){return c.hash()},function(){d.$evalAsync(f)});return f}]}function $c(b,a,c,d){function e(a){try{a.apply(null,ta.call(arguments,1))}finally{if(C--,
0===C)for(;H.length;)try{H.pop()()}catch(b){c.error(b)}}}function f(a,b){(function gb(){q(I,function(a){a()});A=b(gb,a)})()}function g(){v=null;S!=h.url()&&(S=h.url(),q(Z,function(a){a(h.url())}))}var h=this,m=a[0],k=b.location,l=b.history,n=b.setTimeout,r=b.clearTimeout,p={};h.isMock=!1;var C=0,H=[];h.$$completeOutstandingRequest=e;h.$$incOutstandingRequestCount=function(){C++};h.notifyWhenNoOutstandingRequests=function(a){q(I,function(a){a()});0===C?a():H.push(a)};var I=[],A;h.addPollFn=function(a){x(A)&&
f(100,n);I.push(a);return a};var S=k.href,G=a.find("base"),v=null;h.url=function(a,c){k!==b.location&&(k=b.location);if(a){if(S!=a)return S=a,d.history?c?l.replaceState(null,"",a):(l.pushState(null,"",a),G.attr("href",G.attr("href"))):(v=a,c?k.replace(a):k.href=a),h}else return v||k.href.replace(/%27/g,"'")};var Z=[],E=!1;h.onUrlChange=function(a){if(!E){if(d.history)y(b).on("popstate",g);if(d.hashchange)y(b).on("hashchange",g);else h.addPollFn(g);E=!0}Z.push(a);return a};h.baseHref=function(){var a=
G.attr("href");return a?a.replace(/^https?\:\/\/[^\/]*/,""):""};var oa={},$="",va=h.baseHref();h.cookies=function(a,b){var d,e,f,h;if(a)b===s?m.cookie=escape(a)+"=;path="+va+";expires=Thu, 01 Jan 1970 00:00:00 GMT":D(b)&&(d=(m.cookie=escape(a)+"="+escape(b)+";path="+va).length+1,4096<d&&c.warn("Cookie '"+a+"' possibly not set or overflowed because it was too large ("+d+" > 4096 bytes)!"));else{if(m.cookie!==$)for($=m.cookie,d=$.split("; "),oa={},f=0;f<d.length;f++)e=d[f],h=e.indexOf("="),0<h&&(a=
unescape(e.substring(0,h)),oa[a]===s&&(oa[a]=unescape(e.substring(h+1))));return oa}};h.defer=function(a,b){var c;C++;c=n(function(){delete p[c];e(a)},b||0);p[c]=!0;return c};h.defer.cancel=function(a){return p[a]?(delete p[a],r(a),e(t),!0):!1}}function bd(){this.$get=["$window","$log","$sniffer","$document",function(b,a,c,d){return new $c(b,d,a,c)}]}function cd(){this.$get=function(){function b(b,d){function e(a){a!=n&&(r?r==a&&(r=a.n):r=a,f(a.n,a.p),f(a,n),n=a,n.n=null)}function f(a,b){a!=b&&(a&&
(a.p=b),b&&(b.n=a))}if(b in a)throw L("$cacheFactory")("iid",b);var g=0,h=u({},d,{id:b}),m={},k=d&&d.capacity||Number.MAX_VALUE,l={},n=null,r=null;return a[b]={put:function(a,b){var c=l[a]||(l[a]={key:a});e(c);if(!x(b))return a in m||g++,m[a]=b,g>k&&this.remove(r.key),b},get:function(a){var b=l[a];if(b)return e(b),m[a]},remove:function(a){var b=l[a];b&&(b==n&&(n=b.p),b==r&&(r=b.n),f(b.n,b.p),delete l[a],delete m[a],g--)},removeAll:function(){m={};g=0;l={};n=r=null},destroy:function(){l=h=m=null;delete a[b]},
info:function(){return u({},h,{size:g})}}}var a={};b.info=function(){var b={};q(a,function(a,e){b[e]=a.info()});return b};b.get=function(b){return a[b]};return b}}function dd(){this.$get=["$cacheFactory",function(b){return b("templates")}]}function ec(b){var a={},c="Directive",d=/^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,e=/(([\d\w\-_]+)(?:\:([^;]+))?;?)/,f=/^\s*(https?|ftp|mailto|tel|file):/,g=/^\s*(https?|ftp|file):|data:image\//,h=/^(on[a-z]+|formaction)$/;this.directive=function k(d,e){na(d,"directive");
D(d)?(tb(e,"directiveFactory"),a.hasOwnProperty(d)||(a[d]=[],b.factory(d+c,["$injector","$exceptionHandler",function(b,c){var e=[];q(a[d],function(a,f){try{var h=b.invoke(a);B(h)?h={compile:aa(h)}:!h.compile&&h.link&&(h.compile=aa(h.link));h.priority=h.priority||0;h.index=f;h.name=h.name||d;h.require=h.require||h.controller&&h.name;h.restrict=h.restrict||"A";e.push(h)}catch(g){c(g)}});return e}])),a[d].push(e)):q(d,Ob(k));return this};this.aHrefSanitizationWhitelist=function(a){return z(a)?(f=a,this):
f};this.imgSrcSanitizationWhitelist=function(a){return z(a)?(g=a,this):g};this.$get=["$injector","$interpolate","$exceptionHandler","$http","$templateCache","$parse","$controller","$rootScope","$document","$sce","$animate",function(b,l,n,r,p,C,H,I,A,S,G){function v(a,b,c,d,e){a instanceof y||(a=y(a));q(a,function(b,c){3==b.nodeType&&b.nodeValue.match(/\S+/)&&(a[c]=y(b).wrap("<span></span>").parent()[0])});var f=E(a,b,a,c,d,e);return function(b,c){tb(b,"scope");for(var d=c?Da.clone.call(a):a,e=0,h=
d.length;e<h;e++){var g=d[e];1!=g.nodeType&&9!=g.nodeType||d.eq(e).data("$scope",b)}Z(d,"ng-scope");c&&c(d,b);f&&f(b,d,d);return d}}function Z(a,b){try{a.addClass(b)}catch(c){}}function E(a,b,c,d,e,f){function h(a,c,d,e){var f,k,l,n,p,r,C,X=[];p=0;for(r=c.length;p<r;p++)X.push(c[p]);C=p=0;for(r=g.length;p<r;C++)k=X[C],c=g[p++],f=g[p++],l=y(k),c?(c.scope?(n=a.$new(),l.data("$scope",n),Z(l,"ng-scope")):n=a,(l=c.transclude)||!e&&b?c(f,n,k,d,function(b){return function(c){var d=a.$new();d.$$transcluded=
!0;return b(d,c).on("$destroy",rb(d,d.$destroy))}}(l||b)):c(f,n,k,s,e)):f&&f(a,k.childNodes,s,e)}for(var g=[],k,l,n,p=0;p<a.length;p++)l=new R,k=oa(a[p],[],l,0===p?d:s,e),k=(f=k.length?M(k,a[p],l,b,c,null,[],[],f):null)&&f.terminal||!a[p].childNodes||!a[p].childNodes.length?null:E(a[p].childNodes,f?f.transclude:b),g.push(f),g.push(k),n=n||f||k,f=null;return n?h:null}function oa(a,b,c,f,h){var g=c.$attr,k;switch(a.nodeType){case 1:N(b,ka(Ea(a).toLowerCase()),"E",f,h);var l,n,p;k=a.attributes;for(var r=
0,C=k&&k.length;r<C;r++){var H=!1,v=!1;l=k[r];if(!P||8<=P||l.specified){n=l.name;p=ka(n);Fa.test(p)&&(n=cb(p.substr(6),"-"));var q=p.replace(/(Start|End)$/,"");p===q+"Start"&&(H=n,v=n.substr(0,n.length-5)+"end",n=n.substr(0,n.length-6));p=ka(n.toLowerCase());g[p]=n;c[p]=l=Y(P&&"href"==n?decodeURIComponent(a.getAttribute(n,2)):l.value);bc(a,p)&&(c[p]=!0);w(a,b,l,p);N(b,p,"A",f,h,H,v)}}a=a.className;if(D(a)&&""!==a)for(;k=e.exec(a);)p=ka(k[2]),N(b,p,"C",f,h)&&(c[p]=Y(k[3])),a=a.substr(k.index+k[0].length);
break;case 3:t(b,a.nodeValue);break;case 8:try{if(k=d.exec(a.nodeValue))p=ka(k[1]),N(b,p,"M",f,h)&&(c[p]=Y(k[2]))}catch(S){}}b.sort(wa);return b}function $(a,b,c){var d=[],e=0;if(b&&a.hasAttribute&&a.hasAttribute(b)){do{if(!a)throw fa("uterdir",b,c);1==a.nodeType&&(a.hasAttribute(b)&&e++,a.hasAttribute(c)&&e--);d.push(a);a=a.nextSibling}while(0<e)}else d.push(a);return y(d)}function va(a,b,c){return function(d,e,f,h){e=$(e[0],b,c);return a(d,e,f,h)}}function M(a,b,c,d,e,f,h,k,g){function p(a,b,c,
d){if(a){c&&(a=va(a,c,d));a.require=F.require;if(G===F||F.$$isolateScope)a=Q(a,{isolateScope:!0});h.push(a)}if(b){c&&(b=va(b,c,d));b.require=F.require;if(G===F||F.$$isolateScope)b=Q(b,{isolateScope:!0});k.push(b)}}function r(a,b){var c,d="data",e=!1;if(D(a)){for(;"^"==(c=a.charAt(0))||"?"==c;)a=a.substr(1),"^"==c&&(d="inheritedData"),e=e||"?"==c;c=b[d]("$"+a+"Controller");8==b[0].nodeType&&b[0].$$controller&&(c=c||b[0].$$controller,b[0].$$controller=null);if(!c&&!e)throw fa("ctreq",a,ba);}else J(a)&&
(c=[],q(a,function(a){c.push(r(a,b))}));return c}function S(a,d,e,f,g){var p,X,v,E,I,K;p=b===e?c:Mc(c,new R(y(e),c.$attr));X=p.$$element;if(G){var va=/^\s*([@=&])(\??)\s*(\w*)\s*$/;f=y(e);K=d.$new(!0);N&&N===G.$$originalDirective?f.data("$isolateScope",K):f.data("$isolateScopeNoTemplate",K);Z(f,"ng-isolate-scope");q(G.scope,function(a,b){var c=a.match(va)||[],e=c[3]||b,f="?"==c[2],c=c[1],h,g,k;K.$$isolateBindings[b]=c+e;switch(c){case "@":p.$observe(e,function(a){K[b]=a});p.$$observers[e].$$scope=
d;p[e]&&(K[b]=l(p[e])(d));break;case "=":if(f&&!p[e])break;g=C(p[e]);k=g.assign||function(){h=K[b]=g(d);throw fa("nonassign",p[e],G.name);};h=K[b]=g(d);K.$watch(function(){var a=g(d);a!==K[b]&&(a!==h?h=K[b]=a:k(d,a=h=K[b]));return a});break;case "&":g=C(p[e]);K[b]=function(a){return g(d,a)};break;default:throw fa("iscp",G.name,b,a);}})}A&&q(A,function(a){var b={$scope:a===G||a.$$isolateScope?K:d,$element:X,$attrs:p,$transclude:g},c;I=a.controller;"@"==I&&(I=p[a.name]);c=H(I,b);8==X[0].nodeType?X[0].$$controller=
c:X.data("$"+a.name+"Controller",c);a.controllerAs&&(b.$scope[a.controllerAs]=c)});f=0;for(v=h.length;f<v;f++)try{E=h[f],E(E.isolateScope?K:d,X,p,E.require&&r(E.require,X))}catch(M){n(M,ea(X))}f=d;G&&(G.template||null===G.templateUrl)&&(f=K);a&&a(f,e.childNodes,s,g);for(f=k.length-1;0<=f;f--)try{E=k[f],E(E.isolateScope?K:d,X,p,E.require&&r(E.require,X))}catch($){n($,ea(X))}}g=g||{};var E=-Number.MAX_VALUE,I,A=g.controllerDirectives,G=g.newIsolateScopeDirective,N=g.templateDirective;g=g.transcludeDirective;
for(var M=c.$$element=y(b),F,ba,t,wa=d,x,ga=0,w=a.length;ga<w;ga++){F=a[ga];var u=F.$$start,Fa=F.$$end;u&&(M=$(b,u,Fa));t=s;if(E>F.priority)break;if(t=F.scope)I=I||F,F.templateUrl||(Va("new/isolated scope",G,F,M),T(t)&&(G=F));ba=F.name;!F.templateUrl&&F.controller&&(t=F.controller,A=A||{},Va("'"+ba+"' controller",A[ba],F,M),A[ba]=F);if(t=F.transclude)F.$$tlb||(Va("transclusion",g,F,M),g=F),"element"==t?(E=F.priority,t=$(b,u,Fa),M=c.$$element=y(O.createComment(" "+ba+": "+c[ba]+" ")),b=M[0],L(e,y(ta.call(t,
0)),b),wa=v(t,d,E,f&&f.name,{transcludeDirective:g})):(t=y(zb(b)).contents(),M.html(""),wa=v(t,d));if(F.template)if(Va("template",N,F,M),N=F,t=B(F.template)?F.template(M,c):F.template,t=fc(t),F.replace){f=F;t=y("<div>"+Y(t)+"</div>").contents();b=t[0];if(1!=t.length||1!==b.nodeType)throw fa("tplrt",ba,"");L(e,M,b);w={$attr:{}};t=oa(b,[],w);var P=a.splice(ga+1,a.length-(ga+1));G&&z(t);a=a.concat(t).concat(P);gb(c,w);w=a.length}else M.html(t);if(F.templateUrl)Va("template",N,F,M),N=F,F.replace&&(f=
F),S=ad(a.splice(ga,a.length-ga),M,c,e,wa,h,k,{controllerDirectives:A,newIsolateScopeDirective:G,templateDirective:N,transcludeDirective:g}),w=a.length;else if(F.compile)try{x=F.compile(M,c,wa),B(x)?p(null,x,u,Fa):x&&p(x.pre,x.post,u,Fa)}catch(ed){n(ed,ea(M))}F.terminal&&(S.terminal=!0,E=Math.max(E,F.priority))}S.scope=I&&!0===I.scope;S.transclude=g&&wa;return S}function z(a){for(var b=0,c=a.length;b<c;b++)a[b]=Qb(a[b],{$$isolateScope:!0})}function N(d,e,f,h,g,l,p){if(e===g)return null;g=null;if(a.hasOwnProperty(e)){var r;
e=b.get(e+c);for(var C=0,H=e.length;C<H;C++)try{r=e[C],(h===s||h>r.priority)&&-1!=r.restrict.indexOf(f)&&(l&&(r=Qb(r,{$$start:l,$$end:p})),d.push(r),g=r)}catch(E){n(E)}}return g}function gb(a,b){var c=b.$attr,d=a.$attr,e=a.$$element;q(a,function(d,e){"$"!=e.charAt(0)&&(b[e]&&(d+=("style"===e?";":" ")+b[e]),a.$set(e,d,!0,c[e]))});q(b,function(b,f){"class"==f?(Z(e,b),a["class"]=(a["class"]?a["class"]+" ":"")+b):"style"==f?e.attr("style",e.attr("style")+";"+b):"$"==f.charAt(0)||a.hasOwnProperty(f)||
(a[f]=b,d[f]=c[f])})}function ad(a,b,c,d,e,f,h,g){var k=[],n,l,C=b[0],H=a.shift(),v=u({},H,{templateUrl:null,transclude:null,replace:null,$$originalDirective:H}),I=B(H.templateUrl)?H.templateUrl(b,c):H.templateUrl;b.html("");r.get(S.getTrustedResourceUrl(I),{cache:p}).success(function(p){var r;p=fc(p);if(H.replace){p=y("<div>"+Y(p)+"</div>").contents();r=p[0];if(1!=p.length||1!==r.nodeType)throw fa("tplrt",H.name,I);p={$attr:{}};L(d,b,r);var S=oa(r,[],p);T(H.scope)&&z(S);a=S.concat(a);gb(c,p)}else r=
C,b.html(p);a.unshift(v);n=M(a,r,c,e,b,H,f,h,g);q(d,function(a,c){a==r&&(d[c]=b[0])});for(l=E(b[0].childNodes,e);k.length;){p=k.shift();var S=k.shift(),Z=k.shift(),G=k.shift(),A=b[0];S!==C&&(A=zb(r),L(Z,y(S),A));n(l,p,A,d,G)}k=null}).error(function(a,b,c,d){throw fa("tpload",d.url);});return function(a,b,c,d,e){k?(k.push(b),k.push(c),k.push(d),k.push(e)):n(l,b,c,d,e)}}function wa(a,b){var c=b.priority-a.priority;return 0!==c?c:a.name!==b.name?a.name<b.name?-1:1:a.index-b.index}function Va(a,b,c,d){if(b)throw fa("multidir",
b.name,c.name,a,ea(d));}function t(a,b){var c=l(b,!0);c&&a.push({priority:0,compile:aa(function(a,b){var d=b.parent(),e=d.data("$binding")||[];e.push(c);Z(d.data("$binding",e),"ng-binding");a.$watch(c,function(a){b[0].nodeValue=a})})})}function x(a,b){if("xlinkHref"==b||"IMG"!=Ea(a)&&("src"==b||"ngSrc"==b))return S.RESOURCE_URL}function w(a,b,c,d){var e=l(c,!0);if(e){if("multiple"===d&&"SELECT"===Ea(a))throw fa("selmulti",ea(a));b.push({priority:100,compile:function(){return{pre:function(b,c,f){c=
f.$$observers||(f.$$observers={});if(h.test(d))throw fa("nodomevents");if(e=l(f[d],!0,x(a,d)))f[d]=e(b),(c[d]||(c[d]=[])).$$inter=!0,(f.$$observers&&f.$$observers[d].$$scope||b).$watch(e,function(a){f.$set(d,a)})}}}})}}function L(a,b,c){var d=b[0],e=b.length,f=d.parentNode,h,g;if(a)for(h=0,g=a.length;h<g;h++)if(a[h]==d){a[h++]=c;g=h+e-1;for(var k=a.length;h<k;h++,g++)g<k?a[h]=a[g]:delete a[h];a.length-=e-1;break}f&&f.replaceChild(c,d);a=O.createDocumentFragment();a.appendChild(d);c[y.expando]=d[y.expando];
d=1;for(e=b.length;d<e;d++)f=b[d],y(f).remove(),a.appendChild(f),delete b[d];b[0]=c;b.length=1}function Q(a,b){return u(function(){return a.apply(null,arguments)},a,b)}var R=function(a,b){this.$$element=a;this.$attr=b||{}};R.prototype={$normalize:ka,$addClass:function(a){a&&0<a.length&&G.addClass(this.$$element,a)},$removeClass:function(a){a&&0<a.length&&G.removeClass(this.$$element,a)},$set:function(a,b,c,d){function e(a,b){var c=[],d=a.split(/\s+/),f=b.split(/\s+/),h=0;a:for(;h<d.length;h++){for(var g=
d[h],k=0;k<f.length;k++)if(g==f[k])continue a;c.push(g)}return c}if("class"==a)b=b||"",c=this.$$element.attr("class")||"",this.$removeClass(e(c,b).join(" ")),this.$addClass(e(b,c).join(" "));else{var h=bc(this.$$element[0],a);h&&(this.$$element.prop(a,b),d=h);this[a]=b;d?this.$attr[a]=d:(d=this.$attr[a])||(this.$attr[a]=d=cb(a,"-"));h=Ea(this.$$element);if("A"===h&&"href"===a||"IMG"===h&&"src"===a)if(!P||8<=P)h=xa(b).href,""!==h&&("href"===a&&!h.match(f)||"src"===a&&!h.match(g))&&(this[a]=b="unsafe:"+
h);!1!==c&&(null===b||b===s?this.$$element.removeAttr(d):this.$$element.attr(d,b))}(c=this.$$observers)&&q(c[a],function(a){try{a(b)}catch(c){n(c)}})},$observe:function(a,b){var c=this,d=c.$$observers||(c.$$observers={}),e=d[a]||(d[a]=[]);e.push(b);I.$evalAsync(function(){e.$$inter||b(c[a])});return b}};var ba=l.startSymbol(),ga=l.endSymbol(),fc="{{"==ba||"}}"==ga?za:function(a){return a.replace(/\{\{/g,ba).replace(/}}/g,ga)},Fa=/^ngAttr[A-Z]/;return v}]}function ka(b){return Pa(b.replace(fd,""))}
function gd(){var b={},a=/^(\S+)(\s+as\s+(\w+))?$/;this.register=function(a,d){na(a,"controller");T(a)?u(b,a):b[a]=d};this.$get=["$injector","$window",function(c,d){return function(e,f){var g,h,m;D(e)&&(g=e.match(a),h=g[1],m=g[3],e=b.hasOwnProperty(h)?b[h]:ub(f.$scope,h,!0)||ub(d,h,!0),Oa(e,h,!0));g=c.instantiate(e,f);if(m){if(!f||"object"!=typeof f.$scope)throw L("$controller")("noscp",h||e.name,m);f.$scope[m]=g}return g}}]}function hd(){this.$get=["$window",function(b){return y(b.document)}]}function id(){this.$get=
["$log",function(b){return function(a,c){b.error.apply(b,arguments)}}]}function gc(b){var a={},c,d,e;if(!b)return a;q(b.split("\n"),function(b){e=b.indexOf(":");c=w(Y(b.substr(0,e)));d=Y(b.substr(e+1));c&&(a[c]=a[c]?a[c]+(", "+d):d)});return a}function hc(b){var a=T(b)?b:s;return function(c){a||(a=gc(b));return c?a[w(c)]||null:a}}function ic(b,a,c){if(B(c))return c(b,a);q(c,function(c){b=c(b,a)});return b}function jd(){var b=/^\s*(\[|\{[^\{])/,a=/[\}\]]\s*$/,c=/^\)\]\}',?\n/,d={"Content-Type":"application/json;charset=utf-8"},
e=this.defaults={transformResponse:[function(d){D(d)&&(d=d.replace(c,""),b.test(d)&&a.test(d)&&(d=Sb(d)));return d}],transformRequest:[function(a){return T(a)&&"[object File]"!==Ka.apply(a)?ma(a):a}],headers:{common:{Accept:"application/json, text/plain, */*"},post:d,put:d,patch:d},xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN"},f=this.interceptors=[],g=this.responseInterceptors=[];this.$get=["$httpBackend","$browser","$cacheFactory","$rootScope","$q","$injector",function(a,b,c,d,n,r){function p(a){function c(a){var b=
u({},a,{data:ic(a.data,a.headers,d.transformResponse)});return 200<=a.status&&300>a.status?b:n.reject(b)}var d={transformRequest:e.transformRequest,transformResponse:e.transformResponse},f=function(a){function b(a){var c;q(a,function(b,d){B(b)&&(c=b(),null!=c?a[d]=c:delete a[d])})}var c=e.headers,d=u({},a.headers),f,h,c=u({},c.common,c[w(a.method)]);b(c);b(d);a:for(f in c){a=w(f);for(h in d)if(w(h)===a)continue a;d[f]=c[f]}return d}(a);u(d,a);d.headers=f;d.method=Ga(d.method);(a=Eb(d.url)?b.cookies()[d.xsrfCookieName||
e.xsrfCookieName]:s)&&(f[d.xsrfHeaderName||e.xsrfHeaderName]=a);var h=[function(a){f=a.headers;var b=ic(a.data,hc(f),a.transformRequest);x(a.data)&&q(f,function(a,b){"content-type"===w(b)&&delete f[b]});x(a.withCredentials)&&!x(e.withCredentials)&&(a.withCredentials=e.withCredentials);return C(a,b,f).then(c,c)},s],g=n.when(d);for(q(A,function(a){(a.request||a.requestError)&&h.unshift(a.request,a.requestError);(a.response||a.responseError)&&h.push(a.response,a.responseError)});h.length;){a=h.shift();
var k=h.shift(),g=g.then(a,k)}g.success=function(a){g.then(function(b){a(b.data,b.status,b.headers,d)});return g};g.error=function(a){g.then(null,function(b){a(b.data,b.status,b.headers,d)});return g};return g}function C(b,c,f){function g(a,b,c){q&&(200<=a&&300>a?q.put(s,[a,b,gc(c)]):q.remove(s));k(b,a,c);d.$$phase||d.$apply()}function k(a,c,d){c=Math.max(c,0);(200<=c&&300>c?r.resolve:r.reject)({data:a,status:c,headers:hc(d),config:b})}function m(){var a=ab(p.pendingRequests,b);-1!==a&&p.pendingRequests.splice(a,
1)}var r=n.defer(),C=r.promise,q,A,s=H(b.url,b.params);p.pendingRequests.push(b);C.then(m,m);(b.cache||e.cache)&&(!1!==b.cache&&"GET"==b.method)&&(q=T(b.cache)?b.cache:T(e.cache)?e.cache:I);if(q)if(A=q.get(s),z(A)){if(A.then)return A.then(m,m),A;J(A)?k(A[1],A[0],da(A[2])):k(A,200,{})}else q.put(s,C);x(A)&&a(b.method,s,c,g,f,b.timeout,b.withCredentials,b.responseType);return C}function H(a,b){if(!b)return a;var c=[];Jc(b,function(a,b){null===a||x(a)||(J(a)||(a=[a]),q(a,function(a){T(a)&&(a=ma(a));
c.push(ua(b)+"="+ua(a))}))});return a+(-1==a.indexOf("?")?"?":"&")+c.join("&")}var I=c("$http"),A=[];q(f,function(a){A.unshift(D(a)?r.get(a):r.invoke(a))});q(g,function(a,b){var c=D(a)?r.get(a):r.invoke(a);A.splice(b,0,{response:function(a){return c(n.when(a))},responseError:function(a){return c(n.reject(a))}})});p.pendingRequests=[];(function(a){q(arguments,function(a){p[a]=function(b,c){return p(u(c||{},{method:a,url:b}))}})})("get","delete","head","jsonp");(function(a){q(arguments,function(a){p[a]=
function(b,c,d){return p(u(d||{},{method:a,url:b,data:c}))}})})("post","put");p.defaults=e;return p}]}function kd(){this.$get=["$browser","$window","$document",function(b,a,c){return ld(b,md,b.defer,a.angular.callbacks,c[0],a.location.protocol.replace(":",""))}]}function ld(b,a,c,d,e,f){function g(a,b){var c=e.createElement("script"),d=function(){e.body.removeChild(c);b&&b()};c.type="text/javascript";c.src=a;P?c.onreadystatechange=function(){/loaded|complete/.test(c.readyState)&&d()}:c.onload=c.onerror=
d;e.body.appendChild(c);return d}return function(e,m,k,l,n,r,p,C){function H(){A=-1;G&&G();v&&v.abort()}function I(a,d,e,h){var g=f||xa(m).protocol;Z&&c.cancel(Z);G=v=null;d="file"==g?e?200:404:d;a(1223==d?204:d,e,h);b.$$completeOutstandingRequest(t)}var A;b.$$incOutstandingRequestCount();m=m||b.url();if("jsonp"==w(e)){var s="_"+(d.counter++).toString(36);d[s]=function(a){d[s].data=a};var G=g(m.replace("JSON_CALLBACK","angular.callbacks."+s),function(){d[s].data?I(l,200,d[s].data):I(l,A||-2);delete d[s]})}else{var v=
new a;v.open(e,m,!0);q(n,function(a,b){z(a)&&v.setRequestHeader(b,a)});v.onreadystatechange=function(){if(4==v.readyState){var a=v.getAllResponseHeaders();I(l,A||v.status,v.responseType?v.response:v.responseText,a)}};p&&(v.withCredentials=!0);C&&(v.responseType=C);v.send(k||null)}if(0<r)var Z=c(H,r);else r&&r.then&&r.then(H)}}function nd(){var b="{{",a="}}";this.startSymbol=function(a){return a?(b=a,this):b};this.endSymbol=function(b){return b?(a=b,this):a};this.$get=["$parse","$exceptionHandler",
"$sce",function(c,d,e){function f(f,k,l){for(var n,r,p=0,C=[],H=f.length,q=!1,A=[];p<H;)-1!=(n=f.indexOf(b,p))&&-1!=(r=f.indexOf(a,n+g))?(p!=n&&C.push(f.substring(p,n)),C.push(p=c(q=f.substring(n+g,r))),p.exp=q,p=r+h,q=!0):(p!=H&&C.push(f.substring(p)),p=H);(H=C.length)||(C.push(""),H=1);if(l&&1<C.length)throw jc("noconcat",f);if(!k||q)return A.length=H,p=function(a){try{for(var b=0,c=H,h;b<c;b++)"function"==typeof(h=C[b])&&(h=h(a),h=l?e.getTrusted(l,h):e.valueOf(h),null===h||x(h)?h="":"string"!=
typeof h&&(h=ma(h))),A[b]=h;return A.join("")}catch(g){a=jc("interr",f,g.toString()),d(a)}},p.exp=f,p.parts=C,p}var g=b.length,h=a.length;f.startSymbol=function(){return b};f.endSymbol=function(){return a};return f}]}function od(){this.$get=["$rootScope","$window","$q",function(b,a,c){function d(d,g,h,m){var k=a.setInterval,l=a.clearInterval,n=c.defer(),r=n.promise,p=0,C=z(m)&&!m;h=z(h)?h:0;r.then(null,null,d);r.$$intervalId=k(function(){n.notify(p++);0<h&&p>=h&&(n.resolve(p),l(r.$$intervalId),delete e[r.$$intervalId]);
C||b.$apply()},g);e[r.$$intervalId]=n;return r}var e={};d.cancel=function(a){return a&&a.$$intervalId in e?(e[a.$$intervalId].reject("canceled"),clearInterval(a.$$intervalId),delete e[a.$$intervalId],!0):!1};return d}]}function pd(){this.$get=function(){return{id:"en-us",NUMBER_FORMATS:{DECIMAL_SEP:".",GROUP_SEP:",",PATTERNS:[{minInt:1,minFrac:0,maxFrac:3,posPre:"",posSuf:"",negPre:"-",negSuf:"",gSize:3,lgSize:3},{minInt:1,minFrac:2,maxFrac:2,posPre:"\u00a4",posSuf:"",negPre:"(\u00a4",negSuf:")",
gSize:3,lgSize:3}],CURRENCY_SYM:"$"},DATETIME_FORMATS:{MONTH:"January February March April May June July August September October November December".split(" "),SHORTMONTH:"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),DAY:"Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),SHORTDAY:"Sun Mon Tue Wed Thu Fri Sat".split(" "),AMPMS:["AM","PM"],medium:"MMM d, y h:mm:ss a","short":"M/d/yy h:mm a",fullDate:"EEEE, MMMM d, y",longDate:"MMMM d, y",mediumDate:"MMM d, y",shortDate:"M/d/yy",
mediumTime:"h:mm:ss a",shortTime:"h:mm a"},pluralCat:function(b){return 1===b?"one":"other"}}}}function kc(b){b=b.split("/");for(var a=b.length;a--;)b[a]=sb(b[a]);return b.join("/")}function lc(b,a){var c=xa(b);a.$$protocol=c.protocol;a.$$host=c.hostname;a.$$port=U(c.port)||qd[c.protocol]||null}function mc(b,a){var c="/"!==b.charAt(0);c&&(b="/"+b);var d=xa(b);a.$$path=decodeURIComponent(c&&"/"===d.pathname.charAt(0)?d.pathname.substring(1):d.pathname);a.$$search=Ub(d.search);a.$$hash=decodeURIComponent(d.hash);
a.$$path&&"/"!=a.$$path.charAt(0)&&(a.$$path="/"+a.$$path)}function la(b,a){if(0===a.indexOf(b))return a.substr(b.length)}function Wa(b){var a=b.indexOf("#");return-1==a?b:b.substr(0,a)}function Fb(b){return b.substr(0,Wa(b).lastIndexOf("/")+1)}function nc(b,a){this.$$html5=!0;a=a||"";var c=Fb(b);lc(b,this);this.$$parse=function(a){var b=la(c,a);if(!D(b))throw Gb("ipthprfx",a,c);mc(b,this);this.$$path||(this.$$path="/");this.$$compose()};this.$$compose=function(){var a=Vb(this.$$search),b=this.$$hash?
"#"+sb(this.$$hash):"";this.$$url=kc(this.$$path)+(a?"?"+a:"")+b;this.$$absUrl=c+this.$$url.substr(1)};this.$$rewrite=function(d){var e;if((e=la(b,d))!==s)return d=e,(e=la(a,e))!==s?c+(la("/",e)||e):b+d;if((e=la(c,d))!==s)return c+e;if(c==d+"/")return c}}function Hb(b,a){var c=Fb(b);lc(b,this);this.$$parse=function(d){var e=la(b,d)||la(c,d),e="#"==e.charAt(0)?la(a,e):this.$$html5?e:"";if(!D(e))throw Gb("ihshprfx",d,a);mc(e,this);this.$$compose()};this.$$compose=function(){var c=Vb(this.$$search),
e=this.$$hash?"#"+sb(this.$$hash):"";this.$$url=kc(this.$$path)+(c?"?"+c:"")+e;this.$$absUrl=b+(this.$$url?a+this.$$url:"")};this.$$rewrite=function(a){if(Wa(b)==Wa(a))return a}}function oc(b,a){this.$$html5=!0;Hb.apply(this,arguments);var c=Fb(b);this.$$rewrite=function(d){var e;if(b==Wa(d))return d;if(e=la(c,d))return b+a+e;if(c===d+"/")return c}}function hb(b){return function(){return this[b]}}function pc(b,a){return function(c){if(x(c))return this[b];this[b]=a(c);this.$$compose();return this}}
function rd(){var b="",a=!1;this.hashPrefix=function(a){return z(a)?(b=a,this):b};this.html5Mode=function(b){return z(b)?(a=b,this):a};this.$get=["$rootScope","$browser","$sniffer","$rootElement",function(c,d,e,f){function g(a){c.$broadcast("$locationChangeSuccess",h.absUrl(),a)}var h,m=d.baseHref(),k=d.url();a?(m=k.substring(0,k.indexOf("/",k.indexOf("//")+2))+(m||"/"),e=e.history?nc:oc):(m=Wa(k),e=Hb);h=new e(m,"#"+b);h.$$parse(h.$$rewrite(k));f.on("click",function(a){if(!a.ctrlKey&&!a.metaKey&&
2!=a.which){for(var b=y(a.target);"a"!==w(b[0].nodeName);)if(b[0]===f[0]||!(b=b.parent())[0])return;var e=b.prop("href"),g=h.$$rewrite(e);e&&(!b.attr("target")&&g&&!a.isDefaultPrevented())&&(a.preventDefault(),g!=d.url()&&(h.$$parse(g),c.$apply(),W.angular["ff-684208-preventDefault"]=!0))}});h.absUrl()!=k&&d.url(h.absUrl(),!0);d.onUrlChange(function(a){h.absUrl()!=a&&(c.$broadcast("$locationChangeStart",a,h.absUrl()).defaultPrevented?d.url(h.absUrl()):(c.$evalAsync(function(){var b=h.absUrl();h.$$parse(a);
g(b)}),c.$$phase||c.$digest()))});var l=0;c.$watch(function(){var a=d.url(),b=h.$$replace;l&&a==h.absUrl()||(l++,c.$evalAsync(function(){c.$broadcast("$locationChangeStart",h.absUrl(),a).defaultPrevented?h.$$parse(a):(d.url(h.absUrl(),b),g(a))}));h.$$replace=!1;return l});return h}]}function sd(){var b=!0,a=this;this.debugEnabled=function(a){return z(a)?(b=a,this):b};this.$get=["$window",function(c){function d(a){a instanceof Error&&(a.stack?a=a.message&&-1===a.stack.indexOf(a.message)?"Error: "+
a.message+"\n"+a.stack:a.stack:a.sourceURL&&(a=a.message+"\n"+a.sourceURL+":"+a.line));return a}function e(a){var b=c.console||{},e=b[a]||b.log||t;return e.apply?function(){var a=[];q(arguments,function(b){a.push(d(b))});return e.apply(b,a)}:function(a,b){e(a,null==b?"":b)}}return{log:e("log"),info:e("info"),warn:e("warn"),error:e("error"),debug:function(){var c=e("debug");return function(){b&&c.apply(a,arguments)}}()}}]}function ha(b,a,c){if("string"!==typeof b&&"[object String]"!==Ka.apply(b))return b;
if("constructor"===b&&!c)throw pa("isecfld",a);if("_"===b.charAt(0)||"_"===b.charAt(b.length-1))throw pa("isecprv",a);return b}function Xa(b,a){if(b&&b.constructor===b)throw pa("isecfn",a);if(b&&b.document&&b.location&&b.alert&&b.setInterval)throw pa("isecwindow",a);if(b&&(b.nodeName||b.on&&b.find))throw pa("isecdom",a);return b}function ib(b,a,c,d,e){e=e||{};a=a.split(".");for(var f,g=0;1<a.length;g++){f=ha(a.shift(),d);var h=b[f];h||(h={},b[f]=h);b=h;b.then&&e.unwrapPromises&&(qa(d),"$$v"in b||
function(a){a.then(function(b){a.$$v=b})}(b),b.$$v===s&&(b.$$v={}),b=b.$$v)}f=ha(a.shift(),d);return b[f]=c}function qc(b,a,c,d,e,f,g){ha(b,f);ha(a,f);ha(c,f);ha(d,f);ha(e,f);return g.unwrapPromises?function(h,g){var k=g&&g.hasOwnProperty(b)?g:h,l;if(null===k||k===s)return k;(k=k[b])&&k.then&&(qa(f),"$$v"in k||(l=k,l.$$v=s,l.then(function(a){l.$$v=a})),k=k.$$v);if(!a||null===k||k===s)return k;(k=k[a])&&k.then&&(qa(f),"$$v"in k||(l=k,l.$$v=s,l.then(function(a){l.$$v=a})),k=k.$$v);if(!c||null===k||
k===s)return k;(k=k[c])&&k.then&&(qa(f),"$$v"in k||(l=k,l.$$v=s,l.then(function(a){l.$$v=a})),k=k.$$v);if(!d||null===k||k===s)return k;(k=k[d])&&k.then&&(qa(f),"$$v"in k||(l=k,l.$$v=s,l.then(function(a){l.$$v=a})),k=k.$$v);if(!e||null===k||k===s)return k;(k=k[e])&&k.then&&(qa(f),"$$v"in k||(l=k,l.$$v=s,l.then(function(a){l.$$v=a})),k=k.$$v);return k}:function(f,g){var k=g&&g.hasOwnProperty(b)?g:f;if(null===k||k===s)return k;k=k[b];if(!a||null===k||k===s)return k;k=k[a];if(!c||null===k||k===s)return k;
k=k[c];if(!d||null===k||k===s)return k;k=k[d];return e&&null!==k&&k!==s?k=k[e]:k}}function rc(b,a,c){if(Ib.hasOwnProperty(b))return Ib[b];var d=b.split("."),e=d.length,f;if(a.csp)f=6>e?qc(d[0],d[1],d[2],d[3],d[4],c,a):function(b,f){var h=0,g;do g=qc(d[h++],d[h++],d[h++],d[h++],d[h++],c,a)(b,f),f=s,b=g;while(h<e);return g};else{var g="var l, fn, p;\n";q(d,function(b,d){ha(b,c);g+="if(s === null || s === undefined) return s;\nl=s;\ns="+(d?"s":'((k&&k.hasOwnProperty("'+b+'"))?k:s)')+'["'+b+'"];\n'+(a.unwrapPromises?
'if (s && s.then) {\n pw("'+c.replace(/\"/g,'\\"')+'");\n if (!("$$v" in s)) {\n p=s;\n p.$$v = undefined;\n p.then(function(v) {p.$$v=v;});\n}\n s=s.$$v\n}\n':"")});var g=g+"return s;",h=new Function("s","k","pw",g);h.toString=function(){return g};f=function(a,b){return h(a,b,qa)}}"hasOwnProperty"!==b&&(Ib[b]=f);return f}function td(){var b={},a={csp:!1,unwrapPromises:!1,logPromiseWarnings:!0};this.unwrapPromises=function(b){return z(b)?(a.unwrapPromises=!!b,this):a.unwrapPromises};this.logPromiseWarnings=
function(b){return z(b)?(a.logPromiseWarnings=b,this):a.logPromiseWarnings};this.$get=["$filter","$sniffer","$log",function(c,d,e){a.csp=d.csp;qa=function(b){a.logPromiseWarnings&&!sc.hasOwnProperty(b)&&(sc[b]=!0,e.warn("[$parse] Promise found in the expression `"+b+"`. Automatic unwrapping of promises in Angular expressions is deprecated."))};return function(d){var e;switch(typeof d){case "string":if(b.hasOwnProperty(d))return b[d];e=new Jb(a);e=(new Ya(e,c,a)).parse(d,!1);"hasOwnProperty"!==d&&
(b[d]=e);return e;case "function":return d;default:return t}}}]}function ud(){this.$get=["$rootScope","$exceptionHandler",function(b,a){return vd(function(a){b.$evalAsync(a)},a)}]}function vd(b,a){function c(a){return a}function d(a){return g(a)}var e=function(){var h=[],m,k;return k={resolve:function(a){if(h){var c=h;h=s;m=f(a);c.length&&b(function(){for(var a,b=0,d=c.length;b<d;b++)a=c[b],m.then(a[0],a[1],a[2])})}},reject:function(a){k.resolve(g(a))},notify:function(a){if(h){var c=h;h.length&&b(function(){for(var b,
d=0,e=c.length;d<e;d++)b=c[d],b[2](a)})}},promise:{then:function(b,f,g){var k=e(),C=function(d){try{k.resolve((B(b)?b:c)(d))}catch(e){k.reject(e),a(e)}},H=function(b){try{k.resolve((B(f)?f:d)(b))}catch(c){k.reject(c),a(c)}},q=function(b){try{k.notify((B(g)?g:c)(b))}catch(d){a(d)}};h?h.push([C,H,q]):m.then(C,H,q);return k.promise},"catch":function(a){return this.then(null,a)},"finally":function(a){function b(a,c){var d=e();c?d.resolve(a):d.reject(a);return d.promise}function d(e,f){var h=null;try{h=
(a||c)()}catch(g){return b(g,!1)}return h&&B(h.then)?h.then(function(){return b(e,f)},function(a){return b(a,!1)}):b(e,f)}return this.then(function(a){return d(a,!0)},function(a){return d(a,!1)})}}}},f=function(a){return a&&B(a.then)?a:{then:function(c){var d=e();b(function(){d.resolve(c(a))});return d.promise}}},g=function(c){return{then:function(f,g){var l=e();b(function(){try{l.resolve((B(g)?g:d)(c))}catch(b){l.reject(b),a(b)}});return l.promise}}};return{defer:e,reject:g,when:function(h,m,k,l){var n=
e(),r,p=function(b){try{return(B(m)?m:c)(b)}catch(d){return a(d),g(d)}},C=function(b){try{return(B(k)?k:d)(b)}catch(c){return a(c),g(c)}},q=function(b){try{return(B(l)?l:c)(b)}catch(d){a(d)}};b(function(){f(h).then(function(a){r||(r=!0,n.resolve(f(a).then(p,C,q)))},function(a){r||(r=!0,n.resolve(C(a)))},function(a){r||n.notify(q(a))})});return n.promise},all:function(a){var b=e(),c=0,d=J(a)?[]:{};q(a,function(a,e){c++;f(a).then(function(a){d.hasOwnProperty(e)||(d[e]=a,--c||b.resolve(d))},function(a){d.hasOwnProperty(e)||
b.reject(a)})});0===c&&b.resolve(d);return b.promise}}}function wd(){var b=10,a=L("$rootScope");this.digestTtl=function(a){arguments.length&&(b=a);return b};this.$get=["$injector","$exceptionHandler","$parse","$browser",function(c,d,e,f){function g(){this.$id=Za();this.$$phase=this.$parent=this.$$watchers=this.$$nextSibling=this.$$prevSibling=this.$$childHead=this.$$childTail=null;this["this"]=this.$root=this;this.$$destroyed=!1;this.$$asyncQueue=[];this.$$postDigestQueue=[];this.$$listeners={};this.$$isolateBindings=
{}}function h(b){if(l.$$phase)throw a("inprog",l.$$phase);l.$$phase=b}function m(a,b){var c=e(a);Oa(c,b);return c}function k(){}g.prototype={constructor:g,$new:function(a){a?(a=new g,a.$root=this.$root,a.$$asyncQueue=this.$$asyncQueue,a.$$postDigestQueue=this.$$postDigestQueue):(a=function(){},a.prototype=this,a=new a,a.$id=Za());a["this"]=a;a.$$listeners={};a.$parent=this;a.$$watchers=a.$$nextSibling=a.$$childHead=a.$$childTail=null;a.$$prevSibling=this.$$childTail;this.$$childHead?this.$$childTail=
this.$$childTail.$$nextSibling=a:this.$$childHead=this.$$childTail=a;return a},$watch:function(a,b,c){var d=m(a,"watch"),e=this.$$watchers,f={fn:b,last:k,get:d,exp:a,eq:!!c};if(!B(b)){var h=m(b||t,"listener");f.fn=function(a,b,c){h(c)}}if("string"==typeof a&&d.constant){var g=f.fn;f.fn=function(a,b,c){g.call(this,a,b,c);La(e,f)}}e||(e=this.$$watchers=[]);e.unshift(f);return function(){La(e,f)}},$watchCollection:function(a,b){var c=this,d,f,h=0,g=e(a),k=[],l={},m=0;return this.$watch(function(){f=
g(c);var a,b;if(T(f))if(pb(f))for(d!==k&&(d=k,m=d.length=0,h++),a=f.length,m!==a&&(h++,d.length=m=a),b=0;b<a;b++)d[b]!==f[b]&&(h++,d[b]=f[b]);else{d!==l&&(d=l={},m=0,h++);a=0;for(b in f)f.hasOwnProperty(b)&&(a++,d.hasOwnProperty(b)?d[b]!==f[b]&&(h++,d[b]=f[b]):(m++,d[b]=f[b],h++));if(m>a)for(b in h++,d)d.hasOwnProperty(b)&&!f.hasOwnProperty(b)&&(m--,delete d[b])}else d!==f&&(d=f,h++);return h},function(){b(f,d,c)})},$digest:function(){var c,e,f,g,m=this.$$asyncQueue,q=this.$$postDigestQueue,s,t,G=
b,v,y=[],E,z,$;h("$digest");do{t=!1;for(v=this;m.length;)try{$=m.shift(),$.scope.$eval($.expression)}catch(x){d(x)}do{if(g=v.$$watchers)for(s=g.length;s--;)try{(c=g[s])&&((e=c.get(v))!==(f=c.last)&&!(c.eq?Aa(e,f):"number"==typeof e&&"number"==typeof f&&isNaN(e)&&isNaN(f)))&&(t=!0,c.last=c.eq?da(e):e,c.fn(e,f===k?e:f,v),5>G&&(E=4-G,y[E]||(y[E]=[]),z=B(c.exp)?"fn: "+(c.exp.name||c.exp.toString()):c.exp,z+="; newVal: "+ma(e)+"; oldVal: "+ma(f),y[E].push(z)))}catch(M){d(M)}if(!(g=v.$$childHead||v!==this&&
v.$$nextSibling))for(;v!==this&&!(g=v.$$nextSibling);)v=v.$parent}while(v=g);if(t&&!G--)throw l.$$phase=null,a("infdig",b,ma(y));}while(t||m.length);for(l.$$phase=null;q.length;)try{q.shift()()}catch(w){d(w)}},$destroy:function(){if(l!=this&&!this.$$destroyed){var a=this.$parent;this.$broadcast("$destroy");this.$$destroyed=!0;a.$$childHead==this&&(a.$$childHead=this.$$nextSibling);a.$$childTail==this&&(a.$$childTail=this.$$prevSibling);this.$$prevSibling&&(this.$$prevSibling.$$nextSibling=this.$$nextSibling);
this.$$nextSibling&&(this.$$nextSibling.$$prevSibling=this.$$prevSibling);this.$parent=this.$$nextSibling=this.$$prevSibling=this.$$childHead=this.$$childTail=null}},$eval:function(a,b){return e(a)(this,b)},$evalAsync:function(a){l.$$phase||l.$$asyncQueue.length||f.defer(function(){l.$$asyncQueue.length&&l.$digest()});this.$$asyncQueue.push({scope:this,expression:a})},$$postDigest:function(a){this.$$postDigestQueue.push(a)},$apply:function(a){try{return h("$apply"),this.$eval(a)}catch(b){d(b)}finally{l.$$phase=
null;try{l.$digest()}catch(c){throw d(c),c;}}},$on:function(a,b){var c=this.$$listeners[a];c||(this.$$listeners[a]=c=[]);c.push(b);return function(){c[ab(c,b)]=null}},$emit:function(a,b){var c=[],e,f=this,h=!1,g={name:a,targetScope:f,stopPropagation:function(){h=!0},preventDefault:function(){g.defaultPrevented=!0},defaultPrevented:!1},k=[g].concat(ta.call(arguments,1)),l,m;do{e=f.$$listeners[a]||c;g.currentScope=f;l=0;for(m=e.length;l<m;l++)if(e[l])try{e[l].apply(null,k)}catch(q){d(q)}else e.splice(l,
1),l--,m--;if(h)break;f=f.$parent}while(f);return g},$broadcast:function(a,b){var c=this,e=this,f={name:a,targetScope:this,preventDefault:function(){f.defaultPrevented=!0},defaultPrevented:!1},h=[f].concat(ta.call(arguments,1)),g,k;do{c=e;f.currentScope=c;e=c.$$listeners[a]||[];g=0;for(k=e.length;g<k;g++)if(e[g])try{e[g].apply(null,h)}catch(l){d(l)}else e.splice(g,1),g--,k--;if(!(e=c.$$childHead||c!==this&&c.$$nextSibling))for(;c!==this&&!(e=c.$$nextSibling);)c=c.$parent}while(c=e);return f}};var l=
new g;return l}]}function xd(b){if("self"===b)return b;if(D(b)){if(-1<b.indexOf("***"))throw ra("iwcard",b);b=b.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1").replace(/\x08/g,"\\x08").replace("\\*\\*",".*").replace("\\*","[^:/.?&;]*");return RegExp("^"+b+"$")}if($a(b))return RegExp("^"+b.source+"$");throw ra("imatcher");}function tc(b){var a=[];z(b)&&q(b,function(b){a.push(xd(b))});return a}function yd(){this.SCE_CONTEXTS=ca;var b=["self"],a=[];this.resourceUrlWhitelist=function(a){arguments.length&&
(b=tc(a));return b};this.resourceUrlBlacklist=function(b){arguments.length&&(a=tc(b));return a};this.$get=["$log","$document","$injector",function(c,d,e){function f(a){var b=function(a){this.$$unwrapTrustedValue=function(){return a}};a&&(b.prototype=new a);b.prototype.valueOf=function(){return this.$$unwrapTrustedValue()};b.prototype.toString=function(){return this.$$unwrapTrustedValue().toString()};return b}var g=function(a){throw ra("unsafe");};e.has("$sanitize")&&(g=e.get("$sanitize"));var h=f(),
m={};m[ca.HTML]=f(h);m[ca.CSS]=f(h);m[ca.URL]=f(h);m[ca.JS]=f(h);m[ca.RESOURCE_URL]=f(m[ca.URL]);return{trustAs:function(a,b){var c=m.hasOwnProperty(a)?m[a]:null;if(!c)throw ra("icontext",a,b);if(null===b||b===s||""===b)return b;if("string"!==typeof b)throw ra("itype",a);return new c(b)},getTrusted:function(c,d){if(null===d||d===s||""===d)return d;var e=m.hasOwnProperty(c)?m[c]:null;if(e&&d instanceof e)return d.$$unwrapTrustedValue();if(c===ca.RESOURCE_URL){var e=xa(d.toString()),f,h,q=!1;f=0;for(h=
b.length;f<h;f++)if("self"===b[f]?Eb(e):b[f].exec(e.href)){q=!0;break}if(q)for(f=0,h=a.length;f<h;f++)if("self"===a[f]?Eb(e):a[f].exec(e.href)){q=!1;break}if(q)return d;throw ra("insecurl",d.toString());}if(c===ca.HTML)return g(d);throw ra("unsafe");},valueOf:function(a){return a instanceof h?a.$$unwrapTrustedValue():a}}}]}function zd(){var b=!0;this.enabled=function(a){arguments.length&&(b=!!a);return b};this.$get=["$parse","$document","$sceDelegate",function(a,c,d){if(b&&P&&(c=c[0].documentMode,
c!==s&&8>c))throw ra("iequirks");var e=da(ca);e.isEnabled=function(){return b};e.trustAs=d.trustAs;e.getTrusted=d.getTrusted;e.valueOf=d.valueOf;b||(e.trustAs=e.getTrusted=function(a,b){return b},e.valueOf=za);e.parseAs=function(b,c){var d=a(c);return d.literal&&d.constant?d:function(a,c){return e.getTrusted(b,d(a,c))}};var f=e.parseAs,g=e.getTrusted,h=e.trustAs;q(ca,function(a,b){var c=w(b);e[Pa("parse_as_"+c)]=function(b){return f(a,b)};e[Pa("get_trusted_"+c)]=function(b){return g(a,b)};e[Pa("trust_as_"+
c)]=function(b){return h(a,b)}});return e}]}function Ad(){this.$get=["$window","$document",function(b,a){var c={},d=U((/android (\d+)/.exec(w((b.navigator||{}).userAgent))||[])[1]),e=/Boxee/i.test((b.navigator||{}).userAgent),f=a[0]||{},g,h=/^(Moz|webkit|O|ms)(?=[A-Z])/,m=f.body&&f.body.style,k=!1,l=!1;if(m){for(var n in m)if(k=h.exec(n)){g=k[0];g=g.substr(0,1).toUpperCase()+g.substr(1);break}g||(g="WebkitOpacity"in m&&"webkit");k=!!("transition"in m||g+"Transition"in m);l=!!("animation"in m||g+"Animation"in
m);!d||k&&l||(k=D(f.body.style.webkitTransition),l=D(f.body.style.webkitAnimation))}return{history:!(!b.history||!b.history.pushState||4>d||e),hashchange:"onhashchange"in b&&(!f.documentMode||7<f.documentMode),hasEvent:function(a){if("input"==a&&9==P)return!1;if(x(c[a])){var b=f.createElement("div");c[a]="on"+a in b}return c[a]},csp:Rb(),vendorPrefix:g,transitions:k,animations:l,msie:P}}]}function Bd(){this.$get=["$rootScope","$browser","$q","$exceptionHandler",function(b,a,c,d){function e(e,h,m){var k=
c.defer(),l=k.promise,n=z(m)&&!m;h=a.defer(function(){try{k.resolve(e())}catch(a){k.reject(a),d(a)}finally{delete f[l.$$timeoutId]}n||b.$apply()},h);l.$$timeoutId=h;f[h]=k;return l}var f={};e.cancel=function(b){return b&&b.$$timeoutId in f?(f[b.$$timeoutId].reject("canceled"),delete f[b.$$timeoutId],a.defer.cancel(b.$$timeoutId)):!1};return e}]}function xa(b){P&&(R.setAttribute("href",b),b=R.href);R.setAttribute("href",b);return{href:R.href,protocol:R.protocol?R.protocol.replace(/:$/,""):"",host:R.host,
search:R.search?R.search.replace(/^\?/,""):"",hash:R.hash?R.hash.replace(/^#/,""):"",hostname:R.hostname,port:R.port,pathname:R.pathname&&"/"===R.pathname.charAt(0)?R.pathname:"/"+R.pathname}}function Eb(b){b=D(b)?xa(b):b;return b.protocol===uc.protocol&&b.host===uc.host}function Cd(){this.$get=aa(W)}function vc(b){function a(d,e){if(T(d)){var f={};q(d,function(b,c){f[c]=a(c,b)});return f}return b.factory(d+c,e)}var c="Filter";this.register=a;this.$get=["$injector",function(a){return function(b){return a.get(b+
c)}}];a("currency",wc);a("date",xc);a("filter",Dd);a("json",Ed);a("limitTo",Fd);a("lowercase",Gd);a("number",yc);a("orderBy",zc);a("uppercase",Hd)}function Dd(){return function(b,a,c){if(!J(b))return b;var d=typeof c,e=[];e.check=function(a){for(var b=0;b<e.length;b++)if(!e[b](a))return!1;return!0};"function"!==d&&(c="boolean"===d&&c?function(a,b){return bb.equals(a,b)}:function(a,b){b=(""+b).toLowerCase();return-1<(""+a).toLowerCase().indexOf(b)});var f=function(a,b){if("string"==typeof b&&"!"===
b.charAt(0))return!f(a,b.substr(1));switch(typeof a){case "boolean":case "number":case "string":return c(a,b);case "object":switch(typeof b){case "object":return c(a,b);default:for(var d in a)if("$"!==d.charAt(0)&&f(a[d],b))return!0}return!1;case "array":for(d=0;d<a.length;d++)if(f(a[d],b))return!0;return!1;default:return!1}};switch(typeof a){case "boolean":case "number":case "string":a={$:a};case "object":for(var g in a)"$"==g?function(){if(a[g]){var b=g;e.push(function(c){return f(c,a[b])})}}():
function(){if("undefined"!=typeof a[g]){var b=g;e.push(function(c){return f(ub(c,b),a[b])})}}();break;case "function":e.push(a);break;default:return b}for(var d=[],h=0;h<b.length;h++){var m=b[h];e.check(m)&&d.push(m)}return d}}function wc(b){var a=b.NUMBER_FORMATS;return function(b,d){x(d)&&(d=a.CURRENCY_SYM);return Ac(b,a.PATTERNS[1],a.GROUP_SEP,a.DECIMAL_SEP,2).replace(/\u00A4/g,d)}}function yc(b){var a=b.NUMBER_FORMATS;return function(b,d){return Ac(b,a.PATTERNS[0],a.GROUP_SEP,a.DECIMAL_SEP,d)}}
function Ac(b,a,c,d,e){if(isNaN(b)||!isFinite(b))return"";var f=0>b;b=Math.abs(b);var g=b+"",h="",m=[],k=!1;if(-1!==g.indexOf("e")){var l=g.match(/([\d\.]+)e(-?)(\d+)/);l&&"-"==l[2]&&l[3]>e+1?g="0":(h=g,k=!0)}if(k)0<e&&(-1<b&&1>b)&&(h=b.toFixed(e));else{g=(g.split(Bc)[1]||"").length;x(e)&&(e=Math.min(Math.max(a.minFrac,g),a.maxFrac));g=Math.pow(10,e);b=Math.round(b*g)/g;b=(""+b).split(Bc);g=b[0];b=b[1]||"";var l=0,n=a.lgSize,r=a.gSize;if(g.length>=n+r)for(l=g.length-n,k=0;k<l;k++)0===(l-k)%r&&0!==
k&&(h+=c),h+=g.charAt(k);for(k=l;k<g.length;k++)0===(g.length-k)%n&&0!==k&&(h+=c),h+=g.charAt(k);for(;b.length<e;)b+="0";e&&"0"!==e&&(h+=d+b.substr(0,e))}m.push(f?a.negPre:a.posPre);m.push(h);m.push(f?a.negSuf:a.posSuf);return m.join("")}function Kb(b,a,c){var d="";0>b&&(d="-",b=-b);for(b=""+b;b.length<a;)b="0"+b;c&&(b=b.substr(b.length-a));return d+b}function V(b,a,c,d){c=c||0;return function(e){e=e["get"+b]();if(0<c||e>-c)e+=c;0===e&&-12==c&&(e=12);return Kb(e,a,d)}}function jb(b,a){return function(c,
d){var e=c["get"+b](),f=Ga(a?"SHORT"+b:b);return d[f][e]}}function xc(b){function a(a){var b;if(b=a.match(c)){a=new Date(0);var f=0,g=0,h=b[8]?a.setUTCFullYear:a.setFullYear,m=b[8]?a.setUTCHours:a.setHours;b[9]&&(f=U(b[9]+b[10]),g=U(b[9]+b[11]));h.call(a,U(b[1]),U(b[2])-1,U(b[3]));f=U(b[4]||0)-f;g=U(b[5]||0)-g;h=U(b[6]||0);b=Math.round(1E3*parseFloat("0."+(b[7]||0)));m.call(a,f,g,h,b)}return a}var c=/^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
return function(c,e){var f="",g=[],h,m;e=e||"mediumDate";e=b.DATETIME_FORMATS[e]||e;D(c)&&(c=Id.test(c)?U(c):a(c));qb(c)&&(c=new Date(c));if(!Ja(c))return c;for(;e;)(m=Jd.exec(e))?(g=g.concat(ta.call(m,1)),e=g.pop()):(g.push(e),e=null);q(g,function(a){h=Kd[a];f+=h?h(c,b.DATETIME_FORMATS):a.replace(/(^'|'$)/g,"").replace(/''/g,"'")});return f}}function Ed(){return function(b){return ma(b,!0)}}function Fd(){return function(b,a){if(!J(b)&&!D(b))return b;a=U(a);if(D(b))return a?0<=a?b.slice(0,a):b.slice(a,
b.length):"";var c=[],d,e;a>b.length?a=b.length:a<-b.length&&(a=-b.length);0<a?(d=0,e=a):(d=b.length+a,e=b.length);for(;d<e;d++)c.push(b[d]);return c}}function zc(b){return function(a,c,d){function e(a,b){return Na(b)?function(b,c){return a(c,b)}:a}if(!J(a)||!c)return a;c=J(c)?c:[c];c=Lc(c,function(a){var c=!1,d=a||za;if(D(a)){if("+"==a.charAt(0)||"-"==a.charAt(0))c="-"==a.charAt(0),a=a.substring(1);d=b(a)}return e(function(a,b){var c;c=d(a);var e=d(b),f=typeof c,g=typeof e;f==g?("string"==f&&(c=
c.toLowerCase(),e=e.toLowerCase()),c=c===e?0:c<e?-1:1):c=f<g?-1:1;return c},c)});for(var f=[],g=0;g<a.length;g++)f.push(a[g]);return f.sort(e(function(a,b){for(var d=0;d<c.length;d++){var e=c[d](a,b);if(0!==e)return e}return 0},d))}}function sa(b){B(b)&&(b={link:b});b.restrict=b.restrict||"AC";return aa(b)}function Cc(b,a){function c(a,c){c=c?"-"+cb(c,"-"):"";b.removeClass((a?kb:lb)+c).addClass((a?lb:kb)+c)}var d=this,e=b.parent().controller("form")||mb,f=0,g=d.$error={},h=[];d.$name=a.name||a.ngForm;
d.$dirty=!1;d.$pristine=!0;d.$valid=!0;d.$invalid=!1;e.$addControl(d);b.addClass(Ha);c(!0);d.$addControl=function(a){na(a.$name,"input");h.push(a);a.$name&&(d[a.$name]=a)};d.$removeControl=function(a){a.$name&&d[a.$name]===a&&delete d[a.$name];q(g,function(b,c){d.$setValidity(c,!0,a)});La(h,a)};d.$setValidity=function(a,b,h){var n=g[a];if(b)n&&(La(n,h),n.length||(f--,f||(c(b),d.$valid=!0,d.$invalid=!1),g[a]=!1,c(!0,a),e.$setValidity(a,!0,d)));else{f||c(b);if(n){if(-1!=ab(n,h))return}else g[a]=n=[],
f++,c(!1,a),e.$setValidity(a,!1,d);n.push(h);d.$valid=!1;d.$invalid=!0}};d.$setDirty=function(){b.removeClass(Ha).addClass(nb);d.$dirty=!0;d.$pristine=!1;e.$setDirty()};d.$setPristine=function(){b.removeClass(nb).addClass(Ha);d.$dirty=!1;d.$pristine=!0;q(h,function(a){a.$setPristine()})}}function ob(b,a,c,d,e,f){var g=function(){var e=a.val();Na(c.ngTrim||"T")&&(e=Y(e));d.$viewValue!==e&&b.$apply(function(){d.$setViewValue(e)})};if(e.hasEvent("input"))a.on("input",g);else{var h,m=function(){h||(h=
f.defer(function(){g();h=null}))};a.on("keydown",function(a){a=a.keyCode;91===a||(15<a&&19>a||37<=a&&40>=a)||m()});a.on("change",g);if(e.hasEvent("paste"))a.on("paste cut",m)}d.$render=function(){a.val(d.$isEmpty(d.$viewValue)?"":d.$viewValue)};var k=c.ngPattern,l=function(a,b){if(d.$isEmpty(b)||a.test(b))return d.$setValidity("pattern",!0),b;d.$setValidity("pattern",!1);return s};k&&((e=k.match(/^\/(.*)\/([gim]*)$/))?(k=RegExp(e[1],e[2]),e=function(a){return l(k,a)}):e=function(c){var d=b.$eval(k);
if(!d||!d.test)throw L("ngPattern")("noregexp",k,d,ea(a));return l(d,c)},d.$formatters.push(e),d.$parsers.push(e));if(c.ngMinlength){var n=U(c.ngMinlength);e=function(a){if(!d.$isEmpty(a)&&a.length<n)return d.$setValidity("minlength",!1),s;d.$setValidity("minlength",!0);return a};d.$parsers.push(e);d.$formatters.push(e)}if(c.ngMaxlength){var r=U(c.ngMaxlength);e=function(a){if(!d.$isEmpty(a)&&a.length>r)return d.$setValidity("maxlength",!1),s;d.$setValidity("maxlength",!0);return a};d.$parsers.push(e);
d.$formatters.push(e)}}function Lb(b,a){b="ngClass"+b;return function(){return{restrict:"AC",link:function(c,d,e){function f(b){if(!0===a||c.$index%2===a)h&&!Aa(b,h)&&e.$removeClass(g(h)),e.$addClass(g(b));h=da(b)}function g(a){if(J(a))return a.join(" ");if(T(a)){var b=[];q(a,function(a,c){a&&b.push(c)});return b.join(" ")}return a}var h;c.$watch(e[b],f,!0);e.$observe("class",function(a){f(c.$eval(e[b]))});"ngClass"!==b&&c.$watch("$index",function(d,f){var h=d&1;h!==f&1&&(h===a?(h=c.$eval(e[b]),e.$addClass(g(h))):
(h=c.$eval(e[b]),e.$removeClass(g(h))))})}}}}var w=function(b){return D(b)?b.toLowerCase():b},Ga=function(b){return D(b)?b.toUpperCase():b},P,y,Ba,ta=[].slice,Ld=[].push,Ka=Object.prototype.toString,Ma=L("ng"),bb=W.angular||(W.angular={}),Ua,Ea,ia=["0","0","0"];P=U((/msie (\d+)/.exec(w(navigator.userAgent))||[])[1]);isNaN(P)&&(P=U((/trident\/.*; rv:(\d+)/.exec(w(navigator.userAgent))||[])[1]));t.$inject=[];za.$inject=[];var Y=function(){return String.prototype.trim?function(b){return D(b)?b.trim():
b}:function(b){return D(b)?b.replace(/^\s*/,"").replace(/\s*$/,""):b}}();Ea=9>P?function(b){b=b.nodeName?b:b[0];return b.scopeName&&"HTML"!=b.scopeName?Ga(b.scopeName+":"+b.nodeName):b.nodeName}:function(b){return b.nodeName?b.nodeName:b[0].nodeName};var Pc=/[A-Z]/g,Md={full:"1.2.0",major:1,minor:"NG_VERSION_MINOR",dot:0,codeName:"timely-delivery"},Ra=Q.cache={},db=Q.expando="ng-"+(new Date).getTime(),Tc=1,Dc=W.document.addEventListener?function(b,a,c){b.addEventListener(a,c,!1)}:function(b,a,c){b.attachEvent("on"+
a,c)},Ab=W.document.removeEventListener?function(b,a,c){b.removeEventListener(a,c,!1)}:function(b,a,c){b.detachEvent("on"+a,c)},Rc=/([\:\-\_]+(.))/g,Sc=/^moz([A-Z])/,xb=L("jqLite"),Da=Q.prototype={ready:function(b){function a(){c||(c=!0,b())}var c=!1;"complete"===O.readyState?setTimeout(a):(this.on("DOMContentLoaded",a),Q(W).on("load",a))},toString:function(){var b=[];q(this,function(a){b.push(""+a)});return"["+b.join(", ")+"]"},eq:function(b){return 0<=b?y(this[b]):y(this[this.length+b])},length:0,
push:Ld,sort:[].sort,splice:[].splice},fb={};q("multiple selected checked disabled readOnly required open".split(" "),function(b){fb[w(b)]=b});var cc={};q("input select option textarea button form details".split(" "),function(b){cc[Ga(b)]=!0});q({data:$b,inheritedData:eb,scope:function(b){return y(b).data("$scope")||eb(b.parentNode||b,["$isolateScope","$scope"])},isolateScope:function(b){return y(b).data("$isolateScope")||y(b).data("$isolateScopeNoTemplate")},controller:ac,injector:function(b){return eb(b,
"$injector")},removeAttr:function(b,a){b.removeAttribute(a)},hasClass:Bb,css:function(b,a,c){a=Pa(a);if(z(c))b.style[a]=c;else{var d;8>=P&&(d=b.currentStyle&&b.currentStyle[a],""===d&&(d="auto"));d=d||b.style[a];8>=P&&(d=""===d?s:d);return d}},attr:function(b,a,c){var d=w(a);if(fb[d])if(z(c))c?(b[a]=!0,b.setAttribute(a,d)):(b[a]=!1,b.removeAttribute(d));else return b[a]||(b.attributes.getNamedItem(a)||t).specified?d:s;else if(z(c))b.setAttribute(a,c);else if(b.getAttribute)return b=b.getAttribute(a,
2),null===b?s:b},prop:function(b,a,c){if(z(c))b[a]=c;else return b[a]},text:function(){function b(b,d){var e=a[b.nodeType];if(x(d))return e?b[e]:"";b[e]=d}var a=[];9>P?(a[1]="innerText",a[3]="nodeValue"):a[1]=a[3]="textContent";b.$dv="";return b}(),val:function(b,a){if(x(a)){if("SELECT"===Ea(b)&&b.multiple){var c=[];q(b.options,function(a){a.selected&&c.push(a.value||a.text)});return 0===c.length?null:c}return b.value}b.value=a},html:function(b,a){if(x(a))return b.innerHTML;for(var c=0,d=b.childNodes;c<
d.length;c++)Qa(d[c]);b.innerHTML=a}},function(b,a){Q.prototype[a]=function(a,d){var e,f;if((2==b.length&&b!==Bb&&b!==ac?a:d)===s){if(T(a)){for(e=0;e<this.length;e++)if(b===$b)b(this[e],a);else for(f in a)b(this[e],f,a[f]);return this}e=b.$dv;f=e===s?Math.min(this.length,1):this.length;for(var g=0;g<f;g++){var h=b(this[g],a,d);e=e?e+h:h}return e}for(e=0;e<this.length;e++)b(this[e],a,d);return this}});q({removeData:Yb,dealoc:Qa,on:function a(c,d,e,f){if(z(f))throw xb("onargs");var g=ja(c,"events"),
h=ja(c,"handle");g||ja(c,"events",g={});h||ja(c,"handle",h=Uc(c,g));q(d.split(" "),function(d){var f=g[d];if(!f){if("mouseenter"==d||"mouseleave"==d){var l=O.body.contains||O.body.compareDocumentPosition?function(a,c){var d=9===a.nodeType?a.documentElement:a,e=c&&c.parentNode;return a===e||!!(e&&1===e.nodeType&&(d.contains?d.contains(e):a.compareDocumentPosition&&a.compareDocumentPosition(e)&16))}:function(a,c){if(c)for(;c=c.parentNode;)if(c===a)return!0;return!1};g[d]=[];a(c,{mouseleave:"mouseout",
mouseenter:"mouseover"}[d],function(a){var c=a.relatedTarget;c&&(c===this||l(this,c))||h(a,d)})}else Dc(c,d,h),g[d]=[];f=g[d]}f.push(e)})},off:Zb,replaceWith:function(a,c){var d,e=a.parentNode;Qa(a);q(new Q(c),function(c){d?e.insertBefore(c,d.nextSibling):e.replaceChild(c,a);d=c})},children:function(a){var c=[];q(a.childNodes,function(a){1===a.nodeType&&c.push(a)});return c},contents:function(a){return a.childNodes||[]},append:function(a,c){q(new Q(c),function(c){1!==a.nodeType&&11!==a.nodeType||
a.appendChild(c)})},prepend:function(a,c){if(1===a.nodeType){var d=a.firstChild;q(new Q(c),function(c){a.insertBefore(c,d)})}},wrap:function(a,c){c=y(c)[0];var d=a.parentNode;d&&d.replaceChild(c,a);c.appendChild(a)},remove:function(a){Qa(a);var c=a.parentNode;c&&c.removeChild(a)},after:function(a,c){var d=a,e=a.parentNode;q(new Q(c),function(a){e.insertBefore(a,d.nextSibling);d=a})},addClass:Db,removeClass:Cb,toggleClass:function(a,c,d){x(d)&&(d=!Bb(a,c));(d?Db:Cb)(a,c)},parent:function(a){return(a=
a.parentNode)&&11!==a.nodeType?a:null},next:function(a){if(a.nextElementSibling)return a.nextElementSibling;for(a=a.nextSibling;null!=a&&1!==a.nodeType;)a=a.nextSibling;return a},find:function(a,c){return a.getElementsByTagName(c)},clone:zb,triggerHandler:function(a,c,d){c=(ja(a,"events")||{})[c];d=d||[];var e=[{preventDefault:t,stopPropagation:t}];q(c,function(c){c.apply(a,e.concat(d))})}},function(a,c){Q.prototype[c]=function(c,e,f){for(var g,h=0;h<this.length;h++)x(g)?(g=a(this[h],c,e,f),z(g)&&
(g=y(g))):yb(g,a(this[h],c,e,f));return z(g)?g:this};Q.prototype.bind=Q.prototype.on;Q.prototype.unbind=Q.prototype.off});Sa.prototype={put:function(a,c){this[Ca(a)]=c},get:function(a){return this[Ca(a)]},remove:function(a){var c=this[a=Ca(a)];delete this[a];return c}};var Wc=/^function\s*[^\(]*\(\s*([^\)]*)\)/m,Xc=/,/,Yc=/^\s*(_?)(\S+?)\1\s*$/,Vc=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,Ta=L("$injector"),Nd=L("$animate"),Od=["$provide",function(a){this.$$selectors={};this.register=function(c,d){var e=
c+"-animation";if(c&&"."!=c.charAt(0))throw Nd("notcsel",c);this.$$selectors[c.substr(1)]=e;a.factory(e,d)};this.$get=["$timeout",function(a){return{enter:function(d,e,f,g){f=f&&f[f.length-1];var h=e&&e[0]||f&&f.parentNode,m=f&&f.nextSibling||null;q(d,function(a){h.insertBefore(a,m)});g&&a(g,0,!1)},leave:function(d,e){d.remove();e&&a(e,0,!1)},move:function(a,c,f,g){this.enter(a,c,f,g)},addClass:function(d,e,f){e=D(e)?e:J(e)?e.join(" "):"";q(d,function(a){Db(a,e)});f&&a(f,0,!1)},removeClass:function(d,
e,f){e=D(e)?e:J(e)?e.join(" "):"";q(d,function(a){Cb(a,e)});f&&a(f,0,!1)},enabled:t}}]}],fa=L("$compile");ec.$inject=["$provide"];var fd=/^(x[\:\-_]|data[\:\-_])/i,md=W.XMLHttpRequest||function(){try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(a){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(c){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(d){}throw L("$httpBackend")("noxhr");},jc=L("$interpolate"),Pd=/^([^\?#]*)(\?([^#]*))?(#(.*))?$/,qd={http:80,https:443,ftp:21},Gb=
L("$location");oc.prototype=Hb.prototype=nc.prototype={$$html5:!1,$$replace:!1,absUrl:hb("$$absUrl"),url:function(a,c){if(x(a))return this.$$url;var d=Pd.exec(a);d[1]&&this.path(decodeURIComponent(d[1]));(d[2]||d[1])&&this.search(d[3]||"");this.hash(d[5]||"",c);return this},protocol:hb("$$protocol"),host:hb("$$host"),port:hb("$$port"),path:pc("$$path",function(a){return"/"==a.charAt(0)?a:"/"+a}),search:function(a,c){switch(arguments.length){case 0:return this.$$search;case 1:if(D(a))this.$$search=
Ub(a);else if(T(a))this.$$search=a;else throw Gb("isrcharg");break;default:x(c)||null===c?delete this.$$search[a]:this.$$search[a]=c}this.$$compose();return this},hash:pc("$$hash",za),replace:function(){this.$$replace=!0;return this}};var pa=L("$parse"),sc={},qa,Ia={"null":function(){return null},"true":function(){return!0},"false":function(){return!1},undefined:t,"+":function(a,c,d,e){d=d(a,c);e=e(a,c);return z(d)?z(e)?d+e:d:z(e)?e:s},"-":function(a,c,d,e){d=d(a,c);e=e(a,c);return(z(d)?d:0)-(z(e)?
e:0)},"*":function(a,c,d,e){return d(a,c)*e(a,c)},"/":function(a,c,d,e){return d(a,c)/e(a,c)},"%":function(a,c,d,e){return d(a,c)%e(a,c)},"^":function(a,c,d,e){return d(a,c)^e(a,c)},"=":t,"===":function(a,c,d,e){return d(a,c)===e(a,c)},"!==":function(a,c,d,e){return d(a,c)!==e(a,c)},"==":function(a,c,d,e){return d(a,c)==e(a,c)},"!=":function(a,c,d,e){return d(a,c)!=e(a,c)},"<":function(a,c,d,e){return d(a,c)<e(a,c)},">":function(a,c,d,e){return d(a,c)>e(a,c)},"<=":function(a,c,d,e){return d(a,c)<=
e(a,c)},">=":function(a,c,d,e){return d(a,c)>=e(a,c)},"&&":function(a,c,d,e){return d(a,c)&&e(a,c)},"||":function(a,c,d,e){return d(a,c)||e(a,c)},"&":function(a,c,d,e){return d(a,c)&e(a,c)},"|":function(a,c,d,e){return e(a,c)(a,c,d(a,c))},"!":function(a,c,d){return!d(a,c)}},Qd={n:"\n",f:"\f",r:"\r",t:"\t",v:"\v","'":"'",'"':'"'},Jb=function(a){this.options=a};Jb.prototype={constructor:Jb,lex:function(a){this.text=a;this.index=0;this.ch=s;this.lastCh=":";this.tokens=[];var c;for(a=[];this.index<this.text.length;){this.ch=
this.text.charAt(this.index);if(this.is("\"'"))this.readString(this.ch);else if(this.isNumber(this.ch)||this.is(".")&&this.isNumber(this.peek()))this.readNumber();else if(this.isIdent(this.ch))this.readIdent(),this.was("{,")&&("{"===a[0]&&(c=this.tokens[this.tokens.length-1]))&&(c.json=-1===c.text.indexOf("."));else if(this.is("(){}[].,;:?"))this.tokens.push({index:this.index,text:this.ch,json:this.was(":[,")&&this.is("{[")||this.is("}]:,")}),this.is("{[")&&a.unshift(this.ch),this.is("}]")&&a.shift(),
this.index++;else if(this.isWhitespace(this.ch)){this.index++;continue}else{var d=this.ch+this.peek(),e=d+this.peek(2),f=Ia[this.ch],g=Ia[d],h=Ia[e];h?(this.tokens.push({index:this.index,text:e,fn:h}),this.index+=3):g?(this.tokens.push({index:this.index,text:d,fn:g}),this.index+=2):f?(this.tokens.push({index:this.index,text:this.ch,fn:f,json:this.was("[,:")&&this.is("+-")}),this.index+=1):this.throwError("Unexpected next character ",this.index,this.index+1)}this.lastCh=this.ch}return this.tokens},
is:function(a){return-1!==a.indexOf(this.ch)},was:function(a){return-1!==a.indexOf(this.lastCh)},peek:function(a){a=a||1;return this.index+a<this.text.length?this.text.charAt(this.index+a):!1},isNumber:function(a){return"0"<=a&&"9">=a},isWhitespace:function(a){return" "===a||"\r"===a||"\t"===a||"\n"===a||"\v"===a||"\u00a0"===a},isIdent:function(a){return"a"<=a&&"z">=a||"A"<=a&&"Z">=a||"_"===a||"$"===a},isExpOperator:function(a){return"-"===a||"+"===a||this.isNumber(a)},throwError:function(a,c,d){d=
d||this.index;c=z(c)?"s "+c+"-"+this.index+" ["+this.text.substring(c,d)+"]":" "+d;throw pa("lexerr",a,c,this.text);},readNumber:function(){for(var a="",c=this.index;this.index<this.text.length;){var d=w(this.text.charAt(this.index));if("."==d||this.isNumber(d))a+=d;else{var e=this.peek();if("e"==d&&this.isExpOperator(e))a+=d;else if(this.isExpOperator(d)&&e&&this.isNumber(e)&&"e"==a.charAt(a.length-1))a+=d;else if(!this.isExpOperator(d)||e&&this.isNumber(e)||"e"!=a.charAt(a.length-1))break;else this.throwError("Invalid exponent")}this.index++}a*=
1;this.tokens.push({index:c,text:a,json:!0,fn:function(){return a}})},readIdent:function(){for(var a=this,c="",d=this.index,e,f,g,h;this.index<this.text.length;){h=this.text.charAt(this.index);if("."===h||this.isIdent(h)||this.isNumber(h))"."===h&&(e=this.index),c+=h;else break;this.index++}if(e)for(f=this.index;f<this.text.length;){h=this.text.charAt(f);if("("===h){g=c.substr(e-d+1);c=c.substr(0,e-d);this.index=f;break}if(this.isWhitespace(h))f++;else break}d={index:d,text:c};if(Ia.hasOwnProperty(c))d.fn=
Ia[c],d.json=Ia[c];else{var m=rc(c,this.options,this.text);d.fn=u(function(a,c){return m(a,c)},{assign:function(d,e){return ib(d,c,e,a.text,a.options)}})}this.tokens.push(d);g&&(this.tokens.push({index:e,text:".",json:!1}),this.tokens.push({index:e+1,text:g,json:!1}))},readString:function(a){var c=this.index;this.index++;for(var d="",e=a,f=!1;this.index<this.text.length;){var g=this.text.charAt(this.index),e=e+g;if(f)"u"===g?(g=this.text.substring(this.index+1,this.index+5),g.match(/[\da-f]{4}/i)||
this.throwError("Invalid unicode escape [\\u"+g+"]"),this.index+=4,d+=String.fromCharCode(parseInt(g,16))):d=(f=Qd[g])?d+f:d+g,f=!1;else if("\\"===g)f=!0;else{if(g===a){this.index++;this.tokens.push({index:c,text:e,string:d,json:!0,fn:function(){return d}});return}d+=g}this.index++}this.throwError("Unterminated quote",c)}};var Ya=function(a,c,d){this.lexer=a;this.$filter=c;this.options=d};Ya.ZERO=function(){return 0};Ya.prototype={constructor:Ya,parse:function(a,c){this.text=a;this.json=c;this.tokens=
this.lexer.lex(a);c&&(this.assignment=this.logicalOR,this.functionCall=this.fieldAccess=this.objectIndex=this.filterChain=function(){this.throwError("is not valid json",{text:a,index:0})});var d=c?this.primary():this.statements();0!==this.tokens.length&&this.throwError("is an unexpected token",this.tokens[0]);d.literal=!!d.literal;d.constant=!!d.constant;return d},primary:function(){var a;if(this.expect("("))a=this.filterChain(),this.consume(")");else if(this.expect("["))a=this.arrayDeclaration();
else if(this.expect("{"))a=this.object();else{var c=this.expect();(a=c.fn)||this.throwError("not a primary expression",c);c.json&&(a.constant=!0,a.literal=!0)}for(var d;c=this.expect("(","[",".");)"("===c.text?(a=this.functionCall(a,d),d=null):"["===c.text?(d=a,a=this.objectIndex(a)):"."===c.text?(d=a,a=this.fieldAccess(a)):this.throwError("IMPOSSIBLE");return a},throwError:function(a,c){throw pa("syntax",c.text,a,c.index+1,this.text,this.text.substring(c.index));},peekToken:function(){if(0===this.tokens.length)throw pa("ueoe",
this.text);return this.tokens[0]},peek:function(a,c,d,e){if(0<this.tokens.length){var f=this.tokens[0],g=f.text;if(g===a||g===c||g===d||g===e||!(a||c||d||e))return f}return!1},expect:function(a,c,d,e){return(a=this.peek(a,c,d,e))?(this.json&&!a.json&&this.throwError("is not valid json",a),this.tokens.shift(),a):!1},consume:function(a){this.expect(a)||this.throwError("is unexpected, expecting ["+a+"]",this.peek())},unaryFn:function(a,c){return u(function(d,e){return a(d,e,c)},{constant:c.constant})},
ternaryFn:function(a,c,d){return u(function(e,f){return a(e,f)?c(e,f):d(e,f)},{constant:a.constant&&c.constant&&d.constant})},binaryFn:function(a,c,d){return u(function(e,f){return c(e,f,a,d)},{constant:a.constant&&d.constant})},statements:function(){for(var a=[];;)if(0<this.tokens.length&&!this.peek("}",")",";","]")&&a.push(this.filterChain()),!this.expect(";"))return 1===a.length?a[0]:function(c,d){for(var e,f=0;f<a.length;f++){var g=a[f];g&&(e=g(c,d))}return e}},filterChain:function(){for(var a=
this.expression(),c;;)if(c=this.expect("|"))a=this.binaryFn(a,c.fn,this.filter());else return a},filter:function(){for(var a=this.expect(),c=this.$filter(a.text),d=[];;)if(a=this.expect(":"))d.push(this.expression());else{var e=function(a,e,h){h=[h];for(var m=0;m<d.length;m++)h.push(d[m](a,e));return c.apply(a,h)};return function(){return e}}},expression:function(){return this.assignment()},assignment:function(){var a=this.ternary(),c,d;return(d=this.expect("="))?(a.assign||this.throwError("implies assignment but ["+
this.text.substring(0,d.index)+"] can not be assigned to",d),c=this.ternary(),function(d,f){return a.assign(d,c(d,f),f)}):a},ternary:function(){var a=this.logicalOR(),c,d;if(this.expect("?")){c=this.ternary();if(d=this.expect(":"))return this.ternaryFn(a,c,this.ternary());this.throwError("expected :",d)}else return a},logicalOR:function(){for(var a=this.logicalAND(),c;;)if(c=this.expect("||"))a=this.binaryFn(a,c.fn,this.logicalAND());else return a},logicalAND:function(){var a=this.equality(),c;if(c=
this.expect("&&"))a=this.binaryFn(a,c.fn,this.logicalAND());return a},equality:function(){var a=this.relational(),c;if(c=this.expect("==","!=","===","!=="))a=this.binaryFn(a,c.fn,this.equality());return a},relational:function(){var a=this.additive(),c;if(c=this.expect("<",">","<=",">="))a=this.binaryFn(a,c.fn,this.relational());return a},additive:function(){for(var a=this.multiplicative(),c;c=this.expect("+","-");)a=this.binaryFn(a,c.fn,this.multiplicative());return a},multiplicative:function(){for(var a=
this.unary(),c;c=this.expect("*","/","%");)a=this.binaryFn(a,c.fn,this.unary());return a},unary:function(){var a;return this.expect("+")?this.primary():(a=this.expect("-"))?this.binaryFn(Ya.ZERO,a.fn,this.unary()):(a=this.expect("!"))?this.unaryFn(a.fn,this.unary()):this.primary()},fieldAccess:function(a){var c=this,d=this.expect().text,e=rc(d,this.options,this.text);return u(function(c,d,h){return e(h||a(c,d),d)},{assign:function(e,g,h){return ib(a(e,h),d,g,c.text,c.options)}})},objectIndex:function(a){var c=
this,d=this.expression();this.consume("]");return u(function(e,f){var g=a(e,f),h=ha(d(e,f),c.text,!0),m;if(!g)return s;(g=Xa(g[h],c.text))&&(g.then&&c.options.unwrapPromises)&&(m=g,"$$v"in g||(m.$$v=s,m.then(function(a){m.$$v=a})),g=g.$$v);return g},{assign:function(e,f,g){var h=ha(d(e,g),c.text);return Xa(a(e,g),c.text)[h]=f}})},functionCall:function(a,c){var d=[];if(")"!==this.peekToken().text){do d.push(this.expression());while(this.expect(","))}this.consume(")");var e=this;return function(f,g){for(var h=
[],m=c?c(f,g):f,k=0;k<d.length;k++)h.push(d[k](f,g));k=a(f,g,m)||t;Xa(m,e.text);Xa(k,e.text);h=k.apply?k.apply(m,h):k(h[0],h[1],h[2],h[3],h[4]);return Xa(h,e.text)}},arrayDeclaration:function(){var a=[],c=!0;if("]"!==this.peekToken().text){do{var d=this.expression();a.push(d);d.constant||(c=!1)}while(this.expect(","))}this.consume("]");return u(function(c,d){for(var g=[],h=0;h<a.length;h++)g.push(a[h](c,d));return g},{literal:!0,constant:c})},object:function(){var a=[],c=!0;if("}"!==this.peekToken().text){do{var d=
this.expect(),d=d.string||d.text;this.consume(":");var e=this.expression();a.push({key:d,value:e});e.constant||(c=!1)}while(this.expect(","))}this.consume("}");return u(function(c,d){for(var e={},m=0;m<a.length;m++){var k=a[m];e[k.key]=k.value(c,d)}return e},{literal:!0,constant:c})}};var Ib={},ra=L("$sce"),ca={HTML:"html",CSS:"css",URL:"url",RESOURCE_URL:"resourceUrl",JS:"js"},R=O.createElement("a"),uc=xa(W.location.href,!0);vc.$inject=["$provide"];wc.$inject=["$locale"];yc.$inject=["$locale"];var Bc=
".",Kd={yyyy:V("FullYear",4),yy:V("FullYear",2,0,!0),y:V("FullYear",1),MMMM:jb("Month"),MMM:jb("Month",!0),MM:V("Month",2,1),M:V("Month",1,1),dd:V("Date",2),d:V("Date",1),HH:V("Hours",2),H:V("Hours",1),hh:V("Hours",2,-12),h:V("Hours",1,-12),mm:V("Minutes",2),m:V("Minutes",1),ss:V("Seconds",2),s:V("Seconds",1),sss:V("Milliseconds",3),EEEE:jb("Day"),EEE:jb("Day",!0),a:function(a,c){return 12>a.getHours()?c.AMPMS[0]:c.AMPMS[1]},Z:function(a){a=-1*a.getTimezoneOffset();return a=(0<=a?"+":"")+(Kb(Math[0<
a?"floor":"ceil"](a/60),2)+Kb(Math.abs(a%60),2))}},Jd=/((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,Id=/^\-?\d+$/;xc.$inject=["$locale"];var Gd=aa(w),Hd=aa(Ga);zc.$inject=["$parse"];var Rd=aa({restrict:"E",compile:function(a,c){8>=P&&(c.href||c.name||c.$set("href",""),a.append(O.createComment("IE fix")));return function(a,c){c.on("click",function(a){c.attr("href")||a.preventDefault()})}}}),Mb={};q(fb,function(a,c){if("multiple"!=a){var d=ka("ng-"+c);Mb[d]=function(){return{priority:100,
compile:function(){return function(a,f,g){a.$watch(g[d],function(a){g.$set(c,!!a)})}}}}}});q(["src","srcset","href"],function(a){var c=ka("ng-"+a);Mb[c]=function(){return{priority:99,link:function(d,e,f){f.$observe(c,function(c){c&&(f.$set(a,c),P&&e.prop(a,f[a]))})}}}});var mb={$addControl:t,$removeControl:t,$setValidity:t,$setDirty:t,$setPristine:t};Cc.$inject=["$element","$attrs","$scope"];var Ec=function(a){return["$timeout",function(c){return{name:"form",restrict:a?"EAC":"E",controller:Cc,compile:function(){return{pre:function(a,
e,f,g){if(!f.action){var h=function(a){a.preventDefault?a.preventDefault():a.returnValue=!1};Dc(e[0],"submit",h);e.on("$destroy",function(){c(function(){Ab(e[0],"submit",h)},0,!1)})}var m=e.parent().controller("form"),k=f.name||f.ngForm;k&&ib(a,k,g,k);if(m)e.on("$destroy",function(){m.$removeControl(g);k&&ib(a,k,s,k);u(g,mb)})}}}}}]},Sd=Ec(),Td=Ec(!0),Ud=/^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/,Vd=/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}$/,Wd=
/^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/,Fc={text:ob,number:function(a,c,d,e,f,g){ob(a,c,d,e,f,g);e.$parsers.push(function(a){var c=e.$isEmpty(a);if(c||Wd.test(a))return e.$setValidity("number",!0),""===a?null:c?a:parseFloat(a);e.$setValidity("number",!1);return s});e.$formatters.push(function(a){return e.$isEmpty(a)?"":""+a});d.min&&(a=function(a){var c=parseFloat(d.min);if(!e.$isEmpty(a)&&a<c)return e.$setValidity("min",!1),s;e.$setValidity("min",!0);return a},e.$parsers.push(a),e.$formatters.push(a));
d.max&&(a=function(a){var c=parseFloat(d.max);if(!e.$isEmpty(a)&&a>c)return e.$setValidity("max",!1),s;e.$setValidity("max",!0);return a},e.$parsers.push(a),e.$formatters.push(a));e.$formatters.push(function(a){if(e.$isEmpty(a)||qb(a))return e.$setValidity("number",!0),a;e.$setValidity("number",!1);return s})},url:function(a,c,d,e,f,g){ob(a,c,d,e,f,g);a=function(a){if(e.$isEmpty(a)||Ud.test(a))return e.$setValidity("url",!0),a;e.$setValidity("url",!1);return s};e.$formatters.push(a);e.$parsers.push(a)},
email:function(a,c,d,e,f,g){ob(a,c,d,e,f,g);a=function(a){if(e.$isEmpty(a)||Vd.test(a))return e.$setValidity("email",!0),a;e.$setValidity("email",!1);return s};e.$formatters.push(a);e.$parsers.push(a)},radio:function(a,c,d,e){x(d.name)&&c.attr("name",Za());c.on("click",function(){c[0].checked&&a.$apply(function(){e.$setViewValue(d.value)})});e.$render=function(){c[0].checked=d.value==e.$viewValue};d.$observe("value",e.$render)},checkbox:function(a,c,d,e){var f=d.ngTrueValue,g=d.ngFalseValue;D(f)||
(f=!0);D(g)||(g=!1);c.on("click",function(){a.$apply(function(){e.$setViewValue(c[0].checked)})});e.$render=function(){c[0].checked=e.$viewValue};e.$isEmpty=function(a){return a!==f};e.$formatters.push(function(a){return a===f});e.$parsers.push(function(a){return a?f:g})},hidden:t,button:t,submit:t,reset:t},Gc=["$browser","$sniffer",function(a,c){return{restrict:"E",require:"?ngModel",link:function(d,e,f,g){g&&(Fc[w(f.type)]||Fc.text)(d,e,f,g,c,a)}}}],lb="ng-valid",kb="ng-invalid",Ha="ng-pristine",
nb="ng-dirty",Xd=["$scope","$exceptionHandler","$attrs","$element","$parse",function(a,c,d,e,f){function g(a,c){c=c?"-"+cb(c,"-"):"";e.removeClass((a?kb:lb)+c).addClass((a?lb:kb)+c)}this.$modelValue=this.$viewValue=Number.NaN;this.$parsers=[];this.$formatters=[];this.$viewChangeListeners=[];this.$pristine=!0;this.$dirty=!1;this.$valid=!0;this.$invalid=!1;this.$name=d.name;var h=f(d.ngModel),m=h.assign;if(!m)throw L("ngModel")("nonassign",d.ngModel,ea(e));this.$render=t;this.$isEmpty=function(a){return x(a)||
""===a||null===a||a!==a};var k=e.inheritedData("$formController")||mb,l=0,n=this.$error={};e.addClass(Ha);g(!0);this.$setValidity=function(a,c){n[a]!==!c&&(c?(n[a]&&l--,l||(g(!0),this.$valid=!0,this.$invalid=!1)):(g(!1),this.$invalid=!0,this.$valid=!1,l++),n[a]=!c,g(c,a),k.$setValidity(a,c,this))};this.$setPristine=function(){this.$dirty=!1;this.$pristine=!0;e.removeClass(nb).addClass(Ha)};this.$setViewValue=function(d){this.$viewValue=d;this.$pristine&&(this.$dirty=!0,this.$pristine=!1,e.removeClass(Ha).addClass(nb),
k.$setDirty());q(this.$parsers,function(a){d=a(d)});this.$modelValue!==d&&(this.$modelValue=d,m(a,d),q(this.$viewChangeListeners,function(a){try{a()}catch(d){c(d)}}))};var r=this;a.$watch(function(){var c=h(a);if(r.$modelValue!==c){var d=r.$formatters,e=d.length;for(r.$modelValue=c;e--;)c=d[e](c);r.$viewValue!==c&&(r.$viewValue=c,r.$render())}})}],Yd=function(){return{require:["ngModel","^?form"],controller:Xd,link:function(a,c,d,e){var f=e[0],g=e[1]||mb;g.$addControl(f);a.$on("$destroy",function(){g.$removeControl(f)})}}},
Zd=aa({require:"ngModel",link:function(a,c,d,e){e.$viewChangeListeners.push(function(){a.$eval(d.ngChange)})}}),Hc=function(){return{require:"?ngModel",link:function(a,c,d,e){if(e){d.required=!0;var f=function(a){if(d.required&&e.$isEmpty(a))e.$setValidity("required",!1);else return e.$setValidity("required",!0),a};e.$formatters.push(f);e.$parsers.unshift(f);d.$observe("required",function(){f(e.$viewValue)})}}}},$d=function(){return{require:"ngModel",link:function(a,c,d,e){var f=(a=/\/(.*)\//.exec(d.ngList))&&
RegExp(a[1])||d.ngList||",";e.$parsers.push(function(a){if(!x(a)){var c=[];a&&q(a.split(f),function(a){a&&c.push(Y(a))});return c}});e.$formatters.push(function(a){return J(a)?a.join(", "):s});e.$isEmpty=function(a){return!a||!a.length}}}},ae=/^(true|false|\d+)$/,be=function(){return{priority:100,compile:function(a,c){return ae.test(c.ngValue)?function(a,c,f){f.$set("value",a.$eval(f.ngValue))}:function(a,c,f){a.$watch(f.ngValue,function(a){f.$set("value",a)})}}}},ce=sa(function(a,c,d){c.addClass("ng-binding").data("$binding",
d.ngBind);a.$watch(d.ngBind,function(a){c.text(a==s?"":a)})}),de=["$interpolate",function(a){return function(c,d,e){c=a(d.attr(e.$attr.ngBindTemplate));d.addClass("ng-binding").data("$binding",c);e.$observe("ngBindTemplate",function(a){d.text(a)})}}],ee=["$sce","$parse",function(a,c){return function(d,e,f){e.addClass("ng-binding").data("$binding",f.ngBindHtml);var g=c(f.ngBindHtml);d.$watch(function(){return(g(d)||"").toString()},function(c){e.html(a.getTrustedHtml(g(d))||"")})}}],fe=Lb("",!0),ge=
Lb("Odd",0),he=Lb("Even",1),ie=sa({compile:function(a,c){c.$set("ngCloak",s);a.removeClass("ng-cloak")}}),je=[function(){return{scope:!0,controller:"@"}}],Ic={};q("click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste".split(" "),function(a){var c=ka("ng-"+a);Ic[c]=["$parse",function(d){return{compile:function(e,f){var g=d(f[c]);return function(c,d,e){d.on(w(a),function(a){c.$apply(function(){g(c,{$event:a})})})}}}}]});
var ke=["$animate",function(a){return{transclude:"element",priority:600,terminal:!0,restrict:"A",$$tlb:!0,compile:function(c,d,e){return function(c,d,h){var m,k;c.$watch(h.ngIf,function(l){Na(l)?(k=c.$new(),e(k,function(c){m={startNode:c[0],endNode:c[c.length++]=O.createComment(" end ngIf: "+h.ngIf+" ")};a.enter(c,d.parent(),d)})):(k&&(k.$destroy(),k=null),m&&(a.leave(vb(m)),m=null))})}}}}],le=["$http","$templateCache","$anchorScroll","$compile","$animate","$sce",function(a,c,d,e,f,g){return{restrict:"ECA",
priority:400,terminal:!0,transclude:"element",compile:function(h,m,k){var l=m.ngInclude||m.src,n=m.onload||"",r=m.autoscroll;return function(h,m){var q=0,s,t,y=function(){s&&(s.$destroy(),s=null);t&&(f.leave(t),t=null)};h.$watch(g.parseAsResourceUrl(l),function(g){var l=function(){!z(r)||r&&!h.$eval(r)||d()},x=++q;g?(a.get(g,{cache:c}).success(function(a){if(x===q){var c=h.$new();k(c,function(d){y();s=c;t=d;t.html(a);f.enter(t,null,m,l);e(t.contents())(s);s.$emit("$includeContentLoaded");h.$eval(n)})}}).error(function(){x===
q&&y()}),h.$emit("$includeContentRequested")):y()})}}}}],me=sa({compile:function(){return{pre:function(a,c,d){a.$eval(d.ngInit)}}}}),ne=sa({terminal:!0,priority:1E3}),oe=["$locale","$interpolate",function(a,c){var d=/{}/g;return{restrict:"EA",link:function(e,f,g){var h=g.count,m=g.$attr.when&&f.attr(g.$attr.when),k=g.offset||0,l=e.$eval(m)||{},n={},r=c.startSymbol(),p=c.endSymbol(),s=/^when(Minus)?(.+)$/;q(g,function(a,c){s.test(c)&&(l[w(c.replace("when","").replace("Minus","-"))]=f.attr(g.$attr[c]))});
q(l,function(a,e){n[e]=c(a.replace(d,r+h+"-"+k+p))});e.$watch(function(){var c=parseFloat(e.$eval(h));if(isNaN(c))return"";c in l||(c=a.pluralCat(c-k));return n[c](e,f,!0)},function(a){f.text(a)})}}}],pe=["$parse","$animate",function(a,c){var d=L("ngRepeat");return{transclude:"element",priority:1E3,terminal:!0,$$tlb:!0,compile:function(e,f,g){return function(e,f,k){var l=k.ngRepeat,n=l.match(/^\s*(.+)\s+in\s+(.*?)\s*(\s+track\s+by\s+(.+)\s*)?$/),r,p,s,t,z,A,x,G={$id:Ca};if(!n)throw d("iexp",l);k=
n[1];z=n[2];(n=n[4])?(r=a(n),p=function(a,c,d){x&&(G[x]=a);G[A]=c;G.$index=d;return r(e,G)}):(s=function(a,c){return Ca(c)},t=function(a){return a});n=k.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);if(!n)throw d("iidexp",k);A=n[3]||n[1];x=n[2];var v={};e.$watchCollection(z,function(a){var k,n,r=f[0],z,M={},G,N,w,I,D,u,J=[];if(pb(a))D=a,z=p||s;else{z=p||t;D=[];for(w in a)a.hasOwnProperty(w)&&"$"!=w.charAt(0)&&D.push(w);D.sort()}G=D.length;n=J.length=D.length;for(k=0;k<n;k++)if(w=a===D?k:
D[k],I=a[w],I=z(w,I,k),na(I,"`track by` id"),v.hasOwnProperty(I))u=v[I],delete v[I],M[I]=u,J[k]=u;else{if(M.hasOwnProperty(I))throw q(J,function(a){a&&a.startNode&&(v[a.id]=a)}),d("dupes",l,I);J[k]={id:I};M[I]=!1}for(w in v)v.hasOwnProperty(w)&&(u=v[w],k=vb(u),c.leave(k),q(k,function(a){a.$$NG_REMOVED=!0}),u.scope.$destroy());k=0;for(n=D.length;k<n;k++){w=a===D?k:D[k];I=a[w];u=J[k];J[k-1]&&(r=J[k-1].endNode);if(u.startNode){N=u.scope;z=r;do z=z.nextSibling;while(z&&z.$$NG_REMOVED);u.startNode!=z&&
c.move(vb(u),null,y(r));r=u.endNode}else N=e.$new();N[A]=I;x&&(N[x]=w);N.$index=k;N.$first=0===k;N.$last=k===G-1;N.$middle=!(N.$first||N.$last);N.$odd=!(N.$even=0===(k&1));u.startNode||g(N,function(a){a[a.length++]=O.createComment(" end ngRepeat: "+l+" ");c.enter(a,null,y(r));r=a;u.scope=N;u.startNode=r&&r.endNode?r.endNode:a[0];u.endNode=a[a.length-1];M[u.id]=u})}v=M})}}}}],qe=["$animate",function(a){return function(c,d,e){c.$watch(e.ngShow,function(c){a[Na(c)?"removeClass":"addClass"](d,"ng-hide")})}}],
re=["$animate",function(a){return function(c,d,e){c.$watch(e.ngHide,function(c){a[Na(c)?"addClass":"removeClass"](d,"ng-hide")})}}],se=sa(function(a,c,d){a.$watch(d.ngStyle,function(a,d){d&&a!==d&&q(d,function(a,d){c.css(d,"")});a&&c.css(a)},!0)}),te=["$animate",function(a){return{restrict:"EA",require:"ngSwitch",controller:["$scope",function(){this.cases={}}],link:function(c,d,e,f){var g,h,m=[];c.$watch(e.ngSwitch||e.on,function(d){for(var l=0,n=m.length;l<n;l++)m[l].$destroy(),a.leave(h[l]);h=[];
m=[];if(g=f.cases["!"+d]||f.cases["?"])c.$eval(e.change),q(g,function(d){var e=c.$new();m.push(e);d.transclude(e,function(c){var e=d.element;h.push(c);a.enter(c,e.parent(),e)})})})}}}],ue=sa({transclude:"element",priority:800,require:"^ngSwitch",compile:function(a,c,d){return function(a,f,g,h){h.cases["!"+c.ngSwitchWhen]=h.cases["!"+c.ngSwitchWhen]||[];h.cases["!"+c.ngSwitchWhen].push({transclude:d,element:f})}}}),ve=sa({transclude:"element",priority:800,require:"^ngSwitch",compile:function(a,c,d){return function(a,
c,g,h){h.cases["?"]=h.cases["?"]||[];h.cases["?"].push({transclude:d,element:c})}}}),we=sa({controller:["$element","$transclude",function(a,c){if(!c)throw L("ngTransclude")("orphan",ea(a));this.$transclude=c}],link:function(a,c,d,e){e.$transclude(function(a){c.html("");c.append(a)})}}),xe=["$templateCache",function(a){return{restrict:"E",terminal:!0,compile:function(c,d){"text/ng-template"==d.type&&a.put(d.id,c[0].text)}}}],ye=L("ngOptions"),ze=aa({terminal:!0}),Ae=["$compile","$parse",function(a,
c){var d=/^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+(.*?)(?:\s+track\s+by\s+(.*?))?$/,e={$setViewValue:t};return{restrict:"E",require:["select","?ngModel"],controller:["$element","$scope","$attrs",function(a,c,d){var m=this,k={},l=e,n;m.databound=d.ngModel;m.init=function(a,c,d){l=a;n=d};m.addOption=function(c){na(c,'"option value"');k[c]=!0;l.$viewValue==c&&(a.val(c),n.parent()&&n.remove())};m.removeOption=
function(a){this.hasOption(a)&&(delete k[a],l.$viewValue==a&&this.renderUnknownOption(a))};m.renderUnknownOption=function(c){c="? "+Ca(c)+" ?";n.val(c);a.prepend(n);a.val(c);n.prop("selected",!0)};m.hasOption=function(a){return k.hasOwnProperty(a)};c.$on("$destroy",function(){m.renderUnknownOption=t})}],link:function(e,g,h,m){function k(a,c,d,e){d.$render=function(){var a=d.$viewValue;e.hasOption(a)?(v.parent()&&v.remove(),c.val(a),""===a&&A.prop("selected",!0)):x(a)&&A?c.val(""):e.renderUnknownOption(a)};
c.on("change",function(){a.$apply(function(){v.parent()&&v.remove();d.$setViewValue(c.val())})})}function l(a,c,d){var e;d.$render=function(){var a=new Sa(d.$viewValue);q(c.find("option"),function(c){c.selected=z(a.get(c.value))})};a.$watch(function(){Aa(e,d.$viewValue)||(e=da(d.$viewValue),d.$render())});c.on("change",function(){a.$apply(function(){var a=[];q(c.find("option"),function(c){c.selected&&a.push(c.value)});d.$setViewValue(a)})})}function n(e,f,g){function h(){var a={"":[]},c=[""],d,k,
s,u,x;u=g.$modelValue;x=r(e)||[];var A=n?Nb(x):x,H,K,B;K={};s=!1;var E,L;if(t)if(v&&J(u))for(s=new Sa([]),B=0;B<u.length;B++)K[m]=u[B],s.put(v(e,K),u[B]);else s=new Sa(u);for(B=0;H=A.length,B<H;B++){k=B;if(n){k=A[B];if("$"===k.charAt(0))continue;K[n]=k}K[m]=x[k];d=p(e,K)||"";(k=a[d])||(k=a[d]=[],c.push(d));t?d=z(s.remove(v?v(e,K):q(e,K))):(v?(d={},d[m]=u,d=v(e,d)===v(e,K)):d=u===q(e,K),s=s||d);E=l(e,K);E=z(E)?E:"";k.push({id:v?v(e,K):n?A[B]:B,label:E,selected:d})}t||(w||null===u?a[""].unshift({id:"",
label:"",selected:!s}):s||a[""].unshift({id:"?",label:"",selected:!0}));K=0;for(A=c.length;K<A;K++){d=c[K];k=a[d];y.length<=K?(u={element:G.clone().attr("label",d),label:k.label},x=[u],y.push(x),f.append(u.element)):(x=y[K],u=x[0],u.label!=d&&u.element.attr("label",u.label=d));E=null;B=0;for(H=k.length;B<H;B++)s=k[B],(d=x[B+1])?(E=d.element,d.label!==s.label&&E.text(d.label=s.label),d.id!==s.id&&E.val(d.id=s.id),E[0].selected!==s.selected&&E.prop("selected",d.selected=s.selected)):(""===s.id&&w?L=
w:(L=D.clone()).val(s.id).attr("selected",s.selected).text(s.label),x.push({element:L,label:s.label,id:s.id,selected:s.selected}),E?E.after(L):u.element.append(L),E=L);for(B++;x.length>B;)x.pop().element.remove()}for(;y.length>K;)y.pop()[0].element.remove()}var k;if(!(k=u.match(d)))throw ye("iexp",u,ea(f));var l=c(k[2]||k[1]),m=k[4]||k[6],n=k[5],p=c(k[3]||""),q=c(k[2]?k[1]:m),r=c(k[7]),v=k[8]?c(k[8]):null,y=[[{element:f,label:""}]];w&&(a(w)(e),w.removeClass("ng-scope"),w.remove());f.html("");f.on("change",
function(){e.$apply(function(){var a,c=r(e)||[],d={},h,k,l,p,u,x,w;if(t)for(k=[],p=0,x=y.length;p<x;p++)for(a=y[p],l=1,u=a.length;l<u;l++){if((h=a[l].element)[0].selected){h=h.val();n&&(d[n]=h);if(v)for(w=0;w<c.length&&(d[m]=c[w],v(e,d)!=h);w++);else d[m]=c[h];k.push(q(e,d))}}else if(h=f.val(),"?"==h)k=s;else if(""===h)k=null;else if(v)for(w=0;w<c.length;w++){if(d[m]=c[w],v(e,d)==h){k=q(e,d);break}}else d[m]=c[h],n&&(d[n]=h),k=q(e,d);g.$setViewValue(k)})});g.$render=h;e.$watch(h)}if(m[1]){var r=m[0],
p=m[1],t=h.multiple,u=h.ngOptions,w=!1,A,D=y(O.createElement("option")),G=y(O.createElement("optgroup")),v=D.clone();m=0;for(var B=g.children(),E=B.length;m<E;m++)if(""===B[m].value){A=w=B.eq(m);break}r.init(p,w,v);if(t&&(h.required||h.ngRequired)){var L=function(a){p.$setValidity("required",!h.required||a&&a.length);return a};p.$parsers.push(L);p.$formatters.unshift(L);h.$observe("required",function(){L(p.$viewValue)})}u?n(e,g,p):t?l(e,g,p):k(e,g,p,r)}}}}],Be=["$interpolate",function(a){var c={addOption:t,
removeOption:t};return{restrict:"E",priority:100,compile:function(d,e){if(x(e.value)){var f=a(d.text(),!0);f||e.$set("value",d.text())}return function(a,d,e){var k=d.parent(),l=k.data("$selectController")||k.parent().data("$selectController");l&&l.databound?d.prop("selected",!1):l=c;f?a.$watch(f,function(a,c){e.$set("value",a);a!==c&&l.removeOption(c);l.addOption(a)}):l.addOption(e.value);d.on("$destroy",function(){l.removeOption(e.value)})}}}}],Ce=aa({restrict:"E",terminal:!0});(Ba=W.jQuery)?(y=
Ba,u(Ba.fn,{scope:Da.scope,isolateScope:Da.isolateScope,controller:Da.controller,injector:Da.injector,inheritedData:Da.inheritedData}),wb("remove",!0,!0,!1),wb("empty",!1,!1,!1),wb("html",!1,!1,!0)):y=Q;bb.element=y;(function(a){u(a,{bootstrap:Wb,copy:da,extend:u,equals:Aa,element:y,forEach:q,injector:Xb,noop:t,bind:rb,toJson:ma,fromJson:Sb,identity:za,isUndefined:x,isDefined:z,isString:D,isFunction:B,isObject:T,isNumber:qb,isElement:Kc,isArray:J,version:Md,isDate:Ja,lowercase:w,uppercase:Ga,callbacks:{counter:0},
$$minErr:L,$$csp:Rb});Ua=Qc(W);try{Ua("ngLocale")}catch(c){Ua("ngLocale",[]).provider("$locale",pd)}Ua("ng",["ngLocale"],["$provide",function(a){a.provider("$compile",ec).directive({a:Rd,input:Gc,textarea:Gc,form:Sd,script:xe,select:Ae,style:Ce,option:Be,ngBind:ce,ngBindHtml:ee,ngBindTemplate:de,ngClass:fe,ngClassEven:he,ngClassOdd:ge,ngCloak:ie,ngController:je,ngForm:Td,ngHide:re,ngIf:ke,ngInclude:le,ngInit:me,ngNonBindable:ne,ngPluralize:oe,ngRepeat:pe,ngShow:qe,ngStyle:se,ngSwitch:te,ngSwitchWhen:ue,
ngSwitchDefault:ve,ngOptions:ze,ngTransclude:we,ngModel:Yd,ngList:$d,ngChange:Zd,required:Hc,ngRequired:Hc,ngValue:be}).directive(Mb).directive(Ic);a.provider({$anchorScroll:Zc,$animate:Od,$browser:bd,$cacheFactory:cd,$controller:gd,$document:hd,$exceptionHandler:id,$filter:vc,$interpolate:nd,$interval:od,$http:jd,$httpBackend:kd,$location:rd,$log:sd,$parse:td,$rootScope:wd,$q:ud,$sce:zd,$sceDelegate:yd,$sniffer:Ad,$templateCache:dd,$timeout:Bd,$window:Cd})}])})(bb);y(O).ready(function(){Oc(O,Wb)})})(window,
document);!angular.$$csp()&&angular.element(document).find("head").prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide{display:none !important;}ng\\:form{display:block;}.ng-animate-start{clip:rect(0,auto,auto,0);-ms-zoom:1.0001;}.ng-animate-active{clip:rect(-1px,auto,auto,0);-ms-zoom:1;}</style>');
//# sourceMappingURL=angular.min.js.map
|
// Generated by CoffeeScript 1.4.0
(function() {
var Animation, Animations, Bezier, Dynamic, DynamicElement, Dynamics, EaseInOut, Gravity, GravityWithForce, Linear, Loop, Matrix, SelfSpring, Spring, Vector, animationFrame, animationStart, browserSupportPrefixFor, browserSupportTransform, browserSupportWithPrefix, cacheFn, combineVector, convertToMatrix3d, css, decomposeMatrix, defaultForProperty, degProperties, getFirstFrame, hasCommonProperties, interpolateMatrix, keysForTransform, lengthVector, matrixToString, normalizeVector, parseFrames, propertiesAtFrame, pxProperties, recomposeMatrix, set, stopAnimationsForEl, transformProperties, transformStringToMatrixString, unitFor,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__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; };
Vector = (function() {
function Vector(els) {
this.els = els;
this.cross = __bind(this.cross, this);
this.dot = __bind(this.dot, this);
this.e = __bind(this.e, this);
}
Vector.prototype.e = function(i) {
if (i < 1 || i > this.els.length) {
return null;
} else {
return this.els[i - 1];
}
};
Vector.prototype.dot = function(vector) {
var V, n, product;
V = vector.els || vector;
product = 0;
n = this.els.length;
if (n !== V.length) {
return null;
}
n += 1;
while (--n) {
product += this.els[n - 1] * V[n - 1];
}
return product;
};
Vector.prototype.cross = function(vector) {
var A, B;
B = vector.els || vector;
if (this.els.length !== 3 || B.length !== 3) {
return null;
}
A = this.els;
return new Vector([(A[1] * B[2]) - (A[2] * B[1]), (A[2] * B[0]) - (A[0] * B[2]), (A[0] * B[1]) - (A[1] * B[0])]);
};
return Vector;
})();
Matrix = (function() {
function Matrix(els) {
this.els = els;
this.inverse = __bind(this.inverse, this);
this.augment = __bind(this.augment, this);
this.toRightTriangular = __bind(this.toRightTriangular, this);
this.transpose = __bind(this.transpose, this);
this.multiply = __bind(this.multiply, this);
this.dup = __bind(this.dup, this);
this.e = __bind(this.e, this);
}
Matrix.prototype.e = function(i, j) {
if (i < 1 || i > this.els.length || j < 1 || j > this.els[0].length) {
return null;
}
return this.els[i - 1][j - 1];
};
Matrix.prototype.dup = function() {
return new Matrix(this.els);
};
Matrix.prototype.multiply = function(matrix) {
var M, c, cols, elements, i, j, ki, kj, nc, ni, nj, returnVector, sum;
returnVector = matrix.modulus ? true : false;
M = matrix.els || matrix;
if (typeof M[0][0] === 'undefined') {
M = new Matrix(M).els;
}
ni = this.els.length;
ki = ni;
kj = M[0].length;
cols = this.els[0].length;
elements = [];
ni += 1;
while (--ni) {
i = ki - ni;
elements[i] = [];
nj = kj;
nj += 1;
while (--nj) {
j = kj - nj;
sum = 0;
nc = cols;
nc += 1;
while (--nc) {
c = cols - nc;
sum += this.els[i][c] * M[c][j];
}
elements[i][j] = sum;
}
}
M = new Matrix(elements);
if (returnVector) {
return M.col(1);
} else {
return M;
}
};
Matrix.prototype.transpose = function() {
var cols, elements, i, j, ni, nj, rows;
rows = this.els.length;
cols = this.els[0].length;
elements = [];
ni = cols;
ni += 1;
while (--ni) {
i = cols - ni;
elements[i] = [];
nj = rows;
nj += 1;
while (--nj) {
j = rows - nj;
elements[i][j] = this.els[j][i];
}
}
return new Matrix(elements);
};
Matrix.prototype.toRightTriangular = function() {
var M, els, i, j, k, kp, multiplier, n, np, p, _i, _j, _ref, _ref1;
M = this.dup();
n = this.els.length;
k = n;
kp = this.els[0].length;
while (--n) {
i = k - n;
if (M.els[i][i] === 0) {
for (j = _i = _ref = i + 1; _ref <= k ? _i < k : _i > k; j = _ref <= k ? ++_i : --_i) {
if (M.els[j][i] !== 0) {
els = [];
np = kp;
np += 1;
while (--np) {
p = kp - np;
els.push(M.els[i][p] + M.els[j][p]);
}
M.els[i] = els;
break;
}
}
}
if (M.els[i][i] !== 0) {
for (j = _j = _ref1 = i + 1; _ref1 <= k ? _j < k : _j > k; j = _ref1 <= k ? ++_j : --_j) {
multiplier = M.els[j][i] / M.els[i][i];
els = [];
np = kp;
np += 1;
while (--np) {
p = kp - np;
els.push(p <= i ? 0 : M.els[j][p] - M.els[i][p] * multiplier);
}
M.els[j] = els;
}
}
}
return M;
};
Matrix.prototype.augment = function(matrix) {
var M, T, cols, i, j, ki, kj, ni, nj;
M = matrix.els || matrix;
if (typeof M[0][0] === 'undefined') {
M = new Matrix(M).els;
}
T = this.dup();
cols = T.els[0].length;
ni = T.els.length;
ki = ni;
kj = M[0].length;
if (ni !== M.length) {
return null;
}
ni += 1;
while (--ni) {
i = ki - ni;
nj = kj;
nj += 1;
while (--nj) {
j = kj - nj;
T.els[i][cols + j] = M[i][j];
}
}
return T;
};
Matrix.prototype.inverse = function() {
var M, divisor, els, i, inverse_elements, j, ki, kp, new_element, np, p, vni, _i;
vni = this.els.length;
ki = ni;
M = this.augment(Matrix.I(ni)).toRightTriangular();
kp = M.els[0].length;
inverse_elements = [];
ni += 1;
while (--ni) {
i = ni - 1;
els = [];
np = kp;
inverse_elements[i] = [];
divisor = M.els[i][i];
np += 1;
while (--np) {
p = kp - np;
new_element = M.els[i][p] / divisor;
els.push(new_element);
if (p >= ki) {
inverse_elements[i].push(new_element);
}
}
M.els[i] = els;
for (j = _i = 0; 0 <= i ? _i < i : _i > i; j = 0 <= i ? ++_i : --_i) {
els = [];
np = kp;
np += 1;
while (--np) {
p = kp - np;
els.push(M.els[j][p] - M.els[i][p] * M.els[j][i]);
}
M.els[j] = els;
}
}
return new Matrix(inverse_elements);
};
Matrix.I = function(n) {
var els, i, j, k, nj;
els = [];
k = n;
n += 1;
while (--n) {
i = k - n;
els[i] = [];
nj = k;
nj += 1;
while (--nj) {
j = k - nj;
els[i][j] = i === j ? 1 : 0;
}
}
return new Matrix(els);
};
return Matrix;
})();
Dynamic = (function() {
Dynamic.properties = {};
function Dynamic(options) {
var k, v, _ref;
this.options = options != null ? options : {};
this.next = __bind(this.next, this);
this.init = __bind(this.init, this);
_ref = this.options.type.properties;
for (k in _ref) {
v = _ref[k];
if (!(this.options[k] != null) && !v.editable) {
this.options[k] = v["default"];
}
}
}
Dynamic.prototype.init = function() {
return this.t = 0;
};
Dynamic.prototype.next = function(step) {
var r;
if (this.t > 1) {
this.t = 1;
}
r = this.at(this.t);
this.t += step;
return r;
};
Dynamic.prototype.at = function(t) {
return [t, t];
};
return Dynamic;
})();
Linear = (function(_super) {
__extends(Linear, _super);
function Linear() {
return Linear.__super__.constructor.apply(this, arguments);
}
Linear.properties = {
duration: {
min: 100,
max: 4000,
"default": 1000
}
};
Linear.prototype.at = function(t) {
return [t, t];
};
return Linear;
})(Dynamic);
Gravity = (function(_super) {
__extends(Gravity, _super);
Gravity.properties = {
bounce: {
min: 0,
max: 80,
"default": 40
},
gravity: {
min: 1,
max: 4000,
"default": 1000
},
expectedDuration: {
editable: false
}
};
function Gravity(options) {
var _ref;
this.options = options != null ? options : {};
this.at = __bind(this.at, this);
this.curve = __bind(this.curve, this);
this.init = __bind(this.init, this);
this.length = __bind(this.length, this);
this.gravityValue = __bind(this.gravityValue, this);
this.bounceValue = __bind(this.bounceValue, this);
this.duration = __bind(this.duration, this);
this.expectedDuration = __bind(this.expectedDuration, this);
if ((_ref = this.initialForce) == null) {
this.initialForce = false;
}
this.options.duration = this.duration();
Gravity.__super__.constructor.call(this, this.options);
}
Gravity.prototype.expectedDuration = function() {
return this.duration();
};
Gravity.prototype.duration = function() {
return Math.round(1000 * 1000 / this.options.gravity * this.length());
};
Gravity.prototype.bounceValue = function() {
return Math.min(this.options.bounce / 100, 80);
};
Gravity.prototype.gravityValue = function() {
return this.options.gravity / 100;
};
Gravity.prototype.length = function() {
var L, b, bounce, curve, gravity;
bounce = this.bounceValue();
gravity = this.gravityValue();
b = Math.sqrt(2 / gravity);
curve = {
a: -b,
b: b,
H: 1
};
if (this.initialForce) {
curve.a = 0;
curve.b = curve.b * 2;
}
while (curve.H > 0.001) {
L = curve.b - curve.a;
curve = {
a: curve.b,
b: curve.b + L * bounce,
H: curve.H * bounce * bounce
};
}
return curve.b;
};
Gravity.prototype.init = function() {
var L, b, bounce, curve, gravity, _results;
Gravity.__super__.init.apply(this, arguments);
L = this.length();
gravity = this.gravityValue() * L * L;
bounce = this.bounceValue();
b = Math.sqrt(2 / gravity);
this.curves = [];
curve = {
a: -b,
b: b,
H: 1
};
if (this.initialForce) {
curve.a = 0;
curve.b = curve.b * 2;
}
this.curves.push(curve);
_results = [];
while (curve.b < 1 && curve.H > 0.001) {
L = curve.b - curve.a;
curve = {
a: curve.b,
b: curve.b + L * bounce,
H: curve.H * bounce * bounce
};
_results.push(this.curves.push(curve));
}
return _results;
};
Gravity.prototype.curve = function(a, b, H, t) {
var L, c, t2;
L = b - a;
t2 = (2 / L) * t - 1 - (a * 2 / L);
c = t2 * t2 * H - H + 1;
if (this.initialForce) {
c = 1 - c;
}
return c;
};
Gravity.prototype.at = function(t) {
var bounce, curve, gravity, i, v;
bounce = this.options.bounce / 100;
gravity = this.options.gravity;
i = 0;
curve = this.curves[i];
while (!(t >= curve.a && t <= curve.b)) {
i += 1;
curve = this.curves[i];
if (!curve) {
break;
}
}
if (!curve) {
v = this.initialForce ? 0 : 1;
} else {
v = this.curve(curve.a, curve.b, curve.H, t);
}
return [t, v];
};
return Gravity;
})(Dynamic);
GravityWithForce = (function(_super) {
__extends(GravityWithForce, _super);
GravityWithForce.prototype.returnsToSelf = true;
function GravityWithForce(options) {
this.options = options != null ? options : {};
this.initialForce = true;
GravityWithForce.__super__.constructor.call(this, this.options);
}
return GravityWithForce;
})(Gravity);
Spring = (function(_super) {
__extends(Spring, _super);
function Spring() {
this.at = __bind(this.at, this);
return Spring.__super__.constructor.apply(this, arguments);
}
Spring.properties = {
frequency: {
min: 0,
max: 100,
"default": 15
},
friction: {
min: 1,
max: 1000,
"default": 200
},
anticipationStrength: {
min: 0,
max: 1000,
"default": 0
},
anticipationSize: {
min: 0,
max: 99,
"default": 0
},
duration: {
min: 100,
max: 4000,
"default": 1000
}
};
Spring.prototype.at = function(t) {
var A, At, a, angle, b, decal, frequency, friction, frictionT, s, v, y0, yS,
_this = this;
frequency = Math.max(1, this.options.frequency);
friction = Math.pow(20, this.options.friction / 100);
s = this.options.anticipationSize / 100;
decal = Math.max(0, s);
frictionT = (t / (1 - s)) - (s / (1 - s));
if (t < s) {
A = function(t) {
var M, a, b, x0, x1;
M = 0.8;
x0 = s / (1 - s);
x1 = 0;
b = (x0 - (M * x1)) / (x0 - x1);
a = (M - b) / x0;
return (a * t * _this.options.anticipationStrength / 100) + b;
};
yS = (s / (1 - s)) - (s / (1 - s));
y0 = (0 / (1 - s)) - (s / (1 - s));
b = Math.acos(1 / A(yS));
a = (Math.acos(1 / A(y0)) - b) / (frequency * (-s));
} else {
A = function(t) {
return Math.pow(friction / 10, -t) * (1 - t);
};
b = 0;
a = 1;
}
At = A(frictionT);
angle = frequency * (t - s) * a + b;
v = 1 - (At * Math.cos(angle));
return [t, v, At, frictionT, angle];
};
return Spring;
})(Dynamic);
SelfSpring = (function(_super) {
__extends(SelfSpring, _super);
function SelfSpring() {
this.at = __bind(this.at, this);
return SelfSpring.__super__.constructor.apply(this, arguments);
}
SelfSpring.properties = {
frequency: {
min: 0,
max: 100,
"default": 15
},
friction: {
min: 1,
max: 1000,
"default": 200
},
duration: {
min: 100,
max: 4000,
"default": 1000
}
};
SelfSpring.prototype.returnsToSelf = true;
SelfSpring.prototype.at = function(t) {
var A, At, At2, Ax, angle, frequency, friction, v,
_this = this;
frequency = Math.max(1, this.options.frequency);
friction = Math.pow(20, this.options.friction / 100);
A = function(t) {
return 1 - Math.pow(friction / 10, -t) * (1 - t);
};
At = A(t);
At2 = A(1 - t);
Ax = (Math.cos(t * 2 * 3.14 - 3.14) / 2) + 0.5;
Ax = Math.pow(Ax, this.options.friction / 100);
angle = frequency * t;
v = Math.cos(angle) * Ax;
return [t, v, Ax, -Ax];
};
return SelfSpring;
})(Dynamic);
Bezier = (function(_super) {
__extends(Bezier, _super);
Bezier.properties = {
points: {
type: 'points',
"default": [
{
x: 0,
y: 0,
controlPoints: [
{
x: 0.2,
y: 0
}
]
}, {
x: 0.5,
y: 1.2,
controlPoints: [
{
x: 0.3,
y: 1.2
}, {
x: 0.8,
y: 1.2
}
]
}, {
x: 1,
y: 1,
controlPoints: [
{
x: 0.8,
y: 1
}
]
}
]
},
duration: {
min: 100,
max: 4000,
"default": 1000
}
};
function Bezier(options) {
this.options = options != null ? options : {};
this.at = __bind(this.at, this);
this.yForX = __bind(this.yForX, this);
this.B = __bind(this.B, this);
this.returnsToSelf = this.options.points[this.options.points.length - 1].y === 0;
Bezier.__super__.constructor.call(this, this.options);
}
Bezier.prototype.B_ = function(t, p0, p1, p2, p3) {
return (Math.pow(1 - t, 3) * p0) + (3 * Math.pow(1 - t, 2) * t * p1) + (3 * (1 - t) * Math.pow(t, 2) * p2) + Math.pow(t, 3) * p3;
};
Bezier.prototype.B = function(t, p0, p1, p2, p3) {
return {
x: this.B_(t, p0.x, p1.x, p2.x, p3.x),
y: this.B_(t, p0.y, p1.y, p2.y, p3.y)
};
};
Bezier.prototype.yForX = function(xTarget, Bs) {
var B, aB, i, lower, percent, upper, x, xTolerance, _i, _len;
B = null;
for (_i = 0, _len = Bs.length; _i < _len; _i++) {
aB = Bs[_i];
if (xTarget >= aB(0).x && xTarget <= aB(1).x) {
B = aB;
}
if (B !== null) {
break;
}
}
if (!B) {
if (this.returnsToSelf) {
return 0;
} else {
return 1;
}
}
xTolerance = 0.0001;
lower = 0;
upper = 1;
percent = (upper + lower) / 2;
x = B(percent).x;
i = 0;
while (Math.abs(xTarget - x) > xTolerance && i < 100) {
if (xTarget > x) {
lower = percent;
} else {
upper = percent;
}
percent = (upper + lower) / 2;
x = B(percent).x;
i += 1;
}
return B(percent).y;
};
Bezier.prototype.at = function(t) {
var Bs, i, k, points, x, y, _fn,
_this = this;
x = t;
points = this.options.points || Bezier.properties.points["default"];
Bs = [];
_fn = function(pointA, pointB) {
var B;
B = function(t) {
return _this.B(t, pointA, pointA.controlPoints[pointA.controlPoints.length - 1], pointB.controlPoints[0], pointB);
};
return Bs.push(B);
};
for (i in points) {
k = parseInt(i);
if (k >= points.length - 1) {
break;
}
_fn(points[k], points[k + 1]);
}
y = this.yForX(x, Bs);
return [x, y];
};
return Bezier;
})(Dynamic);
EaseInOut = (function(_super) {
__extends(EaseInOut, _super);
EaseInOut.properties = {
friction: {
min: 1,
max: 1000,
"default": 500
},
duration: {
min: 100,
max: 4000,
"default": 1000
}
};
function EaseInOut(options) {
var friction, points;
this.options = options != null ? options : {};
this.at = __bind(this.at, this);
EaseInOut.__super__.constructor.apply(this, arguments);
friction = this.options.friction || EaseInOut.properties.friction["default"];
points = [
{
x: 0,
y: 0,
controlPoints: [
{
x: 1 - (friction / 1000),
y: 0
}
]
}, {
x: 1,
y: 1,
controlPoints: [
{
x: friction / 1000,
y: 1
}
]
}
];
this.bezier = new Bezier({
type: Bezier,
duration: this.options.duration,
points: points
});
}
EaseInOut.prototype.at = function(t) {
return this.bezier.at(t);
};
return EaseInOut;
})(Dynamic);
cacheFn = function(func) {
var cachedMethod, data;
data = {};
cachedMethod = function() {
var k, key, result, _i, _len;
key = "";
for (_i = 0, _len = arguments.length; _i < _len; _i++) {
k = arguments[_i];
key += k.toString() + ",";
}
result = data[key];
if (!result) {
data[key] = result = func.apply(this, arguments);
}
return result;
};
return cachedMethod;
};
browserSupportTransform = function() {
return browserSupportWithPrefix("transform");
};
browserSupportPrefixFor = cacheFn(function(property) {
var k, prefix, prop, propArray, propertyName, _i, _j, _len, _len1, _ref;
propArray = property.split('-');
propertyName = "";
for (_i = 0, _len = propArray.length; _i < _len; _i++) {
prop = propArray[_i];
propertyName += prop.substring(0, 1).toUpperCase() + prop.substring(1);
}
_ref = ["Webkit", "Moz"];
for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
prefix = _ref[_j];
k = prefix + propertyName;
if (document.body.style[k] !== void 0) {
return prefix;
}
}
return '';
});
browserSupportWithPrefix = cacheFn(function(property) {
var prefix;
prefix = browserSupportPrefixFor(property);
if (prefix === 'Moz') {
return "" + prefix + (property.substring(0, 1).toUpperCase() + property.substring(1));
}
if (prefix !== '') {
return "-" + (prefix.toLowerCase()) + "-" + property;
}
return property;
});
lengthVector = function(vector) {
var a, e, _i, _len, _ref;
a = 0;
_ref = vector.els;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
e = _ref[_i];
a += Math.pow(e, 2);
}
return Math.sqrt(a);
};
normalizeVector = function(vector) {
var e, i, length, newElements, _ref;
length = lengthVector(vector);
newElements = [];
_ref = vector.els;
for (i in _ref) {
e = _ref[i];
newElements[i] = e / length;
}
return new Vector(newElements);
};
combineVector = function(a, b, ascl, bscl) {
var i, result, _i;
result = [];
for (i = _i = 0; _i <= 2; i = ++_i) {
result[i] = (ascl * a.els[i]) + (bscl * b.els[i]);
}
return new Vector(result);
};
decomposeMatrix = function(matrix) {
var els, i, inversePerspectiveMatrix, j, k, pdum3, perspective, perspectiveMatrix, quaternion, result, rightHandSide, rotate, row, rowElement, s, scale, skew, t, translate, transposedInversePerspectiveMatrix, type, typeKey, v, w, x, y, z, _i, _j, _k, _l, _m, _n, _o, _p;
translate = [];
scale = [];
skew = [];
quaternion = [];
perspective = [];
els = matrix.els;
if (els[3][3] === 0) {
return false;
}
for (i = _i = 0; _i <= 3; i = ++_i) {
for (j = _j = 0; _j <= 3; j = ++_j) {
els[i][j] /= els[3][3];
}
}
perspectiveMatrix = matrix.dup();
for (i = _k = 0; _k <= 2; i = ++_k) {
perspectiveMatrix.els[i][3] = 0;
}
perspectiveMatrix.els[3][3] = 1;
if (els[0][3] !== 0 || els[1][3] !== 0 || els[2][3] !== 0) {
rightHandSide = new Vector(els.slice(0, 4)[3]);
inversePerspectiveMatrix = perspectiveMatrix.inverse();
transposedInversePerspectiveMatrix = inversePerspectiveMatrix.transpose();
perspective = transposedInversePerspectiveMatrix.multiply(rightHandSide).els;
for (i = _l = 0; _l <= 2; i = ++_l) {
els[i][3] = 0;
}
els[3][3] = 1;
} else {
perspective = [0, 0, 0, 1];
}
for (i = _m = 0; _m <= 2; i = ++_m) {
translate[i] = els[3][i];
els[3][i] = 0;
}
row = [];
for (i = _n = 0; _n <= 2; i = ++_n) {
row[i] = new Vector(els[i].slice(0, 3));
}
scale[0] = lengthVector(row[0]);
row[0] = normalizeVector(row[0]);
skew[0] = row[0].dot(row[1]);
row[1] = combineVector(row[1], row[0], 1.0, -skew[0]);
scale[1] = lengthVector(row[1]);
row[1] = normalizeVector(row[1]);
skew[0] /= scale[1];
skew[1] = row[0].dot(row[2]);
row[2] = combineVector(row[2], row[0], 1.0, -skew[1]);
skew[2] = row[1].dot(row[2]);
row[2] = combineVector(row[2], row[1], 1.0, -skew[2]);
scale[2] = lengthVector(row[2]);
row[2] = normalizeVector(row[2]);
skew[1] /= scale[2];
skew[2] /= scale[2];
pdum3 = row[1].cross(row[2]);
if (row[0].dot(pdum3) < 0) {
for (i = _o = 0; _o <= 2; i = ++_o) {
scale[i] *= -1;
for (j = _p = 0; _p <= 2; j = ++_p) {
row[i].els[j] *= -1;
}
}
}
rowElement = function(index, elementIndex) {
return row[index].els[elementIndex];
};
rotate = [];
rotate[1] = Math.asin(-rowElement(0, 2));
if (Math.cos(rotate[1]) !== 0) {
rotate[0] = Math.atan2(rowElement(1, 2), rowElement(2, 2));
rotate[2] = Math.atan2(rowElement(0, 1), rowElement(0, 0));
} else {
rotate[0] = Math.atan2(-rowElement(2, 0), rowElement(1, 1));
rotate[1] = 0;
}
t = rowElement(0, 0) + rowElement(1, 1) + rowElement(2, 2) + 1.0;
if (t > 1e-4) {
s = 0.5 / Math.sqrt(t);
w = 0.25 / s;
x = (rowElement(2, 1) - rowElement(1, 2)) * s;
y = (rowElement(0, 2) - rowElement(2, 0)) * s;
z = (rowElement(1, 0) - rowElement(0, 1)) * s;
} else if ((rowElement(0, 0) > rowElement(1, 1)) && (rowElement(0, 0) > rowElement(2, 2))) {
s = Math.sqrt(1.0 + rowElement(0, 0) - rowElement(1, 1) - rowElement(2, 2)) * 2.0;
x = 0.25 * s;
y = (rowElement(0, 1) + rowElement(1, 0)) / s;
z = (rowElement(0, 2) + rowElement(2, 0)) / s;
w = (rowElement(2, 1) - rowElement(1, 2)) / s;
} else if (rowElement(1, 1) > rowElement(2, 2)) {
s = Math.sqrt(1.0 + rowElement(1, 1) - rowElement(0, 0) - rowElement(2, 2)) * 2.0;
x = (rowElement(0, 1) + rowElement(1, 0)) / s;
y = 0.25 * s;
z = (rowElement(1, 2) + rowElement(2, 1)) / s;
w = (rowElement(0, 2) - rowElement(2, 0)) / s;
} else {
s = Math.sqrt(1.0 + rowElement(2, 2) - rowElement(0, 0) - rowElement(1, 1)) * 2.0;
x = (rowElement(0, 2) + rowElement(2, 0)) / s;
y = (rowElement(1, 2) + rowElement(2, 1)) / s;
z = 0.25 * s;
w = (rowElement(1, 0) - rowElement(0, 1)) / s;
}
quaternion = [x, y, z, w];
result = {
translate: translate,
scale: scale,
skew: skew,
quaternion: quaternion,
perspective: perspective,
rotate: rotate
};
for (typeKey in result) {
type = result[typeKey];
for (k in type) {
v = type[k];
if (isNaN(v)) {
type[k] = 0;
}
}
}
return result;
};
interpolateMatrix = function(decomposedA, decomposedB, t, only) {
var angle, decomposed, i, invscale, invth, k, qa, qb, scale, th, _i, _j, _k, _l, _len, _ref, _ref1;
if (only == null) {
only = [];
}
decomposed = {};
_ref = ['translate', 'scale', 'skew', 'perspective'];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
k = _ref[_i];
decomposed[k] = [];
for (i = _j = 0, _ref1 = decomposedA[k].length - 1; 0 <= _ref1 ? _j <= _ref1 : _j >= _ref1; i = 0 <= _ref1 ? ++_j : --_j) {
if (only.indexOf(k) > -1 || only.indexOf("" + k + ['x', 'y', 'z'][i]) > -1) {
decomposed[k][i] = (decomposedB[k][i] - decomposedA[k][i]) * t + decomposedA[k][i];
} else {
decomposed[k][i] = decomposedA[k][i];
}
}
}
if (only.indexOf('rotate') !== -1) {
qa = decomposedA.quaternion;
qb = decomposedB.quaternion;
angle = qa[0] * qb[0] + qa[1] * qb[1] + qa[2] * qb[2] + qa[3] * qb[3];
if (angle < 0.0) {
for (i = _k = 0; _k <= 3; i = ++_k) {
qa[i] = -qa[i];
}
angle = -angle;
}
if (angle + 1.0 > .05) {
if (1.0 - angle >= .05) {
th = Math.acos(angle);
invth = 1.0 / Math.sin(th);
scale = Math.sin(th * (1.0 - t)) * invth;
invscale = Math.sin(th * t) * invth;
} else {
scale = 1.0 - t;
invscale = t;
}
} else {
qb[0] = -qa[1];
qb[1] = qa[0];
qb[2] = -qa[3];
qb[3] = qa[2];
scale = Math.sin(piDouble * (.5 - t));
invscale = Math.sin(piDouble * t);
}
decomposed.quaternion = [];
for (i = _l = 0; _l <= 3; i = ++_l) {
decomposed.quaternion[i] = qa[i] * scale + qb[i] * invscale;
}
} else {
decomposed.quaternion = decomposedA.quaternion;
}
return decomposed;
};
recomposeMatrix = function(decomposedMatrix) {
var i, j, match, matrix, quaternion, skew, temp, w, x, y, z, _i, _j, _k, _l;
matrix = Matrix.I(4);
for (i = _i = 0; _i <= 3; i = ++_i) {
matrix.els[i][3] = decomposedMatrix.perspective[i];
}
quaternion = decomposedMatrix.quaternion;
x = quaternion[0];
y = quaternion[1];
z = quaternion[2];
w = quaternion[3];
skew = decomposedMatrix.skew;
match = [[1, 0], [2, 0], [2, 1]];
for (i = _j = 2; _j >= 0; i = --_j) {
if (skew[i]) {
temp = Matrix.I(4);
temp.els[match[i][0]][match[i][1]] = skew[i];
matrix = matrix.multiply(temp);
}
}
matrix = matrix.multiply(new Matrix([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w), 0], [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w), 0], [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y), 0], [0, 0, 0, 1]]));
for (i = _k = 0; _k <= 2; i = ++_k) {
for (j = _l = 0; _l <= 2; j = ++_l) {
matrix.els[i][j] *= decomposedMatrix.scale[i];
}
matrix.els[3][i] = decomposedMatrix.translate[i];
}
return matrix;
};
matrixToString = function(matrix) {
var i, j, str, _i, _j;
str = 'matrix3d(';
for (i = _i = 0; _i <= 3; i = ++_i) {
for (j = _j = 0; _j <= 3; j = ++_j) {
str += matrix.els[i][j];
if (!(i === 3 && j === 3)) {
str += ',';
}
}
}
str += ')';
return str;
};
transformStringToMatrixString = cacheFn(function(transform) {
var matrixEl, result, style;
matrixEl = document.createElement('div');
matrixEl.style[browserSupportTransform()] = transform;
document.body.appendChild(matrixEl);
style = window.getComputedStyle(matrixEl, null);
result = style.transform || style[browserSupportTransform()];
document.body.removeChild(matrixEl);
return result;
});
convertToMatrix3d = function(transform) {
var digits, elements, i, match, matrixElements, _i;
match = transform.match(/matrix3?d?\(([-0-9, \.]*)\)/);
if (match) {
digits = match[1].split(',');
digits = digits.map(parseFloat);
if (digits.length === 6) {
elements = [digits[0], digits[1], 0, 0, digits[2], digits[3], 0, 0, 0, 0, 1, 0, digits[4], digits[5], 0, 1];
} else {
elements = digits;
}
} else {
elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
}
matrixElements = [];
for (i = _i = 0; _i <= 3; i = ++_i) {
matrixElements.push(elements.slice(i * 4, i * 4 + 4));
}
return new Matrix(matrixElements);
};
getFirstFrame = function(properties) {
var frame, k, style, v;
frame = {};
style = window.getComputedStyle(this.el, null);
for (k in properties) {
if (transformProperties.contains(k)) {
k = 'transform';
}
if (!frame[k]) {
v = this.el.style[browserSupportWithPrefix(k)];
if (v == null) {
v = style[browserSupportWithPrefix(k)];
}
frame[k] = v;
}
}
return frame;
};
parseFrames = function(frames) {
var k, match, newFrames, newProperties, percent, properties, transform, transforms, unit, v, vString, value;
newFrames = {};
for (percent in frames) {
properties = frames[percent];
transforms = [];
newProperties = {};
for (k in properties) {
v = properties[k];
if (k === 'transform') {
transforms.push(v);
} else if (transformProperties.contains(k)) {
v = "" + k + "(" + v + (unitFor(k, v)) + ")";
transforms.push(v);
} else {
vString = v + "";
match = vString.match(/([-0-9.]*)(.*)/);
value = parseFloat(match[1]);
unit = match[2];
newProperties[k] = {
value: value,
originalValue: v,
unit: unit
};
}
}
if (transforms.length > 0) {
transform = transforms.join(' ');
newProperties['transform'] = {
value: decomposeMatrix(convertToMatrix3d(transformStringToMatrixString(transform))),
originalValue: transform,
unit: ''
};
}
newFrames[percent] = newProperties;
}
return newFrames;
};
defaultForProperty = function(property) {
if (property === 'opacity') {
return 1;
}
return 0;
};
animationFrame = function(ts) {
var at, dTs, properties, t, _base;
if (this.stopped) {
Loop.remove(this);
return {};
}
t = 0;
if (this.ts) {
dTs = ts - this.ts;
t = dTs / this.options.duration;
} else {
this.ts = ts;
}
at = this.dynamic().at(t);
properties = propertiesAtFrame.call(this, at[1], {
progress: t
});
if (t >= 1) {
Loop.remove(this);
this.animating = false;
this.dynamic().init();
if (typeof (_base = this.options).complete === "function") {
_base.complete(this);
}
}
return properties;
};
propertiesAtFrame = function(t, args) {
var dValue, frame0, frame1, k, newValue, oldValue, progress, properties, transform, unit, v, value;
if (args == null) {
args = {};
}
frame0 = this.frames[0];
frame1 = this.frames[100];
progress = args.progress;
if (progress == null) {
progress = -1;
}
transform = '';
properties = {};
for (k in frame1) {
v = frame1[k];
value = v.value;
unit = v.unit;
newValue = null;
if (progress >= 1) {
if (this.returnsToSelf) {
newValue = frame0[k].value;
} else {
newValue = frame1[k].value;
}
}
if (k === 'transform') {
if (newValue == null) {
newValue = interpolateMatrix(frame0[k].value, frame1[k].value, t, this.keysToInterpolate);
}
properties['transform'] = recomposeMatrix(newValue);
} else {
if (!newValue) {
oldValue = null;
if (frame0[k]) {
oldValue = frame0[k].value;
}
if (!(oldValue != null) || isNaN(oldValue)) {
oldValue = defaultForProperty(k);
}
dValue = value - oldValue;
newValue = oldValue + (dValue * t);
}
properties[k] = newValue;
}
}
return properties;
};
animationStart = function() {
if (!this.options.animated) {
alert('!!! need to do something here');
return;
}
this.animating = true;
this.ts = null;
if (this.stopped) {
this.stopped = false;
}
return Loop.add(this);
};
keysForTransform = function(transform) {
var keys, match, matches, _i, _len;
matches = transform.match(/[a-zA-Z0-9]*\([^)]*\)/g);
keys = [];
if (matches != null) {
for (_i = 0, _len = matches.length; _i < _len; _i++) {
match = matches[_i];
keys.push(match.substring(0, match.indexOf('(')));
}
}
return keys;
};
Animations = [];
hasCommonProperties = function(props1, props2) {
var k, v;
for (k in props1) {
v = props1[k];
if (props2[k] != null) {
return true;
}
}
return false;
};
stopAnimationsForEl = function(el, properties) {
var animation, _i, _len, _results;
_results = [];
for (_i = 0, _len = Animations.length; _i < _len; _i++) {
animation = Animations[_i];
if (animation.el === el && hasCommonProperties(animation.to, properties)) {
_results.push(animation.stop());
} else {
_results.push(void 0);
}
}
return _results;
};
Loop = {
animations: [],
running: false,
start: function() {
this.running = true;
return requestAnimationFrame(this.tick.bind(this));
},
stop: function() {
return this.running = false;
},
tick: function(ts) {
var animation, animations, el, elProperties, found, k, properties, propertiesByEls, v, _i, _j, _k, _len, _len1, _len2, _ref, _ref1;
if (!this.running) {
return;
}
animations = this.animations.slice();
propertiesByEls = [];
for (_i = 0, _len = animations.length; _i < _len; _i++) {
animation = animations[_i];
properties = animationFrame.call(animation, ts);
found = false;
for (_j = 0, _len1 = propertiesByEls.length; _j < _len1; _j++) {
_ref = propertiesByEls[_j], el = _ref[0], elProperties = _ref[1];
if (animation.el === el) {
for (k in properties) {
v = properties[k];
if (k === 'transform' && elProperties[k]) {
v = v.multiply(elProperties[k]);
}
elProperties[k] = v;
}
found = true;
break;
}
}
if (!found) {
propertiesByEls.push([animation.el, properties]);
}
}
for (_k = 0, _len2 = propertiesByEls.length; _k < _len2; _k++) {
_ref1 = propertiesByEls[_k], el = _ref1[0], properties = _ref1[1];
if (properties['transform'] != null) {
properties['transform'] = matrixToString(properties['transform']);
}
css(el, properties);
}
return requestAnimationFrame(this.tick.bind(this));
},
add: function(animation) {
if (this.animations.indexOf(animation) === -1) {
this.animations.push(animation);
}
if (!this.running && this.animations.length > 0) {
return this.start();
}
},
remove: function(animation) {
if (this.running && this.animations.length === 0) {
return this.stop();
}
}
};
set = function(array) {
var obj, v, _i, _len;
obj = {};
for (_i = 0, _len = array.length; _i < _len; _i++) {
v = array[_i];
obj[v] = 1;
}
return {
obj: obj,
contains: function(v) {
return obj[v] != null;
}
};
};
pxProperties = set(['marginTop', 'marginLeft', 'marginBottom', 'marginRight', 'paddingTop', 'paddingLeft', 'paddingBottom', 'paddingRight', 'top', 'left', 'bottom', 'right', 'translateX', 'translateY', 'translateZ']);
degProperties = set(['rotate', 'rotateX', 'rotateY', 'rotateZ', 'skew', 'skewX', 'skewY', 'skewZ']);
transformProperties = set(['translateX', 'translateY', 'translateZ', 'scale', 'scaleX', 'scaleY', 'scaleZ', 'rotate', 'rotateX', 'rotateY', 'rotateZ', 'skew', 'skewX', 'skewY', 'skewZ', 'perspective', 'width', 'height', 'maxWidth', 'maxHeight', 'minWidth', 'minHeight']);
unitFor = function(k, v) {
if (typeof v !== 'number') {
return '';
}
if (pxProperties.contains(k)) {
return 'px';
} else if (degProperties.contains(k)) {
return 'deg';
}
return '';
};
css = function(el, properties) {
var k, transforms, v;
transforms = [];
for (k in properties) {
v = properties[k];
if (k === 'transform') {
transforms.push(v);
}
if (transformProperties.contains(k)) {
transforms.push("" + k + "(" + v + (unitFor(k, v)) + ")");
} else {
el.style[browserSupportWithPrefix(k)] = "" + v + (unitFor(k, v));
}
}
if (transforms.length > 0) {
return el.style[browserSupportWithPrefix("transform")] = transforms.join(' ');
}
};
Animation = (function() {
function Animation(el, to, options) {
var redraw;
this.el = el;
this.to = to;
if (options == null) {
options = {};
}
this.stop = __bind(this.stop, this);
this.start = __bind(this.start, this);
this.dynamic = __bind(this.dynamic, this);
this.setOptions = __bind(this.setOptions, this);
if (window['jQuery'] && this.el instanceof jQuery) {
this.el = this.el[0];
}
this.animating = false;
redraw = this.el.offsetHeight;
this.frames = parseFrames({
0: getFirstFrame.call(this, this.to),
100: this.to
});
this.keysToInterpolate = [];
if (this.frames[100]['transform'] != null) {
this.keysToInterpolate = keysForTransform(this.frames[100]['transform'].originalValue);
this.keysToInterpolate = this.keysToInterpolate.map(function(e) {
return e.toLowerCase();
});
}
this.setOptions(options);
if (this.options.debugName && Dynamics.InteractivePanel) {
Dynamics.InteractivePanel.addAnimation(this);
}
Animations.push(this);
}
Animation.prototype.setOptions = function(options) {
var optionsChanged, _base, _base1, _base2, _base3, _ref, _ref1, _ref2, _ref3, _ref4;
if (options == null) {
options = {};
}
optionsChanged = (_ref = this.options) != null ? _ref.optionsChanged : void 0;
this.options = options;
if ((_ref1 = (_base = this.options).duration) == null) {
_base.duration = 1000;
}
if ((_ref2 = (_base1 = this.options).complete) == null) {
_base1.complete = null;
}
if ((_ref3 = (_base2 = this.options).type) == null) {
_base2.type = Linear;
}
if ((_ref4 = (_base3 = this.options).animated) == null) {
_base3.animated = true;
}
this.returnsToSelf = false || this.dynamic().returnsToSelf;
this._dynamic = null;
if ((this.options.debugName != null) && (Dynamics.Overrides != null) && Dynamics.Overrides["for"](this.options.debugName)) {
this.options = Dynamics.Overrides.getOverride(this.options, this.options.debugName);
}
this.dynamic().init();
return typeof optionsChanged === "function" ? optionsChanged() : void 0;
};
Animation.prototype.dynamic = function() {
var _ref;
if ((_ref = this._dynamic) == null) {
this._dynamic = new this.options.type(this.options);
}
return this._dynamic;
};
Animation.prototype.start = function(options) {
var _ref, _ref1;
if (options == null) {
options = {};
}
if ((_ref = options.delay) == null) {
options.delay = this.options.delay;
}
if ((_ref1 = options.delay) == null) {
options.delay = 0;
}
stopAnimationsForEl(this.el, this.to);
if (options.delay <= 0) {
return animationStart.call(this);
} else {
return setTimeout(animationStart.bind(this), options.delay);
}
};
Animation.prototype.stop = function() {
this.animating = false;
return this.stopped = true;
};
return Animation;
})();
DynamicElement = (function() {
function DynamicElement(el) {
this.delay = __bind(this.delay, this);
this.start = __bind(this.start, this);
this.to = __bind(this.to, this);
this.css = __bind(this.css, this);
this._el = el;
this._delay = 0;
this._animations = [];
}
DynamicElement.prototype.css = function(to) {
css(this._el, to);
return this;
};
DynamicElement.prototype.to = function(to, options) {
if (options == null) {
options = {};
}
options.delay = this._delay;
this._animations.push(new Dynamics.Animation(this._el, to, options));
return this;
};
DynamicElement.prototype.start = function() {
var animation, _i, _len, _ref;
_ref = this._animations;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
animation = _ref[_i];
animation.start();
}
this._animations = [];
this._delay = 0;
return this;
};
DynamicElement.prototype.delay = function(delay) {
this._delay += delay;
return this;
};
return DynamicElement;
})();
this.dynamic = function(el) {
return new DynamicElement(el);
};
Dynamics = {
Animation: Animation,
Types: {
Spring: Spring,
SelfSpring: SelfSpring,
Gravity: Gravity,
GravityWithForce: GravityWithForce,
Linear: Linear,
Bezier: Bezier,
EaseInOut: EaseInOut
},
css: css
};
try {
if (module) {
module.exports = Dynamics;
} else {
this.Dynamics = Dynamics;
}
} catch (e) {
this.Dynamics = Dynamics;
}
}).call(this);
|
//! moment.js locale configuration
//! locale : italian (it)
//! author : Lorenzo : https://github.com/aliem
//! author: Mattia Larentis: https://github.com/nostalgiaz
import moment from '../moment';
export default moment.defineLocale('it', {
months : 'gennaio_febbraio_marzo_aprile_maggio_giugno_luglio_agosto_settembre_ottobre_novembre_dicembre'.split('_'),
monthsShort : 'gen_feb_mar_apr_mag_giu_lug_ago_set_ott_nov_dic'.split('_'),
weekdays : 'Domenica_Lunedì_Martedì_Mercoledì_Giovedì_Venerdì_Sabato'.split('_'),
weekdaysShort : 'Dom_Lun_Mar_Mer_Gio_Ven_Sab'.split('_'),
weekdaysMin : 'Do_Lu_Ma_Me_Gi_Ve_Sa'.split('_'),
longDateFormat : {
LT : 'HH:mm',
LTS : 'HH:mm:ss',
L : 'DD/MM/YYYY',
LL : 'D MMMM YYYY',
LLL : 'D MMMM YYYY HH:mm',
LLLL : 'dddd, D MMMM YYYY HH:mm'
},
calendar : {
sameDay: '[Oggi alle] LT',
nextDay: '[Domani alle] LT',
nextWeek: 'dddd [alle] LT',
lastDay: '[Ieri alle] LT',
lastWeek: function () {
switch (this.day()) {
case 0:
return '[la scorsa] dddd [alle] LT';
default:
return '[lo scorso] dddd [alle] LT';
}
},
sameElse: 'L'
},
relativeTime : {
future : function (s) {
return ((/^[0-9].+$/).test(s) ? 'tra' : 'in') + ' ' + s;
},
past : '%s fa',
s : 'alcuni secondi',
m : 'un minuto',
mm : '%d minuti',
h : 'un\'ora',
hh : '%d ore',
d : 'un giorno',
dd : '%d giorni',
M : 'un mese',
MM : '%d mesi',
y : 'un anno',
yy : '%d anni'
},
ordinalParse : /\d{1,2}º/,
ordinal: '%dº',
week : {
dow : 1, // Monday is the first day of the week.
doy : 4 // The week that contains Jan 4th is the first week of the year.
}
});
|
/*
* /MathJax/jax/output/HTML-CSS/fonts/STIX/General/BoldItalic/SpacingModLetters.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.Hub.Insert(MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS["STIXGeneral-bold-italic"],{688:[852,-328,380,7,365],689:[841,-329,380,7,365],690:[862,-176,350,24,384],691:[690,-344,389,21,384],692:[690,-344,389,2,365],693:[690,-171,389,2,371],694:[684,-345,390,5,466],695:[690,-331,450,15,467],696:[690,-176,350,11,386],699:[685,-369,333,128,332],704:[690,-240,343,-3,323],705:[690,-240,326,20,364],710:[690,-516,333,40,367],711:[690,-516,333,79,411],728:[678,-516,333,71,387],729:[655,-525,333,163,293],730:[754,-541,333,127,340],731:[44,173,333,-40,189],732:[655,-536,333,48,407],733:[697,-516,333,69,498],736:[684,-190,379,14,423],737:[857,-329,222,2,217],738:[690,-331,280,8,274],739:[690,-335,389,3,387],740:[849,-329,328,9,364],748:[70,167,314,5,309],749:[720,-528,395,5,390],759:[-108,227,333,-74,285]});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir+"/General/BoldItalic/SpacingModLetters.js");
|
import zeroFill from '../utils/zero-fill';
import { createDuration } from '../duration/create';
import { addSubtract } from '../moment/add-subtract';
import { isMoment } from '../moment/constructor';
import { addFormatToken } from '../format/format';
import { addRegexToken, matchOffset } from '../parse/regex';
import { addParseToken } from '../parse/token';
import { createLocal } from '../create/local';
import { createUTC } from '../create/utc';
import isDate from '../utils/is-date';
import toInt from '../utils/to-int';
import compareArrays from '../utils/compare-arrays';
import { hooks } from '../utils/hooks';
// FORMATTING
function offset (token, separator) {
addFormatToken(token, 0, 0, function () {
var offset = this.utcOffset();
var sign = '+';
if (offset < 0) {
offset = -offset;
sign = '-';
}
return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2);
});
}
offset('Z', ':');
offset('ZZ', '');
// PARSING
addRegexToken('Z', matchOffset);
addRegexToken('ZZ', matchOffset);
addParseToken(['Z', 'ZZ'], function (input, array, config) {
config._useUTC = true;
config._tzm = offsetFromString(input);
});
// HELPERS
// timezone chunker
// '+10:00' > ['10', '00']
// '-1530' > ['-15', '30']
var chunkOffset = /([\+\-]|\d\d)/gi;
function offsetFromString(string) {
var matches = ((string || '').match(matchOffset) || []);
var chunk = matches[matches.length - 1] || [];
var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
var minutes = +(parts[1] * 60) + toInt(parts[2]);
return parts[0] === '+' ? minutes : -minutes;
}
// Return a moment from input, that is local/utc/zone equivalent to model.
export function cloneWithOffset(input, model) {
var res, diff;
if (model._isUTC) {
res = model.clone();
diff = (isMoment(input) || isDate(input) ? +input : +createLocal(input)) - (+res);
// Use low-level api, because this fn is low-level api.
res._d.setTime(+res._d + diff);
hooks.updateOffset(res, false);
return res;
} else {
return createLocal(input).local();
}
return model._isUTC ? createLocal(input).zone(model._offset || 0) : createLocal(input).local();
}
function getDateOffset (m) {
// On Firefox.24 Date#getTimezoneOffset returns a floating point.
// https://github.com/moment/moment/pull/1871
return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
}
// HOOKS
// This function will be called whenever a moment is mutated.
// It is intended to keep the offset in sync with the timezone.
hooks.updateOffset = function () {};
// MOMENTS
// keepLocalTime = true means only change the timezone, without
// affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
// 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
// +0200, so we adjust the time as needed, to be valid.
//
// Keeping the time actually adds/subtracts (one hour)
// from the actual represented time. That is why we call updateOffset
// a second time. In case it wants us to change the offset again
// _changeInProgress == true case, then we have to adjust, because
// there is no such time in the given timezone.
export function getSetOffset (input, keepLocalTime) {
var offset = this._offset || 0,
localAdjust;
if (input != null) {
if (typeof input === 'string') {
input = offsetFromString(input);
}
if (Math.abs(input) < 16) {
input = input * 60;
}
if (!this._isUTC && keepLocalTime) {
localAdjust = getDateOffset(this);
}
this._offset = input;
this._isUTC = true;
if (localAdjust != null) {
this.add(localAdjust, 'm');
}
if (offset !== input) {
if (!keepLocalTime || this._changeInProgress) {
addSubtract(this, createDuration(input - offset, 'm'), 1, false);
} else if (!this._changeInProgress) {
this._changeInProgress = true;
hooks.updateOffset(this, true);
this._changeInProgress = null;
}
}
return this;
} else {
return this._isUTC ? offset : getDateOffset(this);
}
}
export function getSetZone (input, keepLocalTime) {
if (input != null) {
if (typeof input !== 'string') {
input = -input;
}
this.utcOffset(input, keepLocalTime);
return this;
} else {
return -this.utcOffset();
}
}
export function setOffsetToUTC (keepLocalTime) {
return this.utcOffset(0, keepLocalTime);
}
export function setOffsetToLocal (keepLocalTime) {
if (this._isUTC) {
this.utcOffset(0, keepLocalTime);
this._isUTC = false;
if (keepLocalTime) {
this.subtract(getDateOffset(this), 'm');
}
}
return this;
}
export function setOffsetToParsedOffset () {
if (this._tzm) {
this.utcOffset(this._tzm);
} else if (typeof this._i === 'string') {
this.utcOffset(offsetFromString(this._i));
}
return this;
}
export function hasAlignedHourOffset (input) {
if (!input) {
input = 0;
}
else {
input = createLocal(input).utcOffset();
}
return (this.utcOffset() - input) % 60 === 0;
}
export function isDaylightSavingTime () {
return (
this.utcOffset() > this.clone().month(0).utcOffset() ||
this.utcOffset() > this.clone().month(5).utcOffset()
);
}
export function isDaylightSavingTimeShifted () {
if (this._a) {
var other = this._isUTC ? createUTC(this._a) : createLocal(this._a);
return this.isValid() && compareArrays(this._a, other.toArray()) > 0;
}
return false;
}
export function isLocal () {
return !this._isUTC;
}
export function isUtcOffset () {
return this._isUTC;
}
export function isUtc () {
return this._isUTC && this._offset === 0;
}
|
const { assert } = require('chai');
const sinon = require('sinon');
const Task = require('../src/task');
describe('Task', () => {
beforeEach(() => {
this.clock = sinon.useFakeTimers(new Date(2018, 0, 1, 0, 0, 0, 0));
});
afterEach(() => {
this.clock.restore();
});
it('should emit event on finish a task', async () => {
let finished = false;
let task = new Task(() => 'ok');
task.on('task-finished', () => finished = true);
await task.execute();
assert.equal(true, finished);
});
it('should emit event on error a task', async () => {
let error;
let task = new Task(() => {
throw Error('execution error');
});
task.on('task-failed', (err) => error = err.message);
await task.execute();
assert.equal('execution error', error);
});
it('should emit event on finish a promise task', async () => {
let finished = false;
const promise = () => new Promise((resolve) => resolve('ok'));
let task = new Task(promise);
task.on('task-finished', () => finished = true);
await task.execute();
assert.equal(true, finished);
});
it('should emit event on error a promise task', async () => {
let failed = false;
const promise = () => new Promise((resolve, reject) => reject('errou'));
const task = new Task(promise);
task.on('task-failed', (error) => failed = error);
await task.execute();
assert.equal('errou', failed);
});
});
|
var
extend = require('../../utility/extend'),
Message_Reply = require('../../message/reply'),
Enum_Replies = require('../../enum/replies');
class Message_Reply_YouAreOperator extends Message_Reply {
getValuesForParameters() {
return { };
}
setValuesFromParameters() {
// Deliberately a noop.
}
}
extend(Message_Reply_YouAreOperator.prototype, {
reply: Enum_Replies.RPL_YOUREOPER,
abnf: '":You are now an IRC operator"'
});
module.exports = Message_Reply_YouAreOperator;
|
import minimist from 'minimist';
import server from './server';
const argv = minimist(process.argv, {
default: {
'server-port': 8888,
},
});
server.start({ port: argv['server-port'] });
|
// jshint mocha:true
'use strict';
var assert = require('assert');
var moduleInfo = require('../package-info');
describe('module info', function() {
it('should find the main info and test modules', function(done) {
moduleInfo(function(err, result) {
if (err) {
throw err;
}
assert(result);
assert(result.length);
var foundThis = result.some(function(mod) {
return mod.id === module.id;
});
if (!foundThis) {
assert.fail('test module was not found in results')
}
var foundInfoModule = result.some(function(mod) {
return mod.id === require.resolve('../package-info');
});
if (!foundInfoModule) {
assert.fail('module-info was not found in results');
}
var foundLodash = result.some(function(mod) {
return mod.id === require.resolve('lodash');
});
if (foundLodash) {
assert.fail('lodash should not be loaded yet');
}
done();
});
});
it('should find a newly loaded module', function(done) {
require('lodash');
moduleInfo(function(err, result) {
if (err) {
throw err;
}
assert(result);
assert(result.length);
var foundLodash = result.some(function(mod) {
return mod.id === require.resolve('lodash');
});
if (!foundLodash) {
assert.fail('extra test info was not found in results');
}
done();
});
});
});
describe('package info', function() {
it('should find the main info, not the test module', function(done) {
moduleInfo.packages(function(err, result) {
if (err) {
throw err;
}
assert(result);
assert(result.length);
var foundThis = result.some(function(mod) {
return mod.id === module.id;
});
if (foundThis) {
assert.fail('test module was found in results, but is not package main');
}
var foundInfoModule = result.some(function(mod) {
return mod.id === require.resolve('../package-info');
});
if (!foundInfoModule) {
assert.fail('module-info was not found in results, but is package main');
}
done();
});
});
});
|
import React from "react";
export default function context(name, type = React.PropTypes.any.isRequired) {
return function contextDecorator(Component) {
class ContextDecorator extends React.Component {
render() {
return <Component {...this.context} {...this.props} />;
}
}
ContextDecorator.contextTypes = {[name]: type}
ContextDecorator.displayName = `ContextDecorator`
return ContextDecorator;
};
}
|
// Karma configuration
// Generated on Sun Feb 07 2016 00:16:27 GMT+0100 (CET)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'test/main.js',
{
pattern: 'src/common/main.js',
included: false,
},
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'test/**/*.js': ['babel'],
'src/common/main.js': ['babel'],
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['spec'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
|
'use strict'
const h = require('virtual-dom/h')
const styles = require('./index.css.js')
const renderBar = require('./bar')
const renderMap = require('./map')
const render = (state, actions) =>
h('div', {
className: styles.wrapper + ''
}, [
renderBar(state, actions),
renderMap(state, actions)
])
module.exports = render
|
import { TOGGLE_MODAL } from './types';
import { resetCreateBoundaryError } from '.';
export const toggleCreatePreschoolModal = () => {
return (dispatch) => {
dispatch({
type: TOGGLE_MODAL,
modal: 'createPreschool',
});
dispatch(resetCreateBoundaryError());
};
};
|
Ember.ENV.TESTING = true;
var get = Ember.get;
var set = Ember.set;
var adapter;
var store;
var ajaxUrl;
var ajaxType;
var ajaxHash;
var person;
var Person, Article, Comment;
var expectUrl = function(url, desc) {
equal(ajaxUrl, url, "the URL is " + desc);
};
var expectType = function(type) {
equal(type, ajaxType, "the HTTP method is " + type);
};
var expectData = function(hash) {
deepEqual(ajaxHash.data, hash, "the hash was passed along");
};
var expectAjaxCall = function(type, url, data) {
expectType(type);
expectUrl(url);
if (data) expectData(data);
};
var expectState = function(state, value, p) {
p = p || person;
if (value === undefined) {
value = true;
}
var flag = "is" + state.charAt(0).toUpperCase() + state.substr(1);
equal(get(p, flag), value, "the state is " + (value === false ? "not ": "") + state);
};
module("DS.CouchDBAdapter", {
setup: function() {
adapter = DS.CouchDBAdapter.create({
db: 'DB_NAME',
designDoc: 'DESIGN_DOC',
_ajax: function(url, type, hash) {
var success = hash.success,
self = this;
ajaxUrl = url;
ajaxType = type;
ajaxHash = hash;
if (success) {
hash.success = function(json) {
success.call(self, json);
};
}
}
});
store = DS.Store.create({
adapter: adapter
});
Person = DS.Model.extend({
name: DS.attr('string')
});
Person.toString = function() { return 'Person'; };
Comment = DS.Model.extend({
text: DS.attr('string')
});
Comment.toString = function() { return 'Comment'; };
Article = DS.Model.extend({
label: DS.attr('string')
});
Article.toString = function() { return 'Article'; };
Article.reopen({
writer: DS.belongsTo(Person),
comments: DS.hasMany(Comment)
});
},
teardown: function() {
adapter.destroy();
store.destroy();
}
});
test("is defined", function() {
ok(DS.CouchDBAdapter !== undefined, "DS.CouchDBAdapter is undefined");
});
test("is a subclass of DS.Adapter", function() {
ok(DS.Adapter.detect(DS.CouchDBAdapter), "CouchDBAdapter is a subclass of DS.Adapter");
});
test("finding a record makes a GET to /DB_NAME/:id", function() {
person = store.find(Person, 1);
expectAjaxCall('GET', '/DB_NAME/1');
expectState('loaded', false);
ajaxHash.success({
_id: 1,
_rev: 'abc',
name: 'Hansi Hinterseer'
});
expectState('loaded');
expectState('dirty', false);
equal(person.get('id'), 1);
equal(person.get('name'), 'Hansi Hinterseer');
});
test("creating a person makes a POST to /DB_NAME with data hash", function() {
person = store.createRecord(Person, {
name: 'Tobias Fünke'
});
expectState('new');
store.commit();
expectState('saving');
expectAjaxCall('POST', '/DB_NAME/', {
name: "Tobias Fünke",
ember_type: 'Person'
});
ajaxHash.success({
ok: true,
id: "abc",
rev: "1-abc"
});
expectState('saving', false);
expectState('loaded', true);
expectState('dirty', false);
equal(person.get('name'), "Tobias Fünke");
set(person, 'name', "Dr. Funky");
store.commit();
expectAjaxCall('PUT', '/DB_NAME/abc', {
_id: "abc",
_rev: "1-abc",
ember_type: 'Person',
name: "Dr. Funky"
});
});
test("updating a person makes a PUT to /DB_NAME/:id with data hash", function() {
store.load(Person, {
id: 'abc',
rev: '1-abc',
name: 'Tobias Fünke'
});
person = store.find(Person, 'abc');
expectState('new', false);
expectState('loaded');
expectState('dirty', false);
set(person, 'name', 'Nelly Fünke');
expectState('dirty');
store.commit();
expectAjaxCall('PUT', '/DB_NAME/abc', {
_id: "abc",
_rev: "1-abc",
ember_type: 'Person',
name: "Nelly Fünke"
});
ajaxHash.success({
ok: true,
id: 'abc',
rev: '2-def'
});
expectState('saving', false);
expectState('loaded', true);
expectState('dirty', false);
equal(get(person, 'name'), 'Nelly Fünke', "the data is preserved");
set(person, 'name', "Dr. Funky");
store.commit();
expectAjaxCall('PUT', '/DB_NAME/abc', {
_id: "abc",
_rev: "2-def",
ember_type: 'Person',
name: "Dr. Funky"
});
});
test("updating with a conflicting revision", function() {
store.load(Person, {
id: 'abc',
rev: '1-abc',
name: 'Tobias Fünke'
});
person = store.find(Person, 'abc');
set(person, 'name', 'Nelly Fünke');
store.commit();
ajaxHash.error.call(ajaxHash.context, {
status: 409,
responseText: JSON.stringify({
error: "conflict",
reason: "Document update conflict"
})
});
expectState('valid', false);
});
test("deleting a person makes a DELETE to /DB_NAME/:id", function() {
store.load(Person, {
id: 'abc',
rev: '1-abc',
name: "Tobias Fünke"
});
person = store.find(Person, "abc");
expectState('new', false);
expectState('loaded');
expectState('dirty', false);
person.deleteRecord();
expectState('dirty');
expectState('deleted');
store.commit();
expectState('saving');
expectAjaxCall('DELETE', "/DB_NAME/abc?rev=1-abc");
ajaxHash.success({
ok: true,
rev: '2-abc'
});
expectState('deleted');
});
test("findMany makes a POST to /DB_NAME/_all_docs?include_docs=true", function() {
var persons = store.findMany(Person, ['1', '2']);
expectAjaxCall('POST', '/DB_NAME/_all_docs', {
include_docs: true,
keys: ['1', '2']
});
ajaxHash.success({
rows: [{
doc: { _id: 1, _rev: 'abc', name: 'first'}
}, {
doc: { _id: 2, _rev: 'def', name: 'second'}
}]
});
equal(store.find(Person, 1).get('name'), 'first');
equal(store.find(Person, 2).get('name'), 'second');
});
test("findAll makes a GET to /DB_NAME/_design/DESIGN_DOC/_view/by-ember-type", function() {
var allPersons = store.findAll(Person);
expectAjaxCall('GET', '/DB_NAME/_design/DESIGN_DOC/_view/by-ember-type', {
include_docs: true,
key: '%22Person%22'
});
equal(allPersons.get('length'), 0);
ajaxHash.success({
rows: [
{ doc: { _id: 1, _rev: 'a', name: 'first' } },
{ doc: { _id: 2, _rev: 'b', name: 'second' } },
{ doc: { _id: 3, _rev: 'c', name: 'third' } }
]
});
equal(allPersons.get('length'), 3);
equal(store.find(Person, 1).get('name'), 'first');
equal(store.find(Person, 2).get('name'), 'second');
equal(store.find(Person, 3).get('name'), 'third');
});
test("findAll calls viewForType if useCustomTypeLookup is set to true", function() {
expect(2);
adapter.set('customTypeLookup', true);
adapter.reopen({
viewForType: function(type, viewParams) {
equal(type, Person);
ok(viewParams);
}
});
store.findAll(Person);
});
test("findAll does a GET to view name returned by viewForType if useCustomTypeLookup is set to true", function() {
adapter.set('customTypeLookup', true);
adapter.reopen({
viewForType: function(type, viewParams) {
equal(typeof viewParams, 'object', 'viewParams is an object');
viewParams.key = "myPersonKey";
viewParams.include_docs = false;
return 'myPersonView';
}
});
var allPersons = store.findAll(Person);
expectAjaxCall('GET', '/DB_NAME/_design/DESIGN_DOC/_view/myPersonView', {
key: 'myPersonKey',
include_docs: true // include_docs is overridden
});
ajaxHash.success({
rows: [
{ doc: { _id: 1, _rev: 'a', name: 'first' } },
{ doc: { _id: 2, _rev: 'b', name: 'second' } },
{ doc: { _id: 3, _rev: 'c', name: 'third' } }
]
});
equal(allPersons.get('length'), 3);
equal(store.find(Person, 1).get('name'), 'first');
equal(store.find(Person, 2).get('name'), 'second');
equal(store.find(Person, 3).get('name'), 'third');
});
test("a view is requested via findQuery of type 'view'", function() {
var persons = store.findQuery(Person, {
type: 'view',
viewName: 'PERSONS_VIEW'
});
expectAjaxCall('GET', '/DB_NAME/_design/DESIGN_DOC/_view/PERSONS_VIEW');
expectState('loaded', false, persons);
ajaxHash.success({
rows: [
{ doc: { _id: 1, _rev: 'a', name: 'first' } },
{ doc: { _id: 2, _rev: 'b', name: 'second' } },
{ doc: { _id: 3, _rev: 'c', name: 'third' } }
]
});
expectState('loaded', true, persons);
equal(persons.get('length'), 3);
equal(store.find(Person, 1).get('name'), 'first');
equal(store.find(Person, 2).get('name'), 'second');
equal(store.find(Person, 3).get('name'), 'third');
});
test("a view adds the query options as parameters", function() {
store.findQuery(Person, {
type: 'view',
viewName: 'PERSONS_VIEW',
options: {
keys: ['a', 'b'],
limit: 10,
skip: 42
}
});
expectAjaxCall('GET', '/DB_NAME/_design/DESIGN_DOC/_view/PERSONS_VIEW', {
keys: ['a', 'b'],
limit: 10,
skip: 42
});
});
test("hasMany relationship dirties parent if child is added", function() {
store.load(Comment, {id: 'c1', rev: 'c1rev', text: 'comment 1'});
store.load(Comment, {id: 'c2', rev: 'c2rev', text: 'comment 2'});
store.load(Article, {id: 'a1', rev: 'a1rev', label: 'article', comments: ['c1']});
var article = store.find(Article, 'a1');
ok(article);
equal(article.get('comments.length'), 1);
expectState('dirty', false, article);
var c2 = store.find(Comment, 'c2');
ok(c2);
expectState('dirty', false, c2);
article.get('comments').pushObject(c2);
equal(article.get('comments.length'), 2);
expectState('dirty', true, article);
expectState('dirty', false, c2);
store.commit();
expectAjaxCall('PUT', '/DB_NAME/a1', {
_id: "a1",
_rev: "a1rev",
ember_type: 'Article',
label: "article",
comments: ['c1', 'c2']
});
ajaxHash.success({
ok: true,
id: 'a1',
rev: 'a2rev2'
});
});
test("hasMany relationship dirties parent if child is removed", function() {
store.load(Comment, {id: 'c1', rev: 'c1rev', text: 'comment 1'});
store.load(Comment, {id: 'c2', rev: 'c2rev', text: 'comment 2'});
store.load(Article, {id: 'a1', rev: 'a1rev', label: 'article', comments: ['c1', 'c2']});
var article = store.find(Article, 'a1');
ok(article);
equal(article.get('comments.length'), 2);
expectState('dirty', false, article);
var c2 = store.find(Comment, 'c2');
ok(c2);
article.get('comments').removeObject(c2);
equal(article.get('comments.length'), 1);
expectState('dirty', true, article);
expectState('dirty', false, c2);
store.commit();
expectAjaxCall('PUT', '/DB_NAME/a1', {
_id: "a1",
_rev: "a1rev",
ember_type: 'Article',
label: "article",
comments: ['c1']
});
ajaxHash.success({
ok: true,
id: 'a1',
rev: 'a2rev2'
});
expectState('dirty', false, article);
});
test("hasMany relationship dirties child if child is updated", function() {
store.load(Comment, {id: 'c1', rev: 'c1rev', text: 'comment 1'});
store.load(Article, {id: 'a1', rev: 'a1rev', label: 'article', comments: ['c1']});
var article = store.find(Article, 'a1');
var comment = store.find(Comment, 'c1');
ok(comment);
expectState('dirty', false, article);
expectState('dirty', false, comment);
comment.set('text', 'comment 1 updated');
expectState('dirty', false, article);
expectState('dirty', true, comment);
store.commit();
expectAjaxCall('PUT', '/DB_NAME/c1', {
_id: "c1",
_rev: "c1rev",
ember_type: 'Comment',
text: "comment 1 updated"
});
ajaxHash.success({
ok: true,
id: 'c1',
rev: 'c1rev2'
});
expectState('dirty', false, comment);
});
test("belongsTo relationship dirties if item is deleted", function() {
store.load(Person, {id: 'p1', rev: 'p1rev', name: 'author'});
store.load(Article, {id: 'a1', rev: 'a1rev', label: 'article', writer: 'p1'});
var article = store.find(Article, 'a1');
var person = store.find(Person, 'p1');
ok(article);
ok(person);
equal(article.get('writer'), person);
expectState('dirty', false, article);
expectState('dirty', false, person);
article.set('writer', null);
expectState('dirty', false, person);
expectState('dirty', true, article);
store.commit();
expectAjaxCall('PUT', '/DB_NAME/a1', {
_id: "a1",
_rev: "a1rev",
ember_type: 'Article',
label: "article"
});
ajaxHash.success({
ok: true,
id: 'a1',
rev: 'a1rev2'
});
expectState('dirty', false, article);
});
test("belongsTo relationship dirties parent if item is updated", function() {
store.load(Person, {id: 'p1', rev: 'p1rev', name: 'author 1'});
store.load(Person, {id: 'p2', rev: 'p2rev', name: 'author 2'});
store.load(Article, {id: 'a1', rev: 'a1rev', label: 'article', writer: 'p1'});
var article = store.find(Article, 'a1');
var person = store.find(Person, 'p2');
ok(article);
ok(person);
expectState('dirty', false, article);
expectState('dirty', false, person);
article.set('writer', person);
expectState('dirty', false, person);
expectState('dirty', true, article);
store.commit();
expectAjaxCall('PUT', '/DB_NAME/a1', {
_id: "a1",
_rev: "a1rev",
ember_type: 'Article',
label: "article",
writer: "p2"
});
ajaxHash.success({
ok: true,
id: 'a1',
rev: 'a1rev2'
});
expectState('dirty', false, article);
});
var serializer;
module("DS.CouchDBSerializer", {
setup: function() {
serializer = DS.CouchDBSerializer.create();
},
teardown: function() {
serializer.destroy();
}
});
test("it exists", function() {
ok(DS.CouchDBSerializer !== undefined, "DS.CouchDBSerializer is undefined");
});
test("it is a DS.JSONSerializer", function() {
ok(DS.JSONSerializer.detect(DS.CouchDBSerializer), "DS.CouchDBSerializer is a DS.JSONSerializer");
});
|
#!/usr/bin/env babel-node
// @flow
import spawnAsync from 'crater-util/lib/spawnAsync'
import isDirectory from 'crater-util/lib/isDirectory'
import path from 'path'
import requireEnv from '../requireEnv'
async function installMeteorDeps(): Promise<any> {
const BULID_DIR = requireEnv('BUILD_DIR')
const programsServer = path.join(BULID_DIR, 'meteor', 'bundle', 'programs', 'server')
if (!(await isDirectory(path.join(programsServer, 'node_modules')))) {
console.log('installing Meteor npm dependencies...')
await spawnAsync('npm', ['install'], {
cwd: programsServer,
stdio: 'inherit'
})
} else {
console.log('Meteor npm dependencies are up to date')
}
}
export default installMeteorDeps
|
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
entry: {
app: './src/app.js'
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'build')
},
externals: {
jquery: 'jQuery'
},
module: {
rules: [
{
test: /\.js$/,
include: [
path.resolve(__dirname, "src")
],
loader: "babel-loader"
},
{
test: /\.ejs$/,
use: [
{
loader: "ejs-loader"
}
]
},
{
test: /\.scss$/,
use: [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "resolve-url-loader"
}, {
loader: "sass-loader?sourceMap" // compiles Sass to CSS
}]
},
{
test: /\.css$/,
use: [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}]
},
{
test: /\.woff2?$|\.ttf$|\.eot$|\.svg$|\.gif$/,
use: [{
loader: "file-loader"
}]
}
]
},
resolve: {
alias: {
src: path.resolve('./src')
}
},
plugins: [
new HtmlWebpackPlugin({
template: '!!ejs-compiled-loader!index.ejs',
inject: false
}),
new CopyWebpackPlugin([
{ context: 'src/images', from: '**/*', to: 'images' },
{ context: 'src/__mocks__', from: '**/*', to: '__mocks__' }
])
],
devServer: {
contentBase: path.join(__dirname, "build"),
compress: true,
port: 9000,
historyApiFallback: true
}
};
|
#!/usr/bin/env node
var stee = require('simple-log-tee');
var Command = require('../');
var commands = [
new Command('ls', ['-lRA'], '..')/*,
new Command('grep', ['sh', '-r', '/usr/bin'], './'),
new Command('npm', ['update'], './')*/
];
doTests(commands);
function doTests(commands) {
if (commands.length === 0) {
return;
}
var command = commands.shift();
return testDefault();
function testDefault() {
console.log('** default');
command.run(testRecord);
}
function testRedirect(code) {
console.log('return code:', code);
console.log('** redirect');
command.setOptions({
redirect: command.exec + '_redirect.out'
});
command.run(testRecord);
}
function testRecord(code) {
console.log('return code:', code);
console.log('** record');
command.run({record: command.exec + '_record.out'}, testProgress);
}
function testProgress(code) {
console.log('return code:', code);
console.log('** progress true');
command.run({progress: true}, function (code) {
console.log('return code:', code);
console.log('** progress 5');
command.run({progress: 5}, testProgressRedirect);
});
}
function testProgressRedirect(code) {
console.log('return code:', code);
console.log('** redirect + progress 1');
command.setOptions({
redirect: command.exec + '_redirect-progress_1.out',
progress: 1
});
command.run(function (code) {
console.log('return code:', code);
console.log('** redirect + progress true');
command.setOptions({
redirect: command.exec + '_redirect-progress_true.out',
progress: true
});
command.run(testRecordRedirect);
});
}
function testRecordRedirect(code) {
console.log('return code:', code);
console.log('** record + redirect');
command.setOptions({
record: command.exec + '_record-with-redirect.out',
redirect: command.exec + '_redirect-with-record.out'
});
command.run(testRecordProgress);
}
function testRecordProgress(code) {
console.log('return code:', code);
console.log('** record + progress 3');
command.setOptions({
record: command.exec + '_record-progress_3.out',
progress: 3
});
command.run(testRecordProgressToExistingTee);
}
function testRecordProgressToExistingTee(code) {
console.log('return code:', code);
console.log('** redirect to existing tee');
var record = stee.createLogFileTee(command.exec + '_record-progress-2tee.out');
record.log('using an existing record ...');
command.setOptions({
record: record,
progress: true
});
command.run(function (code) {
record.log('... done recording');
testRecordProgressRedirect(code);
});
}
function testRecordProgressRedirect(code) {
console.log('return code:', code);
console.log('** record + redirect + progress 8');
command.run({
record: command.exec + '_record-with-redirct-progress_8.out',
redirect: command.exec + '_redirect-with-record-progress_8.out',
progress: 8
},
function (code) {
console.log('return code:', code);
doTests(commands);
}
);
}
}
|
'use strict';
var chromedriver = require('chromedriver');
var selenium = require('selenium-webdriver');
/**
* Creates a Selenium WebDriver using Chrome as the browser
* @returns {ThenableWebDriver} selenium web driver
*/
module.exports = function() {
var driver = new selenium.Builder().withCapabilities({
browserName: 'chrome',
javascriptEnabled: true,
acceptSslCerts: true,
chromeOptions: {
args: ['start-maximized', 'disable-extensions']
},
path: chromedriver.path
}).build();
driver.manage().window().maximize();
return driver;
};
|
var TypeHelper = require('./type-helper');
function contains(set, item) {
if (!set) {
console.warn(`
Got invalid argument to ArrayHelper.contains:
${set}
`);
return false;
}
return set.indexOf(item) !== -1;
}
function intersects(a, b) {
var index = a.length;
while (index--) {
if (contains(b, a[index])) {
return true;
}
}
return false;
}
function toArray(value) {
return Array.prototype.slice.call(value);
}
function getValueAfter(array, item, wrap) {
var index = array.indexOf(item);
if (index === -1) {
return null;
}
index++;
if (index === array.length) {
if (wrap) {
return getFirstValue(array);
} else {
return null;
}
}
return array[index];
}
function getValueBefore(array, item, wrap) {
var index = array.indexOf(item);
if (index === -1) {
return null;
}
index--;
if (index === -1) {
if (wrap) {
return getLastValue(array);
} else {
return null;
}
}
return array[index];
}
function flatten(array) {
var
result = [ ],
index = 0;
while (index < array.length) {
let item = array[index];
if (TypeHelper.isArray(item)) {
result = result.concat(item);
}
index++;
}
return result;
}
function combine() {
return flatten(toArray(arguments));
}
function unique() {
var
args = toArray(arguments),
result = [ ];
while (args.length) {
let arg = args.shift();
while (arg.length) {
let value = arg.shift();
if (!result.contains(value)) {
result.push(value);
}
}
}
return result;
}
function getPermutations(a, b) {
var results = [ ];
a.forEach(function each(a_item) {
b.forEach(function each(b_item) {
results.push([a_item, b_item]);
});
});
return results;
}
function sum(array) {
var result = 0;
array.forEach(function each(value) {
if (TypeHelper.isNumber(value)) {
result += value;
}
});
return result;
}
function average(array) {
return sum(array) / array.length;
}
function getLastValue(array) {
return array[array.length - 1];
}
function getFirstValue(array) {
return array[0];
}
module.exports = {
contains,
intersects,
toArray,
getValueAfter,
getValueBefore,
flatten,
combine,
unique,
getPermutations,
sum,
average,
getLastValue,
getFirstValue
};
|
require("node-test-helper");
describe(TEST_NAME, function() {
describe("constructor", function() {
it("should return an error object", function() {
var err = new StdError();
expect(err).to.be.instanceof(StdError);
expect(err).to.be.instanceof(Error);
expect(err.code).to.be.null;
expect(err.name).to.equal("StdError");
expect(err.message).to.equal("Standard Error");
});
it("should return an error object without using new", function() {
var err = StdError();
expect(err).to.be.instanceof(StdError);
expect(err).to.be.instanceof(Error);
expect(err.code).to.be.null;
expect(err.name).to.equal("StdError");
expect(err.message).to.equal("Standard Error");
});
it("should return an error object with custom message", function() {
var err = new StdError("My custom error");
expect(err).to.be.instanceof(StdError);
expect(err).to.be.instanceof(Error);
expect(err.code).to.be.null;
expect(err.name).to.equal("StdError");
expect(err.message).to.equal("My custom error");
});
it("accepts code, name and message options", function() {
var err = new StdError({code: 1000, name: "MyStdError", message: "My StdError"});
expect(err).to.be.instanceof(StdError);
expect(err).to.be.instanceof(Error);
expect(err.code).to.equal(1000);
expect(err.name).to.equal("MyStdError");
expect(err.message).to.equal("My StdError");
});
});
describe(".extend()", function() {
it("requires a valid name", function() {
expect(function() { StdError.extend() }).to.throw(Error, /invalid name/);
expect(function() { StdError.extend() }).to.throw(Error, /invalid name/);
expect(function() { StdError.extend("") }).to.throw(Error, /invalid name/);
expect(function() { StdError.extend("_name") }).to.throw(Error, /invalid name/);
expect(function() { StdError.extend("define") }).to.throw(Error, /invalid name/);
expect(function() { StdError.extend("extend") }).to.throw(Error, /invalid name/);
});
it("should allow instantiation of the derived class", function() {
var DerivedStdError = StdError.extend("DerivedStdError");
var err = new DerivedStdError();
expect(err).to.be.instanceof(DerivedStdError);
expect(err).to.be.instanceof(StdError);
expect(err).to.be.instanceof(Error);
expect(err.code).to.be.null;
expect(err.name).to.equal("DerivedStdError");
expect(err.message).to.equal("DerivedStdError");
});
it("should allow instantiation of the derived class without using new", function() {
var DerivedStdError = StdError.extend("DerivedStdError");
var err = DerivedStdError();
expect(err).to.be.instanceof(DerivedStdError);
expect(err).to.be.instanceof(StdError);
expect(err).to.be.instanceof(Error);
expect(err.code).to.be.null;
expect(err.name).to.equal("DerivedStdError");
expect(err.message).to.equal("DerivedStdError");
});
it("should return an error object with custom message", function() {
var DerivedStdError = StdError.extend("DerivedStdError");
var err = new DerivedStdError("My custom error");
expect(err).to.be.instanceof(DerivedStdError);
expect(err).to.be.instanceof(StdError);
expect(err).to.be.instanceof(Error);
expect(err.code).to.be.null;
expect(err.name).to.equal("DerivedStdError");
expect(err.message).to.equal("My custom error");
});
it("should allow derived class to be extended", function() {
var DerivedStdError = StdError.extend("DerivedStdError");
var MyDerivedStdError = DerivedStdError.extend("MyDerivedStdError");
var err = new MyDerivedStdError();
expect(err).to.be.instanceof(MyDerivedStdError);
expect(err).to.be.instanceof(DerivedStdError);
expect(err).to.be.instanceof(StdError);
expect(err).to.be.instanceof(Error);
expect(err.code).to.be.null;
expect(err.name).to.equal("MyDerivedStdError");
expect(err.message).to.equal("MyDerivedStdError");
});
it("accepts string parameter", function() {
var DerivedStdError = StdError.extend("DerivedStdError");
var err = new DerivedStdError();
expect(err).to.be.instanceof(DerivedStdError);
expect(err).to.be.instanceof(StdError);
expect(err).to.be.instanceof(Error);
expect(err.code).to.be.null;
expect(err.name).to.equal("DerivedStdError");
expect(err.message).to.equal("DerivedStdError");
});
it("accepts object parameter", function() {
var DerivedStdError = StdError.extend({code: 2000, name: "DerivedStdError", message: "Derived StdError"});
var err = new DerivedStdError();
expect(err).to.be.instanceof(DerivedStdError);
expect(err).to.be.instanceof(StdError);
expect(err).to.be.instanceof(Error);
expect(err.code).to.equal(2000);
expect(err.name).to.equal("DerivedStdError");
expect(err.message).to.equal("Derived StdError");
});
});
describe(".define()", function() {
it("requires a valid name", function() {
expect(function() { StdError.define() }).to.throw(Error, /invalid name/);
});
it("allows definition of custom error", function() {
expect(StdError.CustomError).to.not.exist;
StdError.define("CustomError");
expect(StdError.CustomError).to.exist;
var err = StdError.CustomError();
expect(err.code).to.be.null;
expect(err.name).to.equal("CustomError");
expect(err.message).to.equal("CustomError");
expect(StdError.WhateverError).to.not.exist;
StdError.define({code: 2000, name: "WhateverError", message: "Whatever error"});
expect(StdError.WhateverError).to.exist;
var err = new StdError.WhateverError();
expect(err.code).to.equal(2000);
expect(err.name).to.equal("WhateverError");
expect(err.message).to.equal("Whatever error");
});
it("allows definition of custom error derived from another error", function() {
expect(StdError.ParentError).to.not.exist;
StdError.define("ParentError");
expect(StdError.ParentError).to.exist;
expect(StdError.ChildError).to.not.exist;
StdError.define({name: "ChildError", parent: "ParentError"});
expect(StdError.ChildError).to.exist;
var err = new StdError.ChildError();
expect(err).to.be.instanceof(StdError.ChildError);
expect(err).to.be.instanceof(StdError.ParentError);
expect(err).to.be.instanceof(StdError);
expect(err).to.be.instanceof(Error);
var err = new StdError.ChildError();
var fn = function() { throw err }
expect(fn).to.throw(StdError.ChildError);
expect(fn).to.throw(StdError.ParentError);
expect(fn).to.throw(Error);
});
it("allows definition of custom error on the derived error class", function() {
var DerivedStdError = StdError.extend("DerivedStdError");
var err = new DerivedStdError();
expect(DerivedStdError.CustomError).to.not.exist;
DerivedStdError.define("CustomError");
expect(DerivedStdError.CustomError).to.exist;
var err = DerivedStdError.CustomError();
expect(err.code).to.be.null;
expect(err.name).to.equal("CustomError");
expect(err.message).to.equal("CustomError");
expect(DerivedStdError.WhateverError).to.not.exist;
DerivedStdError.define({code: 2000, name: "WhateverError", message: "Whatever error"});
expect(DerivedStdError.WhateverError).to.exist;
var err = new DerivedStdError.WhateverError();
expect(err.code).to.equal(2000);
expect(err.name).to.equal("WhateverError");
expect(err.message).to.equal("Whatever error");
});
});
describe("#toString()", function() {
it("should return the error string", function() {
var err = new StdError();
expect(err.toString()).to.equal("StdError: Standard Error");
var err = StdError();
expect(err.toString()).to.equal("StdError: Standard Error");
var err = StdError("My standard error");
expect(err.toString()).to.equal("StdError: My standard error");
var DerivedStdError = StdError.extend("DerivedStdError");
var err = DerivedStdError();
expect(err.toString()).to.equal("DerivedStdError");
var err = new DerivedStdError();
expect(err.toString()).to.equal("DerivedStdError");
var err = new DerivedStdError("My custom error");
expect(err.toString()).to.equal("DerivedStdError: My custom error");
});
});
describe("error message", function() {
it("should return the error string", function() {
var err = new StdError();
expect(err.message).to.equal("Standard Error");
var err = StdError();
expect(err.message).to.equal("Standard Error");
var err = StdError("My standard error");
expect(err.message).to.equal("My standard error");
var DerivedStdError = StdError.extend("DerivedStdError");
var err = DerivedStdError();
expect(err.message).to.equal("DerivedStdError");
var err = new DerivedStdError();
expect(err.message).to.equal("DerivedStdError");
var err = new DerivedStdError("My custom error");
expect(err.message).to.equal("My custom error");
});
});
});
|
var React=require("react");
var E=React.createElement;
var styles={input:{fontSize:"100%"},deletebutton:{color:"red"}};
var ActionButton=React.createClass({
getHandler:function() {
var handler=this.props.editing?this.props.onUpdateMarkup:this.props.onCreateMarkup;
this.props.setHotkey&&this.props.setHotkey(handler);
return handler;
}
,deleteButton:function(){
if (this.props.editing && !this.props.dirty && this.props.deletable ) {
return E("button",{title:"Ctrl+M",onClick:this.props.onDeleteMarkup,style:styles.deletebutton},"DELETE")
}
}
,render:function () {
var buttontext=this.props.editing?(this.props.dirty?"Update":null):"Create";
return E("span",null
,(buttontext?E("button",{title:"Ctrl+M",onClick:this.getHandler()},buttontext):null)
,this.deleteButton()
);
}
});
module.exports=ActionButton;
|
module.exports = { prefix: 'far', iconName: 'underline', icon: [448, 512, [], "f0cd", "M0 500v-24c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v24c0 6.627-5.373 12-12 12H12c-6.627 0-12-5.373-12-12zM278.066 12v24c0 6.627 5.373 12 12 12h40.44v210.742c0 74.424-39.957 112.144-106.502 112.144-66.896 0-106.501-35.297-106.501-111.005V48h40.44c6.627 0 12-5.373 12-12V12c0-6.627-5.373-12-12-12H22.162c-6.627 0-12 5.373-12 12v24c0 6.627 5.373 12 12 12h40.441v212.45c0 106.712 66.034 161.89 161.401 161.89 93.574 0 161.402-56.006 161.402-161.89V48h40.44c6.627 0 12-5.373 12-12V12c0-6.627-5.373-12-12-12h-135.78c-6.627 0-12 5.373-12 12z"] };
|
import AuthService from './AuthService'
const auth = new AuthService(process.env.REACT_APP_AUTH_CLIENT_ID, process.env.REACT_APP_AUTH_DOMAIN_ADDRESS)
export default auth
|
(function(){
angular
.module('app.chat.authentication')
.factory('authenticationService',authenticationService);
/* @ngInject */
function authenticationService(Restangular,$log){
var getData = function(action, id, action2, id2, flag, isPercentage, page, limit, sort_order, sort_by) {
var queryParams = {
page: page,
limit: limit,
sort_order: sort_order,
sort_by: sort_by,
flag: flag,
is_percentage: isPercentage
};
if (action != null && id != null && action2 != null && id2 != null) {
return Restangular.one(action, id)
.one(action2, id2)
.get(queryParams)
.then(function(response) {
return response;
}, handleError);
} else if (action != null && id != null && action2 != null && id2 == null) {
return Restangular.one(action, id)
.one(action2)
.get(queryParams)
.then(function(response) {
return response;
}, handleError);
} else if (action != null && id != null && action2 == null && id2 == null) {
return Restangular.one(action, id)
.get(queryParams)
.then(function(response) {
return response;
}, handleError);
} else if (action != null && id == null && action2 == null && id2 == null) {
return Restangular.one(action)
.get(queryParams)
.then(function(response) {
return response;
}, handleError);
} else if (action == null && id == null && action2 == null && id2 == null) {
return Restangular.get(queryParams)
.then(function(response) {
return response;
}, handleError);
} else {
return Restangular.one(action, id)
.one(action2, id2)
.get(queryParams)
.then(function(response) {
return response;
}, handleError);
}
};
var postData = function(action,postParams) {
return Restangular.one('auth', action)
.customPOST(postParams)
.then(function(response) {
return response;
}, handleError);
};
function handleError(response) {
$log.log(response);
}
return{
getData : getData,
postData : postData
}
}
})();
|
function fix_broken_images2() {
// document.getElementById("message").style.display = 'none';
document.getElementById("test1").style.display = 'none';
return 'ok';
}
|
import React from 'react'
import PropTypes from 'prop-types'
import { ReactComponent as Heart } from 'assets/heart.svg'
import { ReactComponent as HeartOutline } from 'assets/heart-outline.svg'
import style from './Action.module.scss'
const Action = ({ className, icon, value, onChange }) => {
const component = { component: null }
if (icon === 'favorite') {
if (value) {
component.component = Heart
} else {
component.component = HeartOutline
}
}
if (component.component === null) {
return null
}
return (
<button
type="button"
className={style.button}
onClick={() => {
onChange(!value)
}}
>
<component.component className={`${style.Action} ${className}`} />
</button>
)
}
Action.defaultProps = {
className: '',
icon: '',
type: '',
id: '',
value: null,
onChange: () => {},
}
Action.propTypes = {
className: PropTypes.string,
icon: PropTypes.string,
type: PropTypes.string,
id: PropTypes.string,
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.bool,
PropTypes.number,
]),
onChange: PropTypes.func,
}
export default Action
|
/*
Terminal Kit
Copyright (c) 2009 - 2021 Cédric Ronvel
The MIT License (MIT)
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 string = require( 'string-kit' ) ;
/*
progressBar( options )
* options `object` of options, all of them are OPTIONAL, where:
* width: `number` the total width of the progress bar, default to the max available width
* percent: `boolean` if true, it shows the progress in percent alongside with the progress bar
* eta: `boolean` if true, it shows the Estimated Time of Arrival alongside with the progress bar
* items `number` the number of items, turns the 'item mode' on
* title `string` the title of the current progress bar, turns the 'title mode' on
* barStyle `function` the style of the progress bar items, default to `term.cyan`
* barBracketStyle `function` the style of the progress bar bracket character, default to options.barStyle if given
or `term.blue`
* percentStyle `function` the style of percent value string, default to `term.yellow`
* etaStyle `function` the style of the ETA display, default to `term.bold`
* itemStyle `function` the style of the item display, default to `term.dim`
* titleStyle `function` the style of the title display, default to `term.bold`
* itemSize `number` the size of the item status, default to 33% of width
* titleSize `number` the size of the title, default to 33% of width or title.length depending on context
* barChar `string` the char used for the bar, default to '='
* barHeadChar `string` the char used for the bar, default to '>'
* maxRefreshTime `number` the maximum time between two refresh in ms, default to 500ms
* minRefreshTime `number` the minimum time between two refresh in ms, default to 100ms
* inline `boolean` (default: false) if true it is not locked in place, i.e. it redraws itself on the current line
* syncMode `boolean` true if it should work in sync mode
* y `integer` if set, display the progressBar on that line y-coord
* x `integer` if set and the 'y' option is set, display the progressBar starting on that x-coord
*/
module.exports = function progressBar_( options ) {
if ( ! options || typeof options !== 'object' ) { options = {} ; }
var controller = {} , progress , ready = false , pause = false ,
maxItems , itemsDone = 0 , itemsStarted = [] , itemFiller ,
title , titleFiller ,
width , y , startX , endX , oldWidth ,
wheel , wheelCounter = 0 , itemRollCounter = 0 ,
updateCount = 0 , progressUpdateCount = 0 ,
lastUpdateTime , lastRedrawTime ,
startingTime , redrawTimer ,
etaStartingTime , lastEta , etaFiller ;
etaStartingTime = startingTime = ( new Date() ).getTime() ;
wheel = [ '|' , '/' , '-' , '\\' ] ;
options.syncMode = !! options.syncMode ;
width = options.width || this.width - 1 ;
if ( ! options.barBracketStyle ) {
if ( options.barStyle ) { options.barBracketStyle = options.barStyle ; }
else { options.barBracketStyle = this.blue ; }
}
if ( ! options.barStyle ) { options.barStyle = this.cyan ; }
if ( ! options.percentStyle ) { options.percentStyle = this.yellow ; }
if ( ! options.etaStyle ) { options.etaStyle = this.bold ; }
if ( ! options.itemStyle ) { options.itemStyle = this.dim ; }
if ( ! options.titleStyle ) { options.titleStyle = this.bold ; }
if ( ! options.barChar ) { options.barChar = '=' ; }
else { options.barChar = options.barChar[ 0 ] ; }
if ( ! options.barHeadChar ) { options.barHeadChar = '>' ; }
else { options.barHeadChar = options.barHeadChar[ 0 ] ; }
if ( typeof options.maxRefreshTime !== 'number' ) { options.maxRefreshTime = 500 ; }
if ( typeof options.minRefreshTime !== 'number' ) { options.minRefreshTime = 100 ; }
if ( typeof options.items === 'number' ) { maxItems = options.items ; }
if ( maxItems && typeof options.itemSize !== 'number' ) { options.itemSize = Math.round( width / 3 ) ; }
itemFiller = ' '.repeat( options.itemSize ) ;
if ( options.title && typeof options.title === 'string' ) {
title = options.title ;
if ( typeof options.titleSize !== 'number' ) {
options.titleSize = Math.round( Math.min( options.title.length + 1 , width / 3 ) ) ;
}
}
titleFiller = ' '.repeat( options.titleSize ) ;
etaFiller = ' ' ; // 11 chars
// This is a naive ETA for instance...
var etaString = updated => {
var eta = '' , elapsedTime , elapsedEtaTime , remainingTime ,
averageUpdateDelay , averageUpdateProgress , lastUpdateElapsedTime , fakeProgress ;
if ( progress >= 1 ) {
eta = ' done' ;
}
else if ( progress > 0 ) {
elapsedTime = ( new Date() ).getTime() - startingTime ;
elapsedEtaTime = ( new Date() ).getTime() - etaStartingTime ;
if ( ! updated && progressUpdateCount > 1 ) {
lastUpdateElapsedTime = ( new Date() ).getTime() - lastUpdateTime ;
averageUpdateDelay = elapsedEtaTime / progressUpdateCount ;
averageUpdateProgress = progress / progressUpdateCount ;
//console.log( '\n' , elapsedEtaTime , lastUpdateElapsedTime , averageUpdateDelay , averageUpdateProgress , '\n' ) ;
// Do not update ETA if it's not an update, except if update time is too long
if ( lastUpdateElapsedTime < averageUpdateDelay ) {
fakeProgress = progress + averageUpdateProgress * lastUpdateElapsedTime / averageUpdateDelay ;
}
else {
fakeProgress = progress + averageUpdateProgress ;
}
if ( fakeProgress > 0.99 ) { fakeProgress = 0.99 ; }
}
else {
fakeProgress = progress ;
}
remainingTime = elapsedEtaTime * ( ( 1 - fakeProgress ) / fakeProgress ) / 1000 ;
eta = ' in ' ;
if ( remainingTime < 10 ) { eta += Math.round( remainingTime * 10 ) / 10 + 's' ; }
else if ( remainingTime < 120 ) { eta += Math.round( remainingTime ) + 's' ; }
else if ( remainingTime < 7200 ) { eta += Math.round( remainingTime / 60 ) + 'min' ; }
else if ( remainingTime < 172800 ) { eta += Math.round( remainingTime / 3600 ) + 'hours' ; }
else if ( remainingTime < 31536000 ) { eta += Math.round( remainingTime / 86400 ) + 'days' ; }
else { eta = 'few years' ; }
}
else {
etaStartingTime = ( new Date() ).getTime() ;
}
eta = ( eta + etaFiller ).slice( 0 , etaFiller.length ) ;
lastEta = eta ;
return eta ;
} ;
var redraw = updated => {
var time , itemIndex , itemName = itemFiller , titleName = titleFiller ,
innerBarSize , progressSize , voidSize ,
progressBar = '' , voidBar = '' , percent = '' , eta = '' ;
if ( ! ready || pause ) { return ; }
time = ( new Date() ).getTime() ;
// If progress is >= 1, then it's finished, so we should redraw NOW (before the program eventually quit)
if ( ( ! progress || progress < 1 ) && lastRedrawTime && time < lastRedrawTime + options.minRefreshTime ) {
if ( ! options.syncMode ) {
if ( redrawTimer ) { clearTimeout( redrawTimer ) ; }
redrawTimer = setTimeout( redraw.bind( this , updated ) , lastRedrawTime + options.minRefreshTime - time ) ;
}
return ;
}
this.saveCursor() ;
// If 'y' is null, we are in the blind mode, we haven't get the cursor location
if ( y === null ) { this.column( startX ) ; }
else { this.moveTo( startX , y ) ; }
//this.noFormat( Math.floor( progress * 100 ) + '%' ) ;
innerBarSize = width - 2 ;
if ( options.percent ) {
innerBarSize -= 4 ;
percent = ( ' ' + Math.round( ( progress || 0 ) * 100 ) + '%' ).slice( -4 ) ;
}
if ( options.eta ) {
eta = etaString( updated ) ;
innerBarSize -= eta.length ;
}
innerBarSize -= options.itemSize || 0 ;
if ( maxItems ) {
if ( ! itemsStarted.length ) {
itemName = '' ;
}
else if ( itemsStarted.length === 1 ) {
itemName = ' ' + itemsStarted[ 0 ] ;
}
else {
itemIndex = ( itemRollCounter ++ ) % itemsStarted.length ;
itemName = ' [' + ( itemIndex + 1 ) + '/' + itemsStarted.length + '] ' + itemsStarted[ itemIndex ] ;
}
if ( itemName.length > itemFiller.length ) { itemName = itemName.slice( 0 , itemFiller.length - 1 ) + '…' ; }
else if ( itemName.length < itemFiller.length ) { itemName = ( itemName + itemFiller ).slice( 0 , itemFiller.length ) ; }
}
innerBarSize -= options.titleSize || 0 ;
if ( title ) {
titleName = title ;
if ( titleName.length >= titleFiller.length ) { titleName = titleName.slice( 0 , titleFiller.length - 2 ) + '… ' ; }
else { titleName = ( titleName + titleFiller ).slice( 0 , titleFiller.length ) ; }
}
progressSize = progress === undefined ? 1 : Math.round( innerBarSize * Math.max( Math.min( progress , 1 ) , 0 ) ) ;
voidSize = innerBarSize - progressSize ;
/*
console.log( "Size:" , width ,
voidSize , innerBarSize , progressSize , eta.length , title.length , itemName.length ,
voidSize + progressSize + eta.length + title.length + itemName.length
) ;
//*/
if ( progressSize ) {
if ( progress === undefined ) {
progressBar = wheel[ ++ wheelCounter % wheel.length ] ;
}
else {
progressBar += options.barChar.repeat( progressSize - 1 ) ;
progressBar += options.barHeadChar ;
}
}
voidBar += ' '.repeat( voidSize ) ;
options.titleStyle( titleName ) ;
if ( percent ) { options.percentStyle( percent ) ; }
if ( progress === undefined ) { this( ' ' ) ; }
else { options.barBracketStyle( '[' ) ; }
options.barStyle( progressBar ) ;
this( voidBar ) ;
if ( progress === undefined ) { this( ' ' ) ; /*this( '+' ) ;*/ }
else { options.barBracketStyle( ']' ) ; }
options.etaStyle( eta ) ;
//this( '*' ) ;
options.itemStyle( itemName ) ;
//this( '&' ) ;
this.restoreCursor() ;
if ( ! options.syncMode ) {
if ( redrawTimer ) { clearTimeout( redrawTimer ) ; }
if ( ! progress || progress < 1 ) { redrawTimer = setTimeout( redraw , options.maxRefreshTime ) ; }
}
lastRedrawTime = time ;
} ;
if ( options.syncMode || options.inline || options.y ) {
oldWidth = width ;
if ( options.y ) {
startX = + options.x || 1 ;
y = + options.y || 1 ;
}
else {
startX = 1 ;
y = null ;
}
endX = Math.min( startX + width , this.width ) ;
width = endX - startX ;
if ( width !== oldWidth ) {
// Should resize all part here
if ( options.titleSize ) { options.titleSize = Math.floor( options.titleSize * width / oldWidth ) ; }
if ( options.itemSize ) { options.itemSize = Math.floor( options.itemSize * width / oldWidth ) ; }
}
ready = true ;
redraw() ;
}
else {
// Get the cursor location before getting started
this.getCursorLocation( ( error , x_ , y_ ) => {
if ( error ) {
// Some bad terminals (windows...) doesn't support cursor location request, we should fallback to a decent behavior.
// So we just move to the last line and create a new line.
//cleanup( error ) ; return ;
this.row.eraseLineAfter( this.height )( '\n' ) ;
x_ = 1 ;
y_ = this.height ;
}
var oldWidth_ = width ;
startX = x_ ;
endX = Math.min( x_ + width , this.width ) ;
y = y_ ;
width = endX - startX ;
if ( width !== oldWidth_ ) {
// Should resize all part here
if ( options.titleSize ) { options.titleSize = Math.floor( options.titleSize * width / oldWidth_ ) ; }
if ( options.itemSize ) { options.itemSize = Math.floor( options.itemSize * width / oldWidth_ ) ; }
}
ready = true ;
redraw() ;
} ) ;
}
controller.startItem = name => {
itemsStarted.push( name ) ;
// No need to redraw NOW if there are other items running.
// Let the timer do the job.
if ( itemsStarted.length === 1 ) {
// If progress is >= 1, then it's finished, so we should redraw NOW (before the program eventually quit)
if ( progress >= 1 ) { redraw() ; return ; }
if ( options.syncMode ) {
redraw() ;
}
else {
// Using a setTimeout with a 0ms time and redrawTimer clearing has a nice effect:
// if multiple synchronous update are performed, redraw will be called once
if ( redrawTimer ) { clearTimeout( redrawTimer ) ; }
redrawTimer = setTimeout( redraw , 0 ) ;
}
}
} ;
controller.itemDone = name => {
var index ;
itemsDone ++ ;
if ( maxItems ) { progress = itemsDone / maxItems ; }
else { progress = undefined ; }
lastUpdateTime = ( new Date() ).getTime() ;
updateCount ++ ;
progressUpdateCount ++ ;
index = itemsStarted.indexOf( name ) ;
if ( index >= 0 ) { itemsStarted.splice( index , 1 ) ; }
// If progress is >= 1, then it's finished, so we should redraw NOW (before the program eventually quit)
if ( progress >= 1 ) { redraw( true ) ; return ; }
if ( options.syncMode ) {
redraw() ;
}
else {
// Using a setTimeout with a 0ms time and redrawTimer clearing has a nice effect:
// if multiple synchronous update are performed, redraw will be called once
if ( redrawTimer ) { clearTimeout( redrawTimer ) ; }
redrawTimer = setTimeout( redraw.bind( this , true ) , 0 ) ;
}
} ;
controller.update = toUpdate => {
if ( ! toUpdate ) { toUpdate = {} ; }
else if ( typeof toUpdate === 'number' ) { toUpdate = { progress: toUpdate } ; }
if ( 'progress' in toUpdate ) {
if ( typeof toUpdate.progress !== 'number' ) {
progress = undefined ;
}
else {
// Not sure if it is a good thing to let the user set progress to a value that is lesser than the current one
progress = toUpdate.progress ;
if ( progress > 1 ) { progress = 1 ; }
else if ( progress < 0 ) { progress = 0 ; }
if ( progress > 0 ) { progressUpdateCount ++ ; }
lastUpdateTime = ( new Date() ).getTime() ;
updateCount ++ ;
}
}
if ( typeof toUpdate.items === 'number' ) {
maxItems = toUpdate.items ;
if ( maxItems ) { progress = itemsDone / maxItems ; }
if ( typeof options.itemSize !== 'number' ) {
options.itemSize = Math.round( width / 3 ) ;
itemFiller = ' '.repeat( options.itemSize ) ;
}
}
if ( typeof toUpdate.title === 'string' ) {
title = toUpdate.title ;
if ( typeof options.titleSize !== 'number' ) {
options.titleSize = Math.round( width / 3 ) ;
titleFiller = ' '.repeat( options.titleSize ) ;
}
}
// If progress is >= 1, then it's finished, so we should redraw NOW (before the program eventually quit)
if ( progress >= 1 ) { redraw( true ) ; return ; }
if ( options.syncMode ) {
redraw() ;
}
else {
// Using a setTimeout with a 0ms time and redrawTimer clearing has a nice effect:
// if multiple synchronous update are performed, redraw will be called once
if ( redrawTimer ) { clearTimeout( redrawTimer ) ; }
redrawTimer = setTimeout( redraw.bind( this , true ) , 0 ) ;
}
} ;
controller.pause = controller.stop = () => {
pause = true ;
} ;
controller.resume = () => {
if ( pause ) {
pause = false ;
redraw() ;
}
} ;
controller.reset = () => {
etaStartingTime = startingTime = ( new Date() ).getTime() ;
itemsDone = 0 ;
progress = undefined ;
itemsStarted.length = 0 ;
wheelCounter = itemRollCounter = updateCount = progressUpdateCount = 0 ;
redraw() ;
} ;
return controller ;
} ;
|
/**
* @author: @AngularClass
*/
/*
* When testing with webpack and ES6, we have to do some extra
* things to get testing to work right. Because we are gonna write tests
* in ES6 too, we have to compile those as well. That's handled in
* karma.conf.js with the karma-webpack plugin. This is the entry
* file for webpack test. Just like webpack will create a bundle.js
* file for our client, when we run test, it will compile and bundle them
* all here! Crazy huh. So we need to do some setup
*/
Error.stackTraceLimit = Infinity;
require('core-js/es6');
require('core-js/es7/reflect');
// Typescript emit helpers polyfill
require('ts-helpers');
require('zone.js/dist/zone');
require('zone.js/dist/long-stack-trace-zone');
require('zone.js/dist/proxy'); // since zone.js 0.6.15
require('zone.js/dist/sync-test');
require('zone.js/dist/jasmine-patch'); // put here since zone.js 0.6.14
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');
// RxJS
require('rxjs/Rx');
var testing = require('@angular/core/testing');
var browser = require('@angular/platform-browser-dynamic/testing');
testing.TestBed.initTestEnvironment(
browser.BrowserDynamicTestingModule,
browser.platformBrowserDynamicTesting()
);
window.__karma__ && require('./karma-require');
|
// @flow
import React from "react";
import {render} from "react-dom";
import {Provider} from "react-redux";
import {Router, hashHistory} from "react-router";
import {syncHistoryWithStore} from "react-router-redux";
import routes from "./routes";
import configureStore from "./store/configureStore";
import "./app.global.css";
import db from "../main/database";
import {initNotebook, selectNotebook} from "./actions/note";
db.notebooks.find({}).sort({ createdAt: 1 }).exec(function (err, datas) {
notebooks = datas;
const store = configureStore(notebooks);
store.dispatch(initNotebook(notebooks));
db.config.findOne({key: 'currentNote'}, function(err, data) {
notebooks.map((notebook) => {
data.value == notebook._id && store.dispatch(selectNotebook(notebook));
});
});
const history = syncHistoryWithStore(hashHistory, store);
render(
<Provider store={store}>
<Router history={history} routes={routes}/>
</Provider>,
document.getElementById('root')
);
});
let notebooks = {};
|
"use strict";
module.exports = {
app: {
title: 'ng SKorea',
description: 'Full-Stack JavaScript with MongoDB, Express, AngularJS, and Node.js',
keywords: 'MongoDB, Express, AngularJS, Node.js'
},
port: process.env.PORT || 4545,
templateEngine: 'swig',
sessionSecret: 'OKKYAnuglar',
sessionCollection: 'sessions',
assets: {
lib: {
css: [
'public/lib/bootstrap/dist/css/bootstrap.css',
'public/lib/bootstrap/dist/css/bootstrap-theme.css',
'public/lib/angular-material/angular-material.css',
'public/lib/nvd3/nv.d3.min.css',
'public/lib/reveal.js/css/reveal.css',
'public/lib/highlightjs/styles/github.css',
],
js: [
'public/lib/angular/angular.js',
'public/lib/angular-messages/angular-messages.min.js',
'public/lib/angular-resource/angular-resource.js',
'public/lib/angular-cookies/angular-cookies.js',
'public/lib/angular-animate/angular-animate.js',
'public/lib/angular-touch/angular-touch.js',
'public/lib/angular-sanitize/angular-sanitize.js',
'public/lib/angular-ui-router/release/angular-ui-router.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
'public/lib/jquery/dist/jquery.js',
'public/lib/angular-aria/angular-aria.js',
'public/lib/angular-material/angular-material.js',
'public/lib/gsap/src/uncompressed/TimelineMax.js',
'public/lib/gsap/src/uncompressed/TweenMax.js',
//'public/lib/ng-context-menu/dist/ng-context-menu.js',
'public/lib/gsap/src/uncompressed/utils/Draggable.js',
//'public/lib/gsap/src/uncompressed/plugins/TextPlugin.js',
'public/lib/gsap/src/uncompressed/plugins/ScrollToPlugin.js',
'public/lib/gsap/src/uncompressed/plugins/ColorPropsPlugin.js',
'public/lib/gsap/src/uncompressed/plugins/CSSPlugin.js',
'public/lib/gsap/src/minified/utils/Draggable.min.js',
//'public/lib/3rd/SplitText.min.js'
//'public/lib/threejs/build/three.min.js',
/*
'public/lib/tremulajs/libs/hammer.js',
'public/lib/tremulajs/libs/jsBezier-0.6.js',
'public/lib/tremulajs/dist/Tremula.js',
*/
'public/lib/lodash/lodash.js',
//'public/lib/angular-google-maps/dist/angular-google-maps.js',
'public/lib/d3/d3.min.js',
//'public/lib/d3-timeline/src/d3-timeline.js',
'public/lib/topojson/topojson.js',
'public/lib/angular-smart-table/dist/smart-table.min.js',
'public/lib/tinymce/tinymce.min.js',
'public/lib/tinymce/plugins/image/plugin.min.js',
'public/lib/tinymce/plugins/link/plugin.min.js',
'public/lib/tinymce/plugins/fullscreen/plugin.min.js',
'public/lib/tinymce/plugins/code/plugin.min.js',
'public/lib/tinymce/plugins/table/plugin.min.js',
'public/lib/tinymce/plugins/contextmenu/plugin.min.js',
'public/lib/tinymce/plugins/media/plugin.min.js',
'public/lib/string/lib/string.min.js',
'public/lib/moment/min/moment-with-locales.min.js',
//'public/third/prism/prism.js',
'public/lib/nvd3/nv.d3.min.js',
'public/lib/angular-nvd3/dist/angular-nvd3.min.js',
'public/lib/braintree-angular/dist/braintree-angular.js',
'public/lib/reveal.js/js/reveal.js',
'public/lib/highlightjs/highlight.pack.js',
'public/lib/angular-highlightjs/build/angular-highlightjs.min.js',
'public/lib/pixi/bin/pixi.js',
'public/3rd/particle-engine.js',
'public/3rd/simplexnoise.js',
'public/3rd/moments.js',
'public/lib/firebase/firebase.js',
'public/lib/angularfire/dist/angularfire.js',
]
},
css: [
'public/modules/**/css/*.css'
],
js: [
'public/config.js',
'public/application.js',
'public/modules/*/*.js',
'public/modules/*/*[!tests]*/*.js'
],
tests: [
'public/lib/angular-mocks/angular-mocks.js',
'public/modules/*/tests/*.js'
]
}
};
|
/**
* Created by lcc3536 on 14-6-6.
*/
cc.ex = cc.ex || {};
(function () {
var list = [];
cc.ex.addStartFunc = function (func) {
list.push(func);
};
cc.ex.onStart = function () {
var len = list.length;
for (var i = 0; i < len; ++i) {
list[i]();
}
};
cc.ex.addStartFunc(function () {
cc.winCenter = cc.p(cc.winSize.width / 2, cc.winSize.height / 2);
});
cc.ex.addStartFunc(function () {
cc.Node.prototype.setRotationEx = function (newRotation) {
this.setRotation((360 - newRotation) % 360);
// this.rotation = (360 - newRotation) % 360;
};
});
})();
|
import React from 'react';
import ArboSimplified from './arbo-simplifield';
import { shallow } from 'enzyme';
import { COMPONENT_TYPE } from 'constants/pogues-constants';
const { QUESTION, SEQUENCE, SUBSEQUENCE, QUESTIONNAIRE } = COMPONENT_TYPE;
const mockEvent = {
preventDefault: () => {},
};
describe('<ArboSimplified />', () => {
const spysetSelectedComponentId = jest.fn();
const props = {
questionnaire: { id: '0' },
components: {
0: {
name: '0',
type: QUESTIONNAIRE,
id: '0',
parent: '',
children: ['1'],
},
1: {
name: '1',
type: SEQUENCE,
id: '1',
parent: '0',
children: ['2', '4', '5'],
},
2: {
name: '2',
type: SUBSEQUENCE,
id: '2',
parent: '1',
children: ['3'],
},
3: { name: '3', type: QUESTION, id: '3', parent: '2', children: [] },
4: { name: '4', type: QUESTION, id: '4', parent: '1', children: [] },
5: { name: '5', type: SUBSEQUENCE, id: '5', parent: '1', children: [] },
},
setSelectedComponentId: spysetSelectedComponentId,
};
test('should render without throwing an error', () => {
const wrapper = shallow(<ArboSimplified {...props} />);
expect(wrapper.is('.arbo-simplifield')).toBe(true);
});
test('should render only one level if no node is selected', () => {
const wrapper = shallow(<ArboSimplified {...props} />);
expect(wrapper.find('.arbo-simplifield').length).toBe(1);
});
test('should render two level if a node is selected', () => {
const wrapper = shallow(<ArboSimplified {...props} />);
wrapper.find('button').at(0).simulate('click', mockEvent);
expect(wrapper.find('.arbo-simplifield').length).toBe(2);
});
test('for a question, should add the questions class', () => {
const wrapper = shallow(<ArboSimplified {...props} />);
wrapper.find('button').at(0).simulate('click', mockEvent);
expect(wrapper.find('.questions').length).toBe(1);
});
test('should call setSelectedComponentId when a node is selected', () => {
spysetSelectedComponentId.mockClear();
const wrapper = shallow(<ArboSimplified {...props} />);
wrapper.find('button').at(1).simulate('click', mockEvent);
expect(spysetSelectedComponentId).toBeCalledWith('1');
});
test('should have an icon for all element with children', () => {
const wrapper = shallow(<ArboSimplified {...props} />);
wrapper.find('button').at(0).simulate('click', mockEvent);
wrapper.find('button').at(1).simulate('click', mockEvent);
expect(wrapper.find('.glyphicon').length).toBe(2);
});
test('should update the icon when we click on the link', () => {
const wrapper = shallow(<ArboSimplified {...props} />);
expect(wrapper.find('button').at(0).hasClass('glyphicon-menu-right')).toBe(
true,
);
wrapper.find('button').at(0).simulate('click', mockEvent);
expect(wrapper.find('button').at(0).hasClass('glyphicon-menu-down')).toBe(
true,
);
});
});
|
function Ship(){
this.x=0;
this.y=0;
this.width=25;
this.hieght=20;
this.rotation=0;
this.showFlame=false;
}
Ship.prototype.draw=function(context){
context.save();
context.translate(this.x,this.y);
context.rotate(this.rotation);
context.lineWidth=1;
context.strokeStyle="#fff";
context.beginPath();
context.moveTo(10,0);
context.lineTo(-10,10);
context.lineTo(-5,0);
context.lineTo(-10,-10);
context.lineTo(10,0);
context.stroke();
if(this.showFlame){
context.beginPath();
context.moveTo(-7.5,-5);
context.lineTo(-15,0);
context.lineTo(-7.5,5);
context.stroke();
}
context.restore();
}
|
export default {
count(state) {
return state.count
},
isOdd(state) {
return state.count%2===0 ? '偶数' : '奇数'
}
}
|
Package.describe({
name: "lifefilm:lf-films",
version: '0.0.4',
summary: 'video template for meteorjs telescope (nova react version)',
git: 'https://github.com/fortunto2/lf-films.git',
documentation: 'README.md'
});
Npm.depends({
// 'formsy-material-ui': '0.4.3',
// flexboxgrid: '6.3.0',
});
Package.onUse( function(api) {
api.versionsFrom("METEOR@1.4");
api.use('mongo', ['client', 'server']);
api.use([
'fourseven:scss@3.8.0_1',
'nova:core@0.27.5-nova',
'nova:base-components@0.27.5-nova',
'nova:posts@0.27.5-nova',
'nova:users@0.27.5-nova',
'nova:comments@0.27.5-nova',
// third-party packages
'lifefilm:videojs@5.10.7',
'lifefilm:react-flexbox-grid@0.9.5',
'ostrio:files@1.6.7',
// 'lifefilm:lf-styles@0.26.4-nova',
// 'materialize:materialize',
// 'std:accounts-material@1.1.0'
]);
api.addFiles([
'lib/modules.js'
], ['client', 'server']);
api.addFiles([
'lib/stylesheets/normalize.min.css',
// 'lib/stylesheets/_breakpoints.scss',
// 'lib/stylesheets/_colors.scss',
// 'lib/stylesheets/_variables.scss',
// 'lib/stylesheets/_global.scss',
// 'lib/stylesheets/_accounts.scss',
// 'lib/stylesheets/_categories.scss',
// 'lib/stylesheets/_cheatsheet.scss',
// 'lib/stylesheets/_comments.scss',
// 'lib/stylesheets/_header.scss',
// 'lib/stylesheets/_forms.scss',
// 'lib/stylesheets/_other.scss',
// 'lib/stylesheets/_posts.scss',
// 'lib/stylesheets/_newsletter.scss',
// 'lib/stylesheets/_users.scss',
'lib/stylesheets/main.scss',
], ['client']);
});
|
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const devMode = process.env.NODE_ENV === 'development';
module.exports = {
entry: {
main: './src/client/index.js',
},
devtool: devMode ? 'cheap-module-eval-source-map' : '',
devServer: {
historyApiFallback: true,
disableHostCheck: true,
port: 8080,
},
mode: process.env.NODE_ENV,
module: {
rules: [
{
test: /\.js$|\.jsx$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.scss$/,
use: [
devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader',
],
},
],
},
resolve: {
extensions: ['.js', '.jsx'],
alias: {
'~': path.resolve(__dirname, 'src'),
},
},
optimization: {
splitChunks: {
chunks: 'all',
},
runtimeChunk: true,
},
plugins: [
new MiniCssExtractPlugin({
filename: devMode
? 'assets/[name].css'
: 'assets/[name].[contenthash].css',
chunkFilename: devMode
? 'assets/[id].css'
: 'assets/[id].[contenthash].css',
}),
new OptimizeCssAssetsPlugin(),
new HtmlWebpackPlugin({
template: './src/index.html',
minify:
process.env.NODE_ENV === 'production'
? {
minifyCSS: true,
collapseWhitespace: true,
removeComments: true,
}
: false,
}),
],
output: {
filename: devMode ? 'assets/[name].js' : 'assets/[name].[chunkhash].js',
publicPath: '/',
path: path.resolve(__dirname, 'dist'),
},
};
|
/*globals define, test, equal, ok, $*/
define(function (require) {
'use strict';
var can = require('can'),
menuView = require('views/menuView'),
domTestLoader = require('tests/helpers/domTestLoader');
domTestLoader.setupTestModule('menuView');
test('views/menuView', function () {
var Control = can.Control.extend({
init: function () {
this.element.append(menuView());
}
}), $viewTests = $('#viewTests'),
control = new Control($viewTests);
ok($viewTests.text(), 'Should be rendered at least 1 char');
ok($viewTests.find("li").size(), 'At least one li block should be rendered');
});
});
|
/*
* grunt-refupdate
* https://github.com/chrisedson/grunt-refupdate
*
* Copyright (c) 2014 Chris Edson
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Project configuration
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
'<%= nodeunit.tests %>'
],
options: {
jshintrc: '.jshintrc'
}
},
// Before generating any new files, remove any previously-created files
clean: {
tests: ['tmp']
},
// Configuration to be run (and then tested)
refupdate: {
single_replace: {
options: {
inputFile: "test/input/single_replace",
regex: /abc([0-9]+)u1d/,
outputFile: "tmp/single_replace"
}
},
multi_replace: {
options: {
inputFile: "test/input/multi_replace",
regex: /abc([0-9]+)u1d/g,
outputFile: "tmp/multi_replace"
}
},
custom_iterator: {
options: {
inputFile: "test/input/custom_iterator",
regex: /cabc([6535]+)xa/,
outputFile: "tmp/custom_iterator",
iterator: 5
}
},
no_output: {
options: {
inputFile: "tmp/temp_input",
regex: /abc([0-9]+)u1d/
}
},
multiple_numbers: {
options: {
inputFile: "test/input/multiple_numbers",
regex: /[0-9]+\.[0-9]+\.([0-9]+)/,
outputFile: "tmp/multiple_numbers"
}
}
},
// Unit tests
nodeunit: {
tests: ['test/*_test.js']
}
});
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
// Create temporary file to overwrite in testing
grunt.registerTask('writeTemp', function() {
grunt.file.write('tmp/temp_input', 'abc1235u1d\n');
});
grunt.registerTask('refupdateTests',
['refupdate:single_replace', 'refupdate:multi_replace', 'refupdate:custom_iterator',
'refupdate:no_output', 'refupdate:multiple_numbers']);
// Whenever the "test" task is run, first clean the "tmp" dir, then run this
// plugin's task(s), then test the result.
grunt.registerTask('test', ['jshint', 'clean', 'writeTemp', 'refupdateTests', 'nodeunit']);
// By default, lint and run all tests.
grunt.registerTask('default', ['test']);
};
|
'use strict';
import {
FmkStore
} from 'components/FmkStore';
import {
Fmk
} from 'components/Fmk';
var moment = require('moment');
export class NewsStore extends FmkStore {
getInitialState() {
this.mm = moment();
return {
picture2: 'images/loading.gif'
};
}
$$ = (startingState, action) => {
Fmk.get('/dsapi/', {
'date': this.mm.format("YYYY-MM-DD")
}, (res) => {
this.changeState(res);
});
}
$news$previous = (startingState, action) => {
if (this.mm) {
this.mm.subtract(1, 'days');
this.$$(startingState, action);
}
}
$news$next = (startingState, action) => {
if (this.mm && moment().diff(this.mm, 'days') > 0) {
this.mm.add(1, 'days');
this.$$(startingState, action);
}
}
}
|
import React, { useCallback, useMemo } from 'react';
import PropTypes from 'prop-types';
import AddressInput from '../AddressInput';
import { addressInputItemBuilder } from '../AddressInputItem';
import usePlacesAutocomplete from '../providers/usePlacesAutocomplete';
import useAtlasClient from '../providers/useAtlasClient';
import { dataHooks } from './constants';
const AtlasAddressInput = ({
baseUrl,
token,
debounceMs,
debounceFn,
onChange,
onClear,
onSelect,
onError,
selectOnSubmit,
optionLayout,
optionPrefix,
optionSuffix,
status: statusProp,
...props
}) => {
const client = useAtlasClient({ baseUrl, token });
const {
predictions,
updatePredictions,
clearPredictions,
loading,
} = usePlacesAutocomplete({ client, debounceMs, debounceFn, onError });
// If not loading, show the status passed from props
const status = loading ? 'loading' : statusProp;
const options = useMemo(
() =>
predictions.map(prediction =>
addressInputItemBuilder({
id: prediction.searchId,
mainLabel: prediction.textStructure.mainText,
secondaryLabel: prediction.textStructure.secondaryText,
displayLabel: prediction.description,
optionLayout,
prefix: optionPrefix,
suffix: optionSuffix,
dataHook: dataHooks.item,
}),
),
[predictions, optionLayout, optionPrefix, optionSuffix],
);
const _onChange = useCallback(
event => {
updatePredictions(event.target.value);
onChange && onChange(event);
},
[updatePredictions, onChange],
);
const _onClear = useCallback(() => {
clearPredictions();
onClear && onClear();
}, [clearPredictions, onClear]);
const _onSelect = useCallback(
option => {
const getAddress = () => client.getAddress(option.id);
onSelect && onSelect(option, getAddress);
},
[client, onSelect],
);
// A callback which is called when the user performs a Submit-Action
const _onManualSubmit = useCallback(
inputValue => {
if (selectOnSubmit && onSelect && inputValue) {
const option = addressInputItemBuilder({
id: inputValue,
mainLabel: inputValue,
displayLabel: inputValue,
});
const getAddress = async () => {
// search for address matching input value
const addresses = await client.searchAddresses(inputValue);
// Return first address result
return addresses[0];
};
onSelect(option, getAddress);
}
},
[selectOnSubmit, onSelect, client],
);
return (
<AddressInput
{...props}
options={options}
onChange={_onChange}
onClear={_onClear}
onSelect={_onSelect}
onManuallyInput={_onManualSubmit}
status={status}
/>
);
};
AtlasAddressInput.propTypes = {
/** Custom domain for WixAtlasServiceWeb to retreive predictions from */
baseUrl: PropTypes.string,
/** Authorization token to pass to the Atlas Service */
token: PropTypes.string,
/** Fetch predictions debounce in milliseconds (default: 200) */
debounceMs: PropTypes.number,
/** (callback: Function, debounceMs: number) => Function
* allow passing a custom debounce function (default: lodash debounce) */
debounceFn: PropTypes.func,
/** Applied as data-hook HTML attribute that can be used in the tests */
dataHook: PropTypes.string,
/** A css class to be applied to the component's root element */
className: PropTypes.string,
/** Displays clear button (X) on a non-empty input */
clearButton: PropTypes.bool,
/** The initial input value */
initialValue: PropTypes.string,
/** Controlled mode - value to display */
value: PropTypes.string,
/** When set to true this component is disabled */
disabled: PropTypes.bool,
/** Handler for address selection changes
* @param {DropdownLayoutOption} option selected option
* @param {() => Promise<Address>} getAddress function for retrieving additional place details
*/
onSelect: PropTypes.func,
/** Handler for input changes */
onChange: PropTypes.func,
/** Handler for getting notified upon a clear event, will show the clear button in the component input when passed. */
onClear: PropTypes.func,
/** Handler for input blur */
onBlur: PropTypes.func,
/** Whether to trigger the `onSelect` handler when preforming a Submit-Action (Enter or Tab).
* If set to true, `onSelect` will be called with the following params:
*
* `option`: an option with label set to input value
*
* `getAddress`: function for retrieving additional place details
* uses Atlas's search function to return the closest result to the input value
*
* This is useful when looking for locations for which Atlas does not give suggestions - for example: Apartment/Apt */
selectOnSubmit: PropTypes.bool,
/** Handler for prediction fetching errors
* returns an error object containing: {
* @property {number} httpStatus error http status
* }
* you can read these [guidelines](https://bo.wix.com/wix-docs/rnd/platformization-guidelines/errors#platformization-guidelines_errors_errors)
* to learn about the meaning of each error status
*/
onError: PropTypes.func,
/** Shows a status indication, will mostly be used for “loading” indication upon async request calls. */
status: PropTypes.oneOf(['loading', 'error', 'warning']),
/** The status message to display when hovering the status icon, if not given or empty there will be no tooltip */
statusMessage: PropTypes.node,
/** Border type */
border: PropTypes.oneOf(['standard', 'round', 'bottomLine']),
/** Specifies the size of the input */
size: PropTypes.oneOf(['small', 'medium', 'large']),
/** Placeholder to display */
placeholder: PropTypes.string,
/** Text to show in dropdown when no results found */
noResultsText: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
/** Option: Sets the layout of `mainLabel` and `secondaryLabel`. The possible options can be either side by side: `single-line` or double lined: `double-line`*/
optionLayout: PropTypes.oneOf(['single-line', 'double-line']),
/** Will show the provided node as the option prefix. */
optionPrefix: PropTypes.node,
/** Will show the provided node as the option suffix. */
optionSuffix: PropTypes.node,
};
export default AtlasAddressInput;
|
'use strict';
var path = require('path');
var fs = require('fs');
var extend = require('extend');
var RSVP = require('rsvp');
var findByName = require('./find-by-name');
function config(options) {
var relativePath = options.configPath || path.join('config', 'ember-try.js');
var configFile = path.join(options.project.root, relativePath);
var configData;
if (fs.existsSync(configFile)) {
configData = require(configFile);
if (typeof configData === 'function') {
configData = configData(options.project);
}
}
if (configData && configData.scenarios && !configData.useVersionCompatibility && !options.versionCompatibility) {
return RSVP.resolve(configData);
}
var versionCompatibility = options.versionCompatibility || versionCompatibilityFromPackageJSON(options.project.root);
if (versionCompatibility) {
// Required lazily to improve startup speed.
var autoScenarioConfigForEmber = require('ember-try-config');
return autoScenarioConfigForEmber({versionCompatibility: versionCompatibility, project: options.project}).then(function(autoConfig) {
return mergeAutoConfigAndConfigFileData(autoConfig, configData);
});
} else {
return RSVP.resolve(defaultConfig());
}
}
module.exports = config;
function mergeAutoConfigAndConfigFileData(autoConfig, configData) {
configData = configData || {};
configData.scenarios = configData.scenarios || [];
var conf = extend({}, autoConfig, configData);
var overriddenScenarios = autoConfig.scenarios.map(function(scenario) {
var overriddenScenario = findByName(configData.scenarios, scenario.name);
return extend({}, scenario, overriddenScenario);
});
var additionalScenarios = configData.scenarios.filter(function(scenario) {
return !findByName(autoConfig.scenarios, scenario.name);
});
conf.scenarios = [].concat(overriddenScenarios, additionalScenarios);
return conf;
}
function versionCompatibilityFromPackageJSON(root) {
var packageJSONFile = path.join(root, 'package.json');
if (fs.existsSync(packageJSONFile)) {
var packageJSON = JSON.parse(fs.readFileSync(packageJSONFile));
return packageJSON['ember-addon'] ? packageJSON['ember-addon'].versionCompatibility : null;
}
}
function defaultConfig() {
return {
scenarios: [
{
name: 'default',
bower: {
dependencies: { } /* No dependencies needed as the
default is already specified in
the consuming app's bower.json */
}
},
{
name: 'ember-release',
bower: {
dependencies: {
ember: 'release'
}
}
},
{
name: 'ember-beta',
bower: {
dependencies: {
ember: 'beta'
}
}
},
{
name: 'ember-canary',
bower: {
dependencies: {
ember: 'canary'
}
}
}
]
};
}
// Used for internal testing purposes.
module.exports._defaultConfig = defaultConfig;
|
import test from 'ava';
import delay from 'delay';
import inRange from 'in-range';
import timeSpan from './index.js';
test('main', async t => {
const end = timeSpan();
await delay(100);
t.true(inRange(end(), {start: 80, end: 120}));
t.true(inRange(end.rounded(), {start: 80, end: 120}));
t.true(inRange(end.seconds(), {start: 0.08, end: 0.12}));
// TODO: Remove `Number()` when https://github.com/sindresorhus/in-range/issues/5 is fixed.
t.true(inRange(Number(end.nanoseconds()), {start: 80000000, end: 120000000}));
});
|
'use strict';
/* jshint -W098 */
angular.module('mean.checkout').controller('CheckoutController', ['$scope', '$http', '$location', 'Global', 'Checkout', 'Quartos',
function($scope, $http, $location, Global, Checkout, Quartos) {
$scope.global = Global;
$scope.package = {
name: 'checkout'
};
$scope.params = {
idQuarto: localStorage.getItem('idQuarto'),
idUsuario: $scope.global.user._id,
dateStart: localStorage.getItem('dateStart'),
dateEnd: localStorage.getItem('dateEnd'),
room: {}
};
$scope.reservation = {
date_in: localStorage.getItem('dateStart'),
date_out: localStorage.getItem('dateEnd'),
client: $scope.global.user._id,
value: 0
};
// Calculate the total reservation price
var calcReservationPrice = function (dailyValue, dateStart, dateEnd) {
dateStart = new Date(dateStart);
dateEnd = new Date(dateEnd);
return dailyValue * Math.floor((dateEnd.getTime()-dateStart.getTime())/(1000*60*60*24)) * 0.1;
};
// Get room information
var findQuarto = function() {
Quartos.get({
quartoId: $scope.params.idQuarto
}, function(quarto) {
$scope.params.room = quarto;
$scope.reservation.value = calcReservationPrice($scope.params.room.daily_price, $scope.reservation.date_in, $scope.reservation.date_out);
});
};
findQuarto();
// Submit the form
$scope.reservar = function () {
// Make the payment
var confirmPayment = confirm('Deseja continuar com o pagamento?');
// var reserve;
if (confirmPayment) {
// Send register request
$http.put('/api/reserva', {
reservation: $scope.reservation,
roomId: $scope.params.idQuarto,
daily_value: $scope.params.room.daily_price
})
.success(function(test) {
// TODO: Send request to Financial group
// groupUrl =
// $http.post('', {
// })
$location.url('/');
})
.error(function(error) {
// Error: authentication failed
$location.url('/');
});
} else {
$location.url('/quartos');
}
};
}
]);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.