prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>extglyde.js<|end_file_name|><|fim▁begin|>// extglyde
//
// Glyde Glue Plugin
// (c)2015 by Cylexia, All Rights Reserved
//
// Version: 1.15.0625
//
// MIT License
var ExtGlyde = {
GLUE_STOP_ACTION: -200,
plane: null, // Canvas
resources: null,
styles: null,
buttons: null,
keys: null,
button_sequence: [],
timers: null,
timer_manager: null,
action: "",
action_params: "",
resume_label: "",
last_action_id: "",
window_title: "",
window_width: -1,
window_height: -1,
background_colour: "#fff",
_inited: false,
init: function( canvas, filemanager ) {
"use strict";
if( !ExtGlyde._inited ) {
ExtGlyde.plane = canvas;
ExtGlyde.reset();
ExtGlyde._inited = true;
return true;
}
return false;
},
reset: function() {
ExtGlyde.clearUI();
ExtGlyde.resources = null;
ExtGlyde.styles = null;
ExtGlyde.timers = null;
ExtGlyde.last_action_id = "";
ExtGlyde.window_title = "";
ExtGlyde.window_width = -1;
ExtGlyde.window_height = -1;
ExtGlyde.background_colour = "#fff";
},
setSize: function( w, h ) {
ExtGlyde.window_width = w;
ExtGlyde.window_height = h;
ExtGlyde.plane.width = w;//(w + "px");
ExtGlyde.plane.height = h;//(h + "px");
ExtGlyde._drawRect( ExtGlyde.getBitmap(), {
x: 0, y: 0,
width: w, height: h,
colour: ExtGlyde.background_colour
}, true );
},
getWindowTitle: function() {
return ExtGlyde.window_title;
},
getWindowWidth: function() {
return ExtGlyde.window_width;
},
getWindowHeight: function() {
return ExtGlyde.window_height;
},
/**
* If set then the script requests that the given action be performed then resumed from
* getResumeLabel(). This is cleared once read
* @return the action or null
*/
getAction: function() {
var o = ExtGlyde.action;
ExtGlyde.action = null;
return o;
},
getActionParams: function() {
return ExtGlyde.action_params;
},
/**
* Certain actions call back to the runtime host and need to be resumed, resume from this label
* This is cleared once read
* @return the label
*/
getResumeLabel: function() {
var o = ExtGlyde.resume_label;
ExtGlyde.resume_label = null;
return o;
},
/**
* The bitmap the drawing operations use
* @return
*/
getBitmap: function() {
return ExtGlyde.plane.getContext( "2d" );
},
/**
* Called when this is attached to a {@link com.cylexia.mobile.lib.glue.Glue} instance
*
* @param g the instance being attached to
*/
glueAttach: function( f_plugin, f_glue ) {
window.addEventListener( "keydown", function( e ) {
ExtGlyde._keyDownHandler( f_glue, (e || window.event) );
} );
window.addEventListener( "keypress", function( e ) {
ExtGlyde._keyPressHandler( f_glue, (e || window.event) );
} );
},
/**
* Called to execute a glue command
*
* @param w the command line. The command is in "_"
* @param vars the current Glue variables map
* @return 1 if the command was successful, 0 if it failed or -1 if it didn't belong to this
* plugin
*/
glueCommand: function( glue, w, vars ) {
var cmd = Dict.valueOf( w, "_" );
if( cmd && cmd.startsWith( "f." ) ) {
var wc = Dict.valueOf( w, cmd );
cmd = cmd.substring( 2 );
if( (cmd == "setwidth") || (cmd == "setviewwidth") ) {
return ExtGlyde.setupView( w );
} else if( cmd == "settitle" ) {
return ExtGlyde.setTitle( wc, w );
} else if( cmd == "doaction" ) {
return ExtGlyde.doAction( wc, w );
} else if( (cmd == "clear") || (cmd == "clearview") ) {
ExtGlyde.clearUI();
} else if( cmd == "loadresource" ) {
return ExtGlyde.loadResource( glue, wc, Dict.valueOf( w, "as" ) );
} else if( cmd == "removeresource" ) {
if( ExtGlyde.resources !== null ) {
delete ExtGlyde.resources[wc];
}
} else if( cmd == "setstyle" ) {
ExtGlyde.setStyle( wc, w );
} else if( cmd == "getlastactionid" ) {
Dict.set( vars, Dict.valueOf( w, "into" ), ExtGlyde.last_action_id );
} else if( cmd == "onkey" ) {
if( ExtGlyde.keys === null ) {
ExtGlyde.keys = Dict.create();
}
var ke = Dict.create();
Dict.set( ke, "label", Dict.valueOf( w, "goto" ) );
Dict.set( ke, "id", Dict.valueOf( w, "useid" ) );
Dict.set( ExtGlyde.keys, wc, ke );
} else if( cmd == "starttimer" ) {
ExtGlyde._startTimer( glue, wc, Dict.intValueOf( w, "interval" ), Dict.valueOf( w, "ontickgoto" ) );
} else if( cmd == "stoptimer" ) {
ExtGlyde._stopTimer( wc );
} else if( cmd == "stopalltimers" ) {
ExtGlyde._stopTimer( "" );
} else if( cmd == "drawas" ) {
ExtGlyde.drawAs( wc, w );
} else if( cmd == "writeas" ) {
// TODO: colour
return ExtGlyde.writeAs( wc, w );
} else if( (cmd == "markas") || (cmd == "addbutton") ) {
return ExtGlyde.markAs( wc, w );
} else if( cmd == "paintrectas" ) {
return ExtGlyde.paintRectAs( wc, w, false );
} else if( cmd == "paintfilledrectas" ) {
return ExtGlyde.paintRectAs( wc, w, true );
} else if( cmd == "exit" ) {
if( chrome && chrome.app ) {
chrome.app.window.current().close();
} else if( window ) {
window.close();
}
return Glue.PLUGIN_DONE_EXIT_ALL;
} else {
return -1;
}
return 1;
}
return 0;
},
getLabelForButtonAt: function( i_x, i_y ) {
if( ExtGlyde.buttons !== null ) {
for( var i = 0; i < ExtGlyde.button_sequence.length; i++ ) {
var id = ExtGlyde.button_sequence[i];
var btn = ExtGlyde.buttons[id];
var r = ExtGlyde.Button.getRect( btn );
if( ExtGlyde.Rect.containsPoint( r, i_x, i_y ) ) {
ExtGlyde.last_action_id = id;
return ExtGlyde.Button.getLabel( btn );
}
}
}
return null;
},
/**
* Get the id of the button at the given index
* @param index the index of the button
* @return the id or null if the index is out of bounds
*/
getButtonIdAtIndex: function( index ) {
if( ExtGlyde.button_sequence.length > 0 ) {
if( (index >= 0) && (index < ExtGlyde.button_sequence.length) ) {
return ExtGlyde.button_sequence[index];
}
}
return null;
},<|fim▁hole|> * Get the rect of the given indexed button
* @param index the button index
* @return the rect as ExtGlyde.Rect or null if index is out of bounds
*/
getButtonRectAtIndex: function( index ) {
var id = ExtGlyde.getButtonIdAtIndex( index );
if( id !== null ) {
return ExtGlyde.Button.getRect( ExtGlyde.buttons[id] );
}
return null;
},
/**
* Return the label for the given indexed button. Also sets the lastActionId value
* @param index the index
* @return the label or null if index is out of bounds
*/
getButtonLabelAtIndex: function( index ) {
if( (index >= 0) && (index < ExtGlyde.button_sequence.length) ) {
var id = button_sequence[index];
if( id !== null ) {
ExtGlyde.last_action_id = id;
return ExtGlyde.Button.getLabel( buttons[id] );
}
}
return null;
},
getButtonCount: function() {
return ExtGlyde.button_sequence.length;
},
/**
* Add a definition to the (lazily created) styles map. Note, the complete string is stored
* so beware that keys like "_" and "f.setstyle" are added too
* @param name string: the name of the style
* @param data map: the complete arguments string
*/
setStyle: function( name, data ) {
if( ExtGlyde.styles === null ) {
ExtGlyde.styles = Dict.create();
}
Dict.set( ExtGlyde.styles, name, data );
},
setupView: function( w ) {
if( Dict.containsKey( w, "backgroundcolour" ) ) {
ExtGlyde.background_colour = Dict.valueOf( w, "backgroundcolour" );
} else {
this.background = "#fff";
}
ExtGlyde.setSize( Dict.intValueOf( w, Dict.valueOf( w, "_" ) ), Dict.intValueOf( w, "height" ) );
return true;
},
setTitle: function( wc, w ) {
var tb_title = _.e( "tb_title" );
if( tb_title ) {
tb_title.removeChild( tb_title.childNodes[0] );
_.at( tb_title, wc );
}
if( window ) {
window.title = wc;
document.title = wc;
}
_.e( "windowtitlebar" ).style["display"] = (wc ? "block" : "none");
return 1;
},
clearUI: function() {
ExtGlyde.button_sequence = [];
if( ExtGlyde.buttons !== null ) {
Dict.delete( ExtGlyde.buttons );
}
ExtGlyde.buttons = Dict.create();
if( ExtGlyde.keys !== null ) {
Dict.delete( ExtGlyde.keys );
}
ExtGlyde.keys = Dict.create();
ExtGlyde.setSize( ExtGlyde.window_width, ExtGlyde.window_height );
},
doAction: function( s_action, d_w ) {
"use strict";
ExtGlyde.action = s_action;
ExtGlyde.action_params = Dict.valueOf( d_w, "args", Dict.valueOf( d_w, "withargs" ) );
var done_label = Dict.valueOf( d_w, "ondonegoto" );
ExtGlue.resume_label = (
done_label + "\t" +
Dict.valueOf( d_w, "onerrorgoto", done_label ) + "\t" +
Dict.valueOf( d_w, "onunsupportedgoto", done_label )
);
return ExtFrontEnd.GLUE_STOP_ACTION; // expects labels to be DONE|ERROR|UNSUPPORTED
},
// TODO: this should use a rect and alignment options along with colour support
writeAs: function( s_id, d_args ) {
"use strict";
ExtGlyde.updateFromStyle( d_args );
var text = Dict.valueOf( d_args, "value" );
var rect = ExtGlyde.Rect.createFromCommandArgs( d_args );
var x = ExtGlyde.Rect.getLeft( rect );
var y = ExtGlyde.Rect.getTop( rect );
var rw = ExtGlyde.Rect.getWidth( rect );
var rh = ExtGlyde.Rect.getHeight( rect );
var size = Dict.intValueOf( d_args, "size", 2 );
var thickness = Dict.intValueOf( d_args, "thickness", 1 );
var tw = (VecText.getGlyphWidth( size, thickness ) * text.length);
var th = VecText.getGlyphHeight( size, thickness );
var tx, ty;
if( rw > 0 ) {
var align = Dict.valueOf( d_args, "align", "2" );
if( (align == "2") || (align == "centre") ) {
tx = (x + ((rw - tw) / 2));
} else if( (align == "1" ) || (align == "right") ) {
tx = (x + (rw - tw));
} else {
tx = x;
}
} else {
rw = tw;
tx = x;
}
if( rh > 0 ) {
ty = (y + ((rh - th) / 2));
} else {
rh = th;
ty = y;
}
VecText.drawString( ExtGlyde.getBitmap(), text, Dict.valueOf( d_args, "colour", "#000" ), tx, ty, size, thickness, (thickness + 1) );
rect = ExtGlyde.Rect.create( x, y, rw, rh ); // Dict: ExtGlyde.Rect
return ExtGlyde.buttonise( s_id, rect, d_args );
},
drawAs: function( s_id, d_args ) {
ExtGlyde.updateFromStyle( d_args );
var rect = ExtGlyde.Rect.createFromCommandArgs( d_args );
var rid = Dict.valueOf( d_args, "id", Dict.valueOf( d_args, "resource" ) );
if( ExtGlyde.resources !== null ) {
var b = rid.indexOf( '.' );
if( b > -1 ) {
var resid = rid.substring( 0, b );
var imgid = rid.substring( (b + 1) );
var keys = Dict.keys( ExtGlyde.resources );
for( var i = 0; i < keys.length; i++ ) {
var imgmap = Dict.valueOf( ExtGlyde.resources, keys[i] ); // imgmap: ExtGlyde.ImageMap
var x = ExtGlyde.Rect.getLeft( rect );
var y = ExtGlyde.Rect.getTop( rect );
if( ExtGlyde.ImageMap.drawToCanvas( imgmap, imgid, ExtGlyde.getBitmap(), x, y ) ) {
var maprect = ExtGlyde.ImageMap.getRectWithId( imgmap, imgid );
var imgrect = ExtGlyde.Rect.create(
x, y,
ExtGlyde.Rect.getWidth( maprect ), ExtGlyde.Rect.getHeight( maprect )
);
return ExtGlyde.buttonise( s_id, imgrect, d_args );
}
}
}
}
return false;
},
markAs: function( s_id, d_args ) {
ExtGlyde.updateFromStyle( d_args );
return ExtGlyde.buttonise(
s_id,
ExtGlyde.Rect.createFromCommandArgs( d_args ),
m_args
);
},
paintRectAs: function( s_id, d_args, b_filled ) {
ExtGlyde.updateFromStyle( d_args );
var rect = ExtGlyde.Rect.createFromCommandArgs( d_args );
var d = Dict.create();
Dict.set( d, "rect", rect );
Dict.set( d, "colour", Dict.valueOf( d_args, "colour", "#000" ) );
ExtGlyde._drawRect( ExtGlyde.getBitmap(), d, b_filled );
return ExtGlyde.buttonise( s_id, rect, d_args );
},
buttonise: function( s_id, d_rect, d_args ) {
"use strict";
if( Dict.containsKey( d_args, "border" ) ) {
var d = Dict.create();
Dict.set( d, "rect", d_rect );
Dict.set( d, "colour", Dict.valueOf( d_args, "colour", "#000" ) );
ExtGlyde._drawRect( ExtGlyde.getBitmap(), d );
}
if( Dict.containsKey( d_args, "onclickgoto" ) ) {
return ExtGlyde.addButton( s_id, d_rect, Dict.valueOf( d_args, "onclickgoto" ) );
} else {
return true;
}
},
addButton: function( s_id, d_rect, s_label ) {
if( ExtGlyde.buttons === null ) {
ExtGlyde.buttons = Dict.create();
ExtGlyde.button_sequence = [];
}
if( !Dict.containsKey( ExtGlyde.buttons, s_id ) ) {
Dict.set( ExtGlyde.buttons, s_id, ExtGlyde.Button.createFromRect( d_rect, s_label ) );
ExtGlyde.button_sequence.push( s_id );
return true;
}
return false;
},
updateFromStyle: function( d_a ) {
"use strict";
if( (ExtGlyde.styles === null) || (ExtGlyde.styles.length === 0) ) {
return;
}
if( Dict.containsKey( d_a, "style" ) ) {
var style = Dict.valueOf( styles, Dict.valueOf( d_a, "style" ) );
var keys = Dict.keys( style );
for( var i = 0; i < keys.length; i++ ) {
var k = keys[i];
if( !Dict.containsKey( d_a, k ) ) {
Dict.set( d_a, k, Dict.valueOf( style, keys[i] ) );
}
}
}
},
loadResource: function( o_glue, s_src, s_id ) {
if( ExtGlyde.resources === null ) {
ExtGlyde.resources = Dict.create();
}
if( Dict.containsKey( ExtGlyde.resources, s_id ) ) {
// deallocate
}
// resources can be replaced using the same ids
var data = GlueFileManager.readText( s_src );
Dict.set( ExtGlyde.resources, s_id, ExtGlyde.ImageMap.create( data ) );
return true;
},
_drawRect: function( o_context, d_def, b_filled ) {
"use strict";
var x, y, w, h;
if( Dict.containsKey( d_def, "rect" ) ) {
var r = Dict.dictValueOf( d_def, "rect" );
x = ExtGlyde.Rect.getLeft( r );
y = ExtGlyde.Rect.getTop( r );
w = ExtGlyde.Rect.getWidth( r );
h = ExtGlyde.Rect.getHeight( r );
} else {
x = Dict.intValueOf( d_def, "x" );
y = Dict.intValueOf( d_def, "y" );
w = Dict.intValueOf( d_def, "width" );
h = Dict.intValueOf( d_def, "height" );
}
if( b_filled ) {
o_context.fillStyle = Dict.valueOf( d_def, "colour", "#000" );
o_context.fillRect( x, y, w, h );
} else {
o_context.fillStyle = "none";
o_context.strokeStyle = Dict.valueOf( d_def, "colour", "#000" );
o_context.lineWidth = 1;
o_context.strokeRect( x, y, w, h );
}
},
_timerFired: function() {
if( ExtGlyde.timers ) {
for( var id in ExtGlyde.timers ) {
var t = ExtGlyde.timers[id];
t["count"]--;
if( t["count"] === 0 ) {
t["count"] = t["reset"];
Glue.run( t["glue"], t["label"] );
}
}
}
},
_startTimer: function( o_glue, s_id, i_tenths, s_label ) {
if( !ExtGlyde.timers ) {
ExtGlyde.timer_manager = window.setInterval( ExtGlyde._timerFired, 100 ); // install our timer
ExtGlyde.timers = {};
}
var t = {
"glue": o_glue,
"count": i_tenths,
"reset": i_tenths,
"label": s_label
};
ExtGlyde.timers[s_id] = t;
},
_stopTimer: function( s_id ) {
if( !ExtGlyde.timers ) {
return;
}
if( s_id ) {
if( ExtGlyde.timers[s_id] ) {
delete ExtGlyde.timers[s_id];
}
if( ExtGlyde.timers.length > 0 ) {
return;
}
}
// out of timers or requested that we stop them all
if( ExtGlyde.timer_manager ) {
window.clearInterval( ExtGlyde.timer_manager );
ExtGlyde.timer_manager = null;
}
ExtGlyde.timers = null;
},
// keyboard handling
_keyDownHandler: function( f_glue, e ) {
e = (e || window.event);
var kmap = {
37: "direction_left", 38: "direction_up", 39: "direction_right",
40: "direction_down", 27: "escape", 9: "tab", 13: "enter",
8: "backspace", 46: "delete", 112: "f1", 113: "f2", 114: "f3", 115: "f4",
116: "f5", 117: "f6", 118: "f7", 119: "f8", 120: "f9", 121: "f10",
122: "f11", 123: "f12"
};
if( e.keyCode in kmap ) {
if( ExtGlyde._notifyKeyPress( f_glue, kmap[e.keyCode] ) ) {
e.preventDefault();
}
}
},
_keyPressHandler: function( f_glue, e ) {
e = (e || window.event );
if( ExtGlyde._notifyKeyPress( f_glue, String.fromCharCode( e.charCode ) ) ) {
e.preventDefault();
}
},
_notifyKeyPress: function( f_glue, s_key ) { // boolean
if( ExtGlyde.keys && (s_key in ExtGlyde.keys) ) {
var ke = ExtGlyde.keys[s_key];
ExtGlyde.last_action_id = Dict.valueOf( ke, "id" );
Glue.run( f_glue, Dict.valueOf( ke, "label" ) );
return true;
}
return false;
},
/**
* Stores a button
*/
Button: {
create: function( i_x, i_y, i_w, i_h, s_label ) { // Dict: ExtGlyde.Button
return Button.createFromRect(
ExtGlyde.Rect.create( i_x, i_y, i_w, i_h ),
s_label
);
},
createFromRect: function( d_rect, s_label ) { // Dict: ExtGlyde.Button
var d = Dict.create();
Dict.set( d, "rect", d_rect );
Dict.set( d, "label", s_label );
return d;
},
getLabel: function( d_button ) {
return d_button.label;
},
getRect: function( d_button ) {
return d_button.rect;
}
},
/**
* Access to a Rect
*/
Rect: {
create: function( i_x, i_y, i_w, i_h ) { // Dict: ExtGlyde.Rect
var r = Dict.create();
Dict.set( r, "x", i_x );
Dict.set( r, "y", i_y );
Dict.set( r, "w", i_w );
Dict.set( r, "h", i_h );
return r;
},
createFromCommandArgs: function( d_args ) { // Dict: ExtGlyde.Rect
"use strict";
var x = Dict.intValueOf( d_args, "x", Dict.intValueOf( d_args, "atx" ) );
var y = Dict.intValueOf( d_args, "y", Dict.intValueOf( d_args, "aty" ) );
var w = Dict.intValueOf( d_args, "width" );
var h = Dict.intValueOf( d_args, "height" );
return ExtGlyde.Rect.create( x, y, w, h );
},
containsPoint: function( d_rect, i_x, i_y ) {
var rx = Dict.intValueOf( d_rect, "x" );
var ry = Dict.intValueOf( d_rect, "y" );
if( (i_x >= rx) && (i_y >= ry) ) {
if( (i_x < (rx + Dict.intValueOf( d_rect, "w" ))) && (i_y < (ry + Dict.intValueOf( d_rect, "h" ))) ) {
return true;
}
}
return false;
},
getLeft: function( o_rect ) {
return o_rect.x;
},
getTop: function( o_rect ) {
return o_rect.y;
},
getWidth: function( o_rect ) {
return o_rect.w;
},
getHeight: function( o_rect ) {
return o_rect.h;
},
getRight: function( o_rect ) {
return (o_rect.x + o_rect.w);
},
getBottom: function( o_rect ) {
return (o_rect.y + o_rect.h);
}
},
/**
* Processes a .map source loading the image named in it or the specified image
* @returns a Dict for use with ExtGlyde.ImageMap
*/
ImageMap: {
create: function( s_mapdata ) { // Dict: ImageMap
var im = Dict.create();
var im_rects = Dict.create();
var e, i;
var key, value;
var bmpsrc;
while( (i = s_mapdata.indexOf( ";" )) > -1 ) {
var line = s_mapdata.substr( 0, i ).trim();
s_mapdata = s_mapdata.substr( (i + 1) );
e = line.indexOf( "=" );
if( e > -1 ) {
key = line.substring( 0, e );
value = line.substring( (e + 1) );
if( key.startsWith( "." ) ) {
if( key == ".img" ) {
if( !bmpsrc ) {
bmpsrc = value;
}
}
} else {
Dict.set( im_rects, key, ExtGlyde.ImageMap._decodeRect( value ) );
}
}
}
Dict.set( im, "image", ExtGlyde.ImageMap._loadBitmap( bmpsrc ) );
Dict.set( im, "rects", im_rects );
return im;
},
getRectWithId: function( o_imap, s_id ) { // Dict: ExtGlyde.Rect
var d_rects = Dict.dictValueOf( o_imap, "rects" );
return Dict.dictValueOf( d_rects, s_id );
},
drawToCanvas: function( o_imap, s_id, o_context, i_x, i_y ) { "use strict";
var src = ExtGlyde.ImageMap.getRectWithId( o_imap, s_id ); // Dict: ExtGlyde.Rect
if( src !== null ) {
var w = ExtGlyde.Rect.getWidth( src );
var h = ExtGlyde.Rect.getHeight( src );
o_context.drawImage(
o_imap.image,
ExtGlyde.Rect.getLeft( src ), ExtGlyde.Rect.getTop( src ), w, h,
i_x, i_y, w, h
);
return true;
}
return false;
},
_loadBitmap: function( s_src ) {
var data = GlueFileManager.readBinary( s_src );
if( data !== null ) {
return data;
}
// show an error some how
return null;
},
_decodeRect: function( s_e ) { // Dict
if( s_e.charAt( 1 ) == ':' ) {
var l = (s_e.charCodeAt( 0 ) - 48);
var i = 2, x, y, w, h;
x = ExtGlyde.ImageMap.toInt( s_e.substring( i, (i + l) ) );
i += l;
y = ExtGlyde.ImageMap.toInt( s_e.substring( i, (i + l) ) );
i += l;
w = ExtGlyde.ImageMap.toInt( s_e.substring( i, (i + l) ) );
i += l;
h = ExtGlyde.ImageMap.toInt( s_e.substring( i ) );
return ExtGlyde.Rect.create( x, y, w, h );
}
return null;
},
toInt: function( s_v ) {
var n = parseInt( s_v );
if( !isNaN( n ) ) {
return n;
}
return 0;
}
}
};<|fim▁end|>
|
/**
|
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from cms.utils.urlutils import admin_reverse
from django.core.urlresolvers import reverse
from cms.utils import get_language_from_request
from cms.utils.compat.dj import python_2_unicode_compatible
from django.db import models
from cms.models.fields import PlaceholderField
from hvad.models import TranslatableModel, TranslatedFields
def dynamic_placeholder_1(instance):
return instance.char_1
def dynamic_placeholder_2(instance):
return instance.char_2
@python_2_unicode_compatible
class Example1(models.Model):
char_1 = models.CharField(u'char_1', max_length=255)
char_2 = models.CharField(u'char_2', max_length=255)
char_3 = models.CharField(u'char_3', max_length=255)
char_4 = models.CharField(u'char_4', max_length=255)
date_field = models.DateField(null=True)
placeholder = PlaceholderField('placeholder')
static_admin_url = ''
<|fim▁hole|> return self.char_1
def __str__(self):
return self.char_1
def get_absolute_url(self):
return reverse("example_detail", args=(self.pk,))
def set_static_url(self, request):
language = get_language_from_request(request)
if self.pk:
self.static_admin_url = admin_reverse('placeholderapp_example1_edit_field', args=(self.pk, language))
return self.pk
def dynamic_url(self, request):
language = get_language_from_request(request)
return admin_reverse('placeholderapp_example1_edit_field', args=(self.pk, language))
class TwoPlaceholderExample(models.Model):
char_1 = models.CharField(u'char_1', max_length=255)
char_2 = models.CharField(u'char_2', max_length=255)
char_3 = models.CharField(u'char_3', max_length=255)
char_4 = models.CharField(u'char_4', max_length=255)
placeholder_1 = PlaceholderField('placeholder_1', related_name='p1')
placeholder_2 = PlaceholderField('placeholder_2', related_name='p2')
class DynamicPlaceholderSlotExample(models.Model):
char_1 = models.CharField(u'char_1', max_length=255)
char_2 = models.CharField(u'char_2', max_length=255)
placeholder_1 = PlaceholderField(dynamic_placeholder_1, related_name='dynamic_pl_1')
placeholder_2 = PlaceholderField(dynamic_placeholder_2, related_name='dynamic_pl_2')
class CharPksExample(models.Model):
char_1 = models.CharField(u'char_1', max_length=255)
slug = models.SlugField(u'char_1', max_length=255, primary_key=True)
placeholder_1 = PlaceholderField('placeholder_1', related_name='charpk_p1')
@python_2_unicode_compatible
class MultilingualExample1(TranslatableModel):
translations = TranslatedFields(
char_1=models.CharField(u'char_1', max_length=255),
char_2=models.CharField(u'char_2', max_length=255),
)
placeholder_1 = PlaceholderField('placeholder_1')
def __str__(self):
return self.char_1
def get_absolute_url(self):
return reverse("detail_multi", args=(self.pk,))<|fim▁end|>
|
def __init__(self, *args, **kwargs):
super(Example1, self).__init__(*args, **kwargs)
def callable_item(self, request):
|
<|file_name|>scanner.rs<|end_file_name|><|fim▁begin|>// The MIT License (MIT)
//
// Copyright (c) 2017 Doublify Technologies
//
// 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.
extern crate doublify_toolkit;
use doublify_toolkit::filtering::{Kind, Token, scan};
#[test]
fn scan_raw_query_test_1() {
let raw_query = "subject:{'fdhadzh' 'goodmind'}";
let expected = vec![Token::new(Kind::Identifier, "subject"),
Token::new(Kind::Colon, ":"),
Token::new(Kind::Curly, "{"),
Token::new(Kind::Identifier, "'fdhadzh'"),
Token::new(Kind::Identifier, "'goodmind'"),
Token::new(Kind::Curly, "}")];
let wanted = scan(raw_query);
assert_eq!(expected, wanted);
}
#[test]
fn scan_raw_query_test_2() {
let raw_query = "languages:(\"rust\" \"python\" \"typescript\") is:stable";
let expected = vec![Token::new(Kind::Identifier, "languages"),
Token::new(Kind::Colon, ":"),
Token::new(Kind::Parentheses, "("),
Token::new(Kind::Identifier, "\"rust\""),
Token::new(Kind::Identifier, "\"python\""),
Token::new(Kind::Identifier, "\"typescript\""),
Token::new(Kind::Parentheses, ")"),
Token::new(Kind::Identifier, "is"),
Token::new(Kind::Colon, ":"),<|fim▁hole|>
let wanted = scan(raw_query);
assert_eq!(expected, wanted);
}<|fim▁end|>
|
Token::new(Kind::Identifier, "stable")];
|
<|file_name|>blueprint_templates.py<|end_file_name|><|fim▁begin|>from flask_restful import marshal_with, reqparse
from flask import abort, g
from flask import Blueprint as FlaskBlueprint
from flask_restful import fields
from sqlalchemy.orm.session import make_transient
import logging
import uuid
from pebbles.models import db, BlueprintTemplate, Plugin
from pebbles.forms import BlueprintTemplateForm
from pebbles.server import restful
from pebbles.views.commons import auth, requires_group_manager_or_admin
from pebbles.utils import requires_admin, parse_maximum_lifetime
from pebbles.rules import apply_rules_blueprint_templates
blueprint_templates = FlaskBlueprint('blueprint_templates', __name__)
blueprint_template_fields = {
'id': fields.String(attribute='id'),
'name': fields.String,
'is_enabled': fields.Boolean,
'plugin': fields.String,
'config': fields.Raw,
'schema': fields.Raw,
'form': fields.Raw,
'allowed_attrs': fields.Raw,
'blueprint_schema': fields.Raw,
'blueprint_form': fields.Raw,
'blueprint_model': fields.Raw
}
class BlueprintTemplateList(restful.Resource):
@auth.login_required
@requires_group_manager_or_admin
@marshal_with(blueprint_template_fields)
def get(self):
user = g.user
query = apply_rules_blueprint_templates(user)
query = query.order_by(BlueprintTemplate.name)
results = []
for blueprint_template in query.all():
plugin = Plugin.query.filter_by(id=blueprint_template.plugin).first()
blueprint_template.schema = plugin.schema
blueprint_template.form = plugin.form
# Due to immutable nature of config field, whole dict needs to be reassigned.
# Issue #444 in github
blueprint_template_config = blueprint_template.config
blueprint_template_config['name'] = blueprint_template.name
blueprint_template.config = blueprint_template_config
results.append(blueprint_template)
return results
@auth.login_required
@requires_admin
def post(self):
form = BlueprintTemplateForm()
if not form.validate_on_submit():
logging.warn("validation error on create blueprint_template")
return form.errors, 422
blueprint_template = BlueprintTemplate()
blueprint_template.name = form.name.data
blueprint_template.plugin = form.plugin.data
config = form.config.data
config.pop('name', None)
blueprint_template.config = config
try:
validate_max_lifetime_template(config) # Validate the maximum lifetime from config
except ValueError:
timeformat_error = {"timeformat error": "pattern should be [days]d [hours]h [minutes]m"}
return timeformat_error, 422
if isinstance(form.allowed_attrs.data, dict): # WTForms can only fetch a dict
blueprint_template.allowed_attrs = form.allowed_attrs.data['allowed_attrs']
blueprint_template = blueprint_schemaform_config(blueprint_template)
db.session.add(blueprint_template)
db.session.commit()
class BlueprintTemplateView(restful.Resource):
parser = reqparse.RequestParser()
parser.add_argument('disable_blueprints', type=bool)
@auth.login_required
@requires_group_manager_or_admin
@marshal_with(blueprint_template_fields)
def get(self, template_id):
args = {'template_id': template_id}
query = apply_rules_blueprint_templates(g.user, args)
blueprint_template = query.first()
if not blueprint_template:
abort(404)
return blueprint_template
@auth.login_required
@requires_admin
def put(self, template_id):
form = BlueprintTemplateForm()
if not form.validate_on_submit():
logging.warn("validation error on update blueprint_template config")
return form.errors, 422
blueprint_template = BlueprintTemplate.query.filter_by(id=template_id).first()
if not blueprint_template:
abort(404)
blueprint_template.name = form.config.data.get('name') or form.name.data
blueprint_template.plugin = form.plugin.data
config = form.config.data
config.pop('name', None)
blueprint_template.config = config
try:
validate_max_lifetime_template(config) # Validate the maximum lifetime from config
except ValueError:
timeformat_error = {"timeformat error": "pattern should be [days]d [hours]h [minutes]m"}
return timeformat_error, 422
if isinstance(form.allowed_attrs.data, dict): # WTForms can only fetch a dict
blueprint_template.allowed_attrs = form.allowed_attrs.data['allowed_attrs']
blueprint_template = blueprint_schemaform_config(blueprint_template)
args = self.parser.parse_args()
blueprint_template = toggle_enable_template(form, args, blueprint_template)
db.session.add(blueprint_template)
db.session.commit()
class BlueprintTemplateCopy(restful.Resource):
@auth.login_required
@requires_admin
def put(self, template_id):
template = BlueprintTemplate.query.get_or_404(template_id)
db.session.expunge(template)
make_transient(template)
template.id = uuid.uuid4().hex
template.name = format("%s - %s" % (template.name, 'Copy'))
db.session.add(template)
db.session.commit()
def toggle_enable_template(form, args, blueprint_template):
"""Logic for activating and deactivating a blueprint template"""
if form.is_enabled.raw_data:
blueprint_template.is_enabled = form.is_enabled.raw_data[0] # WTForms Issue#451
else:
blueprint_template.is_enabled = False
if args.get('disable_blueprints'):
# Disable all associated blueprints
blueprints = blueprint_template.blueprints
for blueprint in blueprints:
blueprint.is_enabled = False
return blueprint_template
def blueprint_schemaform_config(blueprint_template):
"""Generates config,schema and model objects used in schemaform ui component for blueprints"""
plugin = Plugin.query.filter_by(id=blueprint_template.plugin).first()
schema = plugin.schema
blueprint_schema = {'type': 'object', 'title': 'Comment', 'description': 'Description', 'required': ['name', 'description'], 'properties': {}}
config = blueprint_template.config
blueprint_model = {}
allowed_attrs = blueprint_template.allowed_attrs
blueprint_form = allowed_attrs
allowed_attrs = ['name', 'description'] + allowed_attrs
for attr in allowed_attrs:
blueprint_schema['properties'][attr] = schema['properties'][attr]
if attr in ('name', 'description'):
blueprint_model[attr] = ''
else:
blueprint_model[attr] = config[attr]
blueprint_form = [
{
"key": "name",
"type": "textfield",
"placeholder": "Blueprint name"
},
{
"key": "description",
"type": "textarea",<|fim▁hole|> blueprint_template.blueprint_schema = blueprint_schema
blueprint_template.blueprint_form = blueprint_form
blueprint_template.blueprint_model = blueprint_model
return blueprint_template
def validate_max_lifetime_template(config):
"""Checks if the maximum lifetime has a valid pattern"""
if 'maximum_lifetime' in config:
max_life_str = str(config['maximum_lifetime'])
if max_life_str:
parse_maximum_lifetime(max_life_str)<|fim▁end|>
|
"placeholder": "Blueprint details"
}
] + blueprint_form
|
<|file_name|>AbstractCommunicator.java<|end_file_name|><|fim▁begin|>/*
* An Abstract communicator interface which implements listeners.
*/
/*
Copywrite 2013 Will Winder
This file is part of Universal Gcode Sender (UGS).
UGS is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
UGS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with UGS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.willwinder.universalgcodesender;
import com.willwinder.universalgcodesender.i18n.Localization;
import com.willwinder.universalgcodesender.listeners.SerialCommunicatorListener;
import com.willwinder.universalgcodesender.types.GcodeCommand;
import java.io.IOException;
import java.util.ArrayList;
/**
*
* @author wwinder
*/
public abstract class AbstractCommunicator {
public static String DEFAULT_TERMINATOR = "\r\n";
private String lineTerminator;
protected Connection conn;
// Callback interfaces
ArrayList<SerialCommunicatorListener> commandSentListeners;
ArrayList<SerialCommunicatorListener> commandCompleteListeners;
ArrayList<SerialCommunicatorListener> commConsoleListeners;
ArrayList<SerialCommunicatorListener> commVerboseConsoleListeners;
ArrayList<SerialCommunicatorListener> commRawResponseListener;
private final ArrayList<Connection> connections;
public AbstractCommunicator() {
this.lineTerminator = DEFAULT_TERMINATOR;
this.commandSentListeners = new ArrayList<SerialCommunicatorListener>();
this.commandCompleteListeners = new ArrayList<SerialCommunicatorListener>();
this.commConsoleListeners = new ArrayList<SerialCommunicatorListener>();
this.commVerboseConsoleListeners = new ArrayList<SerialCommunicatorListener>();<|fim▁hole|> // and instantiate them dynamically.
this.connections = new ArrayList<Connection>();
this.addConnectionType(new SerialConnection());
}
final public void addConnectionType(Connection conn) {
this.connections.add(conn);
}
/*********************/
/* Serial Layer API. */
/*********************/
abstract public void setSingleStepMode(boolean enable);
abstract public boolean getSingleStepMode();
abstract public void queueStringForComm(final String input);
abstract public void sendByteImmediately(byte b) throws IOException;
abstract public boolean areActiveCommands();
abstract public void streamCommands();
abstract public void pauseSend();
abstract public void resumeSend();
abstract public void cancelSend();
abstract public void softReset();
abstract public void responseMessage(String response);
//do common operations (related to the connection, that is shared by all communicators)
protected boolean openCommPort(String name, int baud) throws Exception {
//choose port
for(Connection candidate: connections) {
if(candidate.supports(name)) {
conn = candidate;
conn.setCommunicator(this);
break;
}
}
if(conn==null) {
throw new Exception(Localization.getString("communicator.exception.port") + ": "+name);
}
//open it
conn.openPort(name, baud);
return true;
}
//do common things (related to the connection, that is shared by all communicators)
protected void closeCommPort() {
conn.closePort();
}
/** Getters & Setters. */
void setLineTerminator(String terminator) {
if (terminator == null || terminator.length() < 1) {
this.lineTerminator = DEFAULT_TERMINATOR;
} else {
this.lineTerminator = terminator;
}
}
String getLineTerminator() {
return this.lineTerminator;
}
/* ****************** */
/** Listener helpers. */
/* ****************** */
void setListenAll(SerialCommunicatorListener scl) {
this.addCommandSentListener(scl);
this.addCommandCompleteListener(scl);
this.addCommConsoleListener(scl);
this.addCommVerboseConsoleListener(scl);
this.addCommRawResponseListener(scl);
}
void addCommandSentListener(SerialCommunicatorListener scl) {
this.commandSentListeners.add(scl);
}
void addCommandCompleteListener(SerialCommunicatorListener scl) {
this.commandCompleteListeners.add(scl);
}
void addCommConsoleListener(SerialCommunicatorListener scl) {
this.commConsoleListeners.add(scl);
}
void addCommVerboseConsoleListener(SerialCommunicatorListener scl) {
this.commVerboseConsoleListeners.add(scl);
}
void addCommRawResponseListener(SerialCommunicatorListener scl) {
this.commRawResponseListener.add(scl);
}
// Helper for the console listener.
protected void sendMessageToConsoleListener(String msg) {
this.sendMessageToConsoleListener(msg, false);
}
protected void sendMessageToConsoleListener(String msg, boolean verbose) {
// Exit early if there are no listeners.
if (this.commConsoleListeners == null) {
return;
}
int verbosity;
if (!verbose) {
verbosity = CONSOLE_MESSAGE;
}
else {
verbosity = VERBOSE_CONSOLE_MESSAGE;
}
dispatchListenerEvents(verbosity, this.commConsoleListeners, msg);
}
// Serial Communicator Listener Events
protected static final int COMMAND_SENT = 1;
protected static final int COMMAND_COMPLETE = 2;
protected static final int RAW_RESPONSE = 3;
protected static final int CONSOLE_MESSAGE = 4;
protected static final int VERBOSE_CONSOLE_MESSAGE = 5;
/**
* A bunch of methods to dispatch listener events with various arguments.
*/
static protected void dispatchListenerEvents(int event, ArrayList<SerialCommunicatorListener> sclList, String message) {
if (sclList != null) {
for (SerialCommunicatorListener s : sclList) {
sendEventToListener(event, s, message, null);
}
}
}
static protected void dispatchListenerEvents(int event, ArrayList<SerialCommunicatorListener> sclList, GcodeCommand command) {
if (sclList != null) {
for (SerialCommunicatorListener s : sclList) {
sendEventToListener(event, s, null, command);
}
}
}
static protected void sendEventToListener(int event, SerialCommunicatorListener scl,
String string, GcodeCommand command) {
switch(event) {
case COMMAND_SENT:
scl.commandSent(string);
break;
case CONSOLE_MESSAGE:
scl.messageForConsole(string);
break;
case VERBOSE_CONSOLE_MESSAGE:
scl.verboseMessageForConsole(string);
break;
case RAW_RESPONSE:
scl.rawResponseListener(string);
default:
}
}
}<|fim▁end|>
|
this.commRawResponseListener = new ArrayList<SerialCommunicatorListener>();
//instanciate all known connection drivers
//TODO: Scan the classpath for classes extending Connection,
|
<|file_name|>index.js<|end_file_name|><|fim▁begin|>var i18n = require('i18n');
var _ = require('lodash');
exports.register = function (plugin, options, next) {
i18n.configure(options);
plugin.ext('onPreResponse', function (request, extNext) {
// If is an error message
if(request.response.isBoom) {
i18n.setLocale(getLocale(request, options));
request.response.output.payload.message = i18n.__(request.response.output.payload.message);<|fim▁hole|> }
extNext();
});
next();
};
var getLocale = function(request, options) {
i18n.init(request.raw.req);
if(_.contains(_.keys(i18n.getCatalog()), request.raw.req.language)) {
return request.raw.req.language;
} else {
return options.defaultLocale;
}
};<|fim▁end|>
|
return extNext(request.response);
|
<|file_name|>wsgi.py<|end_file_name|><|fim▁begin|>"""<|fim▁hole|>
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "fitch.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()<|fim▁end|>
|
WSGI config for fitch project.
|
<|file_name|>log.py<|end_file_name|><|fim▁begin|><|fim▁hole|>import time
import logging
def time_zone(t):
if t.tm_isdst == 1 and time.daylight == 1:
tz_sec = time.altzone
tz_name = time.tzname[1]
else:
tz_sec = time.timezone
tz_name = time.tzname[0]
if tz_sec > 0:
tz_sign = '-'
else:
tz_sign = '+'
tz_offset = '%s%02d%02d' % (tz_sign, abs(tz_sec)//3600, abs(tz_sec//60)%60)
return (tz_offset, tz_name)
class JsubFormatter(logging.Formatter):
# Add this method in order to display time zone offset correctly under python 2.x
def formatTime(self, record, datefmt=None):
ct = time.localtime(record.created)
if datefmt:
s = time.strftime(datefmt, ct)
else:
t = time.strftime('%Y-%m-%d %H:%M:%S', ct)
ms = '%03d' % record.msecs
tz_offset, tz_name = time_zone(ct)
s = '%s.%03d %s %s' % (t, record.msecs, tz_offset, tz_name)
return s
_FORMATTER = JsubFormatter('[%(asctime)s][%(name)s|%(levelname)s]: %(message)s')
#_FORMATTER = logging.Formatter('[%(asctime)s](%(name)s:%(levelname)s) %(message)s', '%Y-%m-%d %H:%M:%S')
def add_stream_logger(level):
logger = logging.getLogger('JSUB')
logger.setLevel(level)
ch = logging.StreamHandler()
ch.setFormatter(_FORMATTER)
logger.addHandler(ch)<|fim▁end|>
| |
<|file_name|>test_rail.py<|end_file_name|><|fim▁begin|>import sys
import traceback
import unittest
import unittest.mock
import rail
class TestIdentity(unittest.TestCase):
def test_returns_input_value(self):
value = unittest.mock.Mock()
self.assertEqual(value, rail.identity(value))
class TestNot(unittest.TestCase):
def test_returns_inverse_for_bool(self):
self.assertEquals(True, rail.not_(False))
self.assertEquals(False, rail.not_(True))
def test_returns_inverse_for_truthy(self):
self.assertEquals(True, rail.not_([]))
self.assertEquals(False, rail.not_([0]))
class TestRaise(unittest.TestCase):
def test_raises_exception(self):
with self.assertRaises(ValueError) as context:
rail.raise_(ValueError('exception'))
self.assertEqual('exception', str(context.exception))
def test_preserves_traceback_when_reraising_without_exception(self):
def func(exception):
raise exception
try:
try:
func(ValueError('exception'))
except ValueError:
expected_exc_info = sys.exc_info()
rail.raise_()
except ValueError:
actual_exc_info = sys.exc_info()
self.assertEqual(expected_exc_info[0], actual_exc_info[0])
self.assertEqual(expected_exc_info[1], actual_exc_info[1])
expected_tb = traceback.format_tb(expected_exc_info[2])
actual_tb = traceback.format_tb(actual_exc_info[2])
self.assertEqual(expected_tb, actual_tb[-len(expected_tb):])
def test_preserves_traceback_when_reraising_with_exception(self):
def func(exception):
raise exception
try:
try:
func(ValueError('exception'))
except ValueError as exception:
expected_exc_info = sys.exc_info()
rail.raise_(exception)
except ValueError:
actual_exc_info = sys.exc_info()
self.assertEqual(expected_exc_info[0], actual_exc_info[0])
self.assertEqual(expected_exc_info[1], actual_exc_info[1])
expected_tb = traceback.format_tb(expected_exc_info[2])
actual_tb = traceback.format_tb(actual_exc_info[2])
self.assertEqual(expected_tb, actual_tb[-len(expected_tb):])
class TestTry(unittest.TestCase):
def test_no_exception_raised(self):
input = unittest.mock.Mock()
expected_value = unittest.mock.Mock()
func = unittest.mock.Mock(return_value=expected_value)
handle = unittest.mock.Mock()
self.assertEqual(expected_value, rail.try_(func, handle)(input))
func.assert_called_once_with(input)
handle.assert_not_called()
def test_exception_raised(self):
input = unittest.mock.Mock()
exception = ValueError('value')
func = unittest.mock.Mock(side_effect=lambda _: rail.raise_(exception))
output = unittest.mock.Mock()
handle = unittest.mock.Mock(return_value=output)
self.assertEqual(output, rail.try_(func, handle)(input))
func.assert_called_once_with(input)
handle.assert_called_once_with(exception)
class TestMatch(unittest.TestCase):
def test_no_match_statements_provided(self):
value = unittest.mock.Mock()
with self.assertRaises(rail.UnmatchedValueError) as context:
rail.match()(value)
self.assertEqual(value, context.exception.value)
def test_value_unmatched_by_all_match_statements(self):
value = unittest.mock.Mock()
with self.assertRaises(rail.UnmatchedValueError) as context:
match = rail.match(
(lambda _: False, lambda _: unittest.mock.Mock()),
(lambda _: False, lambda _: unittest.mock.Mock()),
(lambda _: False, lambda _: unittest.mock.Mock())
)
match(value)
self.assertEqual(value, context.exception.value)
def test_value_matches_single_match_statement(self):
expected_value = unittest.mock.Mock()
match = rail.match(
(lambda _: False, lambda _: unittest.mock.Mock()),
(lambda _: True, lambda _: expected_value),
(lambda _: False, lambda _: unittest.mock.Mock())
)
self.assertEqual(expected_value, match(unittest.mock.Mock()))
def test_value_matches_multiple_match_statements(self):
expected_value = unittest.mock.Mock()
match = rail.match(
(lambda _: False, lambda _: unittest.mock.Mock()),
(lambda _: True, lambda _: expected_value),
(lambda _: True, lambda _: unittest.mock.Mock())
)
self.assertEqual(expected_value, match(unittest.mock.Mock()))
class TestMatchType(unittest.TestCase):
def test_no_match_statements_provided(self):
value = unittest.mock.Mock()
with self.assertRaises(rail.UnmatchedValueError) as context:
rail.match_type()(value)
self.assertEqual(value, context.exception.value)
def test_value_unmatched_by_all_match_statements(self):
value = unittest.mock.Mock()
with self.assertRaises(rail.UnmatchedValueError) as context:
match = rail.match_type(
(str, lambda _: unittest.mock.Mock()),
(float, lambda _: unittest.mock.Mock()),
(Exception, lambda _: unittest.mock.Mock())
)
match(value)<|fim▁hole|>
def test_value_matches_single_match_statement(self):
expected_value = unittest.mock.Mock()
match = rail.match_type(
(int, lambda _: unittest.mock.Mock()),
(unittest.mock.Mock, lambda _: expected_value),
(dict, lambda _: unittest.mock.Mock())
)
self.assertEqual(expected_value, match(unittest.mock.Mock()))
def test_value_matches_multiple_match_statements(self):
expected_value = unittest.mock.Mock()
match = rail.match_type(
(bool, lambda _: unittest.mock.Mock()),
(unittest.mock.Mock, lambda _: expected_value),
(unittest.mock.Mock, lambda _: unittest.mock.Mock())
)
self.assertEqual(expected_value, match(unittest.mock.Mock()))
def test_value_subclass_of_match_type(self):
expected_value = unittest.mock.Mock()
match = rail.match_type(
(bool, lambda _: unittest.mock.Mock()),
(object, lambda _: expected_value),
(unittest.mock.Mock, lambda _: unittest.mock.Mock())
)
self.assertEqual(expected_value, match(unittest.mock.Mock()))
class TestMatchLength(unittest.TestCase):
def test_no_match_statements_provided(self):
value = unittest.mock.Mock()
with self.assertRaises(rail.UnmatchedValueError) as context:
rail.match_length()(value)
self.assertEqual(value, context.exception.value)
def test_value_unmatched_by_all_match_statements(self):
value = unittest.mock.Mock()
value.__len__ = unittest.mock.Mock(return_value=2)
with self.assertRaises(rail.UnmatchedValueError) as context:
match = rail.match_length(
(rail.eq(8), lambda _: unittest.mock.Mock()),
(rail.gt(3), lambda _: unittest.mock.Mock())
)
match(value)
self.assertEqual(value, context.exception.value)
def test_value_matches_single_match_statement(self):
expected_value = unittest.mock.Mock()
match = rail.match_length(
(rail.lt(0), lambda _: unittest.mock.Mock()),
(rail.eq(0), lambda _: expected_value),
(rail.gt(0), lambda _: unittest.mock.Mock())
)
value = unittest.mock.Mock()
value.__len__ = unittest.mock.Mock(return_value=0)
self.assertEqual(expected_value, match(value))
def test_value_matches_multiple_match_statements(self):
expected_value = unittest.mock.Mock()
match = rail.match_length(
(rail.lt(0), lambda _: unittest.mock.Mock()),
(rail.ge(0), lambda _: expected_value),
(rail.eq(0), lambda _: unittest.mock.Mock())
)
value = unittest.mock.Mock()
value.__len__ = unittest.mock.Mock(return_value=0)
self.assertEqual(expected_value, match(value))
class TestPartial(unittest.TestCase):
def test_func_with_no_args(self):
@rail.partial
def func():
return 'value'
self.assertEqual('value', func())
def test_func_with_single_arg(self):
@rail.partial
def func(arg):
return arg
value = unittest.mock.Mock()
self.assertEqual(value, func(value))
def test_func_with_multiple_args(self):
@rail.partial
def func(arg1, arg2, arg3):
return arg1, arg2, arg3
val1 = unittest.mock.Mock()
val2 = unittest.mock.Mock()
val3 = unittest.mock.Mock()
self.assertEqual((val1, val2, val3), func(val1, val2, val3))
self.assertEqual((val1, val2, val3), func(val1)(val2, val3))
self.assertEqual((val1, val2, val3), func(val1, val2)(val3))
self.assertEqual((val1, val2, val3), func(val1)(val2)(val3))
def test_func_with_arguments_applied_out_of_order(self):
@rail.partial
def func(arg1, arg2, arg3):
return arg1, arg2, arg3
val1 = unittest.mock.Mock()
val2 = unittest.mock.Mock()
val3 = unittest.mock.Mock()
self.assertEqual((val1, val2, val3), func(arg2=val2)(val1, val3))
self.assertEqual((val1, val2, val3), func(arg3=val3)(val1, val2))
self.assertEqual(
(val1, val2, val3), func(arg2=val2, arg3=val3)(val1)
)
self.assertEqual(
(val1, val2, val3), func(arg3=val3)(arg2=val2)(val1)
)
self.assertEqual((val1, val2, val3), func(val1, arg3=val3)(val2))
def test_func_with_default_arguments(self):
@rail.partial
def func(arg1, arg2, arg3='val3', arg4='val4'):
return arg1, arg2, arg3, arg4
val1 = unittest.mock.Mock()
val2 = unittest.mock.Mock()
val3 = unittest.mock.Mock()
val4 = unittest.mock.Mock()
self.assertEqual((val1, val2, 'val3', 'val4'), func(val1, val2))
self.assertEqual((val1, val2, 'val3', 'val4'), func(val1)(val2))
self.assertEqual(
(val1, val2, val3, val4), func(val1, val2, val3, val4)
)
self.assertEqual(
(val1, val2, val3, val4), func(val1)(val2, val3, val4)
)
self.assertEqual(
(val1, val2, val3, val4), func(val1, arg3=val3)(val2, val4)
)
def test_func_with_default_arguments_only(self):
@rail.partial
def func(arg1='val1', arg2='val2'):
return arg1, arg2
val1 = unittest.mock.Mock()
val2 = unittest.mock.Mock()
self.assertEqual(('val1', 'val2'), func())
self.assertEqual((val1, 'val2'), func(val1))
self.assertEqual(('val1', val2), func(arg2=val2))
self.assertEqual((val1, val2), func(val1, val2))
def test_func_with_argument_list(self):
@rail.partial
def func(arg1, arg2, *args):
return (arg1, arg2) + args
val1 = unittest.mock.Mock()
val2 = unittest.mock.Mock()
val3 = unittest.mock.Mock()
val4 = unittest.mock.Mock()
self.assertEqual((val1, val2), func(val1, val2))
self.assertEqual((val1, val2), func(val1)(val2))
self.assertEqual(
(val1, val2, val3, val4), func(val1, val2, val3, val4)
)
self.assertEqual(
(val1, val2, val3, val4), func(val1)(val2, val3, val4)
)
def test_func_with_argument_list_only(self):
@rail.partial
def func(*args):
return args
val1 = unittest.mock.Mock()
val2 = unittest.mock.Mock()
self.assertEqual((), func())
self.assertEqual((val1,), func(val1))
self.assertEqual((val1, val2), func(val1, val2))
def test_func_with_keyword_arguments(self):
@rail.partial
def func(arg1, arg2, **kwargs):
return (arg1, arg2) + ((kwargs,) if kwargs else ())
val1 = unittest.mock.Mock()
val2 = unittest.mock.Mock()
val3 = unittest.mock.Mock()
val4 = unittest.mock.Mock()
self.assertEqual((val1, val2), func(val1, val2))
self.assertEqual((val1, val2), func(val1)(val2))
self.assertEqual(
(val1, val2, {'val3': val3, 'val4': val4}),
func(val1, val2, val3=val3, val4=val4)
)
self.assertEqual(
(val1, val2, {'val3': val3, 'val4': val4}),
func(val1, val3=val3)(val2, val4=val4)
)
def test_func_with_keyword_arguments_only(self):
@rail.partial
def func(**kwargs):
return kwargs
val1 = unittest.mock.Mock()
val2 = unittest.mock.Mock()
self.assertEqual({}, func())
self.assertEqual({'arg1': val1}, func(arg1=val1))
self.assertEqual(
{'arg1': val1, 'arg2': val2}, func(arg1=val1, arg2=val2)
)
def test_docstring_preserved(self):
@rail.partial
def func1(arg1, arg2):
"""Docstring for func"""
return arg1, arg2
self.assertEqual('Docstring for func', func1.__doc__)
func2 = func1(unittest.mock.Mock())
self.assertEqual('Docstring for func', func2.__doc__)
class TestCompose(unittest.TestCase):
def test_compose_with_no_funcs(self):
func = rail.compose()
value = unittest.mock.Mock()
self.assertEqual(value, func(value))
def test_compose_with_no_exception(self):
expected_value = unittest.mock.Mock()
func = rail.compose(
lambda value: expected_value
)
self.assertEqual(expected_value, func(unittest.mock.Mock()))
def test_compose_with_exception(self):
with self.assertRaises(ValueError) as context:
func = rail.compose(
lambda value: rail.raise_(ValueError('exception'))
)
func(unittest.mock.Mock())
self.assertEqual('exception', str(context.exception))
def test_compose_with_multiple_funcs(self):
return_value1 = unittest.mock.Mock()
return_value2 = unittest.mock.Mock()
return_value3 = unittest.mock.Mock()
func1 = unittest.mock.Mock(return_value=return_value1)
func2 = unittest.mock.Mock(return_value=return_value2)
func3 = unittest.mock.Mock(return_value=return_value3)
func = rail.compose(
func1,
func2,
func3
)
value = unittest.mock.Mock()
self.assertEqual(return_value3, func(value))
func1.assert_called_once_with(value)
func2.assert_called_once_with(return_value1)
func3.assert_called_once_with(return_value2)
class TestPipe(unittest.TestCase):
def test_pipe(self):
val1 = unittest.mock.Mock()
val2 = unittest.mock.Mock()
val3 = unittest.mock.Mock()
self.assertEqual(
(val1, val2, val3),
rail.pipe(
(val1,),
lambda val: val + (val2,),
lambda val: val + (val3,)
)
)
def test_use_pipe_to_create_scope(self):
val1 = unittest.mock.Mock()
val2 = unittest.mock.Mock()
val3 = unittest.mock.Mock()
self.assertEqual(
(val1, val2, val3),
rail.pipe(
(val1,),
lambda arg1: rail.pipe(
(val2,),
lambda arg2: arg1 + arg2,
lambda arg: arg + (val3,)
)
)
)
class TestTee(unittest.TestCase):
def test_with_multiple_funcs(self):
input = unittest.mock.Mock()
func1 = unittest.mock.Mock(return_value=unittest.mock.Mock())
func2 = unittest.mock.Mock(return_value=unittest.mock.Mock())
func3 = unittest.mock.Mock()
self.assertEqual(
input,
rail.pipe(input, rail.tee(func1, func2, func3))
)
func1.assert_called_once_with(input)
func2.assert_called_once_with(func1.return_value)
func3.assert_called_once_with(func2.return_value)
class TestCallWith(unittest.TestCase):
def test_calls_function_with_value(self):
value = unittest.mock.Mock()
func = unittest.mock.Mock()
rail.call_with(value, func)
func.assert_called_once_with(value)
def test_partial_application(self):
value = unittest.mock.Mock()
func = unittest.mock.Mock()
rail.pipe(func, rail.call_with(value))
def test_returns_func_return_value(self):
return_value = unittest.mock.Mock()
func = unittest.mock.Mock(return_value=return_value)
self.assertEqual(
return_value, rail.call_with(unittest.mock.Mock(), func)
)
class TestLt(unittest.TestCase):
def test_pipe_returns_true(self):
self.assertTrue(rail.pipe(5, rail.lt(7)))
def test_pipe_returns_false(self):
self.assertFalse(rail.pipe(8, rail.lt(1)))
class TestLe(unittest.TestCase):
def test_pipe_returns_true_for_different_values(self):
self.assertTrue(rail.pipe(5, rail.le(7)))
def test_pipe_returns_true_for_equal_values(self):
self.assertTrue(rail.pipe(5, rail.le(5)))
def test_pipe_returns_false(self):
self.assertFalse(rail.pipe(8, rail.le(1)))
class TestEq(unittest.TestCase):
def test_pipe_returns_true(self):
value = unittest.mock.Mock()
self.assertTrue(rail.pipe(value, rail.eq(value)))
def test_pipe_returns_false(self):
value1 = unittest.mock.Mock()
value2 = unittest.mock.Mock()
self.assertFalse(rail.pipe(value1, rail.eq(value2)))
class TestNe(unittest.TestCase):
def test_pipe_returns_true(self):
value1 = unittest.mock.Mock()
value2 = unittest.mock.Mock()
self.assertTrue(rail.pipe(value1, rail.ne(value2)))
def test_pipe_returns_false(self):
value = unittest.mock.Mock()
self.assertFalse(rail.pipe(value, rail.ne(value)))
class TestGt(unittest.TestCase):
def test_pipe_returns_true(self):
self.assertTrue(rail.pipe(4, rail.gt(0)))
def test_pipe_returns_false(self):
self.assertFalse(rail.pipe(13, rail.gt(15)))
class TestGe(unittest.TestCase):
def test_pipe_returns_true_for_different_values(self):
self.assertTrue(rail.pipe(6, rail.ge(2)))
def test_pipe_returns_true_for_equal_values(self):
self.assertTrue(rail.pipe(4, rail.ge(4)))
def test_pipe_returns_false(self):
self.assertFalse(rail.pipe(6, rail.ge(9)))
class TestTrack(unittest.TestCase):
def test_compose_with_existing_func(self):
return_value1 = unittest.mock.Mock()
return_value2 = unittest.mock.Mock()
return_value3 = unittest.mock.Mock()
func1 = unittest.mock.Mock(return_value=return_value1)
func2 = unittest.mock.Mock(return_value=return_value2)
func3 = unittest.mock.Mock(return_value=return_value3)
func = rail.Track().compose(
func1
).compose(
func2,
func3
)
value = unittest.mock.Mock()
self.assertEqual(return_value3, func(value))
func1.assert_called_once_with(value)
func2.assert_called_once_with(return_value1)
func3.assert_called_once_with(return_value2)
def test_tee_called_consecutively(self):
func1 = unittest.mock.Mock()
func2 = unittest.mock.Mock()
func = rail.Track().tee(
func1
).tee(
func2
)
value = unittest.mock.Mock()
self.assertEqual(value, func(value))
func1.assert_called_once_with(value)
func2.assert_called_once_with(value)
def test_fold_with_no_exception(self):
expected_value = unittest.mock.Mock()
func = rail.Track().compose(
lambda value: unittest.mock.Mock()
).fold(
lambda value: expected_value,
lambda exception: self.fail()
)
self.assertEqual(expected_value, func(unittest.mock.Mock()))
def test_fold_with_exception(self):
expected_exception = KeyError('key')
actual_exception = rail.pipe(
unittest.mock.Mock(),
rail.Track().compose(
lambda _: rail.raise_(expected_exception)
).fold(
lambda _: self.fail(),
rail.identity
)
)
self.assertEqual(expected_exception, actual_exception)
def test_fold_traceback_with_exception(self):
exception = KeyError('key')
func = rail.Track().compose(
lambda _: rail.raise_(exception)
)
try:
func(unittest.mock.Mock())
except KeyError:
expected_exc_info = sys.exc_info()
try:
rail.pipe(
unittest.mock.Mock(),
func.fold(
lambda _: self.fail(),
rail.raise_
)
)
except KeyError:
actual_exc_info = sys.exc_info()
self.assertEqual(expected_exc_info[0], actual_exc_info[0])
self.assertEqual(expected_exc_info[1], actual_exc_info[1])
expected_tb = traceback.format_tb(expected_exc_info[2])
actual_tb = traceback.format_tb(actual_exc_info[2])
self.assertEqual(expected_tb, actual_tb[-len(expected_tb):])
def test_handle_with_multiple_funcs(self):
expected_exception = ValueError('value')
func = rail.Track().compose(
lambda value: rail.raise_(ValueError('value'))
).handle(
lambda exception: unittest.mock.Mock(),
lambda exception: expected_exception
)
self.assertEqual(expected_exception, func(unittest.mock.Mock()))
def test_handle_with_no_exception(self):
expected_value = unittest.mock.Mock()
func = rail.Track().compose(
lambda value: expected_value
).handle(
lambda exception: self.fail()
)
self.assertEqual(expected_value, func(unittest.mock.Mock()))
def test_handle_with_exception(self):
expected_exception = KeyError('key')
actual_exception = rail.pipe(
unittest.mock.Mock(),
rail.Track().compose(
lambda _: rail.raise_(expected_exception)
).handle(
rail.identity
)
)
self.assertEqual(expected_exception, actual_exception)
def test_handle_traceback_with_exception(self):
exception = KeyError('key')
func = rail.Track().compose(
lambda _: rail.raise_(exception)
)
try:
func(unittest.mock.Mock())
except KeyError:
expected_exc_info = sys.exc_info()
try:
rail.pipe(
unittest.mock.Mock(),
func.handle(
rail.raise_
)
)
except KeyError:
actual_exc_info = sys.exc_info()
self.assertEqual(expected_exc_info[0], actual_exc_info[0])
self.assertEqual(expected_exc_info[1], actual_exc_info[1])
expected_tb = traceback.format_tb(expected_exc_info[2])
actual_tb = traceback.format_tb(actual_exc_info[2])
self.assertEqual(expected_tb, actual_tb[-len(expected_tb):])
if __name__ == '__main__':
unittest.main()<|fim▁end|>
|
self.assertEqual(value, context.exception.value)
|
<|file_name|>scrabble_score_test.py<|end_file_name|><|fim▁begin|>import unittest
from scrabble import score
class WordTest(unittest.TestCase):
def test_invalid_word_scores_zero(self):
self.assertEqual(0, score(''))
self.assertEqual(0, score(' \t\n'))
self.assertEqual(0, score('hous3'))
self.assertEqual(0, score('wo rd'))
def test_scores_very_short_word(self):
self.assertEqual(1, score('a'))
def test_scores_other_very_short_word(self):
self.assertEqual(4, score('f'))
def test_simple_word_scores_the_number_of_letters(self):
self.assertEqual(6, score("street"))
def test_complicated_word_scores_more(self):
self.assertEqual(22, score("quirky"))
def test_scores_are_case_insensitive(self):
self.assertEqual(41, score("OxyphenButazone"))
if __name__ == '__main__':<|fim▁hole|><|fim▁end|>
|
unittest.main()
|
<|file_name|>changepassword.js<|end_file_name|><|fim▁begin|>$(document).ready(function() {
$("#frmChangePass").submit(function() {
//get the url for the form
AJAX.post(<|fim▁hole|> _password : $("#newPass").val(),
_password_confirm : $("#newPass2").val()
},
$("#msgbox_changepass"),
$("#btnChangepass"));
//we dont what the browser to submit the form
return false;
});
});<|fim▁end|>
|
$("#frmChangePass").attr("action"),
{
_password_current : $("#currentPass").val(),
|
<|file_name|>BlockGrid.js<|end_file_name|><|fim▁begin|>import React from 'react';
import $ from 'jquery';
import _ from 'lodash';
import Block from './Block';
export default class BlockGrid extends React.Component {
constructor() {
super();
this.setDefaults();
this.setContainerWidth = this.setContainerWidth.bind(this);
this.handleWindowResize = this.handleWindowResize.bind(this);
this.resizeTimer = null;
// throttle call to this func whenever an image is loaded
this.throttledSetContainerWidth = _.throttle(this.setContainerWidth, 500);
}
setDefaults(){
this.blockWidth = 260; // initial desired block width
this.borderWidth = 5;
this.wrapperWidth = 0;
this.colCount = 0;
this.blocks = [];
this.blockCount = 0;
}
handleWindowResize(){
clearTimeout(this.resizeTimer);
const _this = this;
this.resizeTimer = setTimeout(function() {
$('.block-container').css('width', '100%');
_this.setDefaults();
_this.setContainerWidth();
// above code computes false height of blocks
// so as a lose patch re-position blocks after 500 ms
setTimeout(_this.setContainerWidth, 700);
}, 200);
}
componentDidMount(){
this.setContainerWidth();
/*
height of each block is measured with an error the first time so there are some
space between blocks specially the top values of the grid.
Only solution seems like re calculating positions of the block after few seconds
*/
// _.delay(this.setContainerWidth, 3000);
// reset all blocks when window resized
$(window).resize(this.handleWindowResize);
}
componentWillReceiveProps(nextProps){
// after clicking Load More there will be newProps here
// Re calculate block positions so no error occurs when there are
// all image less blocks
// _.delay(this.setContainerWidth, 2000);
}
componentDidUpdate(prevProps, prevState){
if(this.blockCount != this.props.data.length){
this.setDefaults();<|fim▁hole|> this.setContainerWidth();
}
}
componentWillUnmount(){
$(window).off("resize", this.handleWindowResize);
}
setContainerWidth(){
// setContainerWidth only first time we recieve BlockList data
if(this.wrapperWidth == 0){
this.wrapperWidth = $('.block-container').outerWidth();
this.colCount = Math.round(this.wrapperWidth/this.blockWidth);
$('.block').css('width', this.blockWidth);
this.blockCount = document.getElementsByClassName('block').length;
if(this.blockCount < this.colCount){
this.wrapperWidth = (this.blockWidth*this.blockCount) - ( (this.blockCount - 1) * this.borderWidth);
this.colCount = this.blockCount;
} else {
this.wrapperWidth = (this.blockWidth*this.colCount) - ( (this.colCount - 1) * this.borderWidth);
}
$('.block-container').css('width', this.wrapperWidth);
}
// if wrapperWidth is already calculated than just reset block positions
for( var i = 0; i < this.colCount; i++ )
this.blocks[i] = 0;
this.setBlocks();
}
setBlocks() {
const component = this;
$('.block').each(function(){
var min = Math.min.apply(Math, component.blocks);
var index = $.inArray(min, component.blocks);
var left = index * (component.blockWidth - component.borderWidth) - component.borderWidth;
// for the first blocks that needs to overlap container border
if(left == 0)
left = - component.borderWidth;
// start with overlap on top container border
var top = min + 10 - component.borderWidth;
$(this).css({
'top' : top + 'px',
'left' : left + 'px'
});
component.blocks[index] = top + this.offsetHeight;
});
// set wrapper height
var wrapperHeight = Math.max.apply(Math, this.blocks);
wrapperHeight += this.borderWidth; // block borders
$(".block-container").css("height",wrapperHeight + 'px');
}
renderBlocks() {
const { data } = this.props;
return data.map((pin) => {
return <Block {...pin} key={pin._id} loadHandler={this.throttledSetContainerWidth}/>;
});
}
render() {
return(
<div class="row">
<div class="col-sm-offset-2 col-sm-8 col-xs-offset-1 col-xs-10">
<div class="block-container">
{ this.renderBlocks() }
</div>
</div>
</div>
);
}
}<|fim▁end|>
| |
<|file_name|>vimawesome.rs<|end_file_name|><|fim▁begin|>use std::io;
use std::process::{Command, Stdio};
use std::rc::Rc;
use std::thread;
use serde_json;
use glib;
use gtk;
use gtk::prelude::*;
use super::store::PlugInfo;
pub fn call<F>(query: Option<String>, cb: F)
where
F: FnOnce(io::Result<DescriptionList>) + Send + 'static,
{
thread::spawn(move || {
let mut result = Some(request(query.as_ref().map(|s| s.as_ref())));
let mut cb = Some(cb);
glib::idle_add(move || {
cb.take().unwrap()(result.take().unwrap());
Continue(false)
})
});
}
fn request(query: Option<&str>) -> io::Result<DescriptionList> {
let child = Command::new("curl")
.arg("-s")
.arg(format!(
"https://vimawesome.com/api/plugins?query={}&page=1",
query.unwrap_or("")
))
.stdout(Stdio::piped())
.spawn()?;
let out = child.wait_with_output()?;
if out.status.success() {
if out.stdout.is_empty() {
Ok(DescriptionList::empty())
} else {
let description_list: DescriptionList = serde_json::from_slice(&out.stdout)
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
Ok(description_list)
}
} else {
Err(io::Error::new(
io::ErrorKind::Other,
format!(
"curl exit with error:\n{}",
match out.status.code() {
Some(code) => format!("Exited with status code: {}", code),
None => "Process terminated by signal".to_owned(),
}
),
))
}
}
pub fn build_result_panel<F: Fn(PlugInfo) + 'static>(
list: &DescriptionList,
add_cb: F,
) -> gtk::ScrolledWindow {
let scroll = gtk::ScrolledWindow::new(
Option::<>k::Adjustment>::None,
Option::<>k::Adjustment>::None,
);
scroll.get_style_context().add_class("view");
let panel = gtk::ListBox::new();
let cb_ref = Rc::new(add_cb);
for plug in list.plugins.iter() {
let row = create_plug_row(plug, cb_ref.clone());
panel.add(&row);
}
scroll.add(&panel);
scroll.show_all();
scroll
}
fn create_plug_row<F: Fn(PlugInfo) + 'static>(
plug: &Description,
add_cb: Rc<F>,
) -> gtk::ListBoxRow {
let row = gtk::ListBoxRow::new();
let row_container = gtk::Box::new(gtk::Orientation::Vertical, 5);
row_container.set_border_width(5);
let hbox = gtk::Box::new(gtk::Orientation::Horizontal, 5);
let label_box = create_plug_label(plug);
let button_box = gtk::Box::new(gtk::Orientation::Horizontal, 0);
button_box.set_halign(gtk::Align::End);
let add_btn = gtk::Button::new_with_label("Install");
button_box.pack_start(&add_btn, false, true, 0);
row_container.pack_start(&hbox, true, true, 0);
hbox.pack_start(&label_box, true, true, 0);
hbox.pack_start(&button_box, false, true, 0);
row.add(&row_container);
add_btn.connect_clicked(clone!(plug => move |btn| {
if let Some(ref github_url) = plug.github_url {
btn.set_sensitive(false);
add_cb(PlugInfo::new(plug.name.clone(), github_url.clone()));
}
}));
row
}
fn create_plug_label(plug: &Description) -> gtk::Box {
let label_box = gtk::Box::new(gtk::Orientation::Vertical, 5);
let name_lbl = gtk::Label::new(None);
name_lbl.set_markup(&format!(
"<b>{}</b> by {}",
plug.name,
plug.author
.as_ref()
.map(|s| s.as_ref())
.unwrap_or("unknown",)
));
name_lbl.set_halign(gtk::Align::Start);
let url_lbl = gtk::Label::new(None);
if let Some(url) = plug.github_url.as_ref() {
url_lbl.set_markup(&format!("<a href=\"{}\">{}</a>", url, url));
}
url_lbl.set_halign(gtk::Align::Start);
label_box.pack_start(&name_lbl, true, true, 0);
label_box.pack_start(&url_lbl, true, true, 0);
label_box
}
#[derive(Deserialize, Debug)]
pub struct DescriptionList {
pub plugins: Box<[Description]>,
}
impl DescriptionList {
fn empty() -> DescriptionList {
DescriptionList {
plugins: Box::new([]),
}<|fim▁hole|>pub struct Description {
pub name: String,
pub github_url: Option<String>,
pub author: Option<String>,
pub github_stars: Option<i64>,
}<|fim▁end|>
|
}
}
#[derive(Deserialize, Debug, Clone)]
|
<|file_name|>index.js<|end_file_name|><|fim▁begin|>import React, { useState, useRef } from 'react';
import { computeOutOffsetByIndex, computeInOffsetByIndex } from './lib/Util';
// import { SVGComponent } from './lib-hooks/svgComp-hooks';
import Spline from './lib/Spline';
import DragNode from './lib/Node';
const index = ({
data,
onNodeDeselect,
onNodeMove,
onNodeStartMove,
onNodeSelect,
onNewConnector,
onRemoveConnector
}) => {
const [dataS, setDataS] = useState(data);
const [source, setSource] = useState([]);
const [dragging, setDragging] = useState(false);
const [mousePos, setMousePos] = useState({x: 0, y: 0});
const svgRef = useRef();
const onMouseMove = e => {
let [pX, pY] = [e.clientX, e.clientY];
e.stopPropagation();
e.preventDefault();
const svgRect = svgRef.current.getBoundingClientRect();
// console.log(svgRect);
setMousePos(old => {
return {
...old,
...{x: pX - svgRect.left, y: pY - svgRect.top}
}
});
}
const onMouseUp = e => {
setDragging(false);
}
const handleNodeStart = nid => {
onNodeStartMove(nid);
}
const handleNodeStop = (nid, pos) => {
onNodeMove(nid, pos);
}
const handleNodeMove = (idx, pos) => {
let dataT = dataS;
dataT.nodes[idx].x = pos.x;
dataT.nodes[idx].y = pos.y;
// console.log(dataT);
// console.log({...dataS,...dataT});
setDataS(old => {
return {
...old,
...dataT
}
});
}
const handleStartConnector = (nid, outputIdx) => {
let newSrc = [nid, outputIdx];
setDragging(true);
setSource(newSrc); // Not sure if this will work...
}
const handleCompleteConnector = (nid, inputIdx) => {
if (dragging) {
let fromNode = getNodeById(data.nodes, source[0]);
let fromPinName = fromNode.fields.out[source[1]].name;
let toNode = getNodeById(data.nodes, nid);
let toPinName = toNode.fields.in[inputIdx].name;
onNewConnector(fromNode.nid, fromPinName, toNode.nid, toPinName);
}
setDragging(false);
}
const handleRemoveConnector = connector => {
if (onRemoveConnector) {
onRemoveConnector(connector);
}
}
const handleNodeSelect = nid => {
if (onNodeSelect) {
onNodeSelect(nid);
}
}
const handleNodeDeselect = nid => {
if (onNodeDeselect) {
onNodeDeselect(nid);
}
}
const computePinIdxfromLabel = (pins, pinLabel) => {
let reval = 0;
for (let pin of pins) {
if (pin.name === pinLabel) {
return reval;
} else {
reval++;
}
}
}
const getNodeById = (nodes, nid) => {
let reval = 0;
for(const node of nodes) {
if (node.nid === nid) {
return nodes[reval];
} else {
reval++;
}
}
}
let newConn = null;
let i = 0;
// console.log(dragging);
if (dragging) {
let sourceNode = getNodeById(dataS.nodes, source[0]);
let connectorStart = computeOutOffsetByIndex(sourceNode.x, sourceNode.y, source[1]);
let connectorEnd = {
x: mousePos.x,
y: mousePos.y
};
// console.log(mousePos);
newConn = <Spline
start={connectorStart}
end={connectorEnd}
/>
}
let splineIdx = 0;
return (
<div className={dragging ? 'dragging' : ''}
onMouseMove={onMouseMove}
onMouseUp={onMouseUp}
>
{dataS.nodes.map(node => {
// console.log(node);
return <DragNode
index={i++}
nid={node.nid}
title={node.type}
inputs={node.fields.in}
outputs={node.fields.out}
pos={{x: node.x, y: node.y}}
key={node.nid}
onNodeStart={nid => handleNodeStart(nid)}
onNodeStop={(nid, pos) => handleNodeStop(nid, pos)}
onNodeMove={(idx, pos) => handleNodeMove(idx, pos)}
onStartConnector={(nid, outputIdx) => handleStartConnector(nid, outputIdx)}<|fim▁hole|> onNodeDeselect={nid => handleNodeDeselect(nid)}
/>
})}
<svg style={{position: 'absolute', height: "100%", width: "100%", zIndex: 9000}}
ref={svgRef}>
{data.connections.map(connector => {
// console.log(data);
// console.log(connector);
let fromNode = getNodeById(data.nodes, connector.from_node);
let toNode = getNodeById(data.nodes, connector.to_node);
let splinestart = computeOutOffsetByIndex(fromNode.x, fromNode.y, computePinIdxfromLabel(fromNode.fields.out, connector.from));
let splineend = computeInOffsetByIndex(toNode.x, toNode.y, computePinIdxfromLabel(toNode.fields.in, connector.to));
return <Spline
start={splinestart}
end={splineend}
key={splineIdx++}
mousePos={mousePos}
onRemove={() => handleRemoveConnector(connector)}
/>
})}
{newConn}
</svg>
</div>
);
}
export default index;<|fim▁end|>
|
onCompleteConnector={(nid, inputIdx) => handleCompleteConnector(nid, inputIdx)}
onNodeSelect={nid => handleNodeSelect(nid)}
|
<|file_name|>pair_lj_sdk_coul_msm.cpp<|end_file_name|><|fim▁begin|>/* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Steve Plimpton, [email protected]
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
/* ----------------------------------------------------------------------
Contributing author: Axel Kohlmeyer (Temple U)
This style is a simplified re-implementation of the CG/CMM pair style
------------------------------------------------------------------------- */
#include "pair_lj_sdk_coul_msm.h"
#include <cmath>
#include <cstring>
#include "atom.h"
#include "force.h"
#include "kspace.h"
#include "neigh_list.h"
#include "error.h"
#include "lj_sdk_common.h"
using namespace LAMMPS_NS;
using namespace LJSDKParms;
/* ---------------------------------------------------------------------- */
PairLJSDKCoulMSM::PairLJSDKCoulMSM(LAMMPS *lmp) : PairLJSDKCoulLong(lmp)
{
ewaldflag = pppmflag = 0;
msmflag = 1;
respa_enable = 0;
ftable = NULL;
}
/* ---------------------------------------------------------------------- */
void PairLJSDKCoulMSM::compute(int eflag, int vflag)
{
if (force->kspace->scalar_pressure_flag)
error->all(FLERR,"Must use 'kspace_modify pressure/scalar no' with Pair style");
ev_init(eflag,vflag);
if (evflag) {
if (eflag) {
if (force->newton_pair) eval_msm<1,1,1>();
else eval_msm<1,1,0>();
} else {
if (force->newton_pair) eval_msm<1,0,1>();
else eval_msm<1,0,0>();
}
} else {
if (force->newton_pair) eval_msm<0,0,1>();
else eval_msm<0,0,0>();
}
if (vflag_fdotr) virial_fdotr_compute();
}
/* ---------------------------------------------------------------------- */
template <int EVFLAG, int EFLAG, int NEWTON_PAIR>
void PairLJSDKCoulMSM::eval_msm()
{
int i,ii,j,jj,jtype,itable;
double qtmp,xtmp,ytmp,ztmp,delx,dely,delz,evdwl,ecoul,fpair;
double fraction,table;
double r,rsq,r2inv,forcecoul,forcelj,factor_coul,factor_lj;
double egamma,fgamma,prefactor;
const double * const * const x = atom->x;
double * const * const f = atom->f;
const double * const q = atom->q;
const int * const type = atom->type;
const int nlocal = atom->nlocal;
const double * const special_coul = force->special_coul;
const double * const special_lj = force->special_lj;
const double qqrd2e = force->qqrd2e;
double fxtmp,fytmp,fztmp;
const int inum = list->inum;
const int * const ilist = list->ilist;
const int * const numneigh = list->numneigh;
const int * const * const firstneigh = list->firstneigh;
// loop over neighbors of my atoms
for (ii = 0; ii < inum; ii++) {
i = ilist[ii];
qtmp = q[i];
xtmp = x[i][0];
ytmp = x[i][1];
ztmp = x[i][2];
fxtmp=fytmp=fztmp=0.0;
const int itype = type[i];
const int * const jlist = firstneigh[i];
const int jnum = numneigh[i];
for (jj = 0; jj < jnum; jj++) {
forcecoul = forcelj = evdwl = ecoul = 0.0;
j = jlist[jj];
factor_lj = special_lj[sbmask(j)];
factor_coul = special_coul[sbmask(j)];
j &= NEIGHMASK;
delx = xtmp - x[j][0];
dely = ytmp - x[j][1];
delz = ztmp - x[j][2];
rsq = delx*delx + dely*dely + delz*delz;
jtype = type[j];
if (rsq < cutsq[itype][jtype]) {
r2inv = 1.0/rsq;
const int ljt = lj_type[itype][jtype];
if (rsq < cut_coulsq) {
if (!ncoultablebits || rsq <= tabinnersq) {
r = sqrt(rsq);
prefactor = qqrd2e * qtmp*q[j]/r;
fgamma = 1.0 + (rsq/cut_coulsq)*force->kspace->dgamma(r/cut_coul);
forcecoul = prefactor * fgamma;
if (EFLAG) {
egamma = 1.0 - (r/cut_coul)*force->kspace->gamma(r/cut_coul);
ecoul = prefactor*egamma;
}
if (factor_coul < 1.0) {
forcecoul -= (1.0-factor_coul)*prefactor;
if (EFLAG) ecoul -= (1.0-factor_coul)*prefactor;
}
} else {
union_int_float_t rsq_lookup;
rsq_lookup.f = rsq;
itable = rsq_lookup.i & ncoulmask;
itable >>= ncoulshiftbits;
fraction = (rsq_lookup.f - rtable[itable]) * drtable[itable];
table = ftable[itable] + fraction*dftable[itable];
forcecoul = qtmp*q[j] * table;
if (EFLAG) ecoul = qtmp*q[j] *
(etable[itable] + fraction*detable[itable]);
if (factor_coul < 1.0) {
table = ctable[itable] + fraction*dctable[itable];
prefactor = qtmp*q[j] * table;
forcecoul -= (1.0-factor_coul)*prefactor;
if (EFLAG) ecoul -= (1.0-factor_coul)*prefactor;
}
}
} else forcecoul = 0.0;
if (rsq < cut_ljsq[itype][jtype]) {
if (ljt == LJ12_4) {
const double r4inv=r2inv*r2inv;
forcelj = r4inv*(lj1[itype][jtype]*r4inv*r4inv
- lj2[itype][jtype]);
if (EFLAG)
evdwl = r4inv*(lj3[itype][jtype]*r4inv*r4inv
- lj4[itype][jtype]) - offset[itype][jtype];
} else if (ljt == LJ9_6) {
const double r3inv = r2inv*sqrt(r2inv);
const double r6inv = r3inv*r3inv;
forcelj = r6inv*(lj1[itype][jtype]*r3inv
- lj2[itype][jtype]);
if (EFLAG)
evdwl = r6inv*(lj3[itype][jtype]*r3inv
- lj4[itype][jtype]) - offset[itype][jtype];
} else if (ljt == LJ12_6) {
const double r6inv = r2inv*r2inv*r2inv;
forcelj = r6inv*(lj1[itype][jtype]*r6inv
- lj2[itype][jtype]);<|fim▁hole|> evdwl = r6inv*(lj3[itype][jtype]*r6inv
- lj4[itype][jtype]) - offset[itype][jtype];
}
forcelj *= factor_lj;
if (EFLAG) evdwl *= factor_lj;
}
fpair = (forcecoul + forcelj) * r2inv;
fxtmp += delx*fpair;
fytmp += dely*fpair;
fztmp += delz*fpair;
if (NEWTON_PAIR || j < nlocal) {
f[j][0] -= delx*fpair;
f[j][1] -= dely*fpair;
f[j][2] -= delz*fpair;
}
if (EVFLAG) ev_tally(i,j,nlocal,NEWTON_PAIR,
evdwl,ecoul,fpair,delx,dely,delz);
}
}
f[i][0] += fxtmp;
f[i][1] += fytmp;
f[i][2] += fztmp;
}
}
/* ---------------------------------------------------------------------- */
double PairLJSDKCoulMSM::single(int i, int j, int itype, int jtype,
double rsq,
double factor_coul, double factor_lj,
double &fforce)
{
double r2inv,r,fgamma,egamma,prefactor;
double fraction,table,forcecoul,forcelj,phicoul,philj;
int itable;
forcecoul = forcelj = phicoul = philj = 0.0;
r2inv = 1.0/rsq;
if (rsq < cut_coulsq) {
if (!ncoultablebits || rsq <= tabinnersq) {
r = sqrt(rsq);
prefactor = force->qqrd2e * atom->q[i]*atom->q[j]/r;
egamma = 1.0 - (r/cut_coul)*force->kspace->gamma(r/cut_coul);
fgamma = 1.0 + (rsq/cut_coulsq)*force->kspace->dgamma(r/cut_coul);
forcecoul = prefactor * fgamma;
phicoul = prefactor * egamma;
if (factor_coul < 1.0) {
forcecoul -= (1.0-factor_coul)*prefactor;
phicoul -= (1.0-factor_coul)*prefactor;
}
} else {
union_int_float_t rsq_lookup_single;
rsq_lookup_single.f = rsq;
itable = rsq_lookup_single.i & ncoulmask;
itable >>= ncoulshiftbits;
fraction = (rsq_lookup_single.f - rtable[itable]) * drtable[itable];
table = ftable[itable] + fraction*dftable[itable];
forcecoul = atom->q[i]*atom->q[j] * table;
table = etable[itable] + fraction*detable[itable];
phicoul = atom->q[i]*atom->q[j] * table;
if (factor_coul < 1.0) {
table = ctable[itable] + fraction*dctable[itable];
prefactor = atom->q[i]*atom->q[j] * table;
forcecoul -= (1.0-factor_coul)*prefactor;
phicoul -= (1.0-factor_coul)*prefactor;
}
}
}
if (rsq < cut_ljsq[itype][jtype]) {
const int ljt = lj_type[itype][jtype];
const double ljpow1 = lj_pow1[ljt];
const double ljpow2 = lj_pow2[ljt];
const double ljpref = lj_prefact[ljt];
const double ratio = sigma[itype][jtype]/sqrt(rsq);
const double eps = epsilon[itype][jtype];
forcelj = factor_lj * ljpref*eps * (ljpow1*pow(ratio,ljpow1)
- ljpow2*pow(ratio,ljpow2))/rsq;
philj = factor_lj * (ljpref*eps * (pow(ratio,ljpow1) - pow(ratio,ljpow2))
- offset[itype][jtype]);
}
fforce = (forcecoul + forcelj) * r2inv;
return phicoul + philj;
}
/* ---------------------------------------------------------------------- */
void *PairLJSDKCoulMSM::extract(const char *str, int &dim)
{
dim = 2;
if (strcmp(str,"epsilon") == 0) return (void *) epsilon;
if (strcmp(str,"sigma") == 0) return (void *) sigma;
if (strcmp(str,"lj_type") == 0) return (void *) lj_type;
if (strcmp(str,"lj1") == 0) return (void *) lj1;
if (strcmp(str,"lj2") == 0) return (void *) lj2;
if (strcmp(str,"lj3") == 0) return (void *) lj3;
if (strcmp(str,"lj4") == 0) return (void *) lj4;
if (strcmp(str,"rminsq") == 0) return (void *) rminsq;
if (strcmp(str,"emin") == 0) return (void *) emin;
dim = 0;
if (strcmp(str,"cut_coul") == 0) return (void *) &cut_coul;
if (strcmp(str,"cut_msm") == 0) return (void *) &cut_coul;
return NULL;
}<|fim▁end|>
|
if (EFLAG)
|
<|file_name|>__main__.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python<|fim▁hole|>import argparse
from . import core
from . import gui
def main():
parser = argparse.ArgumentParser(
description="Track opponent's mulligan in the game of Hearthstone.")
parser.add_argument('--gui', action='store_true')
args = parser.parse_args()
if args.gui:
gui.main()
else:
core.main()
if __name__ == '__main__':
main()<|fim▁end|>
| |
<|file_name|>wipe.js<|end_file_name|><|fim▁begin|>var helpers = require('./../../../helpers'),
path = require('path'),
os = require('os'),
should = require('should'),
sinon = require('sinon'),
lib_path = helpers.lib_path(),
join = require('path').join,
custom_dirs = require(join(lib_path, 'agent', 'utils', 'custom-dirs'))
wipe_path = join(lib_path, 'agent', 'actions', 'wipe'),
wipe2 = require(join(lib_path, 'agent', 'actions', 'wipe', 'wipe')),
wipe = require(wipe_path),
wipe_win = require(wipe_path + '/windows'),
sys_index_path = helpers.lib_path('system'),
sys_index = require(sys_index_path),
sys_win = require(join(sys_index_path, 'windows'))
api_path = join(lib_path, 'agent', 'plugins', 'control-panel', 'api'),
keys = require(join(api_path, 'keys'));
var outlook_versions = {
old: {
'2002': '10',
'2003': '11',
'2007': '12',
'2010': '14'
},
new: {
'2013': '15',
'2016': '16',
}
};
var OUTLOOK_NEW = 15,
OUTLOOK_OLD = 10;
var registryPath = {
outlook_version: join('HKEY_CLASSES_ROOT', 'Outlook.Application', 'CurVEr'),
profileRegistry: join('HKEY_CURRENT_USER', 'Software', 'Microsoft'),
firefox: join('HKEY_CLASSES_ROOT', 'FirefoxHTML', 'DefaultIcon'),
thunderbird: join('HKEY_CLASSES_ROOT', 'ThunderbirdEML', 'DefaultIcon')
};
var hash;
describe('wipe valid types', function() {
before(function() {
hash = {
wipe_cloud: false,
wipe_directories: false,
wipe_documents: false,
wipe_passwords: false,
wipe_cookies: false,
wipe_emails: false
}
});
describe('when one type is selected', function() {
describe('and is not directories', function() {
before(function() {
hash.wipe_documents = true;
});
after(function() {
hash.wipe_documents = false;
wipe.directories = [];
});
it('should return documents', function(done) {
var out = wipe.valid_types(hash);
out.should.be.Array;
out.length.should.equal(1);
out[0].should.equal('documents');
done();
})
});
describe('and is directories', function() {
describe('and is only one path', function() {
describe('and the path is blank', function() {
before(function() {
hash.wipe_directories = '';
});
after(function() {
hash.wipe_directories = false;
wipe.directories = [];
});
it('should an empty array', function(done){
var out = wipe.valid_types(hash);
out.should.be.Array;
out.length.should.equal(0);
done();
})
})
describe('and the path is invalid', function() {
before(function() {
hash.wipe_directories = 'not a path';
});
after(function() {
hash.wipe_directories = false;
wipe.directories = [];
});
it('should an empty array', function(done){
var out = wipe.valid_types(hash);
out.should.be.Array;
out.length.should.equal(0);
done();
})
})
describe('and the path is valid', function() {
before(function() {
hash.wipe_directories = '/Users/one/path/to/wipe';
});
after(function() {
hash.wipe_directories = false;
wipe.directories = [];
});
it('should return directories', function(done) {
var out = wipe.valid_types(hash);
out.should.be.Array;
out.length.should.equal(1);
out[0].should.equal('directories');
wipe.directories.length.should.equal(1);
wipe.directories[0].should.equal('/Users/one/path/to/wipe');
done();
})
})
})
describe('and there are more than one path', function() {
describe('and one path is blank', function() {
before(function() {
hash.wipe_directories = '/Users/one/path/to/wipe, ';
});
after(function() {
hash.wipe_directories = false;
wipe.directories = [];
});
it('should return documents', function(done) {
var out = wipe.valid_types(hash);
out.should.be.Array;
out.length.should.equal(1);
out[0].should.equal('directories');
wipe.directories.length.should.equal(1);
wipe.directories[0].should.equal('/Users/one/path/to/wipe');
done();
})
})
describe('and one path is invalid', function() {
describe('and one path is blank', function() {
before(function() {
hash.wipe_directories = '/Users/one/path/to/wipe, invalidpath, /Users/another/valid/path';
});
after(function() {
hash.wipe_directories = false;
wipe.directories = [];
});
it('should return documents', function(done) {
var out = wipe.valid_types(hash);
out.should.be.Array;
out.length.should.equal(1);
out[0].should.equal('directories');
wipe.directories.length.should.equal(2);
wipe.directories[0].should.equal('/Users/one/path/to/wipe');
wipe.directories[1].should.equal('/Users/another/valid/path');
done();
})
})
})
describe('and all paths are valid', function() {
before(function() {
hash.wipe_directories = '/Users/one/path/to/wipe,/Users/another/valid/path,/Users/lastvalid';
});
after(function() {
hash.wipe_directories = false;
wipe.directories = [];
});
it('should return documents', function(done) {
var out = wipe.valid_types(hash);
out.should.be.Array;
out.length.should.equal(1);
out[0].should.equal('directories');
wipe.directories.length.should.equal(3);
wipe.directories[0].should.equal('/Users/one/path/to/wipe');
wipe.directories[1].should.equal('/Users/another/valid/path');
wipe.directories[2].should.equal('/Users/lastvalid');
done();
})
})
})
})
})
describe('when more than one type is selected', function() {
describe('and no includes directories', function() {
before(function() {
hash.wipe_documents = true;
hash.wipe_passwords = true;
hash.wipe_emails = true;
});
after(function() {
hash.wipe_documents = false;
hash.wipe_passwords = false;
hash.wipe_emails = false;
wipe.directories = [];
});
it('should return documents', function(done) {
var out = wipe.valid_types(hash);
out.should.be.Array;
out.length.should.equal(3);
out[0].should.equal('documents');
out[1].should.equal('passwords');
out[2].should.equal('emails');
done();
})
});
describe('and includes directories', function() {
describe('and the path is valid', function() {
before(function() {
hash.wipe_directories = '/Users/valid/path';
hash.wipe_passwords = true;
});
after(function() {
hash.wipe_directories = false;
hash.wipe_passwords = false;
wipe.directories = [];
});
it('should return documents', function(done) {
var out = wipe.valid_types(hash);
out.should.be.Array;
out.length.should.equal(2);
out[0].should.equal('directories');
out[1].should.equal('passwords');
wipe.directories[0].should.equal('/Users/valid/path');
done();
})
})
describe('and the path is invalid', function() {
before(function() {
hash.wipe_directories = 'invalidpath';
hash.wipe_passwords = true;
});
after(function() {
hash.wipe_directories = false;
hash.wipe_passwords = false;
wipe.directories = [];
});
it('should return documents', function(done) {
var out = wipe.valid_types(hash);
out.should.be.Array;
out.length.should.equal(1);
out[0].should.equal('passwords');
wipe.directories.length.should.equal(0);
done();
})
})
});
});
});
describe('in Windows OS', function() {
var platform_stub,
outlook_version,
spy_fetch_dirs;
var opts = { "wipe_directories": "/Users/user/Desktop/file.txt" };
before(() => {
wipe.node_bin = '/usr/local/bin/node';
sys_index.os_name = "windows";
sys_index.check_service = sys_win.check_service;
sys_index.run_as_admin = sys_win.run_as_admin;
platform_stub = sinon.stub(os, 'platform').callsFake(() => { return 'win32'; });
keys_get_stub = sinon.stub(keys, 'get').callsFake(() => {
return { api: 'aaaaaaaaaa', device: 'bbbbbb' }
});
})
after(() => {
platform_stub.restore();
keys_get_stub.restore();
})
describe('on registry commands', function() {
wipe_win.registryManager.query.toString().should.containEql('reg query');
wipe_win.registryManager.add.toString().should.containEql('reg add');
wipe_win.registryManager.delete.toString().should.containEql('reg delete');
wipe_win.registryManager.killtask.toString().should.containEql('taskkill');
})
describe('when running in old Outlook version', function() {
iterate_versions(outlook_versions.old);
});
describe('when running in new Outlook version', function() {
iterate_versions(outlook_versions.new);
});
describe('when service is available', () => {<|fim▁hole|> spy_fetch_dirs = sinon.spy(wipe2, 'fetch_dirs');
sys_win.monitoring_service_go = true;
});
after(() => {
spy_fetch_dirs.restore();
})
it('should wipe through the service', (done) => {
wipe.start("123",opts, (err, em) => {
em.on('end', (err, out) => {
spy_fetch_dirs.calledOnce.should.equal(true);
done();
})
})
})
})
describe('when service is not available', () => {
before(() => {
sys_win.monitoring_service_go = false;
})
it('should not wipe through the service', (done) => {
wipe.start("1234",opts, (err, em) => {
em.on('end', (id,err, out) => {
should.exist(err);
err.message.should.containEql("Wipe command failed.")
done();
})
})
})
})
function iterate_versions(versions) {
Object.keys(versions).forEach(function(k) {
test_outlook_version(k, versions[k]);
});
}
function get_outlook_path(version) {
if (parseInt(version) >= 15) {
return join('HKEY_USERS', 'User1', 'Software', 'Microsoft', 'Office', `${version}.0`, 'Outlook', 'Profiles');
} else if (parseInt(version) < OUTLOOK_NEW && parseInt(version) >= OUTLOOK_OLD) {
return join('HKEY_USERS', 'Software', 'Microsoft', 'User1', 'Windows NT', 'CurrentVersion', 'Windows Messaging Subsystem', 'Profiles');
} else {
return join('HKEY_USERS', 'Software', 'Microsoft', `User1`, 'Windows Messaging Subsystem', 'Profiles');
}
}
function test_outlook_version(version_type, version) {
var stub_path;
var stub_registry;
describe(version_type, function() {
before(function() {
stub_path = sinon.stub(wipe_win, 'getOutlookVersion').callsFake(cb => {
cb(null, version);
})
stub_registry = sinon.stub(wipe_win.registryManager, 'query').callsFake((query, cb) => {
return cb(null, '\r\nUser1\r\n')
})
});
after(function() {
stub_registry.restore();
stub_path.restore();
});
it('returns path', function(done) {
wipe_win.getProfileRegistry(function(err, out) {
out[0].should.equal(get_outlook_path(version));
done();
});
});
});
};
});<|fim▁end|>
|
before(() => {
|
<|file_name|>tradchinese.rs<|end_file_name|><|fim▁begin|>// This is a part of rust-encoding.
// Copyright (c) 2013-2015, Kang Seonghoon.
// See README.md and LICENSE.txt for details.
//! Legacy traditional Chinese encodings.
use std::convert::Into;
use std::default::Default;
use util::StrCharIndex;
use index_tradchinese as index;
use types::*;
/**
* Big5-2003 with common extensions. (XXX with asymmetric HKSCS-2008 support)
*
* This is a traditional Chinese encoding spanning the region `[81-FE] [40-7E A1-FE]`.
* Originally a proprietary encoding by the consortium of five companies (hence the name),
* the Republic of China government standardized Big5-2003 in an appendix of CNS 11643
* so that CNS 11643 plane 1 and plane 2 have
* an almost identical set of characters as Big5 (but with a different mapping).
* The Hong Kong government has an official extension to Big5
* named Hong Kong Supplementary Character Set (HKSCS).
*
* This particular implementation of Big5 includes the widespread ETEN and HKSCS extensions,
* but excludes less common extensions such as Big5+, Big-5E and Unicode-at-on.
*/
#[derive(Clone, Copy)]
pub struct BigFive2003Encoding;
impl Encoding for BigFive2003Encoding {
fn name(&self) -> &'static str { "big5-2003" }
fn whatwg_name(&self) -> Option<&'static str> { Some("big5") } // WHATWG compatibility
fn raw_encoder(&self) -> Box<RawEncoder> { BigFive2003Encoder::new() }
fn raw_decoder(&self) -> Box<RawDecoder> { BigFive2003HKSCS2008Decoder::new() }
}
/// An encoder for Big5-2003.
#[derive(Clone, Copy)]
pub struct BigFive2003Encoder;
impl BigFive2003Encoder {
pub fn new() -> Box<RawEncoder> { Box::new(BigFive2003Encoder) }
}
impl RawEncoder for BigFive2003Encoder {
fn from_self(&self) -> Box<RawEncoder> { BigFive2003Encoder::new() }
fn is_ascii_compatible(&self) -> bool { true }
fn raw_feed(&mut self, input: &str, output: &mut ByteWriter) -> (usize, Option<CodecError>) {
output.writer_hint(input.len());
<|fim▁hole|> let ptr = index::big5::backward(ch as u32);
if ptr == 0xffff {
return (i, Some(CodecError {
upto: j as isize, cause: "unrepresentable character".into()
}));
}
let lead = ptr / 157 + 0x81;
let trail = ptr % 157;
let trailoffset = if trail < 0x3f {0x40} else {0x62};
output.write_byte(lead as u8);
output.write_byte((trail + trailoffset) as u8);
}
}
(input.len(), None)
}
fn raw_finish(&mut self, _output: &mut ByteWriter) -> Option<CodecError> {
None
}
}
/// A decoder for Big5-2003 with HKSCS-2008 extension.
#[derive(Clone, Copy)]
struct BigFive2003HKSCS2008Decoder {
st: bigfive2003::State,
}
impl BigFive2003HKSCS2008Decoder {
pub fn new() -> Box<RawDecoder> {
Box::new(BigFive2003HKSCS2008Decoder { st: Default::default() })
}
}
impl RawDecoder for BigFive2003HKSCS2008Decoder {
fn from_self(&self) -> Box<RawDecoder> { BigFive2003HKSCS2008Decoder::new() }
fn is_ascii_compatible(&self) -> bool { true }
fn raw_feed(&mut self, input: &[u8], output: &mut StringWriter) -> (usize, Option<CodecError>) {
let (st, processed, err) = bigfive2003::raw_feed(self.st, input, output, &());
self.st = st;
(processed, err)
}
fn raw_finish(&mut self, output: &mut StringWriter) -> Option<CodecError> {
let (st, err) = bigfive2003::raw_finish(self.st, output, &());
self.st = st;
err
}
}
stateful_decoder! {
module bigfive2003;
internal pub fn map_two_bytes(lead: u8, trail: u8) -> u32 {
use index_tradchinese as index;
let lead = lead as u16;
let trail = trail as u16;
let index = match (lead, trail) {
(0x81...0xfe, 0x40...0x7e) | (0x81...0xfe, 0xa1...0xfe) => {
let trailoffset = if trail < 0x7f {0x40} else {0x62};
(lead - 0x81) * 157 + trail - trailoffset
}
_ => 0xffff,
};
index::big5::forward(index) // may return two-letter replacements 0..3
}
initial:
// big5 lead = 0x00
state S0(ctx: Context) {
case b @ 0x00...0x7f => ctx.emit(b as u32);
case b @ 0x81...0xfe => S1(ctx, b);
case _ => ctx.err("invalid sequence");
}
transient:
// big5 lead != 0x00
state S1(ctx: Context, lead: u8) {
case b => match map_two_bytes(lead, b) {
0xffff => {
let backup = if b < 0x80 {1} else {0};
ctx.backup_and_err(backup, "invalid sequence")
},
0 /*index=1133*/ => ctx.emit_str("\u{ca}\u{304}"),
1 /*index=1135*/ => ctx.emit_str("\u{ca}\u{30c}"),
2 /*index=1164*/ => ctx.emit_str("\u{ea}\u{304}"),
3 /*index=1166*/ => ctx.emit_str("\u{ea}\u{30c}"),
ch => ctx.emit(ch),
};
}
}
#[cfg(test)]
mod bigfive2003_tests {
extern crate test;
use super::BigFive2003Encoding;
use testutils;
use types::*;
#[test]
fn test_encoder_valid() {
let mut e = BigFive2003Encoding.raw_encoder();
assert_feed_ok!(e, "A", "", [0x41]);
assert_feed_ok!(e, "BC", "", [0x42, 0x43]);
assert_feed_ok!(e, "", "", []);
assert_feed_ok!(e, "\u{4e2d}\u{83ef}\u{6c11}\u{570b}", "",
[0xa4, 0xa4, 0xb5, 0xd8, 0xa5, 0xc1, 0xb0, 0xea]);
assert_feed_ok!(e, "1\u{20ac}/m", "", [0x31, 0xa3, 0xe1, 0x2f, 0x6d]);
assert_feed_ok!(e, "\u{ffed}", "", [0xf9, 0xfe]);
assert_feed_ok!(e, "\u{2550}", "", [0xf9, 0xf9]); // not [0xa2, 0xa4]
assert_finish_ok!(e, []);
}
#[test]
fn test_encoder_invalid() {
let mut e = BigFive2003Encoding.raw_encoder();
assert_feed_err!(e, "", "\u{ffff}", "", []);
assert_feed_err!(e, "?", "\u{ffff}", "!", [0x3f]);
assert_feed_err!(e, "", "\u{3eec}", "\u{4e00}", []); // HKSCS-2008 addition
assert_finish_ok!(e, []);
}
#[test]
fn test_decoder_valid() {
let mut d = BigFive2003Encoding.raw_decoder();
assert_feed_ok!(d, [0x41], [], "A");
assert_feed_ok!(d, [0x42, 0x43], [], "BC");
assert_feed_ok!(d, [], [], "");
assert_feed_ok!(d, [0xa4, 0xa4, 0xb5, 0xd8, 0xa5, 0xc1, 0xb0, 0xea], [],
"\u{4e2d}\u{83ef}\u{6c11}\u{570b}");
assert_feed_ok!(d, [], [0xa4], "");
assert_feed_ok!(d, [0xa4, 0xb5, 0xd8], [0xa5], "\u{4e2d}\u{83ef}");
assert_feed_ok!(d, [0xc1, 0xb0, 0xea], [], "\u{6c11}\u{570b}");
assert_feed_ok!(d, [0x31, 0xa3, 0xe1, 0x2f, 0x6d], [], "1\u{20ac}/m");
assert_feed_ok!(d, [0xf9, 0xfe], [], "\u{ffed}");
assert_feed_ok!(d, [0xf9, 0xf9], [], "\u{2550}");
assert_feed_ok!(d, [0xa2, 0xa4], [], "\u{2550}");
assert_feed_ok!(d, [0x87, 0x7e], [], "\u{3eec}"); // HKSCS-2008 addition
assert_feed_ok!(d, [0x88, 0x62, 0x88, 0x64, 0x88, 0xa3, 0x88, 0xa5], [],
"\u{ca}\u{304}\u{00ca}\u{30c}\u{ea}\u{304}\u{ea}\u{30c}"); // 2-byte output
assert_finish_ok!(d, "");
}
#[test]
fn test_decoder_invalid_lone_lead_immediate_test_finish() {
for i in 0x81..0xff {
let mut d = BigFive2003Encoding.raw_decoder();
assert_feed_ok!(d, [], [i], ""); // wait for a trail
assert_finish_err!(d, "");
}
// 80/FF: immediate failure
let mut d = BigFive2003Encoding.raw_decoder();
assert_feed_err!(d, [], [0x80], [], "");
assert_feed_err!(d, [], [0xff], [], "");
assert_finish_ok!(d, "");
}
#[test]
fn test_decoder_invalid_lone_lead_followed_by_space() {
for i in 0x80..0x100 {
let i = i as u8;
let mut d = BigFive2003Encoding.raw_decoder();
assert_feed_err!(d, [], [i], [0x20], "");
assert_finish_ok!(d, "");
}
}
#[test]
fn test_decoder_invalid_lead_followed_by_invalid_trail() {
// unlike most other cases, valid lead + invalid MSB-set trail are entirely consumed.
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=16771
for i in 0x81..0xff {
let mut d = BigFive2003Encoding.raw_decoder();
assert_feed_err!(d, [], [i, 0x80], [0x20], "");
assert_feed_err!(d, [], [i, 0xff], [0x20], "");
assert_finish_ok!(d, "");
let mut d = BigFive2003Encoding.raw_decoder();
assert_feed_ok!(d, [], [i], "");
assert_feed_err!(d, [], [0x80], [0x20], "");
assert_feed_ok!(d, [], [i], "");
assert_feed_err!(d, [], [0xff], [0x20], "");
assert_finish_ok!(d, "");
}
// 80/FF is not a valid lead and the trail is not consumed
let mut d = BigFive2003Encoding.raw_decoder();
assert_feed_err!(d, [], [0x80], [0x80], "");
assert_feed_err!(d, [], [0x80], [0xff], "");
assert_feed_err!(d, [], [0xff], [0x80], "");
assert_feed_err!(d, [], [0xff], [0xff], "");
assert_finish_ok!(d, "");
}
#[test]
fn test_decoder_feed_after_finish() {
let mut d = BigFive2003Encoding.raw_decoder();
assert_feed_ok!(d, [0xa4, 0x40], [0xa4], "\u{4e00}");
assert_finish_err!(d, "");
assert_feed_ok!(d, [0xa4, 0x40], [], "\u{4e00}");
assert_finish_ok!(d, "");
}
#[bench]
fn bench_encode_short_text(bencher: &mut test::Bencher) {
let s = testutils::TRADITIONAL_CHINESE_TEXT;
bencher.bytes = s.len() as u64;
bencher.iter(|| test::black_box({
BigFive2003Encoding.encode(&s, EncoderTrap::Strict)
}))
}
#[bench]
fn bench_decode_short_text(bencher: &mut test::Bencher) {
let s = BigFive2003Encoding.encode(testutils::TRADITIONAL_CHINESE_TEXT,
EncoderTrap::Strict).ok().unwrap();
bencher.bytes = s.len() as u64;
bencher.iter(|| test::black_box({
BigFive2003Encoding.decode(&s, DecoderTrap::Strict)
}))
}
}<|fim▁end|>
|
for ((i,j), ch) in input.index_iter() {
if ch < '\u{80}' {
output.write_byte(ch as u8);
} else {
|
<|file_name|>filepond.js<|end_file_name|><|fim▁begin|>/*!
* FilePond 4.26.0
* Licensed under MIT, https://opensource.org/licenses/MIT/
* Please visit https://pqina.nl/filepond/ for details.
*/
/* eslint-disable */
(function(global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
? factory(exports)
: typeof define === 'function' && define.amd
? define(['exports'], factory)
: ((global = global || self), factory((global.FilePond = {})));
})(this, function(exports) {
'use strict';
var isNode = function isNode(value) {
return value instanceof HTMLElement;
};
var createStore = function createStore(initialState) {
var queries = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var actions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
// internal state
var state = Object.assign({}, initialState);
// contains all actions for next frame, is clear when actions are requested
var actionQueue = [];
var dispatchQueue = [];
// returns a duplicate of the current state
var getState = function getState() {
return Object.assign({}, state);
};
// returns a duplicate of the actions array and clears the actions array
var processActionQueue = function processActionQueue() {
// create copy of actions queue
var queue = [].concat(actionQueue);
// clear actions queue (we don't want no double actions)
actionQueue.length = 0;
return queue;
};
// processes actions that might block the main UI thread
var processDispatchQueue = function processDispatchQueue() {
// create copy of actions queue
var queue = [].concat(dispatchQueue);
// clear actions queue (we don't want no double actions)
dispatchQueue.length = 0;
// now dispatch these actions
queue.forEach(function(_ref) {
var type = _ref.type,
data = _ref.data;
dispatch(type, data);
});
};
// adds a new action, calls its handler and
var dispatch = function dispatch(type, data, isBlocking) {
// is blocking action (should never block if document is hidden)
if (isBlocking && !document.hidden) {
dispatchQueue.push({ type: type, data: data });
return;
}
// if this action has a handler, handle the action
if (actionHandlers[type]) {
actionHandlers[type](data);
}
// now add action
actionQueue.push({
type: type,
data: data,
});
};
var query = function query(str) {
var _queryHandles;
for (
var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1;
_key < _len;
_key++
) {
args[_key - 1] = arguments[_key];
}
return queryHandles[str]
? (_queryHandles = queryHandles)[str].apply(_queryHandles, args)
: null;
};
var api = {
getState: getState,
processActionQueue: processActionQueue,
processDispatchQueue: processDispatchQueue,
dispatch: dispatch,
query: query,
};
var queryHandles = {};
queries.forEach(function(query) {
queryHandles = Object.assign({}, query(state), {}, queryHandles);
});
var actionHandlers = {};
actions.forEach(function(action) {
actionHandlers = Object.assign({}, action(dispatch, query, state), {}, actionHandlers);
});
return api;
};
var defineProperty = function defineProperty(obj, property, definition) {
if (typeof definition === 'function') {
obj[property] = definition;
return;
}
Object.defineProperty(obj, property, Object.assign({}, definition));
};
var forin = function forin(obj, cb) {
for (var key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
cb(key, obj[key]);
}
};
var createObject = function createObject(definition) {
var obj = {};
forin(definition, function(property) {
defineProperty(obj, property, definition[property]);
});
return obj;
};
var attr = function attr(node, name) {
var value = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
if (value === null) {
return node.getAttribute(name) || node.hasAttribute(name);
}
node.setAttribute(name, value);
};
var ns = 'http://www.w3.org/2000/svg';
var svgElements = ['svg', 'path']; // only svg elements used
var isSVGElement = function isSVGElement(tag) {
return svgElements.includes(tag);
};
var createElement = function createElement(tag, className) {
var attributes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
if (typeof className === 'object') {
attributes = className;
className = null;
}
var element = isSVGElement(tag)
? document.createElementNS(ns, tag)
: document.createElement(tag);
if (className) {
if (isSVGElement(tag)) {
attr(element, 'class', className);
} else {
element.className = className;
}
}
forin(attributes, function(name, value) {
attr(element, name, value);
});
return element;
};
var appendChild = function appendChild(parent) {
return function(child, index) {
if (typeof index !== 'undefined' && parent.children[index]) {
parent.insertBefore(child, parent.children[index]);
} else {
parent.appendChild(child);
}
};
};
var appendChildView = function appendChildView(parent, childViews) {
return function(view, index) {
if (typeof index !== 'undefined') {
childViews.splice(index, 0, view);
} else {
childViews.push(view);
}
return view;
};
};
var removeChildView = function removeChildView(parent, childViews) {
return function(view) {
// remove from child views
childViews.splice(childViews.indexOf(view), 1);
// remove the element
if (view.element.parentNode) {
parent.removeChild(view.element);
}
return view;
};
};
var IS_BROWSER = (function() {
return typeof window !== 'undefined' && typeof window.document !== 'undefined';
})();
var isBrowser = function isBrowser() {
return IS_BROWSER;
};
var testElement = isBrowser() ? createElement('svg') : {};
var getChildCount =
'children' in testElement
? function(el) {
return el.children.length;
}
: function(el) {
return el.childNodes.length;
};
var getViewRect = function getViewRect(elementRect, childViews, offset, scale) {
var left = offset[0] || elementRect.left;
var top = offset[1] || elementRect.top;
var right = left + elementRect.width;
var bottom = top + elementRect.height * (scale[1] || 1);
var rect = {
// the rectangle of the element itself
element: Object.assign({}, elementRect),
// the rectangle of the element expanded to contain its children, does not include any margins
inner: {
left: elementRect.left,
top: elementRect.top,
right: elementRect.right,
bottom: elementRect.bottom,
},
// the rectangle of the element expanded to contain its children including own margin and child margins
// margins will be added after we've recalculated the size
outer: {
left: left,
top: top,
right: right,
bottom: bottom,
},
};
// expand rect to fit all child rectangles
childViews
.filter(function(childView) {
return !childView.isRectIgnored();
})
.map(function(childView) {
return childView.rect;
})
.forEach(function(childViewRect) {
expandRect(rect.inner, Object.assign({}, childViewRect.inner));
expandRect(rect.outer, Object.assign({}, childViewRect.outer));
});
// calculate inner width and height
calculateRectSize(rect.inner);
// append additional margin (top and left margins are included in top and left automatically)
rect.outer.bottom += rect.element.marginBottom;
rect.outer.right += rect.element.marginRight;
// calculate outer width and height
calculateRectSize(rect.outer);
return rect;
};
var expandRect = function expandRect(parent, child) {
// adjust for parent offset
child.top += parent.top;
child.right += parent.left;
child.bottom += parent.top;
child.left += parent.left;
if (child.bottom > parent.bottom) {
parent.bottom = child.bottom;
}
if (child.right > parent.right) {
parent.right = child.right;
}
};
var calculateRectSize = function calculateRectSize(rect) {
rect.width = rect.right - rect.left;
rect.height = rect.bottom - rect.top;
};
var isNumber = function isNumber(value) {
return typeof value === 'number';
};
/**
* Determines if position is at destination
* @param position
* @param destination
* @param velocity
* @param errorMargin
* @returns {boolean}
*/
var thereYet = function thereYet(position, destination, velocity) {
var errorMargin = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0.001;
return Math.abs(position - destination) < errorMargin && Math.abs(velocity) < errorMargin;
};
/**
* Spring animation
*/
var spring =
// default options
function spring() // method definition
{
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref$stiffness = _ref.stiffness,
stiffness = _ref$stiffness === void 0 ? 0.5 : _ref$stiffness,
_ref$damping = _ref.damping,
damping = _ref$damping === void 0 ? 0.75 : _ref$damping,
_ref$mass = _ref.mass,
mass = _ref$mass === void 0 ? 10 : _ref$mass;
var target = null;
var position = null;
var velocity = 0;
var resting = false;
// updates spring state
var interpolate = function interpolate(ts, skipToEndState) {
// in rest, don't animate
if (resting) return;
// need at least a target or position to do springy things
if (!(isNumber(target) && isNumber(position))) {
resting = true;
velocity = 0;
return;
}
// calculate spring force
var f = -(position - target) * stiffness;
// update velocity by adding force based on mass
velocity += f / mass;
// update position by adding velocity
position += velocity;
// slow down based on amount of damping
velocity *= damping;
// we've arrived if we're near target and our velocity is near zero
if (thereYet(position, target, velocity) || skipToEndState) {
position = target;
velocity = 0;
resting = true;
// we done
api.onupdate(position);
api.oncomplete(position);
} else {
// progress update
api.onupdate(position);
}
};
/**
* Set new target value
* @param value
*/
var setTarget = function setTarget(value) {
// if currently has no position, set target and position to this value
if (isNumber(value) && !isNumber(position)) {
position = value;
}
// next target value will not be animated to
if (target === null) {
target = value;
position = value;
}
// let start moving to target
target = value;
// already at target
if (position === target || typeof target === 'undefined') {
// now resting as target is current position, stop moving
resting = true;
velocity = 0;
// done!
api.onupdate(position);
api.oncomplete(position);
return;
}
resting = false;
};
// need 'api' to call onupdate callback
var api = createObject({
interpolate: interpolate,
target: {
set: setTarget,
get: function get() {
return target;
},
},
resting: {
get: function get() {
return resting;
},
},
onupdate: function onupdate(value) {},
oncomplete: function oncomplete(value) {},
});
return api;
};
var easeLinear = function easeLinear(t) {
return t;
};
var easeInOutQuad = function easeInOutQuad(t) {
return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
};
var tween =
// default values
function tween() // method definition
{
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref$duration = _ref.duration,
duration = _ref$duration === void 0 ? 500 : _ref$duration,
_ref$easing = _ref.easing,
easing = _ref$easing === void 0 ? easeInOutQuad : _ref$easing,
_ref$delay = _ref.delay,
delay = _ref$delay === void 0 ? 0 : _ref$delay;
var start = null;
var t;
var p;
var resting = true;
var reverse = false;
var target = null;
var interpolate = function interpolate(ts, skipToEndState) {
if (resting || target === null) return;
if (start === null) {
start = ts;
}
if (ts - start < delay) return;
t = ts - start - delay;
if (t >= duration || skipToEndState) {
t = 1;
p = reverse ? 0 : 1;
api.onupdate(p * target);
api.oncomplete(p * target);
resting = true;
} else {
p = t / duration;
api.onupdate((t >= 0 ? easing(reverse ? 1 - p : p) : 0) * target);
}
};
// need 'api' to call onupdate callback
var api = createObject({
interpolate: interpolate,
target: {
get: function get() {
return reverse ? 0 : target;
},
set: function set(value) {
// is initial value
if (target === null) {
target = value;
api.onupdate(value);
api.oncomplete(value);
return;
}
// want to tween to a smaller value and have a current value
if (value < target) {
target = 1;
reverse = true;
} else {
// not tweening to a smaller value
reverse = false;
target = value;
}
// let's go!
resting = false;
start = null;
},
},
resting: {
get: function get() {
return resting;
},
},
onupdate: function onupdate(value) {},
oncomplete: function oncomplete(value) {},
});
return api;
};
var animator = {
spring: spring,
tween: tween,
};
/*
{ type: 'spring', stiffness: .5, damping: .75, mass: 10 };
{ translation: { type: 'spring', ... }, ... }
{ translation: { x: { type: 'spring', ... } } }
*/
var createAnimator = function createAnimator(definition, category, property) {
// default is single definition
// we check if transform is set, if so, we check if property is set
var def =
definition[category] && typeof definition[category][property] === 'object'
? definition[category][property]
: definition[category] || definition;
var type = typeof def === 'string' ? def : def.type;
var props = typeof def === 'object' ? Object.assign({}, def) : {};
return animator[type] ? animator[type](props) : null;
};
var addGetSet = function addGetSet(keys, obj, props) {
var overwrite = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
obj = Array.isArray(obj) ? obj : [obj];
obj.forEach(function(o) {
keys.forEach(function(key) {
var name = key;
var getter = function getter() {
return props[key];
};
var setter = function setter(value) {
return (props[key] = value);
};
if (typeof key === 'object') {
name = key.key;
getter = key.getter || getter;
setter = key.setter || setter;
}
if (o[name] && !overwrite) {
return;
}
o[name] = {
get: getter,
set: setter,
};
});
});
};
// add to state,
// add getters and setters to internal and external api (if not set)
// setup animators
var animations = function animations(_ref) {
var mixinConfig = _ref.mixinConfig,
viewProps = _ref.viewProps,
viewInternalAPI = _ref.viewInternalAPI,
viewExternalAPI = _ref.viewExternalAPI;
// initial properties
var initialProps = Object.assign({}, viewProps);
// list of all active animations
var animations = [];
// setup animators
forin(mixinConfig, function(property, animation) {
var animator = createAnimator(animation);
if (!animator) {
return;
}
// when the animator updates, update the view state value
animator.onupdate = function(value) {
viewProps[property] = value;
};
// set animator target
animator.target = initialProps[property];
// when value is set, set the animator target value
var prop = {
key: property,
setter: function setter(value) {
// if already at target, we done!
if (animator.target === value) {
return;
}
animator.target = value;
},
getter: function getter() {
return viewProps[property];
},
};
// add getters and setters
addGetSet([prop], [viewInternalAPI, viewExternalAPI], viewProps, true);
// add it to the list for easy updating from the _write method
animations.push(animator);
});
// expose internal write api
return {
write: function write(ts) {
var skipToEndState = document.hidden;
var resting = true;
animations.forEach(function(animation) {
if (!animation.resting) resting = false;
animation.interpolate(ts, skipToEndState);
});
return resting;
},
destroy: function destroy() {},
};
};
var addEvent = function addEvent(element) {
return function(type, fn) {
element.addEventListener(type, fn);
};
};
var removeEvent = function removeEvent(element) {
return function(type, fn) {
element.removeEventListener(type, fn);
};
};
// mixin
var listeners = function listeners(_ref) {
var mixinConfig = _ref.mixinConfig,
viewProps = _ref.viewProps,
viewInternalAPI = _ref.viewInternalAPI,
viewExternalAPI = _ref.viewExternalAPI,
viewState = _ref.viewState,
view = _ref.view;
var events = [];
var add = addEvent(view.element);
var remove = removeEvent(view.element);
viewExternalAPI.on = function(type, fn) {
events.push({
type: type,
fn: fn,
});
add(type, fn);
};
viewExternalAPI.off = function(type, fn) {
events.splice(
events.findIndex(function(event) {
return event.type === type && event.fn === fn;
}),
1
);
remove(type, fn);
};
return {
write: function write() {
// not busy
return true;
},
destroy: function destroy() {
events.forEach(function(event) {
remove(event.type, event.fn);
});
},
};
};
// add to external api and link to props
var apis = function apis(_ref) {
var mixinConfig = _ref.mixinConfig,
viewProps = _ref.viewProps,
viewExternalAPI = _ref.viewExternalAPI;
addGetSet(mixinConfig, viewExternalAPI, viewProps);
};
var isDefined = function isDefined(value) {
return value != null;
};
// add to state,
// add getters and setters to internal and external api (if not set)
// set initial state based on props in viewProps
// apply as transforms each frame
var defaults = {
opacity: 1,
scaleX: 1,
scaleY: 1,
translateX: 0,
translateY: 0,
rotateX: 0,
rotateY: 0,
rotateZ: 0,
originX: 0,
originY: 0,
};
var styles = function styles(_ref) {
var mixinConfig = _ref.mixinConfig,
viewProps = _ref.viewProps,
viewInternalAPI = _ref.viewInternalAPI,
viewExternalAPI = _ref.viewExternalAPI,
view = _ref.view;
// initial props
var initialProps = Object.assign({}, viewProps);
// current props
var currentProps = {};
// we will add those properties to the external API and link them to the viewState
addGetSet(mixinConfig, [viewInternalAPI, viewExternalAPI], viewProps);
// override rect on internal and external rect getter so it takes in account transforms
var getOffset = function getOffset() {
return [viewProps['translateX'] || 0, viewProps['translateY'] || 0];
};
var getScale = function getScale() {
return [viewProps['scaleX'] || 0, viewProps['scaleY'] || 0];
};
var getRect = function getRect() {
return view.rect
? getViewRect(view.rect, view.childViews, getOffset(), getScale())
: null;
};
viewInternalAPI.rect = { get: getRect };
viewExternalAPI.rect = { get: getRect };
// apply view props
mixinConfig.forEach(function(key) {
viewProps[key] =
typeof initialProps[key] === 'undefined' ? defaults[key] : initialProps[key];
});
// expose api
return {
write: function write() {
// see if props have changed
if (!propsHaveChanged(currentProps, viewProps)) {
return;
}
// moves element to correct position on screen
applyStyles(view.element, viewProps);
// store new transforms
Object.assign(currentProps, Object.assign({}, viewProps));
// no longer busy
return true;
},
destroy: function destroy() {},
};
};
var propsHaveChanged = function propsHaveChanged(currentProps, newProps) {
// different amount of keys
if (Object.keys(currentProps).length !== Object.keys(newProps).length) {
return true;
}
// lets analyze the individual props
for (var prop in newProps) {
if (newProps[prop] !== currentProps[prop]) {
return true;
}
}
return false;
};
var applyStyles = function applyStyles(element, _ref2) {
var opacity = _ref2.opacity,
perspective = _ref2.perspective,
translateX = _ref2.translateX,
translateY = _ref2.translateY,
scaleX = _ref2.scaleX,
scaleY = _ref2.scaleY,
rotateX = _ref2.rotateX,
rotateY = _ref2.rotateY,
rotateZ = _ref2.rotateZ,
originX = _ref2.originX,
originY = _ref2.originY,
width = _ref2.width,
height = _ref2.height;
var transforms = '';
var styles = '';
// handle transform origin
if (isDefined(originX) || isDefined(originY)) {
styles += 'transform-origin: ' + (originX || 0) + 'px ' + (originY || 0) + 'px;';
}
// transform order is relevant
// 0. perspective
if (isDefined(perspective)) {
transforms += 'perspective(' + perspective + 'px) ';
}
// 1. translate
if (isDefined(translateX) || isDefined(translateY)) {
transforms +=
'translate3d(' + (translateX || 0) + 'px, ' + (translateY || 0) + 'px, 0) ';
}
// 2. scale
if (isDefined(scaleX) || isDefined(scaleY)) {
transforms +=
'scale3d(' +
(isDefined(scaleX) ? scaleX : 1) +
', ' +
(isDefined(scaleY) ? scaleY : 1) +
', 1) ';
}
// 3. rotate
if (isDefined(rotateZ)) {
transforms += 'rotateZ(' + rotateZ + 'rad) ';
}
if (isDefined(rotateX)) {
transforms += 'rotateX(' + rotateX + 'rad) ';
}
if (isDefined(rotateY)) {
transforms += 'rotateY(' + rotateY + 'rad) ';
}
// add transforms
if (transforms.length) {
styles += 'transform:' + transforms + ';';
}
// add opacity
if (isDefined(opacity)) {
styles += 'opacity:' + opacity + ';';
// if we reach zero, we make the element inaccessible
if (opacity === 0) {
styles += 'visibility:hidden;';
}
// if we're below 100% opacity this element can't be clicked
if (opacity < 1) {
styles += 'pointer-events:none;';
}
}
// add height
if (isDefined(height)) {
styles += 'height:' + height + 'px;';
}
// add width
if (isDefined(width)) {
styles += 'width:' + width + 'px;';
}
// apply styles
var elementCurrentStyle = element.elementCurrentStyle || '';
// if new styles does not match current styles, lets update!
if (styles.length !== elementCurrentStyle.length || styles !== elementCurrentStyle) {
element.style.cssText = styles;
// store current styles so we can compare them to new styles later on
// _not_ getting the style value is faster
element.elementCurrentStyle = styles;
}
};
var Mixins = {
styles: styles,
listeners: listeners,
animations: animations,
apis: apis,
};
var updateRect = function updateRect() {
var rect = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var element = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var style = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
if (!element.layoutCalculated) {
rect.paddingTop = parseInt(style.paddingTop, 10) || 0;
rect.marginTop = parseInt(style.marginTop, 10) || 0;
rect.marginRight = parseInt(style.marginRight, 10) || 0;
rect.marginBottom = parseInt(style.marginBottom, 10) || 0;
rect.marginLeft = parseInt(style.marginLeft, 10) || 0;
element.layoutCalculated = true;
}
rect.left = element.offsetLeft || 0;
rect.top = element.offsetTop || 0;
rect.width = element.offsetWidth || 0;
rect.height = element.offsetHeight || 0;
rect.right = rect.left + rect.width;
rect.bottom = rect.top + rect.height;
rect.scrollTop = element.scrollTop;
rect.hidden = element.offsetParent === null;
return rect;
};
var createView =
// default view definition
function createView() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref$tag = _ref.tag,
tag = _ref$tag === void 0 ? 'div' : _ref$tag,
_ref$name = _ref.name,
name = _ref$name === void 0 ? null : _ref$name,
_ref$attributes = _ref.attributes,
attributes = _ref$attributes === void 0 ? {} : _ref$attributes,
_ref$read = _ref.read,
read = _ref$read === void 0 ? function() {} : _ref$read,
_ref$write = _ref.write,
write = _ref$write === void 0 ? function() {} : _ref$write,
_ref$create = _ref.create,
create = _ref$create === void 0 ? function() {} : _ref$create,
_ref$destroy = _ref.destroy,
destroy = _ref$destroy === void 0 ? function() {} : _ref$destroy,
_ref$filterFrameActio = _ref.filterFrameActionsForChild,
filterFrameActionsForChild =
_ref$filterFrameActio === void 0
? function(child, actions) {
return actions;
}
: _ref$filterFrameActio,
_ref$didCreateView = _ref.didCreateView,
didCreateView = _ref$didCreateView === void 0 ? function() {} : _ref$didCreateView,
_ref$didWriteView = _ref.didWriteView,
didWriteView = _ref$didWriteView === void 0 ? function() {} : _ref$didWriteView,
_ref$ignoreRect = _ref.ignoreRect,
ignoreRect = _ref$ignoreRect === void 0 ? false : _ref$ignoreRect,
_ref$ignoreRectUpdate = _ref.ignoreRectUpdate,
ignoreRectUpdate = _ref$ignoreRectUpdate === void 0 ? false : _ref$ignoreRectUpdate,
_ref$mixins = _ref.mixins,
mixins = _ref$mixins === void 0 ? [] : _ref$mixins;
return function(
// each view requires reference to store
store
) {
var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
// root element should not be changed
var element = createElement(tag, 'filepond--' + name, attributes);
// style reference should also not be changed
var style = window.getComputedStyle(element, null);
// element rectangle
var rect = updateRect();
var frameRect = null;
// rest state
var isResting = false;
// pretty self explanatory
var childViews = [];
// loaded mixins
var activeMixins = [];
// references to created children
var ref = {};
// state used for each instance
var state = {};
// list of writers that will be called to update this view
var writers = [
write, // default writer
];
var readers = [
read, // default reader
];
var destroyers = [
destroy, // default destroy
];
// core view methods
var getElement = function getElement() {
return element;
};
var getChildViews = function getChildViews() {
return childViews.concat();
};
var getReference = function getReference() {
return ref;
};
var createChildView = function createChildView(store) {
return function(view, props) {
return view(store, props);
};
};
var getRect = function getRect() {
if (frameRect) {
return frameRect;
}
frameRect = getViewRect(rect, childViews, [0, 0], [1, 1]);
return frameRect;
};
var getStyle = function getStyle() {
return style;
};
/**
* Read data from DOM
* @private
*/
var _read = function _read() {
frameRect = null;
// read child views
childViews.forEach(function(child) {
return child._read();
});
var shouldUpdate = !(ignoreRectUpdate && rect.width && rect.height);
if (shouldUpdate) {
updateRect(rect, element, style);
}
// readers
var api = { root: internalAPI, props: props, rect: rect };
readers.forEach(function(reader) {
return reader(api);
});
};
/**
* Write data to DOM
* @private
*/
var _write = function _write(ts, frameActions, shouldOptimize) {
// if no actions, we assume that the view is resting
var resting = frameActions.length === 0;
// writers
writers.forEach(function(writer) {
var writerResting = writer({
props: props,
root: internalAPI,
actions: frameActions,
timestamp: ts,
shouldOptimize: shouldOptimize,
});
if (writerResting === false) {
resting = false;
}
});
// run mixins
activeMixins.forEach(function(mixin) {
// if one of the mixins is still busy after write operation, we are not resting
var mixinResting = mixin.write(ts);
if (mixinResting === false) {
resting = false;
}
});
// updates child views that are currently attached to the DOM
childViews
.filter(function(child) {
return !!child.element.parentNode;
})
.forEach(function(child) {
// if a child view is not resting, we are not resting
var childResting = child._write(
ts,
filterFrameActionsForChild(child, frameActions),
shouldOptimize
);
if (!childResting) {
resting = false;
}
});
// append new elements to DOM and update those
childViews
//.filter(child => !child.element.parentNode)
.forEach(function(child, index) {
// skip
if (child.element.parentNode) {
return;
}
// append to DOM
internalAPI.appendChild(child.element, index);
// call read (need to know the size of these elements)
child._read();
// re-call write
child._write(
ts,
filterFrameActionsForChild(child, frameActions),
shouldOptimize
);
// we just added somthing to the dom, no rest
resting = false;
});
// update resting state
isResting = resting;
didWriteView({
props: props,
root: internalAPI,
actions: frameActions,
timestamp: ts,
});
// let parent know if we are resting
return resting;
};
var _destroy = function _destroy() {
activeMixins.forEach(function(mixin) {
return mixin.destroy();
});
destroyers.forEach(function(destroyer) {
destroyer({ root: internalAPI, props: props });
});
childViews.forEach(function(child) {
return child._destroy();
});
};
// sharedAPI
var sharedAPIDefinition = {
element: {
get: getElement,
},
style: {
get: getStyle,
},
childViews: {
get: getChildViews,
},
};
// private API definition
var internalAPIDefinition = Object.assign({}, sharedAPIDefinition, {
rect: {
get: getRect,
},
// access to custom children references
ref: {
get: getReference,
},
// dom modifiers
is: function is(needle) {
return name === needle;
},
appendChild: appendChild(element),
createChildView: createChildView(store),
linkView: function linkView(view) {
childViews.push(view);
return view;
},
unlinkView: function unlinkView(view) {
childViews.splice(childViews.indexOf(view), 1);
},
appendChildView: appendChildView(element, childViews),
removeChildView: removeChildView(element, childViews),
registerWriter: function registerWriter(writer) {
return writers.push(writer);
},
registerReader: function registerReader(reader) {
return readers.push(reader);
},
registerDestroyer: function registerDestroyer(destroyer) {
return destroyers.push(destroyer);
},
invalidateLayout: function invalidateLayout() {
return (element.layoutCalculated = false);
},
// access to data store
dispatch: store.dispatch,
query: store.query,
});
// public view API methods
var externalAPIDefinition = {
element: {
get: getElement,
},
childViews: {
get: getChildViews,
},
rect: {
get: getRect,
},
resting: {
get: function get() {
return isResting;
},
},
isRectIgnored: function isRectIgnored() {
return ignoreRect;
},
_read: _read,
_write: _write,
_destroy: _destroy,
};
// mixin API methods
var mixinAPIDefinition = Object.assign({}, sharedAPIDefinition, {
rect: {
get: function get() {
return rect;
},
},
});
// add mixin functionality
Object.keys(mixins)
.sort(function(a, b) {
// move styles to the back of the mixin list (so adjustments of other mixins are applied to the props correctly)
if (a === 'styles') {
return 1;
} else if (b === 'styles') {
return -1;
}
return 0;
})
.forEach(function(key) {
var mixinAPI = Mixins[key]({
mixinConfig: mixins[key],
viewProps: props,
viewState: state,
viewInternalAPI: internalAPIDefinition,
viewExternalAPI: externalAPIDefinition,
view: createObject(mixinAPIDefinition),
});
if (mixinAPI) {
activeMixins.push(mixinAPI);
}
});
// construct private api
var internalAPI = createObject(internalAPIDefinition);
// create the view
create({
root: internalAPI,
props: props,
});
// append created child views to root node
var childCount = getChildCount(element); // need to know the current child count so appending happens in correct order
childViews.forEach(function(child, index) {
internalAPI.appendChild(child.element, childCount + index);
});
// call did create
didCreateView(internalAPI);
// expose public api
return createObject(externalAPIDefinition);
};
};
var createPainter = function createPainter(read, write) {
var fps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 60;
var name = '__framePainter';
// set global painter
if (window[name]) {
window[name].readers.push(read);
window[name].writers.push(write);
return;
}
window[name] = {
readers: [read],
writers: [write],
};
var painter = window[name];
var interval = 1000 / fps;
var last = null;
var id = null;
var requestTick = null;
var cancelTick = null;
var setTimerType = function setTimerType() {
if (document.hidden) {
requestTick = function requestTick() {
return window.setTimeout(function() {
return tick(performance.now());
}, interval);
};
cancelTick = function cancelTick() {
return window.clearTimeout(id);
};
} else {
requestTick = function requestTick() {
return window.requestAnimationFrame(tick);
};
cancelTick = function cancelTick() {
return window.cancelAnimationFrame(id);
};
}
};
document.addEventListener('visibilitychange', function() {
if (cancelTick) cancelTick();
setTimerType();
tick(performance.now());
});
var tick = function tick(ts) {
// queue next tick
id = requestTick(tick);
// limit fps
if (!last) {
last = ts;
}
var delta = ts - last;
if (delta <= interval) {
// skip frame
return;
}
// align next frame
last = ts - (delta % interval);
// update view
painter.readers.forEach(function(read) {
return read();
});
painter.writers.forEach(function(write) {
return write(ts);
});
};
setTimerType();
tick(performance.now());
return {
pause: function pause() {
cancelTick(id);
},
};
};
var createRoute = function createRoute(routes, fn) {
return function(_ref) {
var root = _ref.root,
props = _ref.props,
_ref$actions = _ref.actions,
actions = _ref$actions === void 0 ? [] : _ref$actions,
timestamp = _ref.timestamp,
shouldOptimize = _ref.shouldOptimize;
actions
.filter(function(action) {
return routes[action.type];
})
.forEach(function(action) {
return routes[action.type]({
root: root,
props: props,
action: action.data,
timestamp: timestamp,
shouldOptimize: shouldOptimize,
});
});
if (fn) {
fn({
root: root,
props: props,
actions: actions,
timestamp: timestamp,
shouldOptimize: shouldOptimize,
});
}
};
};
var insertBefore = function insertBefore(newNode, referenceNode) {
return referenceNode.parentNode.insertBefore(newNode, referenceNode);
};
var insertAfter = function insertAfter(newNode, referenceNode) {
return referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
};
var isArray = function isArray(value) {
return Array.isArray(value);
};
var isEmpty = function isEmpty(value) {
return value == null;
};
var trim = function trim(str) {
return str.trim();
};
var toString = function toString(value) {
return '' + value;
};
var toArray = function toArray(value) {
var splitter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ',';
if (isEmpty(value)) {
return [];
}
if (isArray(value)) {
return value;
}
return toString(value)
.split(splitter)
.map(trim)
.filter(function(str) {
return str.length;
});
};
var isBoolean = function isBoolean(value) {
return typeof value === 'boolean';
};
var toBoolean = function toBoolean(value) {
return isBoolean(value) ? value : value === 'true';
};
var isString = function isString(value) {
return typeof value === 'string';
};
var toNumber = function toNumber(value) {
return isNumber(value)
? value
: isString(value)
? toString(value).replace(/[a-z]+/gi, '')
: 0;
};
var toInt = function toInt(value) {
return parseInt(toNumber(value), 10);
};
var toFloat = function toFloat(value) {
return parseFloat(toNumber(value));
};
var isInt = function isInt(value) {
return isNumber(value) && isFinite(value) && Math.floor(value) === value;
};
var toBytes = function toBytes(value) {
var base = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1000;
// is in bytes
if (isInt(value)) {
return value;
}
// is natural file size
var naturalFileSize = toString(value).trim();
// if is value in megabytes
if (/MB$/i.test(naturalFileSize)) {
naturalFileSize = naturalFileSize.replace(/MB$i/, '').trim();
return toInt(naturalFileSize) * base * base;
}
// if is value in kilobytes
if (/KB/i.test(naturalFileSize)) {
naturalFileSize = naturalFileSize.replace(/KB$i/, '').trim();
return toInt(naturalFileSize) * base;
}
return toInt(naturalFileSize);
};
var isFunction = function isFunction(value) {
return typeof value === 'function';
};
var toFunctionReference = function toFunctionReference(string) {
var ref = self;
var levels = string.split('.');
var level = null;
while ((level = levels.shift())) {
ref = ref[level];
if (!ref) {
return null;
}
}
return ref;
};
var methods = {
process: 'POST',
patch: 'PATCH',
revert: 'DELETE',
fetch: 'GET',
restore: 'GET',
load: 'GET',
};
var createServerAPI = function createServerAPI(outline) {
var api = {};
api.url = isString(outline) ? outline : outline.url || '';
api.timeout = outline.timeout ? parseInt(outline.timeout, 10) : 0;
api.headers = outline.headers ? outline.headers : {};
forin(methods, function(key) {
api[key] = createAction(key, outline[key], methods[key], api.timeout, api.headers);
});
// special treatment for remove
api.remove = outline.remove || null;
// remove generic headers from api object
delete api.headers;
return api;
};
var createAction = function createAction(name, outline, method, timeout, headers) {
// is explicitely set to null so disable
if (outline === null) {
return null;
}
// if is custom function, done! Dev handles everything.
if (typeof outline === 'function') {
return outline;
}
// build action object
var action = {
url: method === 'GET' || method === 'PATCH' ? '?' + name + '=' : '',
method: method,
headers: headers,
withCredentials: false,
timeout: timeout,
onload: null,
ondata: null,
onerror: null,
};
// is a single url
if (isString(outline)) {
action.url = outline;
return action;
}
// overwrite
Object.assign(action, outline);
// see if should reformat headers;
if (isString(action.headers)) {
var parts = action.headers.split(/:(.+)/);
action.headers = {
header: parts[0],
value: parts[1],
};
}
// if is bool withCredentials
action.withCredentials = toBoolean(action.withCredentials);
return action;
};
var toServerAPI = function toServerAPI(value) {
return createServerAPI(value);
};
var isNull = function isNull(value) {
return value === null;
};
var isObject = function isObject(value) {
return typeof value === 'object' && value !== null;
};
var isAPI = function isAPI(value) {
return (
isObject(value) &&
isString(value.url) &&
isObject(value.process) &&
isObject(value.revert) &&
isObject(value.restore) &&
isObject(value.fetch)
);
};
var getType = function getType(value) {
if (isArray(value)) {
return 'array';
}
if (isNull(value)) {
return 'null';
}
if (isInt(value)) {
return 'int';
}
if (/^[0-9]+ ?(?:GB|MB|KB)$/gi.test(value)) {
return 'bytes';
}
if (isAPI(value)) {
return 'api';
}
return typeof value;
};
var replaceSingleQuotes = function replaceSingleQuotes(str) {
return str
.replace(/{\s*'/g, '{"')
.replace(/'\s*}/g, '"}')
.replace(/'\s*:/g, '":')
.replace(/:\s*'/g, ':"')
.replace(/,\s*'/g, ',"')
.replace(/'\s*,/g, '",');
};
var conversionTable = {
array: toArray,
boolean: toBoolean,
int: function int(value) {
return getType(value) === 'bytes' ? toBytes(value) : toInt(value);
},
number: toFloat,
float: toFloat,
bytes: toBytes,
string: function string(value) {
return isFunction(value) ? value : toString(value);
},
function: function _function(value) {
return toFunctionReference(value);
},
serverapi: toServerAPI,
object: function object(value) {
try {
return JSON.parse(replaceSingleQuotes(value));
} catch (e) {
return null;
}
},
};
var convertTo = function convertTo(value, type) {
return conversionTable[type](value);
};
var getValueByType = function getValueByType(newValue, defaultValue, valueType) {
// can always assign default value
if (newValue === defaultValue) {
return newValue;
}
// get the type of the new value
var newValueType = getType(newValue);
// is valid type?
if (newValueType !== valueType) {
// is string input, let's attempt to convert
var convertedValue = convertTo(newValue, valueType);
// what is the type now
newValueType = getType(convertedValue);
// no valid conversions found
if (convertedValue === null) {
throw 'Trying to assign value with incorrect type to "' +
option +
'", allowed type: "' +
valueType +
'"';
} else {
newValue = convertedValue;
}
}
// assign new value
return newValue;
};
var createOption = function createOption(defaultValue, valueType) {
var currentValue = defaultValue;
return {
enumerable: true,
get: function get() {
return currentValue;
},
set: function set(newValue) {
currentValue = getValueByType(newValue, defaultValue, valueType);
},
};
};
var createOptions = function createOptions(options) {
var obj = {};
forin(options, function(prop) {
var optionDefinition = options[prop];
obj[prop] = createOption(optionDefinition[0], optionDefinition[1]);
});
return createObject(obj);
};
var createInitialState = function createInitialState(options) {
return {
// model
items: [],
// timeout used for calling update items
listUpdateTimeout: null,
// timeout used for stacking metadata updates
itemUpdateTimeout: null,
// queue of items waiting to be processed
processingQueue: [],
// options
options: createOptions(options),
};
};
var fromCamels = function fromCamels(string) {
var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '-';
return string
.split(/(?=[A-Z])/)
.map(function(part) {
return part.toLowerCase();
})
.join(separator);
};
var createOptionAPI = function createOptionAPI(store, options) {
var obj = {};
forin(options, function(key) {
obj[key] = {
get: function get() {
return store.getState().options[key];
},
set: function set(value) {
store.dispatch('SET_' + fromCamels(key, '_').toUpperCase(), {
value: value,
});
},
};
});
return obj;
};
var createOptionActions = function createOptionActions(options) {
return function(dispatch, query, state) {
var obj = {};
forin(options, function(key) {
var name = fromCamels(key, '_').toUpperCase();
obj['SET_' + name] = function(action) {
try {
state.options[key] = action.value;
} catch (e) {} // nope, failed
// we successfully set the value of this option
dispatch('DID_SET_' + name, { value: state.options[key] });
};
});
return obj;
};
};
var createOptionQueries = function createOptionQueries(options) {
return function(state) {
var obj = {};
forin(options, function(key) {
obj['GET_' + fromCamels(key, '_').toUpperCase()] = function(action) {
return state.options[key];
};
});
return obj;
};
};
var InteractionMethod = {
API: 1,
DROP: 2,
BROWSE: 3,
PASTE: 4,
NONE: 5,
};
var getUniqueId = function getUniqueId() {
return Math.random()
.toString(36)
.substr(2, 9);
};
function _typeof(obj) {
if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') {
_typeof = function(obj) {
return typeof obj;
};
} else {
_typeof = function(obj) {
return obj &&
typeof Symbol === 'function' &&
obj.constructor === Symbol &&
obj !== Symbol.prototype
? 'symbol'
: typeof obj;
};
}
return _typeof(obj);
}
var REACT_ELEMENT_TYPE;
function _jsx(type, props, key, children) {
if (!REACT_ELEMENT_TYPE) {
REACT_ELEMENT_TYPE =
(typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element')) ||
0xeac7;
}
var defaultProps = type && type.defaultProps;
var childrenLength = arguments.length - 3;
if (!props && childrenLength !== 0) {
props = {
children: void 0,
};
}
if (props && defaultProps) {
for (var propName in defaultProps) {
if (props[propName] === void 0) {
props[propName] = defaultProps[propName];
}
}
} else if (!props) {
props = defaultProps || {};
}
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = new Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 3];
}
props.children = childArray;
}
return {
$$typeof: REACT_ELEMENT_TYPE,
type: type,
key: key === undefined ? null : '' + key,
ref: null,
props: props,
_owner: null,
};
}
function _asyncIterator(iterable) {
var method;
if (typeof Symbol !== 'undefined') {
if (Symbol.asyncIterator) {
method = iterable[Symbol.asyncIterator];
if (method != null) return method.call(iterable);
}
if (Symbol.iterator) {
method = iterable[Symbol.iterator];
if (method != null) return method.call(iterable);
}
}
throw new TypeError('Object is not async iterable');
}
function _AwaitValue(value) {
this.wrapped = value;
}
function _AsyncGenerator(gen) {
var front, back;
function send(key, arg) {
return new Promise(function(resolve, reject) {
var request = {
key: key,
arg: arg,
resolve: resolve,
reject: reject,
next: null,
};
if (back) {
back = back.next = request;
} else {
front = back = request;
resume(key, arg);
}
});
}
function resume(key, arg) {
try {
var result = gen[key](arg);
var value = result.value;
var wrappedAwait = value instanceof _AwaitValue;
Promise.resolve(wrappedAwait ? value.wrapped : value).then(
function(arg) {
if (wrappedAwait) {
resume('next', arg);
return;
}
settle(result.done ? 'return' : 'normal', arg);
},
function(err) {
resume('throw', err);
}
);
} catch (err) {
settle('throw', err);
}
}
function settle(type, value) {
switch (type) {
case 'return':
front.resolve({
value: value,
done: true,
});
break;
case 'throw':
front.reject(value);
break;
default:
front.resolve({
value: value,
done: false,
});
break;
}
front = front.next;
if (front) {
resume(front.key, front.arg);
} else {
back = null;
}
}
this._invoke = send;
if (typeof gen.return !== 'function') {
this.return = undefined;
}
}
if (typeof Symbol === 'function' && Symbol.asyncIterator) {
_AsyncGenerator.prototype[Symbol.asyncIterator] = function() {
return this;
};
}
_AsyncGenerator.prototype.next = function(arg) {
return this._invoke('next', arg);
};
_AsyncGenerator.prototype.throw = function(arg) {
return this._invoke('throw', arg);
};
_AsyncGenerator.prototype.return = function(arg) {
return this._invoke('return', arg);
};
function _wrapAsyncGenerator(fn) {
return function() {
return new _AsyncGenerator(fn.apply(this, arguments));
};
}
function _awaitAsyncGenerator(value) {
return new _AwaitValue(value);
}
function _asyncGeneratorDelegate(inner, awaitWrap) {
var iter = {},
waiting = false;
function pump(key, value) {
waiting = true;
value = new Promise(function(resolve) {
resolve(inner[key](value));
});
return {
done: false,
value: awaitWrap(value),
};
}
if (typeof Symbol === 'function' && Symbol.iterator) {
iter[Symbol.iterator] = function() {
return this;
};
}
iter.next = function(value) {
if (waiting) {
waiting = false;
return value;
}
return pump('next', value);
};
if (typeof inner.throw === 'function') {
iter.throw = function(value) {
if (waiting) {
waiting = false;
throw value;
}
return pump('throw', value);
};
}
if (typeof inner.return === 'function') {
iter.return = function(value) {
return pump('return', value);
};
}
return iter;
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function() {
var self = this,
args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'next', value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'throw', err);
}
_next(undefined);
});
};
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError('Cannot call a class as a function');
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ('value' in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _defineEnumerableProperties(obj, descs) {
for (var key in descs) {
var desc = descs[key];
desc.configurable = desc.enumerable = true;
if ('value' in desc) desc.writable = true;
Object.defineProperty(obj, key, desc);
}
if (Object.getOwnPropertySymbols) {
var objectSymbols = Object.getOwnPropertySymbols(descs);
for (var i = 0; i < objectSymbols.length; i++) {
var sym = objectSymbols[i];
var desc = descs[sym];
desc.configurable = desc.enumerable = true;
if ('value' in desc) desc.writable = true;
Object.defineProperty(obj, sym, desc);
}
}
return obj;
}
function _defaults(obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = Object.getOwnPropertyDescriptor(defaults, key);
if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}
return obj;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true,
});
} else {
obj[key] = value;
}
return obj;
}
function _extends() {
_extends =
Object.assign ||
function(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === 'function') {
ownKeys = ownKeys.concat(
Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
})
);
}
ownKeys.forEach(function(key) {
_defineProperty(target, key, source[key]);
});
}
return target;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly)
symbols = symbols.filter(function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(source, true).forEach(function(key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(source).forEach(function(key) {
Object.defineProperty(
target,
key,
Object.getOwnPropertyDescriptor(source, key)
);
});
}
}
return target;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== 'function' && superClass !== null) {
throw new TypeError('Super expression must either be null or a function');
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true,
},
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf
? Object.getPrototypeOf
: function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf =
Object.setPrototypeOf ||
function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function isNativeReflectConstruct() {
if (typeof Reflect === 'undefined' || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === 'function') return true;
try {
Date.prototype.toString.call(Reflect.construct(Date, [], function() {}));
return true;
} catch (e) {
return false;
}
}
function _construct(Parent, args, Class) {
if (isNativeReflectConstruct()) {
_construct = Reflect.construct;
} else {
_construct = function _construct(Parent, args, Class) {
var a = [null];
a.push.apply(a, args);
var Constructor = Function.bind.apply(Parent, a);
var instance = new Constructor();
if (Class) _setPrototypeOf(instance, Class.prototype);
return instance;
};
}
return _construct.apply(null, arguments);
}
function _isNativeFunction(fn) {
return Function.toString.call(fn).indexOf('[native code]') !== -1;
}
function _wrapNativeSuper(Class) {
var _cache = typeof Map === 'function' ? new Map() : undefined;
_wrapNativeSuper = function _wrapNativeSuper(Class) {
if (Class === null || !_isNativeFunction(Class)) return Class;
if (typeof Class !== 'function') {
throw new TypeError('Super expression must either be null or a function');
}
if (typeof _cache !== 'undefined') {
if (_cache.has(Class)) return _cache.get(Class);
_cache.set(Class, Wrapper);
}
function Wrapper() {
return _construct(Class, arguments, _getPrototypeOf(this).constructor);
}
Wrapper.prototype = Object.create(Class.prototype, {
constructor: {
value: Wrapper,
enumerable: false,
writable: true,
configurable: true,
},
});
return _setPrototypeOf(Wrapper, Class);
};
return _wrapNativeSuper(Class);
}
function _instanceof(left, right) {
if (right != null && typeof Symbol !== 'undefined' && right[Symbol.hasInstance]) {
return !!right[Symbol.hasInstance](left);
} else {
return left instanceof right;
}
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule
? obj
: {
default: obj,
};
}
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};
if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var desc =
Object.defineProperty && Object.getOwnPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: {};
if (desc.get || desc.set) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
}
newObj.default = obj;
return newObj;
}
}
function _newArrowCheck(innerThis, boundThis) {
if (innerThis !== boundThis) {
throw new TypeError('Cannot instantiate an arrow function');
}
}
function _objectDestructuringEmpty(obj) {
if (obj == null) throw new TypeError('Cannot destructure undefined');
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === 'object' || typeof call === 'function')) {
return call;
}
return _assertThisInitialized(self);
}
function _superPropBase(object, property) {
while (!Object.prototype.hasOwnProperty.call(object, property)) {
object = _getPrototypeOf(object);
if (object === null) break;
}
return object;
}
function _get(target, property, receiver) {
if (typeof Reflect !== 'undefined' && Reflect.get) {
_get = Reflect.get;
} else {
_get = function _get(target, property, receiver) {
var base = _superPropBase(target, property);
if (!base) return;
var desc = Object.getOwnPropertyDescriptor(base, property);
if (desc.get) {
return desc.get.call(receiver);
}
return desc.value;
};
}
return _get(target, property, receiver || target);
}
function set(target, property, value, receiver) {
if (typeof Reflect !== 'undefined' && Reflect.set) {
set = Reflect.set;
} else {
set = function set(target, property, value, receiver) {
var base = _superPropBase(target, property);
var desc;
if (base) {
desc = Object.getOwnPropertyDescriptor(base, property);
if (desc.set) {
desc.set.call(receiver, value);
return true;
} else if (!desc.writable) {
return false;
}
}
desc = Object.getOwnPropertyDescriptor(receiver, property);
if (desc) {
if (!desc.writable) {
return false;
}
desc.value = value;
Object.defineProperty(receiver, property, desc);
} else {
_defineProperty(receiver, property, value);
}
return true;
};
}
return set(target, property, value, receiver);
}
function _set(target, property, value, receiver, isStrict) {
var s = set(target, property, value, receiver || target);
if (!s && isStrict) {
throw new Error('failed to set property');
}
return value;
}
function _taggedTemplateLiteral(strings, raw) {
if (!raw) {
raw = strings.slice(0);
}
return Object.freeze(
Object.defineProperties(strings, {
raw: {
value: Object.freeze(raw),
},
})
);
}
function _taggedTemplateLiteralLoose(strings, raw) {
if (!raw) {
raw = strings.slice(0);
}
strings.raw = raw;
return strings;
}
function _temporalRef(val, name) {
if (val === _temporalUndefined) {
throw new ReferenceError(name + ' is not defined - temporal dead zone');
} else {
return val;
}
}
function _readOnlyError(name) {
throw new Error('"' + name + '" is read-only');
}
function _classNameTDZError(name) {
throw new Error('Class "' + name + '" cannot be referenced in computed property keys.');
}
var _temporalUndefined = {};
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
}
function _slicedToArrayLoose(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimitLoose(arr, i) || _nonIterableRest();
}
function _toArray(arr) {
return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest();
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
}
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArray(iter) {
if (
Symbol.iterator in Object(iter) ||
Object.prototype.toString.call(iter) === '[object Arguments]'
)
return Array.from(iter);
}
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i['return'] != null) _i['return']();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _iterableToArrayLimitLoose(arr, i) {
var _arr = [];
for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done; ) {
_arr.push(_step.value);
if (i && _arr.length === i) break;
}
return _arr;
}
function _nonIterableSpread() {
throw new TypeError('Invalid attempt to spread non-iterable instance');
}
function _nonIterableRest() {
throw new TypeError('Invalid attempt to destructure non-iterable instance');
}
function _skipFirstGeneratorNext(fn) {
return function() {
var it = fn.apply(this, arguments);
it.next();
return it;
};
}
function _toPrimitive(input, hint) {
if (typeof input !== 'object' || input === null) return input;
var prim = input[Symbol.toPrimitive];
if (prim !== undefined) {
var res = prim.call(input, hint || 'default');
if (typeof res !== 'object') return res;
throw new TypeError('@@toPrimitive must return a primitive value.');
}
return (hint === 'string' ? String : Number)(input);
}
function _toPropertyKey(arg) {
var key = _toPrimitive(arg, 'string');
return typeof key === 'symbol' ? key : String(key);
}
function _initializerWarningHelper(descriptor, context) {
throw new Error(
'Decorating class property failed. Please ensure that ' +
'proposal-class-properties is enabled and set to use loose mode. ' +
'To use proposal-class-properties in spec mode with decorators, wait for ' +
'the next major version of decorators in stage 2.'
);
}
function _initializerDefineProperty(target, property, descriptor, context) {
if (!descriptor) return;
Object.defineProperty(target, property, {
enumerable: descriptor.enumerable,
configurable: descriptor.configurable,
writable: descriptor.writable,
value: descriptor.initializer ? descriptor.initializer.call(context) : void 0,
});
}
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
var desc = {};
Object.keys(descriptor).forEach(function(key) {
desc[key] = descriptor[key];
});
desc.enumerable = !!desc.enumerable;
desc.configurable = !!desc.configurable;
if ('value' in desc || desc.initializer) {
desc.writable = true;
}
desc = decorators
.slice()
.reverse()
.reduce(function(desc, decorator) {
return decorator(target, property, desc) || desc;
}, desc);
if (context && desc.initializer !== void 0) {
desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
desc.initializer = undefined;
}
if (desc.initializer === void 0) {
Object.defineProperty(target, property, desc);
desc = null;
}
return desc;
}
var id = 0;
function _classPrivateFieldLooseKey(name) {
return '__private_' + id++ + '_' + name;
}
function _classPrivateFieldLooseBase(receiver, privateKey) {
if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) {
throw new TypeError('attempted to use private field on non-instance');
}
return receiver;
}
function _classPrivateFieldGet(receiver, privateMap) {
var descriptor = privateMap.get(receiver);
if (!descriptor) {
throw new TypeError('attempted to get private field on non-instance');
}
if (descriptor.get) {
return descriptor.get.call(receiver);
}
return descriptor.value;
}
function _classPrivateFieldSet(receiver, privateMap, value) {
var descriptor = privateMap.get(receiver);
if (!descriptor) {
throw new TypeError('attempted to set private field on non-instance');
}
if (descriptor.set) {
descriptor.set.call(receiver, value);
} else {
if (!descriptor.writable) {
throw new TypeError('attempted to set read only private field');
}
descriptor.value = value;
}
return value;
}
function _classPrivateFieldDestructureSet(receiver, privateMap) {
if (!privateMap.has(receiver)) {
throw new TypeError('attempted to set private field on non-instance');
}
var descriptor = privateMap.get(receiver);
if (descriptor.set) {
if (!('__destrObj' in descriptor)) {
descriptor.__destrObj = {
set value(v) {
descriptor.set.call(receiver, v);
},
};
}
return descriptor.__destrObj;
} else {
if (!descriptor.writable) {
throw new TypeError('attempted to set read only private field');
}
return descriptor;
}
}
function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) {
if (receiver !== classConstructor) {
throw new TypeError('Private static access of wrong provenance');
}
return descriptor.value;
}
function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) {
if (receiver !== classConstructor) {
throw new TypeError('Private static access of wrong provenance');
}
if (!descriptor.writable) {
throw new TypeError('attempted to set read only private field');
}
descriptor.value = value;
return value;
}
function _classStaticPrivateMethodGet(receiver, classConstructor, method) {
if (receiver !== classConstructor) {
throw new TypeError('Private static access of wrong provenance');
}
return method;
}
function _classStaticPrivateMethodSet() {
throw new TypeError('attempted to set read only static private field');
}
function _decorate(decorators, factory, superClass, mixins) {
var api = _getDecoratorsApi();
if (mixins) {
for (var i = 0; i < mixins.length; i++) {
api = mixins[i](api);
}
}
var r = factory(function initialize(O) {
api.initializeInstanceElements(O, decorated.elements);
}, superClass);
var decorated = api.decorateClass(
_coalesceClassElements(r.d.map(_createElementDescriptor)),
decorators
);
api.initializeClassElements(r.F, decorated.elements);
return api.runClassFinishers(r.F, decorated.finishers);
}
function _getDecoratorsApi() {
_getDecoratorsApi = function() {
return api;
};
var api = {
elementsDefinitionOrder: [['method'], ['field']],
initializeInstanceElements: function(O, elements) {
['method', 'field'].forEach(function(kind) {
elements.forEach(function(element) {
if (element.kind === kind && element.placement === 'own') {
this.defineClassElement(O, element);
}
}, this);
}, this);
},
initializeClassElements: function(F, elements) {
var proto = F.prototype;
['method', 'field'].forEach(function(kind) {
elements.forEach(function(element) {
var placement = element.placement;
if (
element.kind === kind &&
(placement === 'static' || placement === 'prototype')
) {
var receiver = placement === 'static' ? F : proto;
this.defineClassElement(receiver, element);
}
}, this);
}, this);
},
defineClassElement: function(receiver, element) {
var descriptor = element.descriptor;
if (element.kind === 'field') {
var initializer = element.initializer;
descriptor = {
enumerable: descriptor.enumerable,
writable: descriptor.writable,
configurable: descriptor.configurable,
value: initializer === void 0 ? void 0 : initializer.call(receiver),
};
}
Object.defineProperty(receiver, element.key, descriptor);
},
decorateClass: function(elements, decorators) {
var newElements = [];
var finishers = [];
var placements = {
static: [],
prototype: [],
own: [],
};
elements.forEach(function(element) {
this.addElementPlacement(element, placements);
}, this);
elements.forEach(function(element) {
if (!_hasDecorators(element)) return newElements.push(element);
var elementFinishersExtras = this.decorateElement(element, placements);
newElements.push(elementFinishersExtras.element);
newElements.push.apply(newElements, elementFinishersExtras.extras);
finishers.push.apply(finishers, elementFinishersExtras.finishers);
}, this);
if (!decorators) {
return {
elements: newElements,
finishers: finishers,
};
}
var result = this.decorateConstructor(newElements, decorators);
finishers.push.apply(finishers, result.finishers);
result.finishers = finishers;
return result;
},
addElementPlacement: function(element, placements, silent) {
var keys = placements[element.placement];
if (!silent && keys.indexOf(element.key) !== -1) {
throw new TypeError('Duplicated element (' + element.key + ')');
}
keys.push(element.key);
},
decorateElement: function(element, placements) {
var extras = [];
var finishers = [];
for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) {
var keys = placements[element.placement];
keys.splice(keys.indexOf(element.key), 1);
var elementObject = this.fromElementDescriptor(element);
var elementFinisherExtras = this.toElementFinisherExtras(
(0, decorators[i])(elementObject) || elementObject
);
element = elementFinisherExtras.element;
this.addElementPlacement(element, placements);
if (elementFinisherExtras.finisher) {
finishers.push(elementFinisherExtras.finisher);
}
var newExtras = elementFinisherExtras.extras;
if (newExtras) {
for (var j = 0; j < newExtras.length; j++) {
this.addElementPlacement(newExtras[j], placements);
}
extras.push.apply(extras, newExtras);
}
}
return {
element: element,
finishers: finishers,
extras: extras,
};
},
decorateConstructor: function(elements, decorators) {
var finishers = [];
for (var i = decorators.length - 1; i >= 0; i--) {
var obj = this.fromClassDescriptor(elements);
var elementsAndFinisher = this.toClassDescriptor(
(0, decorators[i])(obj) || obj
);
if (elementsAndFinisher.finisher !== undefined) {
finishers.push(elementsAndFinisher.finisher);
}
if (elementsAndFinisher.elements !== undefined) {
elements = elementsAndFinisher.elements;
for (var j = 0; j < elements.length - 1; j++) {
for (var k = j + 1; k < elements.length; k++) {
if (
elements[j].key === elements[k].key &&
elements[j].placement === elements[k].placement
) {
throw new TypeError(
'Duplicated element (' + elements[j].key + ')'
);
}
}
}
}
}
return {
elements: elements,
finishers: finishers,
};
},
fromElementDescriptor: function(element) {
var obj = {
kind: element.kind,
key: element.key,
placement: element.placement,
descriptor: element.descriptor,
};
var desc = {
value: 'Descriptor',
configurable: true,
};
Object.defineProperty(obj, Symbol.toStringTag, desc);
if (element.kind === 'field') obj.initializer = element.initializer;
return obj;
},
toElementDescriptors: function(elementObjects) {
if (elementObjects === undefined) return;
return _toArray(elementObjects).map(function(elementObject) {
var element = this.toElementDescriptor(elementObject);
this.disallowProperty(elementObject, 'finisher', 'An element descriptor');
this.disallowProperty(elementObject, 'extras', 'An element descriptor');
return element;
}, this);
},
toElementDescriptor: function(elementObject) {
var kind = String(elementObject.kind);
if (kind !== 'method' && kind !== 'field') {
throw new TypeError(
'An element descriptor\'s .kind property must be either "method" or' +
' "field", but a decorator created an element descriptor with' +
' .kind "' +
kind +
'"'
);
}
var key = _toPropertyKey(elementObject.key);
var placement = String(elementObject.placement);
if (placement !== 'static' && placement !== 'prototype' && placement !== 'own') {
throw new TypeError(
'An element descriptor\'s .placement property must be one of "static",' +
' "prototype" or "own", but a decorator created an element descriptor' +
' with .placement "' +
placement +
'"'
);
}
var descriptor = elementObject.descriptor;
this.disallowProperty(elementObject, 'elements', 'An element descriptor');
var element = {
kind: kind,
key: key,
placement: placement,
descriptor: Object.assign({}, descriptor),
};
if (kind !== 'field') {
this.disallowProperty(elementObject, 'initializer', 'A method descriptor');
} else {
this.disallowProperty(
descriptor,
'get',
'The property descriptor of a field descriptor'
);
this.disallowProperty(
descriptor,
'set',
'The property descriptor of a field descriptor'
);
this.disallowProperty(
descriptor,
'value',
'The property descriptor of a field descriptor'
);
element.initializer = elementObject.initializer;
}
return element;
},
toElementFinisherExtras: function(elementObject) {
var element = this.toElementDescriptor(elementObject);
var finisher = _optionalCallableProperty(elementObject, 'finisher');
var extras = this.toElementDescriptors(elementObject.extras);
return {
element: element,
finisher: finisher,
extras: extras,
};
},
fromClassDescriptor: function(elements) {
var obj = {
kind: 'class',
elements: elements.map(this.fromElementDescriptor, this),
};
var desc = {
value: 'Descriptor',
configurable: true,
};
Object.defineProperty(obj, Symbol.toStringTag, desc);
return obj;
},
toClassDescriptor: function(obj) {
var kind = String(obj.kind);
if (kind !== 'class') {
throw new TypeError(
'A class descriptor\'s .kind property must be "class", but a decorator' +
' created a class descriptor with .kind "' +
kind +
'"'
);
}
this.disallowProperty(obj, 'key', 'A class descriptor');
this.disallowProperty(obj, 'placement', 'A class descriptor');
this.disallowProperty(obj, 'descriptor', 'A class descriptor');
this.disallowProperty(obj, 'initializer', 'A class descriptor');
this.disallowProperty(obj, 'extras', 'A class descriptor');
var finisher = _optionalCallableProperty(obj, 'finisher');
var elements = this.toElementDescriptors(obj.elements);
return {
elements: elements,
finisher: finisher,
};
},
runClassFinishers: function(constructor, finishers) {
for (var i = 0; i < finishers.length; i++) {
var newConstructor = (0, finishers[i])(constructor);
if (newConstructor !== undefined) {
if (typeof newConstructor !== 'function') {
throw new TypeError('Finishers must return a constructor.');
}
constructor = newConstructor;
}
}
return constructor;
},
disallowProperty: function(obj, name, objectType) {
if (obj[name] !== undefined) {
throw new TypeError(objectType + " can't have a ." + name + ' property.');
}
},
};
return api;
}
function _createElementDescriptor(def) {
var key = _toPropertyKey(def.key);
var descriptor;
if (def.kind === 'method') {
descriptor = {
value: def.value,
writable: true,
configurable: true,
enumerable: false,
};
} else if (def.kind === 'get') {
descriptor = {
get: def.value,
configurable: true,
enumerable: false,
};
} else if (def.kind === 'set') {
descriptor = {
set: def.value,
configurable: true,
enumerable: false,
};
} else if (def.kind === 'field') {
descriptor = {
configurable: true,
writable: true,
enumerable: true,
};
}
var element = {
kind: def.kind === 'field' ? 'field' : 'method',
key: key,
placement: def.static ? 'static' : def.kind === 'field' ? 'own' : 'prototype',
descriptor: descriptor,
};
if (def.decorators) element.decorators = def.decorators;
if (def.kind === 'field') element.initializer = def.value;
return element;
}
function _coalesceGetterSetter(element, other) {
if (element.descriptor.get !== undefined) {
other.descriptor.get = element.descriptor.get;
} else {
other.descriptor.set = element.descriptor.set;
}
}
function _coalesceClassElements(elements) {
var newElements = [];
var isSameElement = function(other) {
return (
other.kind === 'method' &&
other.key === element.key &&
other.placement === element.placement
);
};
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
var other;
if (element.kind === 'method' && (other = newElements.find(isSameElement))) {
if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) {
if (_hasDecorators(element) || _hasDecorators(other)) {
throw new ReferenceError(
'Duplicated methods (' + element.key + ") can't be decorated."
);
}
other.descriptor = element.descriptor;
} else {
if (_hasDecorators(element)) {
if (_hasDecorators(other)) {
throw new ReferenceError(
"Decorators can't be placed on different accessors with for " +
'the same property (' +
element.key +
').'
);
}
other.decorators = element.decorators;
}
_coalesceGetterSetter(element, other);
}
} else {
newElements.push(element);
}
}
return newElements;
}
function _hasDecorators(element) {
return element.decorators && element.decorators.length;
}
function _isDataDescriptor(desc) {
return desc !== undefined && !(desc.value === undefined && desc.writable === undefined);
}
function _optionalCallableProperty(obj, name) {
var value = obj[name];
if (value !== undefined && typeof value !== 'function') {
throw new TypeError("Expected '" + name + "' to be a function");
}
return value;
}
function _classPrivateMethodGet(receiver, privateSet, fn) {
if (!privateSet.has(receiver)) {
throw new TypeError('attempted to get private field on non-instance');
}
return fn;
}
function _classPrivateMethodSet() {
throw new TypeError('attempted to reassign private method');
}
function _wrapRegExp(re, groups) {
_wrapRegExp = function(re, groups) {
return new BabelRegExp(re, groups);
};
var _RegExp = _wrapNativeSuper(RegExp);
var _super = RegExp.prototype;
var _groups = new WeakMap();
function BabelRegExp(re, groups) {
var _this = _RegExp.call(this, re);
_groups.set(_this, groups);
return _this;
}
_inherits(BabelRegExp, _RegExp);
BabelRegExp.prototype.exec = function(str) {
var result = _super.exec.call(this, str);
if (result) result.groups = buildGroups(result, this);
return result;
};
BabelRegExp.prototype[Symbol.replace] = function(str, substitution) {
if (typeof substitution === 'string') {
var groups = _groups.get(this);
return _super[Symbol.replace].call(
this,
str,
substitution.replace(/\$<([^>]+)>/g, function(_, name) {
return '$' + groups[name];
})
);
} else if (typeof substitution === 'function') {
var _this = this;
return _super[Symbol.replace].call(this, str, function() {
var args = [];
args.push.apply(args, arguments);
if (typeof args[args.length - 1] !== 'object') {
args.push(buildGroups(args, _this));
}
return substitution.apply(this, args);
});
} else {
return _super[Symbol.replace].call(this, str, substitution);
}
};
function buildGroups(result, re) {
var g = _groups.get(re);
return Object.keys(g).reduce(function(groups, name) {
groups[name] = result[g[name]];
return groups;
}, Object.create(null));
}
return _wrapRegExp.apply(this, arguments);
}
var arrayRemove = function arrayRemove(arr, index) {
return arr.splice(index, 1);
};
var run = function run(cb, sync) {
if (sync) {
cb();
} else if (document.hidden) {
Promise.resolve(1).then(cb);
} else {
setTimeout(cb, 0);
}
};
var on = function on() {
var listeners = [];
var off = function off(event, cb) {
arrayRemove(
listeners,
listeners.findIndex(function(listener) {
return listener.event === event && (listener.cb === cb || !cb);
})
);
};
var _fire = function fire(event, args, sync) {
listeners
.filter(function(listener) {
return listener.event === event;
})
.map(function(listener) {
return listener.cb;
})
.forEach(function(cb) {
return run(function() {
return cb.apply(void 0, _toConsumableArray(args));
}, sync);
});
};
return {
fireSync: function fireSync(event) {
for (
var _len = arguments.length,
args = new Array(_len > 1 ? _len - 1 : 0),
_key = 1;
_key < _len;
_key++
) {
args[_key - 1] = arguments[_key];
}
_fire(event, args, true);
},
fire: function fire(event) {
for (
var _len2 = arguments.length,
args = new Array(_len2 > 1 ? _len2 - 1 : 0),
_key2 = 1;
_key2 < _len2;
_key2++
) {
args[_key2 - 1] = arguments[_key2];
}
_fire(event, args, false);
},
on: function on(event, cb) {
listeners.push({ event: event, cb: cb });
},
onOnce: function onOnce(event, _cb) {
listeners.push({
event: event,
cb: function cb() {
off(event, _cb);
_cb.apply(void 0, arguments);
},
});
},
off: off,
};
};
var copyObjectPropertiesToObject = function copyObjectPropertiesToObject(
src,
target,
excluded
) {
Object.getOwnPropertyNames(src)
.filter(function(property) {
return !excluded.includes(property);
})
.forEach(function(key) {
return Object.defineProperty(
target,
key,
Object.getOwnPropertyDescriptor(src, key)
);
});
};
var PRIVATE = [
'fire',
'process',
'revert',
'load',
'on',
'off',
'onOnce',
'retryLoad',
'extend',
'archive',
'archived',
'release',
'released',
'requestProcessing',
'freeze',
];
var createItemAPI = function createItemAPI(item) {
var api = {};
copyObjectPropertiesToObject(item, api, PRIVATE);
return api;
};
var removeReleasedItems = function removeReleasedItems(items) {
items.forEach(function(item, index) {
if (item.released) {
arrayRemove(items, index);
}
});
};
var ItemStatus = {
INIT: 1,
IDLE: 2,
PROCESSING_QUEUED: 9,
PROCESSING: 3,
PROCESSING_COMPLETE: 5,
PROCESSING_ERROR: 6,
PROCESSING_REVERT_ERROR: 10,
LOADING: 7,
LOAD_ERROR: 8,
};
var FileOrigin = {
INPUT: 1,
LIMBO: 2,
LOCAL: 3,
};
var getNonNumeric = function getNonNumeric(str) {
return /[^0-9]+/.exec(str);
};
var getDecimalSeparator = function getDecimalSeparator() {
return getNonNumeric((1.1).toLocaleString())[0];
};
var getThousandsSeparator = function getThousandsSeparator() {
// Added for browsers that do not return the thousands separator (happend on native browser Android 4.4.4)
// We check against the normal toString output and if they're the same return a comma when decimal separator is a dot
var decimalSeparator = getDecimalSeparator();
var thousandsStringWithSeparator = (1000.0).toLocaleString();
var thousandsStringWithoutSeparator = (1000.0).toString();
if (thousandsStringWithSeparator !== thousandsStringWithoutSeparator) {
return getNonNumeric(thousandsStringWithSeparator)[0];
}
return decimalSeparator === '.' ? ',' : '.';
};
var Type = {
BOOLEAN: 'boolean',
INT: 'int',
NUMBER: 'number',
STRING: 'string',
ARRAY: 'array',
OBJECT: 'object',
FUNCTION: 'function',
ACTION: 'action',
SERVER_API: 'serverapi',
REGEX: 'regex',
};
// all registered filters
var filters = [];
// loops over matching filters and passes options to each filter, returning the mapped results
var applyFilterChain = function applyFilterChain(key, value, utils) {
return new Promise(function(resolve, reject) {
// find matching filters for this key
var matchingFilters = filters
.filter(function(f) {
return f.key === key;
})
.map(function(f) {
return f.cb;
});
// resolve now
if (matchingFilters.length === 0) {
resolve(value);
return;
}
// first filter to kick things of
var initialFilter = matchingFilters.shift();
// chain filters
matchingFilters
.reduce(
// loop over promises passing value to next promise
function(current, next) {
return current.then(function(value) {
return next(value, utils);
});
},
// call initial filter, will return a promise
initialFilter(value, utils)
// all executed
)
.then(function(value) {
return resolve(value);
})
.catch(function(error) {
return reject(error);
});
});
};
var applyFilters = function applyFilters(key, value, utils) {
return filters
.filter(function(f) {
return f.key === key;
})
.map(function(f) {
return f.cb(value, utils);
});
};
// adds a new filter to the list
var addFilter = function addFilter(key, cb) {
return filters.push({ key: key, cb: cb });
};
var extendDefaultOptions = function extendDefaultOptions(additionalOptions) {
return Object.assign(defaultOptions, additionalOptions);
};
var getOptions = function getOptions() {
return Object.assign({}, defaultOptions);
};
var setOptions = function setOptions(opts) {
forin(opts, function(key, value) {
// key does not exist, so this option cannot be set
if (!defaultOptions[key]) {
return;
}
defaultOptions[key][0] = getValueByType(
value,
defaultOptions[key][0],
defaultOptions[key][1]
);
});
};
// default options on app
var defaultOptions = {
// the id to add to the root element
id: [null, Type.STRING],
// input field name to use
name: ['filepond', Type.STRING],
// disable the field
disabled: [false, Type.BOOLEAN],
// classname to put on wrapper
className: [null, Type.STRING],
// is the field required
required: [false, Type.BOOLEAN],
// Allow media capture when value is set
captureMethod: [null, Type.STRING],
// - "camera", "microphone" or "camcorder",
// - Does not work with multiple on apple devices
// - If set, acceptedFileTypes must be made to match with media wildcard "image/*", "audio/*" or "video/*"
// sync `acceptedFileTypes` property with `accept` attribute
allowSyncAcceptAttribute: [true, Type.BOOLEAN],
// Feature toggles
allowDrop: [true, Type.BOOLEAN], // Allow dropping of files
allowBrowse: [true, Type.BOOLEAN], // Allow browsing the file system
allowPaste: [true, Type.BOOLEAN], // Allow pasting files
allowMultiple: [false, Type.BOOLEAN], // Allow multiple files (disabled by default, as multiple attribute is also required on input to allow multiple)
allowReplace: [true, Type.BOOLEAN], // Allow dropping a file on other file to replace it (only works when multiple is set to false)
allowRevert: [true, Type.BOOLEAN], // Allows user to revert file upload
allowRemove: [true, Type.BOOLEAN], // Allow user to remove a file
allowProcess: [true, Type.BOOLEAN], // Allows user to process a file, when set to false, this removes the file upload button
allowReorder: [false, Type.BOOLEAN], // Allow reordering of files
allowDirectoriesOnly: [false, Type.BOOLEAN], // Allow only selecting directories with browse (no support for filtering dnd at this point)
// Revert mode
forceRevert: [false, Type.BOOLEAN], // Set to 'force' to require the file to be reverted before removal
// Input requirements
maxFiles: [null, Type.INT], // Max number of files
checkValidity: [false, Type.BOOLEAN], // Enables custom validity messages
// Where to put file
itemInsertLocationFreedom: [true, Type.BOOLEAN], // Set to false to always add items to begin or end of list
itemInsertLocation: ['before', Type.STRING], // Default index in list to add items that have been dropped at the top of the list
itemInsertInterval: [75, Type.INT],
// Drag 'n Drop related
dropOnPage: [false, Type.BOOLEAN], // Allow dropping of files anywhere on page (prevents browser from opening file if dropped outside of Up)
dropOnElement: [true, Type.BOOLEAN], // Drop needs to happen on element (set to false to also load drops outside of Up)
dropValidation: [false, Type.BOOLEAN], // Enable or disable validating files on drop
ignoredFiles: [['.ds_store', 'thumbs.db', 'desktop.ini'], Type.ARRAY],
// Upload related
instantUpload: [true, Type.BOOLEAN], // Should upload files immediately on drop
maxParallelUploads: [2, Type.INT], // Maximum files to upload in parallel
// Chunks
chunkUploads: [false, Type.BOOLEAN], // Enable chunked uploads
chunkForce: [false, Type.BOOLEAN], // Force use of chunk uploads even for files smaller than chunk size
chunkSize: [5000000, Type.INT], // Size of chunks (5MB default)
chunkRetryDelays: [[500, 1000, 3000], Type.ARRAY], // Amount of times to retry upload of a chunk when it fails
// The server api end points to use for uploading (see docs)
server: [null, Type.SERVER_API],
// File size calculations, can set to 1024, this is only used for display, properties use file size base 1000
fileSizeBase: [1000, Type.INT],
// Labels and status messages
labelDecimalSeparator: [getDecimalSeparator(), Type.STRING], // Default is locale separator
labelThousandsSeparator: [getThousandsSeparator(), Type.STRING], // Default is locale separator
labelIdle: [
'Drag & Drop your files or <span class="filepond--label-action">Browse</span>',
Type.STRING,
],
labelInvalidField: ['Field contains invalid files', Type.STRING],
labelFileWaitingForSize: ['Waiting for size', Type.STRING],
labelFileSizeNotAvailable: ['Size not available', Type.STRING],
labelFileCountSingular: ['file in list', Type.STRING],
labelFileCountPlural: ['files in list', Type.STRING],
labelFileLoading: ['Loading', Type.STRING],
labelFileAdded: ['Added', Type.STRING], // assistive only
labelFileLoadError: ['Error during load', Type.STRING],
labelFileRemoved: ['Removed', Type.STRING], // assistive only
labelFileRemoveError: ['Error during remove', Type.STRING],
labelFileProcessing: ['Uploading', Type.STRING],
labelFileProcessingComplete: ['Upload complete', Type.STRING],
labelFileProcessingAborted: ['Upload cancelled', Type.STRING],
labelFileProcessingError: ['Error during upload', Type.STRING],
labelFileProcessingRevertError: ['Error during revert', Type.STRING],
labelTapToCancel: ['tap to cancel', Type.STRING],
labelTapToRetry: ['tap to retry', Type.STRING],
labelTapToUndo: ['tap to undo', Type.STRING],
labelButtonRemoveItem: ['Remove', Type.STRING],
labelButtonAbortItemLoad: ['Abort', Type.STRING],
labelButtonRetryItemLoad: ['Retry', Type.STRING],
labelButtonAbortItemProcessing: ['Cancel', Type.STRING],
labelButtonUndoItemProcessing: ['Undo', Type.STRING],
labelButtonRetryItemProcessing: ['Retry', Type.STRING],
labelButtonProcessItem: ['Upload', Type.STRING],
// make sure width and height plus viewpox are even numbers so icons are nicely centered
iconRemove: [
'<svg width="26" height="26" viewBox="0 0 26 26" xmlns="http://www.w3.org/2000/svg"><path d="M11.586 13l-2.293 2.293a1 1 0 0 0 1.414 1.414L13 14.414l2.293 2.293a1 1 0 0 0 1.414-1.414L14.414 13l2.293-2.293a1 1 0 0 0-1.414-1.414L13 11.586l-2.293-2.293a1 1 0 0 0-1.414 1.414L11.586 13z" fill="currentColor" fill-rule="nonzero"/></svg>',
Type.STRING,
],
iconProcess: [
'<svg width="26" height="26" viewBox="0 0 26 26" xmlns="http://www.w3.org/2000/svg"><path d="M14 10.414v3.585a1 1 0 0 1-2 0v-3.585l-1.293 1.293a1 1 0 0 1-1.414-1.415l3-3a1 1 0 0 1 1.414 0l3 3a1 1 0 0 1-1.414 1.415L14 10.414zM9 18a1 1 0 0 1 0-2h8a1 1 0 0 1 0 2H9z" fill="currentColor" fill-rule="evenodd"/></svg>',
Type.STRING,
],
iconRetry: [
'<svg width="26" height="26" viewBox="0 0 26 26" xmlns="http://www.w3.org/2000/svg"><path d="M10.81 9.185l-.038.02A4.997 4.997 0 0 0 8 13.683a5 5 0 0 0 5 5 5 5 0 0 0 5-5 1 1 0 0 1 2 0A7 7 0 1 1 9.722 7.496l-.842-.21a.999.999 0 1 1 .484-1.94l3.23.806c.535.133.86.675.73 1.21l-.804 3.233a.997.997 0 0 1-1.21.73.997.997 0 0 1-.73-1.21l.23-.928v-.002z" fill="currentColor" fill-rule="nonzero"/></svg>',
Type.STRING,
],
iconUndo: [
'<svg width="26" height="26" viewBox="0 0 26 26" xmlns="http://www.w3.org/2000/svg"><path d="M9.185 10.81l.02-.038A4.997 4.997 0 0 1 13.683 8a5 5 0 0 1 5 5 5 5 0 0 1-5 5 1 1 0 0 0 0 2A7 7 0 1 0 7.496 9.722l-.21-.842a.999.999 0 1 0-1.94.484l.806 3.23c.133.535.675.86 1.21.73l3.233-.803a.997.997 0 0 0 .73-1.21.997.997 0 0 0-1.21-.73l-.928.23-.002-.001z" fill="currentColor" fill-rule="nonzero"/></svg>',
Type.STRING,
],
iconDone: [
'<svg width="26" height="26" viewBox="0 0 26 26" xmlns="http://www.w3.org/2000/svg"><path d="M18.293 9.293a1 1 0 0 1 1.414 1.414l-7.002 7a1 1 0 0 1-1.414 0l-3.998-4a1 1 0 1 1 1.414-1.414L12 15.586l6.294-6.293z" fill="currentColor" fill-rule="nonzero"/></svg>',
Type.STRING,
],
// event handlers
oninit: [null, Type.FUNCTION],
onwarning: [null, Type.FUNCTION],
onerror: [null, Type.FUNCTION],
onactivatefile: [null, Type.FUNCTION],
oninitfile: [null, Type.FUNCTION],
onaddfilestart: [null, Type.FUNCTION],
onaddfileprogress: [null, Type.FUNCTION],
onaddfile: [null, Type.FUNCTION],
onprocessfilestart: [null, Type.FUNCTION],
onprocessfileprogress: [null, Type.FUNCTION],
onprocessfileabort: [null, Type.FUNCTION],
onprocessfilerevert: [null, Type.FUNCTION],
onprocessfile: [null, Type.FUNCTION],
onprocessfiles: [null, Type.FUNCTION],
onremovefile: [null, Type.FUNCTION],
onpreparefile: [null, Type.FUNCTION],
onupdatefiles: [null, Type.FUNCTION],
onreorderfiles: [null, Type.FUNCTION],
// hooks
beforeDropFile: [null, Type.FUNCTION],
beforeAddFile: [null, Type.FUNCTION],
beforeRemoveFile: [null, Type.FUNCTION],
beforePrepareFile: [null, Type.FUNCTION],
// styles
stylePanelLayout: [null, Type.STRING], // null 'integrated', 'compact', 'circle'
stylePanelAspectRatio: [null, Type.STRING], // null or '3:2' or 1
styleItemPanelAspectRatio: [null, Type.STRING],
styleButtonRemoveItemPosition: ['left', Type.STRING],
styleButtonProcessItemPosition: ['right', Type.STRING],
styleLoadIndicatorPosition: ['right', Type.STRING],
styleProgressIndicatorPosition: ['right', Type.STRING],
styleButtonRemoveItemAlign: [false, Type.BOOLEAN],
// custom initial files array
files: [[], Type.ARRAY],
// show support by displaying credits
credits: [['https://pqina.nl/', 'Powered by PQINA'], Type.ARRAY],
};
var getItemByQuery = function getItemByQuery(items, query) {
// just return first index
if (isEmpty(query)) {
return items[0] || null;
}
// query is index
if (isInt(query)) {
return items[query] || null;
}
// if query is item, get the id
if (typeof query === 'object') {
query = query.id;
}
// assume query is a string and return item by id
return (
items.find(function(item) {
return item.id === query;
}) || null
);
};
var getNumericAspectRatioFromString = function getNumericAspectRatioFromString(aspectRatio) {
if (isEmpty(aspectRatio)) {
return aspectRatio;
}
if (/:/.test(aspectRatio)) {
var parts = aspectRatio.split(':');
return parts[1] / parts[0];
}
return parseFloat(aspectRatio);
};
var getActiveItems = function getActiveItems(items) {
return items.filter(function(item) {
return !item.archived;
});
};
var Status = {
EMPTY: 0,
IDLE: 1, // waiting
ERROR: 2, // a file is in error state
BUSY: 3, // busy processing or loading
READY: 4, // all files uploaded
};
var ITEM_ERROR = [
ItemStatus.LOAD_ERROR,
ItemStatus.PROCESSING_ERROR,
ItemStatus.PROCESSING_REVERT_ERROR,
];
var ITEM_BUSY = [
ItemStatus.LOADING,
ItemStatus.PROCESSING,
ItemStatus.PROCESSING_QUEUED,
ItemStatus.INIT,
];
var ITEM_READY = [ItemStatus.PROCESSING_COMPLETE];
var isItemInErrorState = function isItemInErrorState(item) {
return ITEM_ERROR.includes(item.status);
};
var isItemInBusyState = function isItemInBusyState(item) {
return ITEM_BUSY.includes(item.status);
};
var isItemInReadyState = function isItemInReadyState(item) {
return ITEM_READY.includes(item.status);
};
var queries = function queries(state) {
return {
GET_STATUS: function GET_STATUS() {
var items = getActiveItems(state.items);
var EMPTY = Status.EMPTY,
ERROR = Status.ERROR,
BUSY = Status.BUSY,
IDLE = Status.IDLE,
READY = Status.READY;
if (items.length === 0) return EMPTY;
if (items.some(isItemInErrorState)) return ERROR;
if (items.some(isItemInBusyState)) return BUSY;
if (items.some(isItemInReadyState)) return READY;
return IDLE;
},
GET_ITEM: function GET_ITEM(query) {
return getItemByQuery(state.items, query);
},
GET_ACTIVE_ITEM: function GET_ACTIVE_ITEM(query) {
return getItemByQuery(getActiveItems(state.items), query);
},
GET_ACTIVE_ITEMS: function GET_ACTIVE_ITEMS() {
return getActiveItems(state.items);
},
GET_ITEMS: function GET_ITEMS() {
return state.items;
},
GET_ITEM_NAME: function GET_ITEM_NAME(query) {
var item = getItemByQuery(state.items, query);
return item ? item.filename : null;
},
GET_ITEM_SIZE: function GET_ITEM_SIZE(query) {
var item = getItemByQuery(state.items, query);
return item ? item.fileSize : null;
},
GET_STYLES: function GET_STYLES() {
return Object.keys(state.options)
.filter(function(key) {
return /^style/.test(key);
})
.map(function(option) {
return {
name: option,
value: state.options[option],
};
});
},
GET_PANEL_ASPECT_RATIO: function GET_PANEL_ASPECT_RATIO() {
var isShapeCircle = /circle/.test(state.options.stylePanelLayout);
var aspectRatio = isShapeCircle
? 1
: getNumericAspectRatioFromString(state.options.stylePanelAspectRatio);
return aspectRatio;
},
GET_ITEM_PANEL_ASPECT_RATIO: function GET_ITEM_PANEL_ASPECT_RATIO() {
return state.options.styleItemPanelAspectRatio;
},
GET_ITEMS_BY_STATUS: function GET_ITEMS_BY_STATUS(status) {
return getActiveItems(state.items).filter(function(item) {
return item.status === status;
});
},
GET_TOTAL_ITEMS: function GET_TOTAL_ITEMS() {
return getActiveItems(state.items).length;
},
IS_ASYNC: function IS_ASYNC() {
return (
isObject(state.options.server) &&
(isObject(state.options.server.process) ||
isFunction(state.options.server.process))
);
},
};
};
var hasRoomForItem = function hasRoomForItem(state) {
var count = getActiveItems(state.items).length;
// if cannot have multiple items, to add one item it should currently not contain items
if (!state.options.allowMultiple) {
return count === 0;
}
// if allows multiple items, we check if a max item count has been set, if not, there's no limit
var maxFileCount = state.options.maxFiles;
if (maxFileCount === null) {
return true;
}
// we check if the current count is smaller than the max count, if so, another file can still be added
if (count < maxFileCount) {
return true;
}
// no more room for another file
return false;
};
var limit = function limit(value, min, max) {
return Math.max(Math.min(max, value), min);
};
var arrayInsert = function arrayInsert(arr, index, item) {
return arr.splice(index, 0, item);
};
var insertItem = function insertItem(items, item, index) {
if (isEmpty(item)) {
return null;
}
// if index is undefined, append
if (typeof index === 'undefined') {
items.push(item);
return item;
}
// limit the index to the size of the items array
index = limit(index, 0, items.length);
// add item to array
arrayInsert(items, index, item);
// expose
return item;
};
var isBase64DataURI = function isBase64DataURI(str) {
return /^\s*data:([a-z]+\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)?)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s]*)\s*$/i.test(
str
);
};
var getFilenameFromURL = function getFilenameFromURL(url) {
return url
.split('/')
.pop()
.split('?')
.shift();
};
var getExtensionFromFilename = function getExtensionFromFilename(name) {
return name.split('.').pop();
};
var guesstimateExtension = function guesstimateExtension(type) {
// if no extension supplied, exit here
if (typeof type !== 'string') {
return '';
}
// get subtype
var subtype = type.split('/').pop();
// is svg subtype
if (/svg/.test(subtype)) {
return 'svg';
}
if (/zip|compressed/.test(subtype)) {
return 'zip';
}
if (/plain/.test(subtype)) {
return 'txt';
}
if (/msword/.test(subtype)) {
return 'doc';
}
// if is valid subtype
if (/[a-z]+/.test(subtype)) {
// always use jpg extension
if (subtype === 'jpeg') {
return 'jpg';
}
// return subtype
return subtype;
}
return '';
};
var leftPad = function leftPad(value) {
var padding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
return (padding + value).slice(-padding.length);
};
var getDateString = function getDateString() {
var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date();
return (
date.getFullYear() +
'-' +
leftPad(date.getMonth() + 1, '00') +
'-' +
leftPad(date.getDate(), '00') +
'_' +
leftPad(date.getHours(), '00') +
'-' +
leftPad(date.getMinutes(), '00') +
'-' +
leftPad(date.getSeconds(), '00')
);
};
var getFileFromBlob = function getFileFromBlob(blob, filename) {
var type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var extension = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
var file =
typeof type === 'string'
? blob.slice(0, blob.size, type)
: blob.slice(0, blob.size, blob.type);
file.lastModifiedDate = new Date();
// copy relative path
if (blob._relativePath) file._relativePath = blob._relativePath;
// if blob has name property, use as filename if no filename supplied
if (!isString(filename)) {
filename = getDateString();
}
// if filename supplied but no extension and filename has extension
if (filename && extension === null && getExtensionFromFilename(filename)) {
file.name = filename;
} else {
extension = extension || guesstimateExtension(file.type);
file.name = filename + (extension ? '.' + extension : '');
}
return file;
};
var getBlobBuilder = function getBlobBuilder() {
return (window.BlobBuilder =
window.BlobBuilder ||
window.WebKitBlobBuilder ||
window.MozBlobBuilder ||
window.MSBlobBuilder);
};
var createBlob = function createBlob(arrayBuffer, mimeType) {
var BB = getBlobBuilder();
if (BB) {
var bb = new BB();
bb.append(arrayBuffer);
return bb.getBlob(mimeType);
}
return new Blob([arrayBuffer], {
type: mimeType,
});
};
var getBlobFromByteStringWithMimeType = function getBlobFromByteStringWithMimeType(
byteString,
mimeType
) {
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return createBlob(ab, mimeType);
};
var getMimeTypeFromBase64DataURI = function getMimeTypeFromBase64DataURI(dataURI) {
return (/^data:(.+);/.exec(dataURI) || [])[1] || null;
};
var getBase64DataFromBase64DataURI = function getBase64DataFromBase64DataURI(dataURI) {
// get data part of string (remove data:image/jpeg...,)
var data = dataURI.split(',')[1];
// remove any whitespace as that causes InvalidCharacterError in IE
return data.replace(/\s/g, '');
};
var getByteStringFromBase64DataURI = function getByteStringFromBase64DataURI(dataURI) {
return atob(getBase64DataFromBase64DataURI(dataURI));
};
var getBlobFromBase64DataURI = function getBlobFromBase64DataURI(dataURI) {
var mimeType = getMimeTypeFromBase64DataURI(dataURI);
var byteString = getByteStringFromBase64DataURI(dataURI);
return getBlobFromByteStringWithMimeType(byteString, mimeType);
};
var getFileFromBase64DataURI = function getFileFromBase64DataURI(dataURI, filename, extension) {
return getFileFromBlob(getBlobFromBase64DataURI(dataURI), filename, null, extension);
};
var getFileNameFromHeader = function getFileNameFromHeader(header) {
// test if is content disposition header, if not exit
if (!/^content-disposition:/i.test(header)) return null;
// get filename parts
var matches = header
.split(/filename=|filename\*=.+''/)
.splice(1)
.map(function(name) {
return name.trim().replace(/^["']|[;"']{0,2}$/g, '');
})
.filter(function(name) {
return name.length;
});
return matches.length ? decodeURI(matches[matches.length - 1]) : null;
};
var getFileSizeFromHeader = function getFileSizeFromHeader(header) {
if (/content-length:/i.test(header)) {
var size = header.match(/[0-9]+/)[0];
return size ? parseInt(size, 10) : null;
}
return null;
};
var getTranfserIdFromHeader = function getTranfserIdFromHeader(header) {
if (/x-content-transfer-id:/i.test(header)) {
var id = (header.split(':')[1] || '').trim();
return id || null;
}
return null;
};
var getFileInfoFromHeaders = function getFileInfoFromHeaders(headers) {
var info = {
source: null,
name: null,
size: null,
};
var rows = headers.split('\n');
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (
var _iterator = rows[Symbol.iterator](), _step;
!(_iteratorNormalCompletion = (_step = _iterator.next()).done);
_iteratorNormalCompletion = true
) {
var header = _step.value;
var name = getFileNameFromHeader(header);
if (name) {
info.name = name;
continue;
}
var size = getFileSizeFromHeader(header);
if (size) {
info.size = size;
continue;
}
var source = getTranfserIdFromHeader(header);
if (source) {
info.source = source;
continue;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return info;
};
var createFileLoader = function createFileLoader(fetchFn) {
var state = {
source: null,
complete: false,
progress: 0,
size: null,
timestamp: null,
duration: 0,
request: null,
};
var getProgress = function getProgress() {
return state.progress;
};
var abort = function abort() {
if (state.request && state.request.abort) {
state.request.abort();
}
};
// load source
var load = function load() {
// get quick reference
var source = state.source;
api.fire('init', source);
// Load Files
if (source instanceof File) {
api.fire('load', source);
} else if (source instanceof Blob) {
// Load blobs, set default name to current date
api.fire('load', getFileFromBlob(source, source.name));
} else if (isBase64DataURI(source)) {
// Load base 64, set default name to current date
api.fire('load', getFileFromBase64DataURI(source));
} else {
// Deal as if is external URL, let's load it!
loadURL(source);
}
};
// loads a url
var loadURL = function loadURL(url) {
// is remote url and no fetch method supplied
if (!fetchFn) {
api.fire('error', {
type: 'error',
body: "Can't load URL",
code: 400,
});
return;
}
// set request start
state.timestamp = Date.now();
// load file
state.request = fetchFn(
url,
function(response) {
// update duration
state.duration = Date.now() - state.timestamp;
// done!
state.complete = true;
// turn blob response into a file
if (response instanceof Blob) {
response = getFileFromBlob(
response,
response.name || getFilenameFromURL(url)
);
}
api.fire(
'load',
// if has received blob, we go with blob, if no response, we return null
response instanceof Blob ? response : response ? response.body : null
);
},
function(error) {
api.fire(
'error',
typeof error === 'string'
? {
type: 'error',
code: 0,
body: error,
}
: error
);
},
function(computable, current, total) {
// collected some meta data already
if (total) {
state.size = total;
}
// update duration
state.duration = Date.now() - state.timestamp;
// if we can't compute progress, we're not going to fire progress events
if (!computable) {
state.progress = null;
return;
}
// update progress percentage
state.progress = current / total;
// expose
api.fire('progress', state.progress);
},
function() {
api.fire('abort');
},
function(response) {
var fileinfo = getFileInfoFromHeaders(
typeof response === 'string' ? response : response.headers
);
api.fire('meta', {
size: state.size || fileinfo.size,
filename: fileinfo.name,
source: fileinfo.source,
});
}
);
};
var api = Object.assign({}, on(), {
setSource: function setSource(source) {
return (state.source = source);
},
getProgress: getProgress, // file load progress
abort: abort, // abort file load
load: load, // start load
});
return api;
};
var isGet = function isGet(method) {
return /GET|HEAD/.test(method);
};
var sendRequest = function sendRequest(data, url, options) {
var api = {
onheaders: function onheaders() {},
onprogress: function onprogress() {},
onload: function onload() {},
ontimeout: function ontimeout() {},
onerror: function onerror() {},
onabort: function onabort() {},
abort: function abort() {
aborted = true;
xhr.abort();
},
};
// timeout identifier, only used when timeout is defined
var aborted = false;
var headersReceived = false;
// set default options
options = Object.assign(
{
method: 'POST',
headers: {},
withCredentials: false,
},
options
);
// encode url
url = encodeURI(url);
// if method is GET, add any received data to url
if (isGet(options.method) && data) {
url =
'' +
url +
encodeURIComponent(typeof data === 'string' ? data : JSON.stringify(data));
}
// create request
var xhr = new XMLHttpRequest();
// progress of load
var process = isGet(options.method) ? xhr : xhr.upload;
process.onprogress = function(e) {
// no progress event when aborted ( onprogress is called once after abort() )
if (aborted) {
return;
}
api.onprogress(e.lengthComputable, e.loaded, e.total);
};
// tries to get header info to the app as fast as possible
xhr.onreadystatechange = function() {
// not interesting in these states ('unsent' and 'openend' as they don't give us any additional info)
if (xhr.readyState < 2) {
return;
}
// no server response
if (xhr.readyState === 4 && xhr.status === 0) {
return;
}
if (headersReceived) {
return;
}
headersReceived = true;
// we've probably received some useful data in response headers
api.onheaders(xhr);
};
// load successful
xhr.onload = function() {
// is classified as valid response
if (xhr.status >= 200 && xhr.status < 300) {
api.onload(xhr);
} else {
api.onerror(xhr);
}
};
// error during load
xhr.onerror = function() {
return api.onerror(xhr);
};
// request aborted
xhr.onabort = function() {
aborted = true;
api.onabort();
};
// request timeout
xhr.ontimeout = function() {
return api.ontimeout(xhr);
};
// open up open up!
xhr.open(options.method, url, true);
// set timeout if defined (do it after open so IE11 plays ball)
if (isInt(options.timeout)) {
xhr.timeout = options.timeout;
}
// add headers
Object.keys(options.headers).forEach(function(key) {
var value = unescape(encodeURIComponent(options.headers[key]));
xhr.setRequestHeader(key, value);
});
// set type of response
if (options.responseType) {
xhr.responseType = options.responseType;
}
// set credentials
if (options.withCredentials) {
xhr.withCredentials = true;
}
// let's send our data
xhr.send(data);
return api;
};
var createResponse = function createResponse(type, code, body, headers) {
return {
type: type,
code: code,
body: body,
headers: headers,
};
};
var createTimeoutResponse = function createTimeoutResponse(cb) {
return function(xhr) {
cb(createResponse('error', 0, 'Timeout', xhr.getAllResponseHeaders()));
};
};
var hasQS = function hasQS(str) {
return /\?/.test(str);
};
var buildURL = function buildURL() {
var url = '';
for (var _len = arguments.length, parts = new Array(_len), _key = 0; _key < _len; _key++) {
parts[_key] = arguments[_key];
}
parts.forEach(function(part) {
url += hasQS(url) && hasQS(part) ? part.replace(/\?/, '&') : part;
});
return url;
};
var createFetchFunction = function createFetchFunction() {
var apiUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var action = arguments.length > 1 ? arguments[1] : undefined;
// custom handler (should also handle file, load, error, progress and abort)
if (typeof action === 'function') {
return action;
}
// no action supplied
if (!action || !isString(action.url)) {
return null;
}
// set onload hanlder
var onload =
action.onload ||
function(res) {
return res;
};
var onerror =
action.onerror ||
function(res) {
return null;
};
// internal handler
return function(url, load, error, progress, abort, headers) {
// do local or remote request based on if the url is external
var request = sendRequest(
url,
buildURL(apiUrl, action.url),
Object.assign({}, action, {
responseType: 'blob',
})
);
request.onload = function(xhr) {
// get headers
var headers = xhr.getAllResponseHeaders();
// get filename
var filename = getFileInfoFromHeaders(headers).name || getFilenameFromURL(url);
// create response
load(
createResponse(
'load',
xhr.status,
action.method === 'HEAD'
? null
: getFileFromBlob(onload(xhr.response), filename),
headers
)
);
};
request.onerror = function(xhr) {
error(
createResponse(
'error',
xhr.status,
onerror(xhr.response) || xhr.statusText,
xhr.getAllResponseHeaders()
)
);
};
request.onheaders = function(xhr) {
headers(createResponse('headers', xhr.status, null, xhr.getAllResponseHeaders()));
};
request.ontimeout = createTimeoutResponse(error);
request.onprogress = progress;
request.onabort = abort;
// should return request
return request;
};
};
var ChunkStatus = {
QUEUED: 0,
COMPLETE: 1,
PROCESSING: 2,
ERROR: 3,
WAITING: 4,
};
/*
function signature:
(file, metadata, load, error, progress, abort, transfer, options) => {
return {
abort:() => {}
}
}
*/
// apiUrl, action, name, file, metadata, load, error, progress, abort, transfer, options
var processFileChunked = function processFileChunked(
apiUrl,
action,
name,
file,
metadata,
load,
error,
progress,
abort,
transfer,
options
) {
// all chunks
var chunks = [];
var chunkTransferId = options.chunkTransferId,
chunkServer = options.chunkServer,
chunkSize = options.chunkSize,
chunkRetryDelays = options.chunkRetryDelays;
// default state
var state = {
serverId: chunkTransferId,
aborted: false,
};
// set onload handlers
var ondata =
action.ondata ||
function(fd) {
return fd;
};
var onload =
action.onload ||
function(xhr, method) {
return method === 'HEAD' ? xhr.getResponseHeader('Upload-Offset') : xhr.response;
};
var onerror =
action.onerror ||
function(res) {
return null;
};
// create server hook
var requestTransferId = function requestTransferId(cb) {
var formData = new FormData();
// add metadata under same name
if (isObject(metadata)) formData.append(name, JSON.stringify(metadata));
var headers =
typeof action.headers === 'function'
? action.headers(file, metadata)
: Object.assign({}, action.headers, {
'Upload-Length': file.size,
});
var requestParams = Object.assign({}, action, {
headers: headers,
});
// send request object
var request = sendRequest(
ondata(formData),
buildURL(apiUrl, action.url),
requestParams
);
request.onload = function(xhr) {
return cb(onload(xhr, requestParams.method));
};
request.onerror = function(xhr) {
return error(
createResponse(
'error',
xhr.status,
onerror(xhr.response) || xhr.statusText,
xhr.getAllResponseHeaders()
)
);
};
request.ontimeout = createTimeoutResponse(error);
};
var requestTransferOffset = function requestTransferOffset(cb) {
var requestUrl = buildURL(apiUrl, chunkServer.url, state.serverId);
var headers =
typeof action.headers === 'function'
? action.headers(state.serverId)
: Object.assign({}, action.headers);
var requestParams = {
headers: headers,
method: 'HEAD',
};
var request = sendRequest(null, requestUrl, requestParams);
request.onload = function(xhr) {
return cb(onload(xhr, requestParams.method));
};
request.onerror = function(xhr) {
return error(
createResponse(
'error',
xhr.status,
onerror(xhr.response) || xhr.statusText,
xhr.getAllResponseHeaders()
)
);
};
request.ontimeout = createTimeoutResponse(error);
};
// create chunks
var lastChunkIndex = Math.floor(file.size / chunkSize);
for (var i = 0; i <= lastChunkIndex; i++) {
var offset = i * chunkSize;
var data = file.slice(offset, offset + chunkSize, 'application/offset+octet-stream');
chunks[i] = {
index: i,
size: data.size,
offset: offset,
data: data,
file: file,
progress: 0,
retries: _toConsumableArray(chunkRetryDelays),
status: ChunkStatus.QUEUED,
error: null,
request: null,
timeout: null,
};
}
var completeProcessingChunks = function completeProcessingChunks() {
return load(state.serverId);
};
var canProcessChunk = function canProcessChunk(chunk) {
return chunk.status === ChunkStatus.QUEUED || chunk.status === ChunkStatus.ERROR;
};
var processChunk = function processChunk(chunk) {
// processing is paused, wait here
if (state.aborted) return;
// get next chunk to process
chunk = chunk || chunks.find(canProcessChunk);
// no more chunks to process
if (!chunk) {
// all done?
if (
chunks.every(function(chunk) {
return chunk.status === ChunkStatus.COMPLETE;
})
) {
completeProcessingChunks();
}
// no chunk to handle
return;
}
// now processing this chunk
chunk.status = ChunkStatus.PROCESSING;
chunk.progress = null;
// allow parsing of formdata
var ondata =
chunkServer.ondata ||
function(fd) {
return fd;
};
var onerror =
chunkServer.onerror ||
function(res) {
return null;
};
// send request object
var requestUrl = buildURL(apiUrl, chunkServer.url, state.serverId);
var headers =
typeof chunkServer.headers === 'function'
? chunkServer.headers(chunk)
: Object.assign({}, chunkServer.headers, {
'Content-Type': 'application/offset+octet-stream',
'Upload-Offset': chunk.offset,
'Upload-Length': file.size,
'Upload-Name': file.name,
});
var request = (chunk.request = sendRequest(
ondata(chunk.data),
requestUrl,
Object.assign({}, chunkServer, {
headers: headers,
})
));
request.onload = function() {
// done!
chunk.status = ChunkStatus.COMPLETE;
// remove request reference
chunk.request = null;
// start processing more chunks
processChunks();
};
request.onprogress = function(lengthComputable, loaded, total) {
chunk.progress = lengthComputable ? loaded : null;
updateTotalProgress();
};
request.onerror = function(xhr) {
chunk.status = ChunkStatus.ERROR;
chunk.request = null;
chunk.error = onerror(xhr.response) || xhr.statusText;
if (!retryProcessChunk(chunk)) {
error(
createResponse(
'error',
xhr.status,
onerror(xhr.response) || xhr.statusText,
xhr.getAllResponseHeaders()
)
);
}
};
request.ontimeout = function(xhr) {
chunk.status = ChunkStatus.ERROR;
chunk.request = null;
if (!retryProcessChunk(chunk)) {
createTimeoutResponse(error)(xhr);
}
};
request.onabort = function() {
chunk.status = ChunkStatus.QUEUED;
chunk.request = null;
abort();
};
};
var retryProcessChunk = function retryProcessChunk(chunk) {
// no more retries left
if (chunk.retries.length === 0) return false;
// new retry
chunk.status = ChunkStatus.WAITING;
clearTimeout(chunk.timeout);
chunk.timeout = setTimeout(function() {
processChunk(chunk);
}, chunk.retries.shift());
// we're going to retry
return true;
};
var updateTotalProgress = function updateTotalProgress() {
// calculate total progress fraction
var totalBytesTransfered = chunks.reduce(function(p, chunk) {
if (p === null || chunk.progress === null) return null;
return p + chunk.progress;
}, 0);
// can't compute progress
if (totalBytesTransfered === null) return progress(false, 0, 0);
// calculate progress values
var totalSize = chunks.reduce(function(total, chunk) {
return total + chunk.size;
}, 0);
// can update progress indicator
progress(true, totalBytesTransfered, totalSize);
};
// process new chunks
var processChunks = function processChunks() {
var totalProcessing = chunks.filter(function(chunk) {
return chunk.status === ChunkStatus.PROCESSING;
}).length;
if (totalProcessing >= 1) return;
processChunk();
};
var abortChunks = function abortChunks() {
chunks.forEach(function(chunk) {
clearTimeout(chunk.timeout);
if (chunk.request) {
chunk.request.abort();
}
});
};
// let's go!
if (!state.serverId) {
requestTransferId(function(serverId) {
// stop here if aborted, might have happened in between request and callback
if (state.aborted) return;
// pass back to item so we can use it if something goes wrong
transfer(serverId);
// store internally
state.serverId = serverId;
processChunks();
});
} else {
requestTransferOffset(function(offset) {
// stop here if aborted, might have happened in between request and callback
if (state.aborted) return;
// mark chunks with lower offset as complete
chunks
.filter(function(chunk) {
return chunk.offset < offset;
})
.forEach(function(chunk) {
chunk.status = ChunkStatus.COMPLETE;
chunk.progress = chunk.size;
});
// continue processing
processChunks();
});
}
return {
abort: function abort() {
state.aborted = true;
abortChunks();
},
};
};
/*
function signature:
(file, metadata, load, error, progress, abort) => {
return {
abort:() => {}
}
}
*/
var createFileProcessorFunction = function createFileProcessorFunction(
apiUrl,
action,
name,
options
) {
return function(file, metadata, load, error, progress, abort, transfer) {
// no file received
if (!file) return;
// if was passed a file, and we can chunk it, exit here
var canChunkUpload = options.chunkUploads;
var shouldChunkUpload = canChunkUpload && file.size > options.chunkSize;
var willChunkUpload = canChunkUpload && (shouldChunkUpload || options.chunkForce);
if (file instanceof Blob && willChunkUpload)
return processFileChunked(
apiUrl,
action,
name,
file,
metadata,
load,
error,
progress,
abort,
transfer,
options
);
// set handlers
var ondata =
action.ondata ||
function(fd) {
return fd;
};
var onload =
action.onload ||
function(res) {
return res;
};
var onerror =
action.onerror ||
function(res) {
return null;
};
var headers =
typeof action.headers === 'function'
? action.headers(file, metadata) || {}
: Object.assign(
{},
action.headers
);
var requestParams = Object.assign({}, action, {
headers: headers,
});
// create formdata object
var formData = new FormData();
// add metadata under same name
if (isObject(metadata)) {
formData.append(name, JSON.stringify(metadata));
}
// Turn into an array of objects so no matter what the input, we can handle it the same way
(file instanceof Blob ? [{ name: null, file: file }] : file).forEach(function(item) {
formData.append(
name,
item.file,
item.name === null ? item.file.name : '' + item.name + item.file.name
);
});
// send request object
var request = sendRequest(
ondata(formData),
buildURL(apiUrl, action.url),
requestParams
);
request.onload = function(xhr) {
load(
createResponse(
'load',
xhr.status,
onload(xhr.response),
xhr.getAllResponseHeaders()
)
);
};
request.onerror = function(xhr) {
error(
createResponse(
'error',
xhr.status,
onerror(xhr.response) || xhr.statusText,
xhr.getAllResponseHeaders()
)
);
};
request.ontimeout = createTimeoutResponse(error);
request.onprogress = progress;
request.onabort = abort;
// should return request
return request;
};
};
var createProcessorFunction = function createProcessorFunction() {
var apiUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var action = arguments.length > 1 ? arguments[1] : undefined;
var name = arguments.length > 2 ? arguments[2] : undefined;
var options = arguments.length > 3 ? arguments[3] : undefined;
// custom handler (should also handle file, load, error, progress and abort)
if (typeof action === 'function')
return function() {
for (
var _len = arguments.length, params = new Array(_len), _key = 0;
_key < _len;
_key++
) {
params[_key] = arguments[_key];
}
return action.apply(void 0, [name].concat(params, [options]));
};
// no action supplied
if (!action || !isString(action.url)) return null;
// internal handler
return createFileProcessorFunction(apiUrl, action, name, options);
};
/*
function signature:
(uniqueFileId, load, error) => { }
*/
var createRevertFunction = function createRevertFunction() {
var apiUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var action = arguments.length > 1 ? arguments[1] : undefined;
// is custom implementation
if (typeof action === 'function') {
return action;
}
// no action supplied, return stub function, interface will work, but file won't be removed
if (!action || !isString(action.url)) {
return function(uniqueFileId, load) {
return load();
};
}
// set onload hanlder
var onload =
action.onload ||
function(res) {
return res;
};
var onerror =
action.onerror ||
function(res) {
return null;
};
// internal implementation
return function(uniqueFileId, load, error) {
var request = sendRequest(
uniqueFileId,
apiUrl + action.url,
action // contains method, headers and withCredentials properties
);
request.onload = function(xhr) {
load(
createResponse(
'load',
xhr.status,
onload(xhr.response),
xhr.getAllResponseHeaders()
)
);
};
request.onerror = function(xhr) {
error(
createResponse(
'error',
xhr.status,
onerror(xhr.response) || xhr.statusText,
xhr.getAllResponseHeaders()
)
);
};
request.ontimeout = createTimeoutResponse(error);
return request;
};
};
var getRandomNumber = function getRandomNumber() {
var min = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var max = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
return min + Math.random() * (max - min);
};
var createPerceivedPerformanceUpdater = function createPerceivedPerformanceUpdater(cb) {
var duration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1000;
var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
var tickMin = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 25;
var tickMax = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 250;
var timeout = null;
var start = Date.now();
var tick = function tick() {
var runtime = Date.now() - start;
var delay = getRandomNumber(tickMin, tickMax);
if (runtime + delay > duration) {
delay = runtime + delay - duration;
}
var progress = runtime / duration;
if (progress >= 1 || document.hidden) {
cb(1);
return;
}
cb(progress);
timeout = setTimeout(tick, delay);
};
tick();
return {
clear: function clear() {
clearTimeout(timeout);
},
};
};
var createFileProcessor = function createFileProcessor(processFn) {
var state = {
complete: false,
perceivedProgress: 0,
perceivedPerformanceUpdater: null,
progress: null,
timestamp: null,
perceivedDuration: 0,
duration: 0,
request: null,
response: null,
};
var process = function process(file, metadata) {
var progressFn = function progressFn() {
// we've not yet started the real download, stop here
// the request might not go through, for instance, there might be some server trouble
// if state.progress is null, the server does not allow computing progress and we show the spinner instead
if (state.duration === 0 || state.progress === null) return;
// as we're now processing, fire the progress event
api.fire('progress', api.getProgress());
};
var completeFn = function completeFn() {
state.complete = true;
api.fire('load-perceived', state.response.body);
};
// let's start processing
api.fire('start');
// set request start
state.timestamp = Date.now();
// create perceived performance progress indicator
state.perceivedPerformanceUpdater = createPerceivedPerformanceUpdater(
function(progress) {
state.perceivedProgress = progress;
state.perceivedDuration = Date.now() - state.timestamp;
progressFn();
// if fake progress is done, and a response has been received,
// and we've not yet called the complete method
if (state.response && state.perceivedProgress === 1 && !state.complete) {
// we done!
completeFn();
}
},
// random delay as in a list of files you start noticing
// files uploading at the exact same speed
getRandomNumber(750, 1500)
);
// remember request so we can abort it later
state.request = processFn(
// the file to process
file,
// the metadata to send along
metadata,
// callbacks (load, error, progress, abort, transfer)
// load expects the body to be a server id if
// you want to make use of revert
function(response) {
// we put the response in state so we can access
// it outside of this method
state.response = isObject(response)
? response
: {
type: 'load',
code: 200,
body: '' + response,
headers: {},
};
// update duration
state.duration = Date.now() - state.timestamp;
// force progress to 1 as we're now done
state.progress = 1;
// actual load is done let's share results
api.fire('load', state.response.body);
// we are really done
// if perceived progress is 1 ( wait for perceived progress to complete )
// or if server does not support progress ( null )
if (state.perceivedProgress === 1) {
completeFn();
}
},
// error is expected to be an object with type, code, body
function(error) {
// cancel updater
state.perceivedPerformanceUpdater.clear();
// update others about this error
api.fire(
'error',
isObject(error)
? error
: {
type: 'error',
code: 0,
body: '' + error,
}
);
},
// actual processing progress
function(computable, current, total) {
// update actual duration
state.duration = Date.now() - state.timestamp;
// update actual progress
state.progress = computable ? current / total : null;
progressFn();
},
// abort does not expect a value
function() {
// stop updater
state.perceivedPerformanceUpdater.clear();
// fire the abort event so we can switch visuals
api.fire('abort', state.response ? state.response.body : null);
},
// register the id for this transfer
function(transferId) {
api.fire('transfer', transferId);
}
);
};
var abort = function abort() {
// no request running, can't abort
if (!state.request) return;
// stop updater
state.perceivedPerformanceUpdater.clear();
// abort actual request
if (state.request.abort) state.request.abort();
// if has response object, we've completed the request
state.complete = true;
};
var reset = function reset() {
abort();
state.complete = false;
state.perceivedProgress = 0;
state.progress = 0;
state.timestamp = null;
state.perceivedDuration = 0;
state.duration = 0;
state.request = null;
state.response = null;
};
var getProgress = function getProgress() {
return state.progress ? Math.min(state.progress, state.perceivedProgress) : null;
};
var getDuration = function getDuration() {
return Math.min(state.duration, state.perceivedDuration);
};
var api = Object.assign({}, on(), {
process: process, // start processing file
abort: abort, // abort active process request
getProgress: getProgress,
getDuration: getDuration,
reset: reset,
});
return api;
};
var getFilenameWithoutExtension = function getFilenameWithoutExtension(name) {
return name.substr(0, name.lastIndexOf('.')) || name;
};
var createFileStub = function createFileStub(source) {
var data = [source.name, source.size, source.type];
// is blob or base64, then we need to set the name
if (source instanceof Blob || isBase64DataURI(source)) {
data[0] = source.name || getDateString();
} else if (isBase64DataURI(source)) {
// if is base64 data uri we need to determine the average size and type
data[1] = source.length;
data[2] = getMimeTypeFromBase64DataURI(source);
} else if (isString(source)) {
// url
data[0] = getFilenameFromURL(source);
data[1] = 0;
data[2] = 'application/octet-stream';
}
return {
name: data[0],
size: data[1],
type: data[2],
};
};
var isFile = function isFile(value) {
return !!(value instanceof File || (value instanceof Blob && value.name));
};
var deepCloneObject = function deepCloneObject(src) {
if (!isObject(src)) return src;
var target = isArray(src) ? [] : {};
for (var key in src) {
if (!src.hasOwnProperty(key)) continue;
var v = src[key];
target[key] = v && isObject(v) ? deepCloneObject(v) : v;
}
return target;
};
var createItem = function createItem() {
var origin = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var serverFileReference =
arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var file = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
// unique id for this item, is used to identify the item across views
var id = getUniqueId();
/**
* Internal item state
*/
var state = {
// is archived
archived: false,
// if is frozen, no longer fires events
frozen: false,
// removed from view
released: false,
// original source
source: null,
// file model reference
file: file,
// id of file on server
serverFileReference: serverFileReference,
// id of file transfer on server
transferId: null,
// is aborted
processingAborted: false,
// current item status
status: serverFileReference ? ItemStatus.PROCESSING_COMPLETE : ItemStatus.INIT,
// active processes
activeLoader: null,
activeProcessor: null,
};
// callback used when abort processing is called to link back to the resolve method
var abortProcessingRequestComplete = null;
/**
* Externally added item metadata
*/
var metadata = {};
// item data
var setStatus = function setStatus(status) {
return (state.status = status);
};
// fire event unless the item has been archived
var fire = function fire(event) {
if (state.released || state.frozen) return;
for (
var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1;
_key < _len;
_key++
) {
params[_key - 1] = arguments[_key];
}
api.fire.apply(api, [event].concat(params));
};
// file data
var getFileExtension = function getFileExtension() {
return getExtensionFromFilename(state.file.name);
};
var getFileType = function getFileType() {
return state.file.type;
};
var getFileSize = function getFileSize() {
return state.file.size;
};
var getFile = function getFile() {
return state.file;
};
//
// logic to load a file
//
var load = function load(source, loader, onload) {
// remember the original item source
state.source = source;
// source is known
api.fireSync('init');
// file stub is already there
if (state.file) {
api.fireSync('load-skip');
return;
}
// set a stub file object while loading the actual data
state.file = createFileStub(source);
// starts loading
loader.on('init', function() {
fire('load-init');
});
// we'eve received a size indication, let's update the stub
loader.on('meta', function(meta) {
// set size of file stub
state.file.size = meta.size;
// set name of file stub
state.file.filename = meta.filename;
// if has received source, we done
if (meta.source) {
origin = FileOrigin.LIMBO;
state.serverFileReference = meta.source;
state.status = ItemStatus.PROCESSING_COMPLETE;
}
// size has been updated
fire('load-meta');
});
// the file is now loading we need to update the progress indicators
loader.on('progress', function(progress) {
setStatus(ItemStatus.LOADING);
fire('load-progress', progress);
});
// an error was thrown while loading the file, we need to switch to error state
loader.on('error', function(error) {
setStatus(ItemStatus.LOAD_ERROR);
fire('load-request-error', error);
});
// user or another process aborted the file load (cannot retry)
loader.on('abort', function() {
setStatus(ItemStatus.INIT);
fire('load-abort');
});
// done loading
loader.on('load', function(file) {
// as we've now loaded the file the loader is no longer required
state.activeLoader = null;
// called when file has loaded succesfully
var success = function success(result) {
// set (possibly) transformed file
state.file = isFile(result) ? result : state.file;
// file received
if (origin === FileOrigin.LIMBO && state.serverFileReference) {
setStatus(ItemStatus.PROCESSING_COMPLETE);
} else {
setStatus(ItemStatus.IDLE);
}
fire('load');
};
var error = function error(result) {
// set original file
state.file = file;
fire('load-meta');
setStatus(ItemStatus.LOAD_ERROR);
fire('load-file-error', result);
};
// if we already have a server file reference, we don't need to call the onload method
if (state.serverFileReference) {
success(file);
return;
}
// no server id, let's give this file the full treatment
onload(file, success, error);
});
// set loader source data
loader.setSource(source);
// set as active loader
state.activeLoader = loader;
// load the source data
loader.load();
};
var retryLoad = function retryLoad() {
if (!state.activeLoader) {
return;
}
state.activeLoader.load();
};
var abortLoad = function abortLoad() {
if (state.activeLoader) {
state.activeLoader.abort();
return;
}
setStatus(ItemStatus.INIT);
fire('load-abort');
};
//
// logic to process a file
//
var process = function process(processor, onprocess) {
// processing was aborted
if (state.processingAborted) {
state.processingAborted = false;
return;
}
// now processing
setStatus(ItemStatus.PROCESSING);
// reset abort callback
abortProcessingRequestComplete = null;
// if no file loaded we'll wait for the load event
if (!(state.file instanceof Blob)) {
api.on('load', function() {
process(processor, onprocess);
});
return;
}
// setup processor
processor.on('load', function(serverFileReference) {
// need this id to be able to revert the upload
state.transferId = null;
state.serverFileReference = serverFileReference;
});
// register transfer id
processor.on('transfer', function(transferId) {
// need this id to be able to revert the upload
state.transferId = transferId;
});
processor.on('load-perceived', function(serverFileReference) {
// no longer required
state.activeProcessor = null;
// need this id to be able to rever the upload
state.transferId = null;
state.serverFileReference = serverFileReference;
setStatus(ItemStatus.PROCESSING_COMPLETE);
fire('process-complete', serverFileReference);
});
processor.on('start', function() {
fire('process-start');
});
processor.on('error', function(error) {
state.activeProcessor = null;
setStatus(ItemStatus.PROCESSING_ERROR);
fire('process-error', error);
});
processor.on('abort', function(serverFileReference) {
state.activeProcessor = null;
// if file was uploaded but processing was cancelled during perceived processor time store file reference
state.transferId = null;
state.serverFileReference = serverFileReference;
setStatus(ItemStatus.IDLE);
fire('process-abort');
// has timeout so doesn't interfere with remove action
if (abortProcessingRequestComplete) {
abortProcessingRequestComplete();
}
});
processor.on('progress', function(progress) {
fire('process-progress', progress);
});
// when successfully transformed
var success = function success(file) {
// if was archived in the mean time, don't process
if (state.archived) return;
// process file!
processor.process(file, Object.assign({}, metadata));
};
// something went wrong during transform phase
var error = console.error;
// start processing the file
onprocess(state.file, success, error);
// set as active processor
state.activeProcessor = processor;
};
var requestProcessing = function requestProcessing() {
state.processingAborted = false;
setStatus(ItemStatus.PROCESSING_QUEUED);
};
var abortProcessing = function abortProcessing() {
return new Promise(function(resolve) {
if (!state.activeProcessor) {
state.processingAborted = true;
setStatus(ItemStatus.IDLE);
fire('process-abort');
resolve();
return;
}
abortProcessingRequestComplete = function abortProcessingRequestComplete() {
resolve();
};
state.activeProcessor.abort();
});
};
//
// logic to revert a processed file
//
var revert = function revert(revertFileUpload, forceRevert) {
return new Promise(function(resolve, reject) {
// cannot revert without a server id for this process
if (state.serverFileReference === null) {
resolve();
return;
}
// revert the upload (fire and forget)
revertFileUpload(
state.serverFileReference,
function() {
// reset file server id as now it's no available on the server
state.serverFileReference = null;
resolve();
},
function(error) {
// don't set error state when reverting is optional, it will always resolve
if (!forceRevert) {
resolve();
return;
}
// oh no errors
setStatus(ItemStatus.PROCESSING_REVERT_ERROR);
fire('process-revert-error');
reject(error);
}
);
// fire event
setStatus(ItemStatus.IDLE);
fire('process-revert');
});
};
// exposed methods
var _setMetadata = function setMetadata(key, value, silent) {
var keys = key.split('.');
var root = keys[0];
var last = keys.pop();
var data = metadata;
keys.forEach(function(key) {
return (data = data[key]);
});
// compare old value against new value, if they're the same, we're not updating
if (JSON.stringify(data[last]) === JSON.stringify(value)) return;
// update value
data[last] = value;
// don't fire update
if (silent) return;
// fire update
fire('metadata-update', {
key: root,
value: metadata[root],
});
};
var getMetadata = function getMetadata(key) {
return deepCloneObject(key ? metadata[key] : metadata);
};
var api = Object.assign(
{
id: {
get: function get() {
return id;
},
},
origin: {
get: function get() {
return origin;
},
},
serverId: {
get: function get() {
return state.serverFileReference;
},
},
transferId: {
get: function get() {
return state.transferId;
},
},
status: {
get: function get() {
return state.status;
},
},
filename: {
get: function get() {
return state.file.name;
},
},
filenameWithoutExtension: {
get: function get() {
return getFilenameWithoutExtension(state.file.name);
},
},
fileExtension: { get: getFileExtension },
fileType: { get: getFileType },
fileSize: { get: getFileSize },
file: { get: getFile },
relativePath: {
get: function get() {
return state.file._relativePath;
},
},
source: {
get: function get() {
return state.source;
},
},
getMetadata: getMetadata,
setMetadata: function setMetadata(key, value, silent) {
if (isObject(key)) {
var data = key;
Object.keys(data).forEach(function(key) {
_setMetadata(key, data[key], value);
});
return key;
}
_setMetadata(key, value, silent);
return value;
},
extend: function extend(name, handler) {
return (itemAPI[name] = handler);
},
abortLoad: abortLoad,
retryLoad: retryLoad,
requestProcessing: requestProcessing,
abortProcessing: abortProcessing,
load: load,
process: process,
revert: revert,
},
on(),
{
freeze: function freeze() {
return (state.frozen = true);
},
release: function release() {
return (state.released = true);
},
released: {
get: function get() {
return state.released;
},
},
archive: function archive() {
return (state.archived = true);
},
archived: {
get: function get() {
return state.archived;
},
},
}
);
// create it here instead of returning it instantly so we can extend it later
var itemAPI = createObject(api);
return itemAPI;
};
var getItemIndexByQuery = function getItemIndexByQuery(items, query) {
// just return first index
if (isEmpty(query)) {
return 0;
}
// invalid queries
if (!isString(query)) {
return -1;
}
// return item by id (or -1 if not found)
return items.findIndex(function(item) {
return item.id === query;
});
};
var getItemById = function getItemById(items, itemId) {
var index = getItemIndexByQuery(items, itemId);
if (index < 0) {
return;
}
return items[index] || null;
};
var fetchBlob = function fetchBlob(url, load, error, progress, abort, headers) {
var request = sendRequest(null, url, {
method: 'GET',
responseType: 'blob',
});
request.onload = function(xhr) {
// get headers
var headers = xhr.getAllResponseHeaders();
// get filename
var filename = getFileInfoFromHeaders(headers).name || getFilenameFromURL(url);
// create response
load(
createResponse('load', xhr.status, getFileFromBlob(xhr.response, filename), headers)
);
};
request.onerror = function(xhr) {
error(createResponse('error', xhr.status, xhr.statusText, xhr.getAllResponseHeaders()));
};
request.onheaders = function(xhr) {
headers(createResponse('headers', xhr.status, null, xhr.getAllResponseHeaders()));
};
request.ontimeout = createTimeoutResponse(error);
request.onprogress = progress;
request.onabort = abort;
// should return request
return request;
};
var getDomainFromURL = function getDomainFromURL(url) {
if (url.indexOf('//') === 0) {
url = location.protocol + url;
}
return url
.toLowerCase()
.replace('blob:', '')
.replace(/([a-z])?:\/\//, '$1')
.split('/')[0];
};
var isExternalURL = function isExternalURL(url) {
return (
(url.indexOf(':') > -1 || url.indexOf('//') > -1) &&
getDomainFromURL(location.href) !== getDomainFromURL(url)
);
};
var dynamicLabel = function dynamicLabel(label) {
return function() {
return isFunction(label) ? label.apply(void 0, arguments) : label;
};
};
var isMockItem = function isMockItem(item) {
return !isFile(item.file);
};
var listUpdated = function listUpdated(dispatch, state) {
clearTimeout(state.listUpdateTimeout);
state.listUpdateTimeout = setTimeout(function() {
dispatch('DID_UPDATE_ITEMS', { items: getActiveItems(state.items) });
}, 0);
};
var optionalPromise = function optionalPromise(fn) {
for (
var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1;
_key < _len;
_key++
) {
params[_key - 1] = arguments[_key];
}
return new Promise(function(resolve) {
if (!fn) {
return resolve(true);
}
var result = fn.apply(void 0, params);
if (result == null) {
return resolve(true);
}
if (typeof result === 'boolean') {
return resolve(result);
}
if (typeof result.then === 'function') {
result.then(resolve);
}
});
};
var sortItems = function sortItems(state, compare) {
state.items.sort(function(a, b) {
return compare(createItemAPI(a), createItemAPI(b));
});
};
// returns item based on state
var getItemByQueryFromState = function getItemByQueryFromState(state, itemHandler) {
return function() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var query = _ref.query,
_ref$success = _ref.success,
success = _ref$success === void 0 ? function() {} : _ref$success,
_ref$failure = _ref.failure,
failure = _ref$failure === void 0 ? function() {} : _ref$failure,
options = _objectWithoutProperties(_ref, ['query', 'success', 'failure']);
var item = getItemByQuery(state.items, query);
if (!item) {
failure({
error: createResponse('error', 0, 'Item not found'),
file: null,
});
return;
}
itemHandler(item, success, failure, options || {});
};
};
var actions = function actions(dispatch, query, state) {
return {
/**
* Aborts all ongoing processes
*/
ABORT_ALL: function ABORT_ALL() {
getActiveItems(state.items).forEach(function(item) {
item.freeze();
item.abortLoad();
item.abortProcessing();
});
},
/**
* Sets initial files
*/
DID_SET_FILES: function DID_SET_FILES(_ref2) {
var _ref2$value = _ref2.value,
value = _ref2$value === void 0 ? [] : _ref2$value;
// map values to file objects
var files = value.map(function(file) {
return {
source: file.source ? file.source : file,
options: file.options,
};
});
// loop over files, if file is in list, leave it be, if not, remove
// test if items should be moved
var activeItems = getActiveItems(state.items);
activeItems.forEach(function(item) {
// if item not is in new value, remove
if (
!files.find(function(file) {
return file.source === item.source || file.source === item.file;
})
) {
dispatch('REMOVE_ITEM', { query: item, remove: false });
}
});
// add new files
activeItems = getActiveItems(state.items);
files.forEach(function(file, index) {
// if file is already in list
if (
activeItems.find(function(item) {
return item.source === file.source || item.file === file.source;
})
)
return;
// not in list, add
dispatch(
'ADD_ITEM',
Object.assign({}, file, {
interactionMethod: InteractionMethod.NONE,
index: index,
})
);
});
},
DID_UPDATE_ITEM_METADATA: function DID_UPDATE_ITEM_METADATA(_ref3) {
var id = _ref3.id,
action = _ref3.action;
// if is called multiple times in close succession we combined all calls together to save resources
clearTimeout(state.itemUpdateTimeout);
state.itemUpdateTimeout = setTimeout(function() {
var item = getItemById(state.items, id);
// only revert and attempt to upload when we're uploading to a server
if (!query('IS_ASYNC')) {
// should we update the output data
applyFilterChain('SHOULD_PREPARE_OUTPUT', false, {
item: item,
query: query,
action: action,
}).then(function(shouldPrepareOutput) {
// plugins determined the output data should be prepared (or not), can be adjusted with beforePrepareOutput hook
var beforePrepareFile = query('GET_BEFORE_PREPARE_FILE');
if (beforePrepareFile)
shouldPrepareOutput = beforePrepareFile(item, shouldPrepareOutput);
if (!shouldPrepareOutput) return;
dispatch(
'REQUEST_PREPARE_OUTPUT',
{
query: id,
item: item,
success: function success(file) {
dispatch('DID_PREPARE_OUTPUT', { id: id, file: file });
},
},
true
);
});
return;
}
// for async scenarios
var upload = function upload() {
// we push this forward a bit so the interface is updated correctly
setTimeout(function() {
dispatch('REQUEST_ITEM_PROCESSING', { query: id });
}, 32);
};
var revert = function revert(doUpload) {
item.revert(
createRevertFunction(
state.options.server.url,
state.options.server.revert
),
query('GET_FORCE_REVERT')
)
.then(doUpload ? upload : function() {})
.catch(function() {});
};
var abort = function abort(doUpload) {
item.abortProcessing().then(doUpload ? upload : function() {});
};
// if we should re-upload the file immediately
if (item.status === ItemStatus.PROCESSING_COMPLETE) {
return revert(state.options.instantUpload);
}
// if currently uploading, cancel upload
if (item.status === ItemStatus.PROCESSING) {
return abort(state.options.instantUpload);
}
if (state.options.instantUpload) {
upload();
}
}, 0);
},
MOVE_ITEM: function MOVE_ITEM(_ref4) {
var query = _ref4.query,
index = _ref4.index;
var item = getItemByQuery(state.items, query);
if (!item) return;
var currentIndex = state.items.indexOf(item);
index = limit(index, 0, state.items.length - 1);
if (currentIndex === index) return;
state.items.splice(index, 0, state.items.splice(currentIndex, 1)[0]);
},
SORT: function SORT(_ref5) {
var compare = _ref5.compare;
sortItems(state, compare);
dispatch('DID_SORT_ITEMS', {
items: query('GET_ACTIVE_ITEMS'),
});
},
ADD_ITEMS: function ADD_ITEMS(_ref6) {
var items = _ref6.items,
index = _ref6.index,
interactionMethod = _ref6.interactionMethod,
_ref6$success = _ref6.success,
success = _ref6$success === void 0 ? function() {} : _ref6$success,
_ref6$failure = _ref6.failure,
failure = _ref6$failure === void 0 ? function() {} : _ref6$failure;
var currentIndex = index;
if (index === -1 || typeof index === 'undefined') {
var insertLocation = query('GET_ITEM_INSERT_LOCATION');
var totalItems = query('GET_TOTAL_ITEMS');
currentIndex = insertLocation === 'before' ? 0 : totalItems;
}
var ignoredFiles = query('GET_IGNORED_FILES');
var isValidFile = function isValidFile(source) {
return isFile(source)
? !ignoredFiles.includes(source.name.toLowerCase())
: !isEmpty(source);
};
var validItems = items.filter(isValidFile);
var promises = validItems.map(function(source) {
return new Promise(function(resolve, reject) {
dispatch('ADD_ITEM', {
interactionMethod: interactionMethod,
source: source.source || source,
success: resolve,
failure: reject,
index: currentIndex++,
options: source.options || {},
});
});
});
Promise.all(promises)
.then(success)
.catch(failure);
},
/**
* @param source
* @param index
* @param interactionMethod
*/
ADD_ITEM: function ADD_ITEM(_ref7) {
var source = _ref7.source,
_ref7$index = _ref7.index,
index = _ref7$index === void 0 ? -1 : _ref7$index,
interactionMethod = _ref7.interactionMethod,
_ref7$success = _ref7.success,
success = _ref7$success === void 0 ? function() {} : _ref7$success,
_ref7$failure = _ref7.failure,
failure = _ref7$failure === void 0 ? function() {} : _ref7$failure,
_ref7$options = _ref7.options,
options = _ref7$options === void 0 ? {} : _ref7$options;
// if no source supplied
if (isEmpty(source)) {
failure({
error: createResponse('error', 0, 'No source'),
file: null,
});
return;
}
// filter out invalid file items, used to filter dropped directory contents
if (
isFile(source) &&
state.options.ignoredFiles.includes(source.name.toLowerCase())
) {
// fail silently
return;
}
// test if there's still room in the list of files
if (!hasRoomForItem(state)) {
// if multiple allowed, we can't replace
// or if only a single item is allowed but we're not allowed to replace it we exit
if (
state.options.allowMultiple ||
(!state.options.allowMultiple && !state.options.allowReplace)
) {
var error = createResponse('warning', 0, 'Max files');
dispatch('DID_THROW_MAX_FILES', {
source: source,
error: error,
});
failure({ error: error, file: null });
return;
}
// let's replace the item
// id of first item we're about to remove
var _item = getActiveItems(state.items)[0];
// if has been processed remove it from the server as well
if (
_item.status === ItemStatus.PROCESSING_COMPLETE ||
_item.status === ItemStatus.PROCESSING_REVERT_ERROR
) {
var forceRevert = query('GET_FORCE_REVERT');
_item
.revert(
createRevertFunction(
state.options.server.url,
state.options.server.revert
),
forceRevert
)
.then(function() {
if (!forceRevert) return;
// try to add now
dispatch('ADD_ITEM', {
source: source,
index: index,
interactionMethod: interactionMethod,
success: success,
failure: failure,
options: options,
});
})
.catch(function() {}); // no need to handle this catch state for now
if (forceRevert) return;
}
// remove first item as it will be replaced by this item
dispatch('REMOVE_ITEM', { query: _item.id });
}
// where did the file originate
var origin =
options.type === 'local'
? FileOrigin.LOCAL
: options.type === 'limbo'
? FileOrigin.LIMBO
: FileOrigin.INPUT;
// create a new blank item
var item = createItem(
// where did this file come from
origin,
// an input file never has a server file reference
origin === FileOrigin.INPUT ? null : source,
// file mock data, if defined
options.file
);
// set initial meta data
Object.keys(options.metadata || {}).forEach(function(key) {
item.setMetadata(key, options.metadata[key]);
});
// created the item, let plugins add methods
applyFilters('DID_CREATE_ITEM', item, { query: query, dispatch: dispatch });
// where to insert new items
var itemInsertLocation = query('GET_ITEM_INSERT_LOCATION');
// adjust index if is not allowed to pick location
if (!state.options.itemInsertLocationFreedom) {
index = itemInsertLocation === 'before' ? -1 : state.items.length;
}
// add item to list
insertItem(state.items, item, index);
// sort items in list
if (isFunction(itemInsertLocation) && source) {
sortItems(state, itemInsertLocation);
}
// get a quick reference to the item id
var id = item.id;
// observe item events
item.on('init', function() {
dispatch('DID_INIT_ITEM', { id: id });
});
item.on('load-init', function() {
dispatch('DID_START_ITEM_LOAD', { id: id });
});
item.on('load-meta', function() {
dispatch('DID_UPDATE_ITEM_META', { id: id });
});
item.on('load-progress', function(progress) {
dispatch('DID_UPDATE_ITEM_LOAD_PROGRESS', { id: id, progress: progress });
});
item.on('load-request-error', function(error) {
var mainStatus = dynamicLabel(state.options.labelFileLoadError)(error);
// is client error, no way to recover
if (error.code >= 400 && error.code < 500) {
dispatch('DID_THROW_ITEM_INVALID', {
id: id,
error: error,
status: {
main: mainStatus,
sub: error.code + ' (' + error.body + ')',
},
});
// reject the file so can be dealt with through API
failure({ error: error, file: createItemAPI(item) });
return;
}
// is possible server error, so might be possible to retry
dispatch('DID_THROW_ITEM_LOAD_ERROR', {
id: id,
error: error,
status: {
main: mainStatus,
sub: state.options.labelTapToRetry,
},
});
});
item.on('load-file-error', function(error) {
dispatch('DID_THROW_ITEM_INVALID', {
id: id,
error: error.status,
status: error.status,
});
failure({ error: error.status, file: createItemAPI(item) });
});
item.on('load-abort', function() {
dispatch('REMOVE_ITEM', { query: id });
});
item.on('load-skip', function() {
dispatch('COMPLETE_LOAD_ITEM', {
query: id,
item: item,
data: {
source: source,
success: success,
},
});
});
item.on('load', function() {
var handleAdd = function handleAdd(shouldAdd) {
// no should not add this file
if (!shouldAdd) {
dispatch('REMOVE_ITEM', {
query: id,
});
return;
}
// now interested in metadata updates
item.on('metadata-update', function(change) {
dispatch('DID_UPDATE_ITEM_METADATA', { id: id, change: change });
});
// let plugins decide if the output data should be prepared at this point
// means we'll do this and wait for idle state
applyFilterChain('SHOULD_PREPARE_OUTPUT', false, {
item: item,
query: query,
}).then(function(shouldPrepareOutput) {
// plugins determined the output data should be prepared (or not), can be adjusted with beforePrepareOutput hook
var beforePrepareFile = query('GET_BEFORE_PREPARE_FILE');
if (beforePrepareFile)
shouldPrepareOutput = beforePrepareFile(item, shouldPrepareOutput);
var loadComplete = function loadComplete() {
dispatch('COMPLETE_LOAD_ITEM', {
query: id,
item: item,
data: {
source: source,
success: success,
},
});
listUpdated(dispatch, state);
};
// exit
if (shouldPrepareOutput) {
// wait for idle state and then run PREPARE_OUTPUT
dispatch(
'REQUEST_PREPARE_OUTPUT',
{
query: id,
item: item,
success: function success(file) {
dispatch('DID_PREPARE_OUTPUT', { id: id, file: file });
loadComplete();
},
},
true
);
return;
}
loadComplete();
});
};
// item loaded, allow plugins to
// - read data (quickly)
// - add metadata
applyFilterChain('DID_LOAD_ITEM', item, { query: query, dispatch: dispatch })
.then(function() {
optionalPromise(query('GET_BEFORE_ADD_FILE'), createItemAPI(item)).then(
handleAdd
);
})
.catch(function() {
handleAdd(false);
});
});
item.on('process-start', function() {
dispatch('DID_START_ITEM_PROCESSING', { id: id });
});
item.on('process-progress', function(progress) {
dispatch('DID_UPDATE_ITEM_PROCESS_PROGRESS', { id: id, progress: progress });
});
item.on('process-error', function(error) {
dispatch('DID_THROW_ITEM_PROCESSING_ERROR', {
id: id,
error: error,
status: {
main: dynamicLabel(state.options.labelFileProcessingError)(error),
sub: state.options.labelTapToRetry,
},
});
});
item.on('process-revert-error', function(error) {
dispatch('DID_THROW_ITEM_PROCESSING_REVERT_ERROR', {
id: id,
error: error,
status: {
main: dynamicLabel(state.options.labelFileProcessingRevertError)(error),
sub: state.options.labelTapToRetry,
},
});
});
item.on('process-complete', function(serverFileReference) {
dispatch('DID_COMPLETE_ITEM_PROCESSING', {
id: id,
error: null,
serverFileReference: serverFileReference,
});
dispatch('DID_DEFINE_VALUE', { id: id, value: serverFileReference });
});
item.on('process-abort', function() {
dispatch('DID_ABORT_ITEM_PROCESSING', { id: id });
});
item.on('process-revert', function() {
dispatch('DID_REVERT_ITEM_PROCESSING', { id: id });
dispatch('DID_DEFINE_VALUE', { id: id, value: null });
});
// let view know the item has been inserted
dispatch('DID_ADD_ITEM', {
id: id,
index: index,
interactionMethod: interactionMethod,
});
listUpdated(dispatch, state);
// start loading the source
var _ref8 = state.options.server || {},
url = _ref8.url,
load = _ref8.load,
restore = _ref8.restore,
fetch = _ref8.fetch;
item.load(
source,
// this creates a function that loads the file based on the type of file (string, base64, blob, file) and location of file (local, remote, limbo)
createFileLoader(
origin === FileOrigin.INPUT
? // input, if is remote, see if should use custom fetch, else use default fetchBlob
isString(source) && isExternalURL(source)
? fetch
? createFetchFunction(url, fetch)
: fetchBlob // remote url
: fetchBlob // try to fetch url
: // limbo or local
origin === FileOrigin.LIMBO
? createFetchFunction(url, restore) // limbo
: createFetchFunction(url, load) // local
),
// called when the file is loaded so it can be piped through the filters
function(file, success, error) {
// let's process the file
applyFilterChain('LOAD_FILE', file, { query: query })
.then(success)
.catch(error);
}
);
},
REQUEST_PREPARE_OUTPUT: function REQUEST_PREPARE_OUTPUT(_ref9) {
var item = _ref9.item,
success = _ref9.success,
_ref9$failure = _ref9.failure,
failure = _ref9$failure === void 0 ? function() {} : _ref9$failure;
// error response if item archived
var err = {
error: createResponse('error', 0, 'Item not found'),
file: null,
};
// don't handle archived items, an item could have been archived (load aborted) while waiting to be prepared
if (item.archived) return failure(err);
// allow plugins to alter the file data
applyFilterChain('PREPARE_OUTPUT', item.file, { query: query, item: item }).then(
function(result) {
applyFilterChain('COMPLETE_PREPARE_OUTPUT', result, {
query: query,
item: item,
}).then(function(result) {
// don't handle archived items, an item could have been archived (load aborted) while being prepared
if (item.archived) return failure(err);
// we done!
success(result);
});
}
);
},
COMPLETE_LOAD_ITEM: function COMPLETE_LOAD_ITEM(_ref10) {
var item = _ref10.item,
data = _ref10.data;
var success = data.success,
source = data.source;
// sort items in list
var itemInsertLocation = query('GET_ITEM_INSERT_LOCATION');
if (isFunction(itemInsertLocation) && source) {
sortItems(state, itemInsertLocation);
}
// let interface know the item has loaded
dispatch('DID_LOAD_ITEM', {
id: item.id,
error: null,
serverFileReference: item.origin === FileOrigin.INPUT ? null : source,
});
// item has been successfully loaded and added to the
// list of items so can now be safely returned for use
success(createItemAPI(item));
// if this is a local server file we need to show a different state
if (item.origin === FileOrigin.LOCAL) {
dispatch('DID_LOAD_LOCAL_ITEM', { id: item.id });
return;
}
// if is a temp server file we prevent async upload call here (as the file is already on the server)
if (item.origin === FileOrigin.LIMBO) {
dispatch('DID_COMPLETE_ITEM_PROCESSING', {
id: item.id,
error: null,
serverFileReference: source,
});
dispatch('DID_DEFINE_VALUE', {
id: item.id,
value: source,
});
return;
}
// id we are allowed to upload the file immediately, lets do it
if (query('IS_ASYNC') && state.options.instantUpload) {
dispatch('REQUEST_ITEM_PROCESSING', { query: item.id });
}
},
RETRY_ITEM_LOAD: getItemByQueryFromState(state, function(item) {
// try loading the source one more time
item.retryLoad();
}),
REQUEST_ITEM_PREPARE: getItemByQueryFromState(state, function(item, _success, failure) {
dispatch(
'REQUEST_PREPARE_OUTPUT',
{
query: item.id,
item: item,
success: function success(file) {
dispatch('DID_PREPARE_OUTPUT', { id: item.id, file: file });
_success({
file: item,
output: file,
});
},
failure: failure,
},
true
);
}),
REQUEST_ITEM_PROCESSING: getItemByQueryFromState(state, function(
item,
success,
failure
) {
// cannot be queued (or is already queued)
var itemCanBeQueuedForProcessing =
// waiting for something
item.status === ItemStatus.IDLE ||
// processing went wrong earlier
item.status === ItemStatus.PROCESSING_ERROR;
// not ready to be processed
if (!itemCanBeQueuedForProcessing) {
var processNow = function processNow() {
return dispatch('REQUEST_ITEM_PROCESSING', {
query: item,
success: success,
failure: failure,
});
};
var process = function process() {
return document.hidden ? processNow() : setTimeout(processNow, 32);
};
// if already done processing or tried to revert but didn't work, try again
if (
item.status === ItemStatus.PROCESSING_COMPLETE ||
item.status === ItemStatus.PROCESSING_REVERT_ERROR
) {
item.revert(
createRevertFunction(
state.options.server.url,
state.options.server.revert
),
query('GET_FORCE_REVERT')
)
.then(process)
.catch(function() {}); // don't continue with processing if something went wrong
} else if (item.status === ItemStatus.PROCESSING) {
item.abortProcessing().then(process);
}
return;
}
// already queued for processing
if (item.status === ItemStatus.PROCESSING_QUEUED) return;
item.requestProcessing();
dispatch('DID_REQUEST_ITEM_PROCESSING', { id: item.id });
dispatch('PROCESS_ITEM', { query: item, success: success, failure: failure }, true);
}),
PROCESS_ITEM: getItemByQueryFromState(state, function(item, success, failure) {
var maxParallelUploads = query('GET_MAX_PARALLEL_UPLOADS');
var totalCurrentUploads = query('GET_ITEMS_BY_STATUS', ItemStatus.PROCESSING)
.length;
// queue and wait till queue is freed up
if (totalCurrentUploads === maxParallelUploads) {
// queue for later processing
state.processingQueue.push({
id: item.id,
success: success,
failure: failure,
});
// stop it!
return;
}
// if was not queued or is already processing exit here
if (item.status === ItemStatus.PROCESSING) return;
var processNext = function processNext() {
// process queueud items
var queueEntry = state.processingQueue.shift();
// no items left
if (!queueEntry) return;
// get item reference
var id = queueEntry.id,
success = queueEntry.success,
failure = queueEntry.failure;
var itemReference = getItemByQuery(state.items, id);
// if item was archived while in queue, jump to next
if (!itemReference || itemReference.archived) {
processNext();
return;
}
// process queued item
dispatch(
'PROCESS_ITEM',
{ query: id, success: success, failure: failure },
true
);
};
// we done function
item.onOnce('process-complete', function() {
success(createItemAPI(item));
processNext();
// All items processed? No errors?
var allItemsProcessed =
query('GET_ITEMS_BY_STATUS', ItemStatus.PROCESSING_COMPLETE).length ===
state.items.length;
if (allItemsProcessed) {
dispatch('DID_COMPLETE_ITEM_PROCESSING_ALL');
}
});
// we error function
item.onOnce('process-error', function(error) {
failure({ error: error, file: createItemAPI(item) });
processNext();
});
// start file processing
var options = state.options;
item.process(
createFileProcessor(
createProcessorFunction(
options.server.url,
options.server.process,
options.name,
{
chunkTransferId: item.transferId,
chunkServer: options.server.patch,
chunkUploads: options.chunkUploads,
chunkForce: options.chunkForce,
chunkSize: options.chunkSize,
chunkRetryDelays: options.chunkRetryDelays,
}
)
),
// called when the file is about to be processed so it can be piped through the transform filters
function(file, success, error) {
// allow plugins to alter the file data
applyFilterChain('PREPARE_OUTPUT', file, { query: query, item: item })
.then(function(file) {
dispatch('DID_PREPARE_OUTPUT', { id: item.id, file: file });
success(file);
})
.catch(error);
}
);
}),
RETRY_ITEM_PROCESSING: getItemByQueryFromState(state, function(item) {
dispatch('REQUEST_ITEM_PROCESSING', { query: item });
}),
REQUEST_REMOVE_ITEM: getItemByQueryFromState(state, function(item) {
optionalPromise(query('GET_BEFORE_REMOVE_FILE'), createItemAPI(item)).then(function(
shouldRemove
) {
if (!shouldRemove) {
return;
}
dispatch('REMOVE_ITEM', { query: item });
});
}),
RELEASE_ITEM: getItemByQueryFromState(state, function(item) {
item.release();
}),
REMOVE_ITEM: getItemByQueryFromState(state, function(item, success, failure, options) {
var removeFromView = function removeFromView() {
// get id reference
var id = item.id;
// archive the item, this does not remove it from the list
getItemById(state.items, id).archive();
// tell the view the item has been removed
dispatch('DID_REMOVE_ITEM', { error: null, id: id, item: item });
// now the list has been modified
listUpdated(dispatch, state);
// correctly removed
success(createItemAPI(item));
};
// if this is a local file and the server.remove function has been configured, send source there so dev can remove file from server
var server = state.options.server;
if (
item.origin === FileOrigin.LOCAL &&
server &&
isFunction(server.remove) &&
options.remove !== false
) {
dispatch('DID_START_ITEM_REMOVE', { id: item.id });
server.remove(
item.source,
function() {
return removeFromView();
},
function(status) {
dispatch('DID_THROW_ITEM_REMOVE_ERROR', {
id: item.id,
error: createResponse('error', 0, status, null),
status: {
main: dynamicLabel(state.options.labelFileRemoveError)(status),
sub: state.options.labelTapToRetry,
},
});
}
);
} else {
// if is requesting revert and can revert need to call revert handler (not calling request_ because that would also trigger beforeRemoveHook)
if (
options.revert &&
item.origin !== FileOrigin.LOCAL &&
item.serverId !== null
) {
item.revert(
createRevertFunction(
state.options.server.url,
state.options.server.revert
),
query('GET_FORCE_REVERT')
);
}
// can now safely remove from view
removeFromView();
}
}),
ABORT_ITEM_LOAD: getItemByQueryFromState(state, function(item) {
item.abortLoad();
}),
ABORT_ITEM_PROCESSING: getItemByQueryFromState(state, function(item) {
// test if is already processed
if (item.serverId) {
dispatch('REVERT_ITEM_PROCESSING', { id: item.id });
return;
}
// abort
item.abortProcessing().then(function() {
var shouldRemove = state.options.instantUpload;
if (shouldRemove) {
dispatch('REMOVE_ITEM', { query: item.id });
}
});
}),
REQUEST_REVERT_ITEM_PROCESSING: getItemByQueryFromState(state, function(item) {
// not instant uploading, revert immediately
if (!state.options.instantUpload) {
dispatch('REVERT_ITEM_PROCESSING', { query: item });
return;
}
// if we're instant uploading the file will also be removed if we revert,
// so if a before remove file hook is defined we need to run it now
var handleRevert = function handleRevert(shouldRevert) {
if (!shouldRevert) return;
dispatch('REVERT_ITEM_PROCESSING', { query: item });
};
var fn = query('GET_BEFORE_REMOVE_FILE');
if (!fn) {
return handleRevert(true);
}
var requestRemoveResult = fn(createItemAPI(item));
if (requestRemoveResult == null) {
// undefined or null
return handleRevert(true);
}
if (typeof requestRemoveResult === 'boolean') {
return handleRevert(requestRemoveResult);
}
if (typeof requestRemoveResult.then === 'function') {
requestRemoveResult.then(handleRevert);
}
}),
REVERT_ITEM_PROCESSING: getItemByQueryFromState(state, function(item) {
item.revert(
createRevertFunction(state.options.server.url, state.options.server.revert),
query('GET_FORCE_REVERT')
)
.then(function() {
var shouldRemove = state.options.instantUpload || isMockItem(item);
if (shouldRemove) {
dispatch('REMOVE_ITEM', { query: item.id });
}
})
.catch(function() {});
}),
SET_OPTIONS: function SET_OPTIONS(_ref11) {
var options = _ref11.options;
forin(options, function(key, value) {
dispatch('SET_' + fromCamels(key, '_').toUpperCase(), { value: value });
});
},
};
};
var formatFilename = function formatFilename(name) {
return name;
};
var createElement$1 = function createElement(tagName) {
return document.createElement(tagName);
};
var text = function text(node, value) {
var textNode = node.childNodes[0];
if (!textNode) {
textNode = document.createTextNode(value);
node.appendChild(textNode);
} else if (value !== textNode.nodeValue) {
textNode.nodeValue = value;
}
};
var polarToCartesian = function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
var angleInRadians = (((angleInDegrees % 360) - 90) * Math.PI) / 180.0;
return {
x: centerX + radius * Math.cos(angleInRadians),
y: centerY + radius * Math.sin(angleInRadians),
};
};
var describeArc = function describeArc(x, y, radius, startAngle, endAngle, arcSweep) {
var start = polarToCartesian(x, y, radius, endAngle);
var end = polarToCartesian(x, y, radius, startAngle);
return ['M', start.x, start.y, 'A', radius, radius, 0, arcSweep, 0, end.x, end.y].join(' ');
};
var percentageArc = function percentageArc(x, y, radius, from, to) {
var arcSweep = 1;
if (to > from && to - from <= 0.5) {
arcSweep = 0;
}
if (from > to && from - to >= 0.5) {
arcSweep = 0;
}
return describeArc(
x,
y,
radius,
Math.min(0.9999, from) * 360,
Math.min(0.9999, to) * 360,
arcSweep
);
};
var create = function create(_ref) {
var root = _ref.root,
props = _ref.props;
// start at 0
props.spin = false;
props.progress = 0;
props.opacity = 0;
// svg
var svg = createElement('svg');
root.ref.path = createElement('path', {
'stroke-width': 2,
'stroke-linecap': 'round',
});
svg.appendChild(root.ref.path);
root.ref.svg = svg;
root.appendChild(svg);
};
var write = function write(_ref2) {
var root = _ref2.root,
props = _ref2.props;
if (props.opacity === 0) {
return;
}
if (props.align) {
root.element.dataset.align = props.align;
}
// get width of stroke
var ringStrokeWidth = parseInt(attr(root.ref.path, 'stroke-width'), 10);
// calculate size of ring
var size = root.rect.element.width * 0.5;
// ring state
var ringFrom = 0;
var ringTo = 0;
// now in busy mode
if (props.spin) {
ringFrom = 0;
ringTo = 0.5;
} else {
ringFrom = 0;
ringTo = props.progress;
}
// get arc path
var coordinates = percentageArc(size, size, size - ringStrokeWidth, ringFrom, ringTo);
// update progress bar
attr(root.ref.path, 'd', coordinates);
// hide while contains 0 value
attr(root.ref.path, 'stroke-opacity', props.spin || props.progress > 0 ? 1 : 0);
};
var progressIndicator = createView({
tag: 'div',
name: 'progress-indicator',
ignoreRectUpdate: true,
ignoreRect: true,
create: create,
write: write,
mixins: {
apis: ['progress', 'spin', 'align'],
styles: ['opacity'],
animations: {
opacity: { type: 'tween', duration: 500 },
progress: {
type: 'spring',
stiffness: 0.95,
damping: 0.65,
mass: 10,
},
},
},
});
var create$1 = function create(_ref) {
var root = _ref.root,
props = _ref.props;
root.element.innerHTML = (props.icon || '') + ('<span>' + props.label + '</span>');
props.isDisabled = false;
};
var write$1 = function write(_ref2) {
var root = _ref2.root,
props = _ref2.props;
var isDisabled = props.isDisabled;
var shouldDisable = root.query('GET_DISABLED') || props.opacity === 0;
if (shouldDisable && !isDisabled) {
props.isDisabled = true;
attr(root.element, 'disabled', 'disabled');
} else if (!shouldDisable && isDisabled) {
props.isDisabled = false;
root.element.removeAttribute('disabled');
}
};
var fileActionButton = createView({
tag: 'button',
attributes: {
type: 'button',
},
ignoreRect: true,
ignoreRectUpdate: true,
name: 'file-action-button',
mixins: {
apis: ['label'],
styles: ['translateX', 'translateY', 'scaleX', 'scaleY', 'opacity'],
animations: {
scaleX: 'spring',
scaleY: 'spring',
translateX: 'spring',
translateY: 'spring',
opacity: { type: 'tween', duration: 250 },
},
listeners: true,
},
create: create$1,
write: write$1,
});
var toNaturalFileSize = function toNaturalFileSize(bytes) {
var decimalSeparator =
arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '.';
var base = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1000;
// no negative byte sizes
bytes = Math.round(Math.abs(bytes));
var KB = base;
var MB = base * base;
var GB = base * base * base;
// just bytes
if (bytes < KB) {
return bytes + ' bytes';
}
// kilobytes
if (bytes < MB) {
return Math.floor(bytes / KB) + ' KB';
}
// megabytes
if (bytes < GB) {
return removeDecimalsWhenZero(bytes / MB, 1, decimalSeparator) + ' MB';
}
// gigabytes
return removeDecimalsWhenZero(bytes / GB, 2, decimalSeparator) + ' GB';
};
var removeDecimalsWhenZero = function removeDecimalsWhenZero(value, decimalCount, separator) {
return value
.toFixed(decimalCount)
.split('.')
.filter(function(part) {
return part !== '0';
})
.join(separator);
};
var create$2 = function create(_ref) {
var root = _ref.root,
props = _ref.props;
// filename
var fileName = createElement$1('span');
fileName.className = 'filepond--file-info-main';
// hide for screenreaders
// the file is contained in a fieldset with legend that contains the filename
// no need to read it twice
attr(fileName, 'aria-hidden', 'true');
root.appendChild(fileName);
root.ref.fileName = fileName;
// filesize
var fileSize = createElement$1('span');
fileSize.className = 'filepond--file-info-sub';
root.appendChild(fileSize);
root.ref.fileSize = fileSize;
// set initial values
text(fileSize, root.query('GET_LABEL_FILE_WAITING_FOR_SIZE'));
text(fileName, formatFilename(root.query('GET_ITEM_NAME', props.id)));
};
var updateFile = function updateFile(_ref2) {
var root = _ref2.root,
props = _ref2.props;
text(
root.ref.fileSize,
toNaturalFileSize(
root.query('GET_ITEM_SIZE', props.id),
'.',
root.query('GET_FILE_SIZE_BASE')
)
);
text(root.ref.fileName, formatFilename(root.query('GET_ITEM_NAME', props.id)));
};
var updateFileSizeOnError = function updateFileSizeOnError(_ref3) {
var root = _ref3.root,
props = _ref3.props;
// if size is available don't fallback to unknown size message
if (isInt(root.query('GET_ITEM_SIZE', props.id))) {
return;
}
text(root.ref.fileSize, root.query('GET_LABEL_FILE_SIZE_NOT_AVAILABLE'));
};
var fileInfo = createView({
name: 'file-info',
ignoreRect: true,
ignoreRectUpdate: true,
write: createRoute({
DID_LOAD_ITEM: updateFile,
DID_UPDATE_ITEM_META: updateFile,
DID_THROW_ITEM_LOAD_ERROR: updateFileSizeOnError,
DID_THROW_ITEM_INVALID: updateFileSizeOnError,
}),
didCreateView: function didCreateView(root) {
applyFilters('CREATE_VIEW', Object.assign({}, root, { view: root }));
},
create: create$2,
mixins: {
styles: ['translateX', 'translateY'],
animations: {
translateX: 'spring',
translateY: 'spring',
},
},
});
var toPercentage = function toPercentage(value) {
return Math.round(value * 100);
};
var create$3 = function create(_ref) {
var root = _ref.root;
// main status
var main = createElement$1('span');
main.className = 'filepond--file-status-main';
root.appendChild(main);
root.ref.main = main;
// sub status
var sub = createElement$1('span');
sub.className = 'filepond--file-status-sub';
root.appendChild(sub);
root.ref.sub = sub;
didSetItemLoadProgress({ root: root, action: { progress: null } });
};
var didSetItemLoadProgress = function didSetItemLoadProgress(_ref2) {
var root = _ref2.root,
action = _ref2.action;
var title =
action.progress === null
? root.query('GET_LABEL_FILE_LOADING')
: root.query('GET_LABEL_FILE_LOADING') + ' ' + toPercentage(action.progress) + '%';
text(root.ref.main, title);
text(root.ref.sub, root.query('GET_LABEL_TAP_TO_CANCEL'));
};
var didSetItemProcessProgress = function didSetItemProcessProgress(_ref3) {
var root = _ref3.root,
action = _ref3.action;
var title =
action.progress === null
? root.query('GET_LABEL_FILE_PROCESSING')
: root.query('GET_LABEL_FILE_PROCESSING') +
' ' +
toPercentage(action.progress) +
'%';
text(root.ref.main, title);
text(root.ref.sub, root.query('GET_LABEL_TAP_TO_CANCEL'));
};
var didRequestItemProcessing = function didRequestItemProcessing(_ref4) {
var root = _ref4.root;
text(root.ref.main, root.query('GET_LABEL_FILE_PROCESSING'));
text(root.ref.sub, root.query('GET_LABEL_TAP_TO_CANCEL'));
};
var didAbortItemProcessing = function didAbortItemProcessing(_ref5) {
var root = _ref5.root;
text(root.ref.main, root.query('GET_LABEL_FILE_PROCESSING_ABORTED'));
text(root.ref.sub, root.query('GET_LABEL_TAP_TO_RETRY'));
};
var didCompleteItemProcessing = function didCompleteItemProcessing(_ref6) {
var root = _ref6.root;
text(root.ref.main, root.query('GET_LABEL_FILE_PROCESSING_COMPLETE'));
text(root.ref.sub, root.query('GET_LABEL_TAP_TO_UNDO'));
};
var clear = function clear(_ref7) {
var root = _ref7.root;
text(root.ref.main, '');
text(root.ref.sub, '');
};
var error = function error(_ref8) {
var root = _ref8.root,
action = _ref8.action;
text(root.ref.main, action.status.main);
text(root.ref.sub, action.status.sub);
};
var fileStatus = createView({
name: 'file-status',
ignoreRect: true,
ignoreRectUpdate: true,
write: createRoute({
DID_LOAD_ITEM: clear,
DID_REVERT_ITEM_PROCESSING: clear,
DID_REQUEST_ITEM_PROCESSING: didRequestItemProcessing,
DID_ABORT_ITEM_PROCESSING: didAbortItemProcessing,
DID_COMPLETE_ITEM_PROCESSING: didCompleteItemProcessing,
DID_UPDATE_ITEM_PROCESS_PROGRESS: didSetItemProcessProgress,
DID_UPDATE_ITEM_LOAD_PROGRESS: didSetItemLoadProgress,
DID_THROW_ITEM_LOAD_ERROR: error,
DID_THROW_ITEM_INVALID: error,
DID_THROW_ITEM_PROCESSING_ERROR: error,
DID_THROW_ITEM_PROCESSING_REVERT_ERROR: error,
DID_THROW_ITEM_REMOVE_ERROR: error,
}),
didCreateView: function didCreateView(root) {
applyFilters('CREATE_VIEW', Object.assign({}, root, { view: root }));
},
create: create$3,
mixins: {
styles: ['translateX', 'translateY', 'opacity'],
animations: {
opacity: { type: 'tween', duration: 250 },
translateX: 'spring',
translateY: 'spring',
},
},
});
/**
* Button definitions for the file view
*/
var Buttons = {
AbortItemLoad: {
label: 'GET_LABEL_BUTTON_ABORT_ITEM_LOAD',
action: 'ABORT_ITEM_LOAD',
className: 'filepond--action-abort-item-load',
align: 'LOAD_INDICATOR_POSITION', // right
},
RetryItemLoad: {
label: 'GET_LABEL_BUTTON_RETRY_ITEM_LOAD',
action: 'RETRY_ITEM_LOAD',
icon: 'GET_ICON_RETRY',
className: 'filepond--action-retry-item-load',
align: 'BUTTON_PROCESS_ITEM_POSITION', // right
},
RemoveItem: {
label: 'GET_LABEL_BUTTON_REMOVE_ITEM',
action: 'REQUEST_REMOVE_ITEM',
icon: 'GET_ICON_REMOVE',
className: 'filepond--action-remove-item',
align: 'BUTTON_REMOVE_ITEM_POSITION', // left
},
ProcessItem: {
label: 'GET_LABEL_BUTTON_PROCESS_ITEM',
action: 'REQUEST_ITEM_PROCESSING',
icon: 'GET_ICON_PROCESS',
className: 'filepond--action-process-item',
align: 'BUTTON_PROCESS_ITEM_POSITION', // right
},
AbortItemProcessing: {
label: 'GET_LABEL_BUTTON_ABORT_ITEM_PROCESSING',
action: 'ABORT_ITEM_PROCESSING',
className: 'filepond--action-abort-item-processing',
align: 'BUTTON_PROCESS_ITEM_POSITION', // right
},
RetryItemProcessing: {
label: 'GET_LABEL_BUTTON_RETRY_ITEM_PROCESSING',
action: 'RETRY_ITEM_PROCESSING',
icon: 'GET_ICON_RETRY',
className: 'filepond--action-retry-item-processing',
align: 'BUTTON_PROCESS_ITEM_POSITION', // right
},
RevertItemProcessing: {
label: 'GET_LABEL_BUTTON_UNDO_ITEM_PROCESSING',
action: 'REQUEST_REVERT_ITEM_PROCESSING',
icon: 'GET_ICON_UNDO',
className: 'filepond--action-revert-item-processing',
align: 'BUTTON_PROCESS_ITEM_POSITION', // right
},
};
// make a list of buttons, we can then remove buttons from this list if they're disabled
var ButtonKeys = [];
forin(Buttons, function(key) {
ButtonKeys.push(key);
});
var calculateFileInfoOffset = function calculateFileInfoOffset(root) {
if (getRemoveIndicatorAligment(root) === 'right') return 0;
var buttonRect = root.ref.buttonRemoveItem.rect.element;
return buttonRect.hidden ? null : buttonRect.width + buttonRect.left;
};
var calculateButtonWidth = function calculateButtonWidth(root) {
var buttonRect = root.ref.buttonAbortItemLoad.rect.element;
return buttonRect.width;
};
// Force on full pixels so text stays crips
var calculateFileVerticalCenterOffset = function calculateFileVerticalCenterOffset(root) {
return Math.floor(root.ref.buttonRemoveItem.rect.element.height / 4);
};
var calculateFileHorizontalCenterOffset = function calculateFileHorizontalCenterOffset(root) {
return Math.floor(root.ref.buttonRemoveItem.rect.element.left / 2);
};
var getLoadIndicatorAlignment = function getLoadIndicatorAlignment(root) {
return root.query('GET_STYLE_LOAD_INDICATOR_POSITION');
};
var getProcessIndicatorAlignment = function getProcessIndicatorAlignment(root) {
return root.query('GET_STYLE_PROGRESS_INDICATOR_POSITION');
};
var getRemoveIndicatorAligment = function getRemoveIndicatorAligment(root) {
return root.query('GET_STYLE_BUTTON_REMOVE_ITEM_POSITION');
};
var DefaultStyle = {
buttonAbortItemLoad: { opacity: 0 },
buttonRetryItemLoad: { opacity: 0 },
buttonRemoveItem: { opacity: 0 },
buttonProcessItem: { opacity: 0 },
buttonAbortItemProcessing: { opacity: 0 },
buttonRetryItemProcessing: { opacity: 0 },
buttonRevertItemProcessing: { opacity: 0 },
loadProgressIndicator: { opacity: 0, align: getLoadIndicatorAlignment },
processProgressIndicator: { opacity: 0, align: getProcessIndicatorAlignment },
processingCompleteIndicator: { opacity: 0, scaleX: 0.75, scaleY: 0.75 },
info: { translateX: 0, translateY: 0, opacity: 0 },
status: { translateX: 0, translateY: 0, opacity: 0 },
};
var IdleStyle = {
buttonRemoveItem: { opacity: 1 },
buttonProcessItem: { opacity: 1 },
info: { translateX: calculateFileInfoOffset },
status: { translateX: calculateFileInfoOffset },
};
var ProcessingStyle = {
buttonAbortItemProcessing: { opacity: 1 },
processProgressIndicator: { opacity: 1 },
status: { opacity: 1 },
};
var StyleMap = {
DID_THROW_ITEM_INVALID: {
buttonRemoveItem: { opacity: 1 },
info: { translateX: calculateFileInfoOffset },
status: { translateX: calculateFileInfoOffset, opacity: 1 },
},
DID_START_ITEM_LOAD: {
buttonAbortItemLoad: { opacity: 1 },
loadProgressIndicator: { opacity: 1 },
status: { opacity: 1 },
},
DID_THROW_ITEM_LOAD_ERROR: {
buttonRetryItemLoad: { opacity: 1 },
buttonRemoveItem: { opacity: 1 },
info: { translateX: calculateFileInfoOffset },
status: { opacity: 1 },
},
DID_START_ITEM_REMOVE: {
processProgressIndicator: { opacity: 1, align: getRemoveIndicatorAligment },
info: { translateX: calculateFileInfoOffset },
status: { opacity: 0 },
},
DID_THROW_ITEM_REMOVE_ERROR: {
processProgressIndicator: { opacity: 0, align: getRemoveIndicatorAligment },
buttonRemoveItem: { opacity: 1 },
info: { translateX: calculateFileInfoOffset },
status: { opacity: 1, translateX: calculateFileInfoOffset },
},
DID_LOAD_ITEM: IdleStyle,
DID_LOAD_LOCAL_ITEM: {
buttonRemoveItem: { opacity: 1 },
info: { translateX: calculateFileInfoOffset },
status: { translateX: calculateFileInfoOffset },
},
DID_START_ITEM_PROCESSING: ProcessingStyle,
DID_REQUEST_ITEM_PROCESSING: ProcessingStyle,
DID_UPDATE_ITEM_PROCESS_PROGRESS: ProcessingStyle,
DID_COMPLETE_ITEM_PROCESSING: {
buttonRevertItemProcessing: { opacity: 1 },
info: { opacity: 1 },
status: { opacity: 1 },
},
DID_THROW_ITEM_PROCESSING_ERROR: {
buttonRemoveItem: { opacity: 1 },
buttonRetryItemProcessing: { opacity: 1 },
status: { opacity: 1 },
info: { translateX: calculateFileInfoOffset },
},
DID_THROW_ITEM_PROCESSING_REVERT_ERROR: {
buttonRevertItemProcessing: { opacity: 1 },
status: { opacity: 1 },
info: { opacity: 1 },
},
DID_ABORT_ITEM_PROCESSING: {
buttonRemoveItem: { opacity: 1 },
buttonProcessItem: { opacity: 1 },
info: { translateX: calculateFileInfoOffset },
status: { opacity: 1 },
},
DID_REVERT_ITEM_PROCESSING: IdleStyle,
};
// complete indicator view
var processingCompleteIndicatorView = createView({
create: function create(_ref) {
var root = _ref.root;
root.element.innerHTML = root.query('GET_ICON_DONE');
},
name: 'processing-complete-indicator',
ignoreRect: true,
mixins: {
styles: ['scaleX', 'scaleY', 'opacity'],
animations: {
scaleX: 'spring',
scaleY: 'spring',
opacity: { type: 'tween', duration: 250 },
},
},
});
/**
* Creates the file view
*/
var create$4 = function create(_ref2) {
var root = _ref2.root,
props = _ref2.props;
var id = props.id;
// allow reverting upload
var allowRevert = root.query('GET_ALLOW_REVERT');
// allow remove file
var allowRemove = root.query('GET_ALLOW_REMOVE');
// allow processing upload
var allowProcess = root.query('GET_ALLOW_PROCESS');
// is instant uploading, need this to determine the icon of the undo button
var instantUpload = root.query('GET_INSTANT_UPLOAD');
// is async set up
var isAsync = root.query('IS_ASYNC');
// should align remove item buttons
var alignRemoveItemButton = root.query('GET_STYLE_BUTTON_REMOVE_ITEM_ALIGN');
// enabled buttons array
var buttonFilter;
if (isAsync) {
if (allowProcess && !allowRevert) {
// only remove revert button
buttonFilter = function buttonFilter(key) {
return !/RevertItemProcessing/.test(key);
};
} else if (!allowProcess && allowRevert) {
// only remove process button
buttonFilter = function buttonFilter(key) {
return !/ProcessItem|RetryItemProcessing|AbortItemProcessing/.test(key);
};
} else if (!allowProcess && !allowRevert) {
// remove all process buttons
buttonFilter = function buttonFilter(key) {
return !/Process/.test(key);
};
}
} else {
// no process controls available
buttonFilter = function buttonFilter(key) {
return !/Process/.test(key);
};
}
var enabledButtons = buttonFilter ? ButtonKeys.filter(buttonFilter) : ButtonKeys.concat();
// update icon and label for revert button when instant uploading
if (instantUpload && allowRevert) {
Buttons['RevertItemProcessing'].label = 'GET_LABEL_BUTTON_REMOVE_ITEM';
Buttons['RevertItemProcessing'].icon = 'GET_ICON_REMOVE';
}
// remove last button (revert) if not allowed
if (isAsync && !allowRevert) {
var map = StyleMap['DID_COMPLETE_ITEM_PROCESSING'];
map.info.translateX = calculateFileHorizontalCenterOffset;
map.info.translateY = calculateFileVerticalCenterOffset;
map.status.translateY = calculateFileVerticalCenterOffset;
map.processingCompleteIndicator = { opacity: 1, scaleX: 1, scaleY: 1 };
}
// should align center
if (isAsync && !allowProcess) {
[
'DID_START_ITEM_PROCESSING',
'DID_REQUEST_ITEM_PROCESSING',
'DID_UPDATE_ITEM_PROCESS_PROGRESS',
'DID_THROW_ITEM_PROCESSING_ERROR',
].forEach(function(key) {
StyleMap[key].status.translateY = calculateFileVerticalCenterOffset;
});
StyleMap['DID_THROW_ITEM_PROCESSING_ERROR'].status.translateX = calculateButtonWidth;
}
// move remove button to right
if (alignRemoveItemButton && allowRevert) {
Buttons['RevertItemProcessing'].align = 'BUTTON_REMOVE_ITEM_POSITION';
var _map = StyleMap['DID_COMPLETE_ITEM_PROCESSING'];
_map.info.translateX = calculateFileInfoOffset;
_map.status.translateY = calculateFileVerticalCenterOffset;
_map.processingCompleteIndicator = { opacity: 1, scaleX: 1, scaleY: 1 };
}
if (!allowRemove) {
Buttons['RemoveItem'].disabled = true;
}
// create the button views
forin(Buttons, function(key, definition) {
// create button
var buttonView = root.createChildView(fileActionButton, {
label: root.query(definition.label),
icon: root.query(definition.icon),
opacity: 0,
});
// should be appended?
if (enabledButtons.includes(key)) {
root.appendChildView(buttonView);
}
// toggle
if (definition.disabled) {
buttonView.element.setAttribute('disabled', 'disabled');
buttonView.element.setAttribute('hidden', 'hidden');
}
// add position attribute
buttonView.element.dataset.align = root.query('GET_STYLE_' + definition.align);
// add class
buttonView.element.classList.add(definition.className);
// handle interactions
buttonView.on('click', function(e) {
e.stopPropagation();
if (definition.disabled) return;
root.dispatch(definition.action, { query: id });
});
// set reference
root.ref['button' + key] = buttonView;
});
// checkmark
root.ref.processingCompleteIndicator = root.appendChildView(
root.createChildView(processingCompleteIndicatorView)
);
root.ref.processingCompleteIndicator.element.dataset.align = root.query(
'GET_STYLE_BUTTON_PROCESS_ITEM_POSITION'
);
// create file info view
root.ref.info = root.appendChildView(root.createChildView(fileInfo, { id: id }));
// create file status view
root.ref.status = root.appendChildView(root.createChildView(fileStatus, { id: id }));
// add progress indicators
var loadIndicatorView = root.appendChildView(
root.createChildView(progressIndicator, {
opacity: 0,
align: root.query('GET_STYLE_LOAD_INDICATOR_POSITION'),
})
);
loadIndicatorView.element.classList.add('filepond--load-indicator');
root.ref.loadProgressIndicator = loadIndicatorView;
var progressIndicatorView = root.appendChildView(
root.createChildView(progressIndicator, {
opacity: 0,
align: root.query('GET_STYLE_PROGRESS_INDICATOR_POSITION'),
})
);
progressIndicatorView.element.classList.add('filepond--process-indicator');
root.ref.processProgressIndicator = progressIndicatorView;
// current active styles
root.ref.activeStyles = [];
};
var write$2 = function write(_ref3) {
var root = _ref3.root,
actions = _ref3.actions,
props = _ref3.props;
// route actions
route({ root: root, actions: actions, props: props });
// select last state change action
var action = actions
.concat()
.filter(function(action) {
return /^DID_/.test(action.type);
})
.reverse()
.find(function(action) {
return StyleMap[action.type];
});
// a new action happened, let's get the matching styles
if (action) {
// define new active styles
root.ref.activeStyles = [];
var stylesToApply = StyleMap[action.type];
forin(DefaultStyle, function(name, defaultStyles) {
// get reference to control
var control = root.ref[name];
// loop over all styles for this control
forin(defaultStyles, function(key, defaultValue) {
var value =
stylesToApply[name] && typeof stylesToApply[name][key] !== 'undefined'
? stylesToApply[name][key]
: defaultValue;
root.ref.activeStyles.push({ control: control, key: key, value: value });
});
});
}
// apply active styles to element
root.ref.activeStyles.forEach(function(_ref4) {
var control = _ref4.control,
key = _ref4.key,
value = _ref4.value;
control[key] = typeof value === 'function' ? value(root) : value;
});
};
var route = createRoute({
DID_SET_LABEL_BUTTON_ABORT_ITEM_PROCESSING: function DID_SET_LABEL_BUTTON_ABORT_ITEM_PROCESSING(
_ref5
) {
var root = _ref5.root,
action = _ref5.action;
root.ref.buttonAbortItemProcessing.label = action.value;
},
DID_SET_LABEL_BUTTON_ABORT_ITEM_LOAD: function DID_SET_LABEL_BUTTON_ABORT_ITEM_LOAD(_ref6) {
var root = _ref6.root,
action = _ref6.action;
root.ref.buttonAbortItemLoad.label = action.value;
},
DID_SET_LABEL_BUTTON_ABORT_ITEM_REMOVAL: function DID_SET_LABEL_BUTTON_ABORT_ITEM_REMOVAL(
_ref7
) {
var root = _ref7.root,
action = _ref7.action;
root.ref.buttonAbortItemRemoval.label = action.value;
},
DID_REQUEST_ITEM_PROCESSING: function DID_REQUEST_ITEM_PROCESSING(_ref8) {
var root = _ref8.root;
root.ref.processProgressIndicator.spin = true;
root.ref.processProgressIndicator.progress = 0;
},
DID_START_ITEM_LOAD: function DID_START_ITEM_LOAD(_ref9) {
var root = _ref9.root;
root.ref.loadProgressIndicator.spin = true;
root.ref.loadProgressIndicator.progress = 0;
},
DID_START_ITEM_REMOVE: function DID_START_ITEM_REMOVE(_ref10) {
var root = _ref10.root;
root.ref.processProgressIndicator.spin = true;
root.ref.processProgressIndicator.progress = 0;
},
DID_UPDATE_ITEM_LOAD_PROGRESS: function DID_UPDATE_ITEM_LOAD_PROGRESS(_ref11) {
var root = _ref11.root,
action = _ref11.action;
root.ref.loadProgressIndicator.spin = false;
root.ref.loadProgressIndicator.progress = action.progress;
},
DID_UPDATE_ITEM_PROCESS_PROGRESS: function DID_UPDATE_ITEM_PROCESS_PROGRESS(_ref12) {
var root = _ref12.root,
action = _ref12.action;
root.ref.processProgressIndicator.spin = false;
root.ref.processProgressIndicator.progress = action.progress;
},
});
var file = createView({
create: create$4,
write: write$2,
didCreateView: function didCreateView(root) {
applyFilters('CREATE_VIEW', Object.assign({}, root, { view: root }));
},
name: 'file',
});
/**
* Creates the file view
*/
var create$5 = function create(_ref) {
var root = _ref.root,
props = _ref.props;
// filename
root.ref.fileName = createElement$1('legend');
root.appendChild(root.ref.fileName);
// file appended
root.ref.file = root.appendChildView(root.createChildView(file, { id: props.id }));
// data has moved to data.js
root.ref.data = false;
};
/**
* Data storage
*/
var didLoadItem = function didLoadItem(_ref2) {
var root = _ref2.root,
props = _ref2.props;
// updates the legend of the fieldset so screenreaders can better group buttons
text(root.ref.fileName, formatFilename(root.query('GET_ITEM_NAME', props.id)));
};
var fileWrapper = createView({
create: create$5,
ignoreRect: true,
write: createRoute({
DID_LOAD_ITEM: didLoadItem,
}),
didCreateView: function didCreateView(root) {
applyFilters('CREATE_VIEW', Object.assign({}, root, { view: root }));
},
tag: 'fieldset',
name: 'file-wrapper',
});
var PANEL_SPRING_PROPS = { type: 'spring', damping: 0.6, mass: 7 };
var create$6 = function create(_ref) {
var root = _ref.root,
props = _ref.props;
[
{
name: 'top',
},
{
name: 'center',
props: {
translateY: null,
scaleY: null,
},
mixins: {
animations: {
scaleY: PANEL_SPRING_PROPS,
},
styles: ['translateY', 'scaleY'],
},
},
{
name: 'bottom',
props: {
translateY: null,
},
mixins: {
animations: {
translateY: PANEL_SPRING_PROPS,
},
styles: ['translateY'],
},
},
].forEach(function(section) {
createSection(root, section, props.name);
});
root.element.classList.add('filepond--' + props.name);
root.ref.scalable = null;
};
var createSection = function createSection(root, section, className) {
var viewConstructor = createView({
name: 'panel-' + section.name + ' filepond--' + className,
mixins: section.mixins,
ignoreRectUpdate: true,
});
var view = root.createChildView(viewConstructor, section.props);
root.ref[section.name] = root.appendChildView(view);
};
var write$3 = function write(_ref2) {
var root = _ref2.root,
props = _ref2.props;
// update scalable state
if (root.ref.scalable === null || props.scalable !== root.ref.scalable) {
root.ref.scalable = isBoolean(props.scalable) ? props.scalable : true;
root.element.dataset.scalable = root.ref.scalable;
}
// no height, can't set
if (!props.height) return;
// get child rects
var topRect = root.ref.top.rect.element;
var bottomRect = root.ref.bottom.rect.element;
// make sure height never is smaller than bottom and top seciton heights combined (will probably never happen, but who knows)
var height = Math.max(topRect.height + bottomRect.height, props.height);
// offset center part
root.ref.center.translateY = topRect.height;
// scale center part
// use math ceil to prevent transparent lines because of rounding errors
root.ref.center.scaleY = (height - topRect.height - bottomRect.height) / 100;
// offset bottom part
root.ref.bottom.translateY = height - bottomRect.height;
};
var panel = createView({
name: 'panel',
read: function read(_ref3) {
var root = _ref3.root,
props = _ref3.props;
return (props.heightCurrent = root.ref.bottom.translateY);
},
write: write$3,
create: create$6,
ignoreRect: true,
mixins: {
apis: ['height', 'heightCurrent', 'scalable'],
},
});
var createDragHelper = function createDragHelper(items) {
var itemIds = items.map(function(item) {
return item.id;
});
var prevIndex = undefined;
return {
setIndex: function setIndex(index) {
prevIndex = index;
},
getIndex: function getIndex() {
return prevIndex;
},
getItemIndex: function getItemIndex(item) {
return itemIds.indexOf(item.id);
},
};
};
var ITEM_TRANSLATE_SPRING = {
type: 'spring',
stiffness: 0.75,
damping: 0.45,
mass: 10,
};
var ITEM_SCALE_SPRING = 'spring';
var StateMap = {
DID_START_ITEM_LOAD: 'busy',
DID_UPDATE_ITEM_LOAD_PROGRESS: 'loading',
DID_THROW_ITEM_INVALID: 'load-invalid',
DID_THROW_ITEM_LOAD_ERROR: 'load-error',
DID_LOAD_ITEM: 'idle',
DID_THROW_ITEM_REMOVE_ERROR: 'remove-error',
DID_START_ITEM_REMOVE: 'busy',
DID_START_ITEM_PROCESSING: 'busy processing',
DID_REQUEST_ITEM_PROCESSING: 'busy processing',
DID_UPDATE_ITEM_PROCESS_PROGRESS: 'processing',
DID_COMPLETE_ITEM_PROCESSING: 'processing-complete',
DID_THROW_ITEM_PROCESSING_ERROR: 'processing-error',
DID_THROW_ITEM_PROCESSING_REVERT_ERROR: 'processing-revert-error',
DID_ABORT_ITEM_PROCESSING: 'cancelled',
DID_REVERT_ITEM_PROCESSING: 'idle',
};
/**
* Creates the file view
*/
var create$7 = function create(_ref) {
var root = _ref.root,
props = _ref.props;
// select
root.ref.handleClick = function(e) {
return root.dispatch('DID_ACTIVATE_ITEM', { id: props.id });
};
// set id
root.element.id = 'filepond--item-' + props.id;
root.element.addEventListener('click', root.ref.handleClick);
// file view
root.ref.container = root.appendChildView(
root.createChildView(fileWrapper, { id: props.id })
);
// file panel
root.ref.panel = root.appendChildView(root.createChildView(panel, { name: 'item-panel' }));
// default start height
root.ref.panel.height = null;
// by default not marked for removal
props.markedForRemoval = false;
// if not allowed to reorder file items, exit here
if (!root.query('GET_ALLOW_REORDER')) return;
// set to idle so shows grab cursor
root.element.dataset.dragState = 'idle';
var grab = function grab(e) {
if (!e.isPrimary) return;
var removedActivateListener = false;
var origin = {
x: e.pageX,
y: e.pageY,
};
props.dragOrigin = {
x: root.translateX,
y: root.translateY,
};
props.dragCenter = {
x: e.offsetX,
y: e.offsetY,
};
var dragState = createDragHelper(root.query('GET_ACTIVE_ITEMS'));
root.dispatch('DID_GRAB_ITEM', { id: props.id, dragState: dragState });
var drag = function drag(e) {
if (!e.isPrimary) return;
e.stopPropagation();
e.preventDefault();
props.dragOffset = {
x: e.pageX - origin.x,
y: e.pageY - origin.y,
};
// if dragged stop listening to clicks, will re-add when done dragging
var dist =
props.dragOffset.x * props.dragOffset.x +
props.dragOffset.y * props.dragOffset.y;
if (dist > 16 && !removedActivateListener) {
removedActivateListener = true;
root.element.removeEventListener('click', root.ref.handleClick);
}
root.dispatch('DID_DRAG_ITEM', { id: props.id, dragState: dragState });
};
var drop = function drop(e) {
if (!e.isPrimary) return;
document.removeEventListener('pointermove', drag);
document.removeEventListener('pointerup', drop);
props.dragOffset = {
x: e.pageX - origin.x,
y: e.pageY - origin.y,
};
root.dispatch('DID_DROP_ITEM', { id: props.id, dragState: dragState });
// start listening to clicks again
if (removedActivateListener) {
setTimeout(function() {
return root.element.addEventListener('click', root.ref.handleClick);
}, 0);
}
};
document.addEventListener('pointermove', drag);
document.addEventListener('pointerup', drop);
};
root.element.addEventListener('pointerdown', grab);
};
var route$1 = createRoute({
DID_UPDATE_PANEL_HEIGHT: function DID_UPDATE_PANEL_HEIGHT(_ref2) {
var root = _ref2.root,
action = _ref2.action;
root.height = action.height;
},
});
var write$4 = createRoute(
{
DID_GRAB_ITEM: function DID_GRAB_ITEM(_ref3) {
var root = _ref3.root,
props = _ref3.props;
props.dragOrigin = {
x: root.translateX,
y: root.translateY,
};
},
DID_DRAG_ITEM: function DID_DRAG_ITEM(_ref4) {
var root = _ref4.root;
root.element.dataset.dragState = 'drag';
},
DID_DROP_ITEM: function DID_DROP_ITEM(_ref5) {
var root = _ref5.root,
props = _ref5.props;
props.dragOffset = null;
props.dragOrigin = null;
root.element.dataset.dragState = 'drop';
},
},
function(_ref6) {
var root = _ref6.root,
actions = _ref6.actions,
props = _ref6.props,
shouldOptimize = _ref6.shouldOptimize;
if (root.element.dataset.dragState === 'drop') {
if (root.scaleX <= 1) {
root.element.dataset.dragState = 'idle';
}
}
// select last state change action
var action = actions
.concat()
.filter(function(action) {
return /^DID_/.test(action.type);
})
.reverse()
.find(function(action) {
return StateMap[action.type];
});
// no need to set same state twice
if (action && action.type !== props.currentState) {
// set current state
props.currentState = action.type;
// set state
root.element.dataset.filepondItemState = StateMap[props.currentState] || '';
}
// route actions
var aspectRatio =
root.query('GET_ITEM_PANEL_ASPECT_RATIO') || root.query('GET_PANEL_ASPECT_RATIO');
if (!aspectRatio) {
route$1({ root: root, actions: actions, props: props });
if (!root.height && root.ref.container.rect.element.height > 0) {
root.height = root.ref.container.rect.element.height;
}
} else if (!shouldOptimize) {
root.height = root.rect.element.width * aspectRatio;
}
// sync panel height with item height
if (shouldOptimize) {
root.ref.panel.height = null;
}
root.ref.panel.height = root.height;
}
);
var item = createView({
create: create$7,
write: write$4,
destroy: function destroy(_ref7) {
var root = _ref7.root,
props = _ref7.props;
root.element.removeEventListener('click', root.ref.handleClick);
root.dispatch('RELEASE_ITEM', { query: props.id });
},
tag: 'li',
name: 'item',
mixins: {
apis: [
'id',
'interactionMethod',
'markedForRemoval',
'spawnDate',
'dragCenter',
'dragOrigin',
'dragOffset',
],
styles: ['translateX', 'translateY', 'scaleX', 'scaleY', 'opacity', 'height'],
animations: {
scaleX: ITEM_SCALE_SPRING,
scaleY: ITEM_SCALE_SPRING,
translateX: ITEM_TRANSLATE_SPRING,
translateY: ITEM_TRANSLATE_SPRING,
opacity: { type: 'tween', duration: 150 },
},
},
});
var getItemsPerRow = function(horizontalSpace, itemWidth) {
// add one pixel leeway, when using percentages for item width total items can be 1.99 per row
return Math.max(1, Math.floor((horizontalSpace + 1) / itemWidth));
};
var getItemIndexByPosition = function getItemIndexByPosition(view, children, positionInView) {
if (!positionInView) return;
var horizontalSpace = view.rect.element.width;
// const children = view.childViews;
var l = children.length;
var last = null;
// -1, don't move items to accomodate (either add to top or bottom)
if (l === 0 || positionInView.top < children[0].rect.element.top) return -1;
// let's get the item width
var item = children[0];
var itemRect = item.rect.element;
var itemHorizontalMargin = itemRect.marginLeft + itemRect.marginRight;
var itemWidth = itemRect.width + itemHorizontalMargin;
var itemsPerRow = getItemsPerRow(horizontalSpace, itemWidth);
// stack
if (itemsPerRow === 1) {
for (var index = 0; index < l; index++) {
var child = children[index];
var childMid = child.rect.outer.top + child.rect.element.height * 0.5;
if (positionInView.top < childMid) {
return index;
}
}
return l;
}
// grid
var itemVerticalMargin = itemRect.marginTop + itemRect.marginBottom;
var itemHeight = itemRect.height + itemVerticalMargin;
for (var _index = 0; _index < l; _index++) {
var indexX = _index % itemsPerRow;
var indexY = Math.floor(_index / itemsPerRow);
var offsetX = indexX * itemWidth;
var offsetY = indexY * itemHeight;
var itemTop = offsetY - itemRect.marginTop;
var itemRight = offsetX + itemWidth;
var itemBottom = offsetY + itemHeight + itemRect.marginBottom;
if (positionInView.top < itemBottom && positionInView.top > itemTop) {
if (positionInView.left < itemRight) {
return _index;
} else if (_index !== l - 1) {
last = _index;
} else {
last = null;
}
}
}
if (last !== null) {
return last;
}
return l;
};
var dropAreaDimensions = {
height: 0,
width: 0,
get getHeight() {
return this.height;
},
set setHeight(val) {
if (this.height === 0 || val === 0) this.height = val;
},
get getWidth() {
return this.width;
},
set setWidth(val) {
if (this.width === 0 || val === 0) this.width = val;
},
setDimensions: function setDimensions(height, width) {
if (this.height === 0 || height === 0) this.height = height;
if (this.width === 0 || width === 0) this.width = width;
},
};
var create$8 = function create(_ref) {
var root = _ref.root;
// need to set role to list as otherwise it won't be read as a list by VoiceOver
attr(root.element, 'role', 'list');
root.ref.lastItemSpanwDate = Date.now();
};
/**
* Inserts a new item
* @param root
* @param action
*/
var addItemView = function addItemView(_ref2) {
var root = _ref2.root,
action = _ref2.action;
var id = action.id,
index = action.index,
interactionMethod = action.interactionMethod;
root.ref.addIndex = index;
var now = Date.now();
var spawnDate = now;
var opacity = 1;
if (interactionMethod !== InteractionMethod.NONE) {
opacity = 0;
var cooldown = root.query('GET_ITEM_INSERT_INTERVAL');
var dist = now - root.ref.lastItemSpanwDate;
spawnDate = dist < cooldown ? now + (cooldown - dist) : now;
}
root.ref.lastItemSpanwDate = spawnDate;
root.appendChildView(
root.createChildView(
// view type
item,
// props
{
spawnDate: spawnDate,
id: id,
opacity: opacity,
interactionMethod: interactionMethod,
}
),
index
);
};
var moveItem = function moveItem(item, x, y) {
var vx = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
var vy = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 1;
// set to null to remove animation while dragging
if (item.dragOffset) {
item.translateX = null;
item.translateY = null;
item.translateX = item.dragOrigin.x + item.dragOffset.x;
item.translateY = item.dragOrigin.y + item.dragOffset.y;
item.scaleX = 1.025;
item.scaleY = 1.025;
} else {
item.translateX = x;
item.translateY = y;
if (Date.now() > item.spawnDate) {
// reveal element
if (item.opacity === 0) {
introItemView(item, x, y, vx, vy);
}
// make sure is default scale every frame
item.scaleX = 1;
item.scaleY = 1;
item.opacity = 1;
}
}
};
var introItemView = function introItemView(item, x, y, vx, vy) {
if (item.interactionMethod === InteractionMethod.NONE) {
item.translateX = null;
item.translateX = x;
item.translateY = null;
item.translateY = y;
} else if (item.interactionMethod === InteractionMethod.DROP) {
item.translateX = null;
item.translateX = x - vx * 20;
item.translateY = null;
item.translateY = y - vy * 10;
item.scaleX = 0.8;
item.scaleY = 0.8;
} else if (item.interactionMethod === InteractionMethod.BROWSE) {
item.translateY = null;
item.translateY = y - 30;
} else if (item.interactionMethod === InteractionMethod.API) {
item.translateX = null;
item.translateX = x - 30;
item.translateY = null;
}
};
/**
* Removes an existing item
* @param root
* @param action
*/
var removeItemView = function removeItemView(_ref3) {
var root = _ref3.root,
action = _ref3.action;
var id = action.id;
// get the view matching the given id
var view = root.childViews.find(function(child) {
return child.id === id;
});
// if no view found, exit
if (!view) {
return;
}
// animate view out of view
view.scaleX = 0.9;
view.scaleY = 0.9;
view.opacity = 0;
// mark for removal
view.markedForRemoval = true;
};
var getItemHeight = function getItemHeight(child) {
return (
child.rect.element.height +
child.rect.element.marginBottom * 0.5 +
child.rect.element.marginTop * 0.5
);
};
var getItemWidth = function getItemWidth(child) {
return (
child.rect.element.width +
child.rect.element.marginLeft * 0.5 +
child.rect.element.marginRight * 0.5
);
};
var dragItem = function dragItem(_ref4) {
var root = _ref4.root,
action = _ref4.action;
var id = action.id,
dragState = action.dragState;
// reference to item
var item = root.query('GET_ITEM', { id: id });
// get the view matching the given id
var view = root.childViews.find(function(child) {
return child.id === id;
});
var numItems = root.childViews.length;
var oldIndex = dragState.getItemIndex(item);
// if no view found, exit
if (!view) return;
var dragPosition = {
x: view.dragOrigin.x + view.dragOffset.x + view.dragCenter.x,
y: view.dragOrigin.y + view.dragOffset.y + view.dragCenter.y,
};
// get drag area dimensions
var dragHeight = getItemHeight(view);
var dragWidth = getItemWidth(view);
// get rows and columns (There will always be at least one row and one column if a file is present)
var cols = Math.floor(root.rect.outer.width / dragWidth);
if (cols > numItems) cols = numItems;
// rows are used to find when we have left the preview area bounding box
var rows = Math.floor(numItems / cols + 1);
dropAreaDimensions.setHeight = dragHeight * rows;
dropAreaDimensions.setWidth = dragWidth * cols;
// get new index of dragged item
var location = {
y: Math.floor(dragPosition.y / dragHeight),
x: Math.floor(dragPosition.x / dragWidth),
getGridIndex: function getGridIndex() {
if (
dragPosition.y > dropAreaDimensions.getHeight ||
dragPosition.y < 0 ||
dragPosition.x > dropAreaDimensions.getWidth ||
dragPosition.x < 0
)
return oldIndex;
return this.y * cols + this.x;
},
getColIndex: function getColIndex() {
var items = root.query('GET_ACTIVE_ITEMS');
var visibleChildren = root.childViews.filter(function(child) {
return child.rect.element.height;
});
var children = items.map(function(item) {
return visibleChildren.find(function(childView) {
return childView.id === item.id;
});
});
var currentIndex = children.findIndex(function(child) {
return child === view;
});
var dragHeight = getItemHeight(view);
var l = children.length;
var idx = l;
var childHeight = 0;
var childBottom = 0;
var childTop = 0;
for (var i = 0; i < l; i++) {
childHeight = getItemHeight(children[i]);
childTop = childBottom;
childBottom = childTop + childHeight;
if (dragPosition.y < childBottom) {
if (currentIndex > i) {
if (dragPosition.y < childTop + dragHeight) {
idx = i;
break;
}
continue;
}
idx = i;
break;
}
}
return idx;
},
};
// get new index
var index = cols > 1 ? location.getGridIndex() : location.getColIndex();
root.dispatch('MOVE_ITEM', { query: view, index: index });
// if the index of the item changed, dispatch reorder action
var currentIndex = dragState.getIndex();
if (currentIndex === undefined || currentIndex !== index) {
dragState.setIndex(index);
if (currentIndex === undefined) return;
root.dispatch('DID_REORDER_ITEMS', {
items: root.query('GET_ACTIVE_ITEMS'),
origin: oldIndex,
target: index,
});
}
};
/**
* Setup action routes
*/
var route$2 = createRoute({
DID_ADD_ITEM: addItemView,
DID_REMOVE_ITEM: removeItemView,
DID_DRAG_ITEM: dragItem,
});
/**
* Write to view
* @param root
* @param actions
* @param props
*/
var write$5 = function write(_ref5) {
var root = _ref5.root,
props = _ref5.props,
actions = _ref5.actions,
shouldOptimize = _ref5.shouldOptimize;
// route actions
route$2({ root: root, props: props, actions: actions });
var dragCoordinates = props.dragCoordinates;
// available space on horizontal axis
var horizontalSpace = root.rect.element.width;
// only draw children that have dimensions
var visibleChildren = root.childViews.filter(function(child) {
return child.rect.element.height;
});
// sort based on current active items
var children = root
.query('GET_ACTIVE_ITEMS')
.map(function(item) {
return visibleChildren.find(function(child) {
return child.id === item.id;
});
})
.filter(function(item) {
return item;
});
// get index
var dragIndex = dragCoordinates
? getItemIndexByPosition(root, children, dragCoordinates)
: null;
// add index is used to reserve the dropped/added item index till the actual item is rendered
var addIndex = root.ref.addIndex || null;
// add index no longer needed till possibly next draw
root.ref.addIndex = null;
var dragIndexOffset = 0;
var removeIndexOffset = 0;
var addIndexOffset = 0;
if (children.length === 0) return;
var childRect = children[0].rect.element;
var itemVerticalMargin = childRect.marginTop + childRect.marginBottom;
var itemHorizontalMargin = childRect.marginLeft + childRect.marginRight;
var itemWidth = childRect.width + itemHorizontalMargin;
var itemHeight = childRect.height + itemVerticalMargin;
var itemsPerRow = getItemsPerRow(horizontalSpace, itemWidth);
// stack
if (itemsPerRow === 1) {
var offsetY = 0;
var dragOffset = 0;
children.forEach(function(child, index) {
if (dragIndex) {
var dist = index - dragIndex;
if (dist === -2) {
dragOffset = -itemVerticalMargin * 0.25;
} else if (dist === -1) {
dragOffset = -itemVerticalMargin * 0.75;
} else if (dist === 0) {
dragOffset = itemVerticalMargin * 0.75;
} else if (dist === 1) {
dragOffset = itemVerticalMargin * 0.25;
} else {
dragOffset = 0;
}
}
if (shouldOptimize) {
child.translateX = null;
child.translateY = null;
}
if (!child.markedForRemoval) {
moveItem(child, 0, offsetY + dragOffset);
}
var itemHeight = child.rect.element.height + itemVerticalMargin;
var visualHeight = itemHeight * (child.markedForRemoval ? child.opacity : 1);
offsetY += visualHeight;
});
}
// grid
else {
var prevX = 0;
var prevY = 0;
children.forEach(function(child, index) {
if (index === dragIndex) {
dragIndexOffset = 1;
}
if (index === addIndex) {
addIndexOffset += 1;
}
if (child.markedForRemoval && child.opacity < 0.5) {
removeIndexOffset -= 1;
}
var visualIndex = index + addIndexOffset + dragIndexOffset + removeIndexOffset;
var indexX = visualIndex % itemsPerRow;
var indexY = Math.floor(visualIndex / itemsPerRow);
var offsetX = indexX * itemWidth;
var offsetY = indexY * itemHeight;
var vectorX = Math.sign(offsetX - prevX);
var vectorY = Math.sign(offsetY - prevY);
prevX = offsetX;
prevY = offsetY;
if (child.markedForRemoval) return;
if (shouldOptimize) {
child.translateX = null;
child.translateY = null;
}
moveItem(child, offsetX, offsetY, vectorX, vectorY);
});
}
};
/**
* Filters actions that are meant specifically for a certain child of the list
* @param child
* @param actions
*/
var filterSetItemActions = function filterSetItemActions(child, actions) {
return actions.filter(function(action) {
// if action has an id, filter out actions that don't have this child id
if (action.data && action.data.id) {
return child.id === action.data.id;
}
// allow all other actions
return true;
});
};
var list = createView({
create: create$8,
write: write$5,
tag: 'ul',
name: 'list',
didWriteView: function didWriteView(_ref6) {
var root = _ref6.root;
root.childViews
.filter(function(view) {
return view.markedForRemoval && view.opacity === 0 && view.resting;
})
.forEach(function(view) {
view._destroy();
root.removeChildView(view);
});
},
filterFrameActionsForChild: filterSetItemActions,
mixins: {
apis: ['dragCoordinates'],
},
});
var create$9 = function create(_ref) {
var root = _ref.root,
props = _ref.props;
root.ref.list = root.appendChildView(root.createChildView(list));
props.dragCoordinates = null;
props.overflowing = false;
};
var storeDragCoordinates = function storeDragCoordinates(_ref2) {
var root = _ref2.root,
props = _ref2.props,
action = _ref2.action;
if (!root.query('GET_ITEM_INSERT_LOCATION_FREEDOM')) return;
props.dragCoordinates = {
left: action.position.scopeLeft - root.ref.list.rect.element.left,
top:
action.position.scopeTop -
(root.rect.outer.top + root.rect.element.marginTop + root.rect.element.scrollTop),
};
};
var clearDragCoordinates = function clearDragCoordinates(_ref3) {
var props = _ref3.props;
props.dragCoordinates = null;
};
var route$3 = createRoute({
DID_DRAG: storeDragCoordinates,
DID_END_DRAG: clearDragCoordinates,
});
var write$6 = function write(_ref4) {
var root = _ref4.root,
props = _ref4.props,
actions = _ref4.actions;
// route actions
route$3({ root: root, props: props, actions: actions });
// current drag position
root.ref.list.dragCoordinates = props.dragCoordinates;
// if currently overflowing but no longer received overflow
if (props.overflowing && !props.overflow) {
props.overflowing = false;
// reset overflow state
root.element.dataset.state = '';
root.height = null;
}
// if is not overflowing currently but does receive overflow value
if (props.overflow) {
var newHeight = Math.round(props.overflow);
if (newHeight !== root.height) {
props.overflowing = true;
root.element.dataset.state = 'overflow';
root.height = newHeight;
}
}
};
var listScroller = createView({
create: create$9,
write: write$6,
name: 'list-scroller',
mixins: {
apis: ['overflow', 'dragCoordinates'],
styles: ['height', 'translateY'],
animations: {
translateY: 'spring',
},
},
});
var attrToggle = function attrToggle(element, name, state) {
var enabledValue = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '';
if (state) {
attr(element, name, enabledValue);
} else {
element.removeAttribute(name);
}
};
var resetFileInput = function resetFileInput(input) {
// no value, no need to reset
if (!input || input.value === '') {
return;
}
try {
// for modern browsers
input.value = '';
} catch (err) {}
// for IE10
if (input.value) {
// quickly append input to temp form and reset form
var form = createElement$1('form');
var parentNode = input.parentNode;
var ref = input.nextSibling;
form.appendChild(input);
form.reset();
// re-inject input where it originally was
if (ref) {
parentNode.insertBefore(input, ref);
} else {
parentNode.appendChild(input);
}
}
};
var create$a = function create(_ref) {
var root = _ref.root,
props = _ref.props;
// set id so can be referenced from outside labels
root.element.id = 'filepond--browser-' + props.id;
// set name of element (is removed when a value is set)
attr(root.element, 'name', root.query('GET_NAME'));
// we have to link this element to the status element
attr(root.element, 'aria-controls', 'filepond--assistant-' + props.id);
// set label, we use labelled by as otherwise the screenreader does not read the "browse" text in the label (as it has tabindex: 0)
attr(root.element, 'aria-labelledby', 'filepond--drop-label-' + props.id);
// set configurable props
setAcceptedFileTypes({
root: root,
action: { value: root.query('GET_ACCEPTED_FILE_TYPES') },
});
toggleAllowMultiple({ root: root, action: { value: root.query('GET_ALLOW_MULTIPLE') } });
toggleDirectoryFilter({
root: root,
action: { value: root.query('GET_ALLOW_DIRECTORIES_ONLY') },
});
toggleDisabled({ root: root });
toggleRequired({ root: root, action: { value: root.query('GET_REQUIRED') } });
setCaptureMethod({ root: root, action: { value: root.query('GET_CAPTURE_METHOD') } });
// handle changes to the input field
root.ref.handleChange = function(e) {
if (!root.element.value) {
return;
}
// extract files and move value of webkitRelativePath path to _relativePath
var files = Array.from(root.element.files).map(function(file) {
file._relativePath = file.webkitRelativePath;
return file;
});
// we add a little delay so the OS file select window can move out of the way before we add our file
setTimeout(function() {
// load files
props.onload(files);
// reset input, it's just for exposing a method to drop files, should not retain any state
resetFileInput(root.element);
}, 250);
};
root.element.addEventListener('change', root.ref.handleChange);
};
var setAcceptedFileTypes = function setAcceptedFileTypes(_ref2) {
var root = _ref2.root,
action = _ref2.action;
if (!root.query('GET_ALLOW_SYNC_ACCEPT_ATTRIBUTE')) return;
attrToggle(
root.element,
'accept',
!!action.value,
action.value ? action.value.join(',') : ''
);
};
var toggleAllowMultiple = function toggleAllowMultiple(_ref3) {
var root = _ref3.root,
action = _ref3.action;
attrToggle(root.element, 'multiple', action.value);
};
var toggleDirectoryFilter = function toggleDirectoryFilter(_ref4) {
var root = _ref4.root,
action = _ref4.action;
attrToggle(root.element, 'webkitdirectory', action.value);
};
var toggleDisabled = function toggleDisabled(_ref5) {
var root = _ref5.root;
var isDisabled = root.query('GET_DISABLED');
var doesAllowBrowse = root.query('GET_ALLOW_BROWSE');
var disableField = isDisabled || !doesAllowBrowse;
attrToggle(root.element, 'disabled', disableField);
};
var toggleRequired = function toggleRequired(_ref6) {
var root = _ref6.root,
action = _ref6.action;
// want to remove required, always possible
if (!action.value) {
attrToggle(root.element, 'required', false);
}
// if want to make required, only possible when zero items
else if (root.query('GET_TOTAL_ITEMS') === 0) {
attrToggle(root.element, 'required', true);
}
};
var setCaptureMethod = function setCaptureMethod(_ref7) {
var root = _ref7.root,
action = _ref7.action;
attrToggle(
root.element,
'capture',
!!action.value,
action.value === true ? '' : action.value
);
};
var updateRequiredStatus = function updateRequiredStatus(_ref8) {
var root = _ref8.root;
var element = root.element;
// always remove the required attribute when more than zero items
if (root.query('GET_TOTAL_ITEMS') > 0) {
attrToggle(element, 'required', false);
attrToggle(element, 'name', false);
} else {
// add name attribute
attrToggle(element, 'name', true, root.query('GET_NAME'));
// remove any validation messages
var shouldCheckValidity = root.query('GET_CHECK_VALIDITY');
if (shouldCheckValidity) {
element.setCustomValidity('');
}
// we only add required if the field has been deemed required
if (root.query('GET_REQUIRED')) {
attrToggle(element, 'required', true);
}
}
};
var updateFieldValidityStatus = function updateFieldValidityStatus(_ref9) {
var root = _ref9.root;
var shouldCheckValidity = root.query('GET_CHECK_VALIDITY');
if (!shouldCheckValidity) return;
root.element.setCustomValidity(root.query('GET_LABEL_INVALID_FIELD'));
};
var browser = createView({
tag: 'input',
name: 'browser',
ignoreRect: true,
ignoreRectUpdate: true,
attributes: {
type: 'file',
},
create: create$a,
destroy: function destroy(_ref10) {
var root = _ref10.root;
root.element.removeEventListener('change', root.ref.handleChange);
},
write: createRoute({
DID_LOAD_ITEM: updateRequiredStatus,
DID_REMOVE_ITEM: updateRequiredStatus,
DID_THROW_ITEM_INVALID: updateFieldValidityStatus,
DID_SET_DISABLED: toggleDisabled,
DID_SET_ALLOW_BROWSE: toggleDisabled,
DID_SET_ALLOW_DIRECTORIES_ONLY: toggleDirectoryFilter,
DID_SET_ALLOW_MULTIPLE: toggleAllowMultiple,
DID_SET_ACCEPTED_FILE_TYPES: setAcceptedFileTypes,
DID_SET_CAPTURE_METHOD: setCaptureMethod,
DID_SET_REQUIRED: toggleRequired,
}),
});
var Key = {
ENTER: 13,
SPACE: 32,
};
var create$b = function create(_ref) {
var root = _ref.root,
props = _ref.props;
// create the label and link it to the file browser
var label = createElement$1('label');
attr(label, 'for', 'filepond--browser-' + props.id);
// use for labeling file input (aria-labelledby on file input)
attr(label, 'id', 'filepond--drop-label-' + props.id);
// hide the label for screenreaders, the input element will read the contents of the label when it's focussed. If we don't set aria-hidden the screenreader will also navigate the contents of the label separately from the input.
attr(label, 'aria-hidden', 'true');
// handle keys
root.ref.handleKeyDown = function(e) {
var isActivationKey = e.keyCode === Key.ENTER || e.keyCode === Key.SPACE;
if (!isActivationKey) return;
// stops from triggering the element a second time
e.preventDefault();
// click link (will then in turn activate file input)
root.ref.label.click();
};
root.ref.handleClick = function(e) {
var isLabelClick = e.target === label || label.contains(e.target);
// don't want to click twice
if (isLabelClick) return;
// click link (will then in turn activate file input)
root.ref.label.click();
};
// attach events
label.addEventListener('keydown', root.ref.handleKeyDown);
root.element.addEventListener('click', root.ref.handleClick);
// update
updateLabelValue(label, props.caption);
// add!
root.appendChild(label);
root.ref.label = label;
};
var updateLabelValue = function updateLabelValue(label, value) {
label.innerHTML = value;
var clickable = label.querySelector('.filepond--label-action');
if (clickable) {
attr(clickable, 'tabindex', '0');
}
return value;
};
var dropLabel = createView({
name: 'drop-label',
ignoreRect: true,
create: create$b,
destroy: function destroy(_ref2) {
var root = _ref2.root;
root.ref.label.addEventListener('keydown', root.ref.handleKeyDown);
root.element.removeEventListener('click', root.ref.handleClick);
},
write: createRoute({
DID_SET_LABEL_IDLE: function DID_SET_LABEL_IDLE(_ref3) {
var root = _ref3.root,
action = _ref3.action;
updateLabelValue(root.ref.label, action.value);
},
}),
mixins: {
styles: ['opacity', 'translateX', 'translateY'],
animations: {
opacity: { type: 'tween', duration: 150 },
translateX: 'spring',
translateY: 'spring',
},
},
});
var blob = createView({
name: 'drip-blob',
ignoreRect: true,
mixins: {
styles: ['translateX', 'translateY', 'scaleX', 'scaleY', 'opacity'],
animations: {
scaleX: 'spring',
scaleY: 'spring',
translateX: 'spring',
translateY: 'spring',
opacity: { type: 'tween', duration: 250 },
},
},
});
var addBlob = function addBlob(_ref) {
var root = _ref.root;
var centerX = root.rect.element.width * 0.5;
var centerY = root.rect.element.height * 0.5;
root.ref.blob = root.appendChildView(
root.createChildView(blob, {
opacity: 0,
scaleX: 2.5,
scaleY: 2.5,
translateX: centerX,
translateY: centerY,
})
);
};
var moveBlob = function moveBlob(_ref2) {
var root = _ref2.root,
action = _ref2.action;
if (!root.ref.blob) {
addBlob({ root: root });
return;
}
root.ref.blob.translateX = action.position.scopeLeft;
root.ref.blob.translateY = action.position.scopeTop;
root.ref.blob.scaleX = 1;
root.ref.blob.scaleY = 1;
root.ref.blob.opacity = 1;
};
var hideBlob = function hideBlob(_ref3) {
var root = _ref3.root;
if (!root.ref.blob) {
return;
}
root.ref.blob.opacity = 0;
};
var explodeBlob = function explodeBlob(_ref4) {
var root = _ref4.root;
if (!root.ref.blob) {
return;
}
root.ref.blob.scaleX = 2.5;
root.ref.blob.scaleY = 2.5;
root.ref.blob.opacity = 0;
};
var write$7 = function write(_ref5) {
var root = _ref5.root,
props = _ref5.props,
actions = _ref5.actions;
route$4({ root: root, props: props, actions: actions });
var blob = root.ref.blob;
if (actions.length === 0 && blob && blob.opacity === 0) {
root.removeChildView(blob);
root.ref.blob = null;
}
};
var route$4 = createRoute({
DID_DRAG: moveBlob,
DID_DROP: explodeBlob,
DID_END_DRAG: hideBlob,
});
var drip = createView({
ignoreRect: true,
ignoreRectUpdate: true,
name: 'drip',
write: write$7,
});
var create$c = function create(_ref) {
var root = _ref.root;
return (root.ref.fields = {});
};
var getField = function getField(root, id) {
return root.ref.fields[id];
};
var syncFieldPositionsWithItems = function syncFieldPositionsWithItems(root) {
root.query('GET_ACTIVE_ITEMS').forEach(function(item) {
if (!root.ref.fields[item.id]) return;
root.element.appendChild(root.ref.fields[item.id]);
});
};
var didReorderItems = function didReorderItems(_ref2) {
var root = _ref2.root;
return syncFieldPositionsWithItems(root);
};
var didAddItem = function didAddItem(_ref3) {
var root = _ref3.root,
action = _ref3.action;
var dataContainer = createElement$1('input');
dataContainer.type = 'hidden';
dataContainer.name = root.query('GET_NAME');
dataContainer.disabled = root.query('GET_DISABLED');
root.ref.fields[action.id] = dataContainer;
syncFieldPositionsWithItems(root);
};
var didLoadItem$1 = function didLoadItem(_ref4) {
var root = _ref4.root,
action = _ref4.action;
var field = getField(root, action.id);
if (!field || action.serverFileReference === null) return;
field.value = action.serverFileReference;
};
var didSetDisabled = function didSetDisabled(_ref5) {
var root = _ref5.root;
root.element.disabled = root.query('GET_DISABLED');
};
var didRemoveItem = function didRemoveItem(_ref6) {
var root = _ref6.root,
action = _ref6.action;
var field = getField(root, action.id);
if (!field) return;
if (field.parentNode) field.parentNode.removeChild(field);
delete root.ref.fields[action.id];
};
var didDefineValue = function didDefineValue(_ref7) {
var root = _ref7.root,
action = _ref7.action;
var field = getField(root, action.id);
if (!field) return;
if (action.value === null) {
field.removeAttribute('value');
} else {
field.value = action.value;
}
syncFieldPositionsWithItems(root);
};
var write$8 = createRoute({
DID_SET_DISABLED: didSetDisabled,
DID_ADD_ITEM: didAddItem,
DID_LOAD_ITEM: didLoadItem$1,
DID_REMOVE_ITEM: didRemoveItem,
DID_DEFINE_VALUE: didDefineValue,
DID_REORDER_ITEMS: didReorderItems,
DID_SORT_ITEMS: didReorderItems,
});
var data = createView({
tag: 'fieldset',
name: 'data',
create: create$c,
write: write$8,
ignoreRect: true,
});
var getRootNode = function getRootNode(element) {
return 'getRootNode' in element ? element.getRootNode() : document;
};
var images = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg', 'tiff'];
var text$1 = ['css', 'csv', 'html', 'txt'];
var map = {
zip: 'zip|compressed',
epub: 'application/epub+zip',
};
var guesstimateMimeType = function guesstimateMimeType() {
var extension = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
extension = extension.toLowerCase();
if (images.includes(extension)) {
return (
'image/' +
(extension === 'jpg' ? 'jpeg' : extension === 'svg' ? 'svg+xml' : extension)
);
}
if (text$1.includes(extension)) {
return 'text/' + extension;
}
return map[extension] || '';
};
var requestDataTransferItems = function requestDataTransferItems(dataTransfer) {
return new Promise(function(resolve, reject) {
// try to get links from transfer, if found we'll exit immediately (unless a file is in the dataTransfer as well, this is because Firefox could represent the file as a URL and a file object at the same time)
var links = getLinks(dataTransfer);
if (links.length && !hasFiles(dataTransfer)) {
return resolve(links);
}
// try to get files from the transfer
getFiles(dataTransfer).then(resolve);
});
};
/**
* Test if datatransfer has files
*/
var hasFiles = function hasFiles(dataTransfer) {
if (dataTransfer.files) return dataTransfer.files.length > 0;
return false;
};
/**
* Extracts files from a DataTransfer object
*/
var getFiles = function getFiles(dataTransfer) {
return new Promise(function(resolve, reject) {
// get the transfer items as promises
var promisedFiles = (dataTransfer.items ? Array.from(dataTransfer.items) : [])
// only keep file system items (files and directories)
.filter(function(item) {
return isFileSystemItem(item);
})
// map each item to promise
.map(function(item) {
return getFilesFromItem(item);
});
// if is empty, see if we can extract some info from the files property as a fallback
if (!promisedFiles.length) {
// TODO: test for directories (should not be allowed)
// Use FileReader, problem is that the files property gets lost in the process
resolve(dataTransfer.files ? Array.from(dataTransfer.files) : []);
return;
}
// done!
Promise.all(promisedFiles)
.then(function(returnedFileGroups) {
// flatten groups
var files = [];
returnedFileGroups.forEach(function(group) {
files.push.apply(files, group);
});
// done (filter out empty files)!
resolve(
files
.filter(function(file) {
return file;
})
.map(function(file) {
if (!file._relativePath)
file._relativePath = file.webkitRelativePath;
return file;
})
);
})
.catch(console.error);
});
};
var isFileSystemItem = function isFileSystemItem(item) {
if (isEntry(item)) {
var entry = getAsEntry(item);
if (entry) {
return entry.isFile || entry.isDirectory;
}
}
return item.kind === 'file';
};
var getFilesFromItem = function getFilesFromItem(item) {
return new Promise(function(resolve, reject) {
if (isDirectoryEntry(item)) {
getFilesInDirectory(getAsEntry(item))
.then(resolve)
.catch(reject);
return;
}
resolve([item.getAsFile()]);
});
};
var getFilesInDirectory = function getFilesInDirectory(entry) {
return new Promise(function(resolve, reject) {
var files = [];
// the total entries to read
var dirCounter = 0;
var fileCounter = 0;
var resolveIfDone = function resolveIfDone() {
if (fileCounter === 0 && dirCounter === 0) {
resolve(files);
}
};
// the recursive function
var readEntries = function readEntries(dirEntry) {
dirCounter++;
var directoryReader = dirEntry.createReader();
// directories are returned in batches, we need to process all batches before we're done
var readBatch = function readBatch() {
directoryReader.readEntries(function(entries) {
if (entries.length === 0) {
dirCounter--;
resolveIfDone();
return;
}
entries.forEach(function(entry) {
// recursively read more directories
if (entry.isDirectory) {
readEntries(entry);
} else {
// read as file
fileCounter++;
entry.file(function(file) {
var correctedFile = correctMissingFileType(file);
if (entry.fullPath)
correctedFile._relativePath = entry.fullPath;
files.push(correctedFile);
fileCounter--;
resolveIfDone();
});
}
});
// try to get next batch of files
readBatch();
}, reject);
};
// read first batch of files
readBatch();
};
// go!
readEntries(entry);
});
};
var correctMissingFileType = function correctMissingFileType(file) {
if (file.type.length) return file;
var date = file.lastModifiedDate;
var name = file.name;
var type = guesstimateMimeType(getExtensionFromFilename(file.name));
if (!type.length) return file;
file = file.slice(0, file.size, type);
file.name = name;
file.lastModifiedDate = date;
return file;
};
var isDirectoryEntry = function isDirectoryEntry(item) {
return isEntry(item) && (getAsEntry(item) || {}).isDirectory;
};
var isEntry = function isEntry(item) {
return 'webkitGetAsEntry' in item;
};
var getAsEntry = function getAsEntry(item) {
return item.webkitGetAsEntry();
};
/**
* Extracts links from a DataTransfer object
*/
var getLinks = function getLinks(dataTransfer) {
var links = [];
try {
// look in meta data property
links = getLinksFromTransferMetaData(dataTransfer);
if (links.length) {
return links;
}
links = getLinksFromTransferURLData(dataTransfer);
} catch (e) {
// nope nope nope (probably IE trouble)
}
return links;
};
var getLinksFromTransferURLData = function getLinksFromTransferURLData(dataTransfer) {
var data = dataTransfer.getData('url');
if (typeof data === 'string' && data.length) {
return [data];
}
return [];
};
var getLinksFromTransferMetaData = function getLinksFromTransferMetaData(dataTransfer) {
var data = dataTransfer.getData('text/html');
if (typeof data === 'string' && data.length) {
var matches = data.match(/src\s*=\s*"(.+?)"/);
if (matches) {
return [matches[1]];
}
}
return [];
};
var dragNDropObservers = [];
var eventPosition = function eventPosition(e) {
return {
pageLeft: e.pageX,
pageTop: e.pageY,
scopeLeft: e.offsetX || e.layerX,
scopeTop: e.offsetY || e.layerY,
};
};
var createDragNDropClient = function createDragNDropClient(
element,
scopeToObserve,
filterElement
) {
var observer = getDragNDropObserver(scopeToObserve);
var client = {
element: element,
filterElement: filterElement,
state: null,
ondrop: function ondrop() {},
onenter: function onenter() {},
ondrag: function ondrag() {},
onexit: function onexit() {},
onload: function onload() {},
allowdrop: function allowdrop() {},
};
client.destroy = observer.addListener(client);
return client;
};
var getDragNDropObserver = function getDragNDropObserver(element) {
// see if already exists, if so, return
var observer = dragNDropObservers.find(function(item) {
return item.element === element;
});
if (observer) {
return observer;
}
// create new observer, does not yet exist for this element
var newObserver = createDragNDropObserver(element);
dragNDropObservers.push(newObserver);
return newObserver;
};
var createDragNDropObserver = function createDragNDropObserver(element) {
var clients = [];
var routes = {
dragenter: dragenter,
dragover: dragover,
dragleave: dragleave,
drop: drop,
};
var handlers = {};
forin(routes, function(event, createHandler) {
handlers[event] = createHandler(element, clients);
element.addEventListener(event, handlers[event], false);
});
var observer = {
element: element,
addListener: function addListener(client) {
// add as client
clients.push(client);
// return removeListener function
return function() {
// remove client
clients.splice(clients.indexOf(client), 1);
// if no more clients, clean up observer
if (clients.length === 0) {
dragNDropObservers.splice(dragNDropObservers.indexOf(observer), 1);
forin(routes, function(event) {
element.removeEventListener(event, handlers[event], false);
});
}
};
},
};
return observer;
};
var elementFromPoint = function elementFromPoint(root, point) {
if (!('elementFromPoint' in root)) {
root = document;
}
return root.elementFromPoint(point.x, point.y);
};
var isEventTarget = function isEventTarget(e, target) {
// get root
var root = getRootNode(target);
// get element at position
// if root is not actual shadow DOM and does not have elementFromPoint method, use the one on document
var elementAtPosition = elementFromPoint(root, {
x: e.pageX - window.pageXOffset,
y: e.pageY - window.pageYOffset,
});
// test if target is the element or if one of its children is
return elementAtPosition === target || target.contains(elementAtPosition);
};
var initialTarget = null;
var setDropEffect = function setDropEffect(dataTransfer, effect) {
// is in try catch as IE11 will throw error if not
try {
dataTransfer.dropEffect = effect;
} catch (e) {}
};
var dragenter = function dragenter(root, clients) {
return function(e) {
e.preventDefault();
initialTarget = e.target;
clients.forEach(function(client) {
var element = client.element,
onenter = client.onenter;
if (isEventTarget(e, element)) {
client.state = 'enter';
// fire enter event
onenter(eventPosition(e));
}
});
};
};
var dragover = function dragover(root, clients) {
return function(e) {
e.preventDefault();
var dataTransfer = e.dataTransfer;
requestDataTransferItems(dataTransfer).then(function(items) {
var overDropTarget = false;
clients.some(function(client) {
var filterElement = client.filterElement,
element = client.element,
onenter = client.onenter,
onexit = client.onexit,
ondrag = client.ondrag,
allowdrop = client.allowdrop;
// by default we can drop
setDropEffect(dataTransfer, 'copy');
// allow transfer of these items
var allowsTransfer = allowdrop(items);
// only used when can be dropped on page
if (!allowsTransfer) {
setDropEffect(dataTransfer, 'none');
return;
}
// targetting this client
if (isEventTarget(e, element)) {
overDropTarget = true;
// had no previous state, means we are entering this client
if (client.state === null) {
client.state = 'enter';
onenter(eventPosition(e));
return;
}
// now over element (no matter if it allows the drop or not)
client.state = 'over';
// needs to allow transfer
if (filterElement && !allowsTransfer) {
setDropEffect(dataTransfer, 'none');
return;
}
// dragging
ondrag(eventPosition(e));
} else {
// should be over an element to drop
if (filterElement && !overDropTarget) {
setDropEffect(dataTransfer, 'none');
}
// might have just left this client?
if (client.state) {
client.state = null;
onexit(eventPosition(e));
}
}
});
});
};
};
var drop = function drop(root, clients) {
return function(e) {
e.preventDefault();
var dataTransfer = e.dataTransfer;
requestDataTransferItems(dataTransfer).then(function(items) {
clients.forEach(function(client) {
var filterElement = client.filterElement,
element = client.element,
ondrop = client.ondrop,
onexit = client.onexit,
allowdrop = client.allowdrop;
client.state = null;
// if we're filtering on element we need to be over the element to drop
if (filterElement && !isEventTarget(e, element)) return;
// no transfer for this client
if (!allowdrop(items)) return onexit(eventPosition(e));
// we can drop these items on this client
ondrop(eventPosition(e), items);
});
});
};
};
var dragleave = function dragleave(root, clients) {
return function(e) {
if (initialTarget !== e.target) {
return;
}
clients.forEach(function(client) {
var onexit = client.onexit;
client.state = null;
onexit(eventPosition(e));
});
};
};
var createHopper = function createHopper(scope, validateItems, options) {
// is now hopper scope
scope.classList.add('filepond--hopper');
// shortcuts
var catchesDropsOnPage = options.catchesDropsOnPage,
requiresDropOnElement = options.requiresDropOnElement,
_options$filterItems = options.filterItems,
filterItems =
_options$filterItems === void 0
? function(items) {
return items;
}
: _options$filterItems;
// create a dnd client
var client = createDragNDropClient(
scope,
catchesDropsOnPage ? document.documentElement : scope,
requiresDropOnElement
);
// current client state
var lastState = '';
var currentState = '';
// determines if a file may be dropped
client.allowdrop = function(items) {
// TODO: if we can, throw error to indicate the items cannot by dropped
return validateItems(filterItems(items));
};
client.ondrop = function(position, items) {
var filteredItems = filterItems(items);
if (!validateItems(filteredItems)) {
api.ondragend(position);
return;
}
currentState = 'drag-drop';
api.onload(filteredItems, position);
};
client.ondrag = function(position) {
api.ondrag(position);
};
client.onenter = function(position) {
currentState = 'drag-over';
api.ondragstart(position);
};
client.onexit = function(position) {
currentState = 'drag-exit';
api.ondragend(position);
};
var api = {
updateHopperState: function updateHopperState() {
if (lastState !== currentState) {
scope.dataset.hopperState = currentState;
lastState = currentState;
}
},
onload: function onload() {},
ondragstart: function ondragstart() {},
ondrag: function ondrag() {},
ondragend: function ondragend() {},
destroy: function destroy() {
// destroy client
client.destroy();
},
};
return api;
};
var listening = false;
var listeners$1 = [];
var handlePaste = function handlePaste(e) {
// if is pasting in input or textarea and the target is outside of a filepond scope, ignore
var activeEl = document.activeElement;
if (activeEl && /textarea|input/i.test(activeEl.nodeName)) {
// test textarea or input is contained in filepond root
var inScope = false;
var element = activeEl;
while (element !== document.body) {
if (element.classList.contains('filepond--root')) {
inScope = true;
break;
}
element = element.parentNode;
}
if (!inScope) return;
}
requestDataTransferItems(e.clipboardData).then(function(files) {
// no files received
if (!files.length) {
return;
}
// notify listeners of received files
listeners$1.forEach(function(listener) {
return listener(files);
});
});
};
var listen = function listen(cb) {
// can't add twice
if (listeners$1.includes(cb)) {
return;
}
// add initial listener
listeners$1.push(cb);
// setup paste listener for entire page
if (listening) {
return;
}
listening = true;
document.addEventListener('paste', handlePaste);
};
var unlisten = function unlisten(listener) {
arrayRemove(listeners$1, listeners$1.indexOf(listener));
// clean up
if (listeners$1.length === 0) {
document.removeEventListener('paste', handlePaste);
listening = false;
}
};
var createPaster = function createPaster() {
var cb = function cb(files) {
api.onload(files);
};
var api = {
destroy: function destroy() {
unlisten(cb);
},
onload: function onload() {},
};
listen(cb);
return api;
};
/**
* Creates the file view
*/
var create$d = function create(_ref) {
var root = _ref.root,
props = _ref.props;
root.element.id = 'filepond--assistant-' + props.id;
attr(root.element, 'role', 'status');
attr(root.element, 'aria-live', 'polite');
attr(root.element, 'aria-relevant', 'additions');
};
var addFilesNotificationTimeout = null;
var notificationClearTimeout = null;
var filenames = [];
var assist = function assist(root, message) {
root.element.textContent = message;
};
var clear$1 = function clear(root) {
root.element.textContent = '';
};
var listModified = function listModified(root, filename, label) {
var total = root.query('GET_TOTAL_ITEMS');
assist(
root,
label +
' ' +
filename +
', ' +
total +
' ' +
(total === 1
? root.query('GET_LABEL_FILE_COUNT_SINGULAR')
: root.query('GET_LABEL_FILE_COUNT_PLURAL'))
);
// clear group after set amount of time so the status is not read twice
clearTimeout(notificationClearTimeout);
notificationClearTimeout = setTimeout(function() {
clear$1(root);
}, 1500);
};
var isUsingFilePond = function isUsingFilePond(root) {
return root.element.parentNode.contains(document.activeElement);
};
var itemAdded = function itemAdded(_ref2) {
var root = _ref2.root,
action = _ref2.action;
if (!isUsingFilePond(root)) {
return;
}
root.element.textContent = '';
var item = root.query('GET_ITEM', action.id);
filenames.push(item.filename);
clearTimeout(addFilesNotificationTimeout);
addFilesNotificationTimeout = setTimeout(function() {
listModified(root, filenames.join(', '), root.query('GET_LABEL_FILE_ADDED'));
filenames.length = 0;
}, 750);
};
var itemRemoved = function itemRemoved(_ref3) {
var root = _ref3.root,
action = _ref3.action;
if (!isUsingFilePond(root)) {
return;
}
var item = action.item;
listModified(root, item.filename, root.query('GET_LABEL_FILE_REMOVED'));
};
var itemProcessed = function itemProcessed(_ref4) {
var root = _ref4.root,
action = _ref4.action;
// will also notify the user when FilePond is not being used, as the user might be occupied with other activities while uploading a file
var item = root.query('GET_ITEM', action.id);
var filename = item.filename;
var label = root.query('GET_LABEL_FILE_PROCESSING_COMPLETE');
assist(root, filename + ' ' + label);
};
var itemProcessedUndo = function itemProcessedUndo(_ref5) {
var root = _ref5.root,
action = _ref5.action;
var item = root.query('GET_ITEM', action.id);
var filename = item.filename;
var label = root.query('GET_LABEL_FILE_PROCESSING_ABORTED');
assist(root, filename + ' ' + label);
};
var itemError = function itemError(_ref6) {
var root = _ref6.root,
action = _ref6.action;
var item = root.query('GET_ITEM', action.id);
var filename = item.filename;
// will also notify the user when FilePond is not being used, as the user might be occupied with other activities while uploading a file
assist(root, action.status.main + ' ' + filename + ' ' + action.status.sub);
};
var assistant = createView({
create: create$d,
ignoreRect: true,
ignoreRectUpdate: true,
write: createRoute({
DID_LOAD_ITEM: itemAdded,
DID_REMOVE_ITEM: itemRemoved,
DID_COMPLETE_ITEM_PROCESSING: itemProcessed,
DID_ABORT_ITEM_PROCESSING: itemProcessedUndo,
DID_REVERT_ITEM_PROCESSING: itemProcessedUndo,
DID_THROW_ITEM_REMOVE_ERROR: itemError,
DID_THROW_ITEM_LOAD_ERROR: itemError,
DID_THROW_ITEM_INVALID: itemError,
DID_THROW_ITEM_PROCESSING_ERROR: itemError,
}),
tag: 'span',
name: 'assistant',
});
var toCamels = function toCamels(string) {
var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '-';
return string.replace(new RegExp(separator + '.', 'g'), function(sub) {
return sub.charAt(1).toUpperCase();
});
};
var debounce = function debounce(func) {
var interval = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 16;
var immidiateOnly =
arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
var last = Date.now();
var timeout = null;
return function() {
for (
var _len = arguments.length, args = new Array(_len), _key = 0;
_key < _len;
_key++
) {
args[_key] = arguments[_key];
}
clearTimeout(timeout);
var dist = Date.now() - last;
var fn = function fn() {
last = Date.now();
func.apply(void 0, args);
};
if (dist < interval) {
// we need to delay by the difference between interval and dist
// for example: if distance is 10 ms and interval is 16 ms,
// we need to wait an additional 6ms before calling the function)
if (!immidiateOnly) {
timeout = setTimeout(fn, interval - dist);
}
} else {
// go!
fn();
}
};
};
var MAX_FILES_LIMIT = 1000000;
var prevent = function prevent(e) {
return e.preventDefault();
};
var create$e = function create(_ref) {
var root = _ref.root,
props = _ref.props;
// Add id
var id = root.query('GET_ID');
if (id) {
root.element.id = id;
}
// Add className
var className = root.query('GET_CLASS_NAME');
if (className) {
className
.split(' ')
.filter(function(name) {
return name.length;
})
.forEach(function(name) {
root.element.classList.add(name);
});
}
// Field label
root.ref.label = root.appendChildView(
root.createChildView(
dropLabel,
Object.assign({}, props, {
translateY: null,
caption: root.query('GET_LABEL_IDLE'),
})
)
);
// List of items
root.ref.list = root.appendChildView(
root.createChildView(listScroller, { translateY: null })
);
// Background panel
root.ref.panel = root.appendChildView(root.createChildView(panel, { name: 'panel-root' }));
// Assistant notifies assistive tech when content changes
root.ref.assistant = root.appendChildView(
root.createChildView(assistant, Object.assign({}, props))
);
// Data
root.ref.data = root.appendChildView(root.createChildView(data, Object.assign({}, props)));
// Measure (tests if fixed height was set)
// DOCTYPE needs to be set for this to work
root.ref.measure = createElement$1('div');
root.ref.measure.style.height = '100%';
root.element.appendChild(root.ref.measure);
// information on the root height or fixed height status
root.ref.bounds = null;
// apply initial style properties
root.query('GET_STYLES')
.filter(function(style) {
return !isEmpty(style.value);
})
.map(function(_ref2) {
var name = _ref2.name,
value = _ref2.value;
root.element.dataset[name] = value;
});
// determine if width changed
root.ref.widthPrevious = null;
root.ref.widthUpdated = debounce(function() {
root.ref.updateHistory = [];
root.dispatch('DID_RESIZE_ROOT');
}, 250);
// history of updates
root.ref.previousAspectRatio = null;
root.ref.updateHistory = [];
// prevent scrolling and zooming on iOS (only if supports pointer events, for then we can enable reorder)
var canHover = window.matchMedia('(pointer: fine) and (hover: hover)').matches;
var hasPointerEvents = 'PointerEvent' in window;
if (root.query('GET_ALLOW_REORDER') && hasPointerEvents && !canHover) {
root.element.addEventListener('touchmove', prevent, { passive: false });
root.element.addEventListener('gesturestart', prevent);
}
// add credits
var credits = root.query('GET_CREDITS');
var hasCredits = credits.length === 2;
if (hasCredits) {
var frag = document.createElement('a');
frag.className = 'filepond--credits';
frag.setAttribute('aria-hidden', 'true');
frag.href = credits[0];
frag.tabindex = -1;
frag.target = '_blank';
frag.rel = 'noopener noreferrer';
frag.textContent = credits[1];
root.element.appendChild(frag);
root.ref.credits = frag;
}
};
var write$9 = function write(_ref3) {
var root = _ref3.root,
props = _ref3.props,
actions = _ref3.actions;
// route actions
route$5({ root: root, props: props, actions: actions });
// apply style properties
actions
.filter(function(action) {
return /^DID_SET_STYLE_/.test(action.type);
})
.filter(function(action) {
return !isEmpty(action.data.value);
})
.map(function(_ref4) {
var type = _ref4.type,
data = _ref4.data;
var name = toCamels(type.substr(8).toLowerCase(), '_');
root.element.dataset[name] = data.value;
root.invalidateLayout();
});
if (root.rect.element.hidden) return;
if (root.rect.element.width !== root.ref.widthPrevious) {
root.ref.widthPrevious = root.rect.element.width;
root.ref.widthUpdated();
}
// get box bounds, we do this only once
var bounds = root.ref.bounds;
if (!bounds) {
bounds = root.ref.bounds = calculateRootBoundingBoxHeight(root);
// destroy measure element
root.element.removeChild(root.ref.measure);
root.ref.measure = null;
}
// get quick references to various high level parts of the upload tool
var _root$ref = root.ref,
hopper = _root$ref.hopper,
label = _root$ref.label,
list = _root$ref.list,
panel = _root$ref.panel;
// sets correct state to hopper scope
if (hopper) {
hopper.updateHopperState();
}
// bool to indicate if we're full or not
var aspectRatio = root.query('GET_PANEL_ASPECT_RATIO');
var isMultiItem = root.query('GET_ALLOW_MULTIPLE');
var totalItems = root.query('GET_TOTAL_ITEMS');
var maxItems = isMultiItem ? root.query('GET_MAX_FILES') || MAX_FILES_LIMIT : 1;
var atMaxCapacity = totalItems === maxItems;
// action used to add item
var addAction = actions.find(function(action) {
return action.type === 'DID_ADD_ITEM';
});
// if reached max capacity and we've just reached it
if (atMaxCapacity && addAction) {
// get interaction type
var interactionMethod = addAction.data.interactionMethod;
// hide label
label.opacity = 0;
if (isMultiItem) {
label.translateY = -40;
} else {
if (interactionMethod === InteractionMethod.API) {
label.translateX = 40;
} else if (interactionMethod === InteractionMethod.BROWSE) {
label.translateY = 40;
} else {
label.translateY = 30;
}
}
} else if (!atMaxCapacity) {
label.opacity = 1;
label.translateX = 0;
label.translateY = 0;
}
var listItemMargin = calculateListItemMargin(root);
var listHeight = calculateListHeight(root);
var labelHeight = label.rect.element.height;
var currentLabelHeight = !isMultiItem || atMaxCapacity ? 0 : labelHeight;
var listMarginTop = atMaxCapacity ? list.rect.element.marginTop : 0;
var listMarginBottom = totalItems === 0 ? 0 : list.rect.element.marginBottom;
var visualHeight =
currentLabelHeight + listMarginTop + listHeight.visual + listMarginBottom;
var boundsHeight =
currentLabelHeight + listMarginTop + listHeight.bounds + listMarginBottom;
// link list to label bottom position
list.translateY =
Math.max(0, currentLabelHeight - list.rect.element.marginTop) - listItemMargin.top;
if (aspectRatio) {
// fixed aspect ratio
// calculate height based on width
var width = root.rect.element.width;
var height = width * aspectRatio;
// clear history if aspect ratio has changed
if (aspectRatio !== root.ref.previousAspectRatio) {
root.ref.previousAspectRatio = aspectRatio;
root.ref.updateHistory = [];
}
// remember this width
var history = root.ref.updateHistory;
history.push(width);
var MAX_BOUNCES = 2;
if (history.length > MAX_BOUNCES * 2) {
var l = history.length;
var bottom = l - 10;
var bounces = 0;
for (var i = l; i >= bottom; i--) {
if (history[i] === history[i - 2]) {
bounces++;
}
if (bounces >= MAX_BOUNCES) {
// dont adjust height
return;
}
}
}
// fix height of panel so it adheres to aspect ratio
panel.scalable = false;
panel.height = height;
// available height for list
var listAvailableHeight =
// the height of the panel minus the label height
height -
currentLabelHeight -
// the room we leave open between the end of the list and the panel bottom
(listMarginBottom - listItemMargin.bottom) -
// if we're full we need to leave some room between the top of the panel and the list
(atMaxCapacity ? listMarginTop : 0);
if (listHeight.visual > listAvailableHeight) {
list.overflow = listAvailableHeight;
} else {
list.overflow = null;
}
// set container bounds (so pushes siblings downwards)
root.height = height;
} else if (bounds.fixedHeight) {
// fixed height
// fix height of panel
panel.scalable = false;
// available height for list
var _listAvailableHeight =
// the height of the panel minus the label height
bounds.fixedHeight -
currentLabelHeight -
// the room we leave open between the end of the list and the panel bottom
(listMarginBottom - listItemMargin.bottom) -
// if we're full we need to leave some room between the top of the panel and the list
(atMaxCapacity ? listMarginTop : 0);
// set list height
if (listHeight.visual > _listAvailableHeight) {
list.overflow = _listAvailableHeight;
} else {
list.overflow = null;
}
// no need to set container bounds as these are handles by CSS fixed height
} else if (bounds.cappedHeight) {
// max-height
// not a fixed height panel
var isCappedHeight = visualHeight >= bounds.cappedHeight;
var panelHeight = Math.min(bounds.cappedHeight, visualHeight);
panel.scalable = true;
panel.height = isCappedHeight
? panelHeight
: panelHeight - listItemMargin.top - listItemMargin.bottom;
// available height for list
var _listAvailableHeight2 =
// the height of the panel minus the label height
panelHeight -
currentLabelHeight -
// the room we leave open between the end of the list and the panel bottom
(listMarginBottom - listItemMargin.bottom) -
// if we're full we need to leave some room between the top of the panel and the list
(atMaxCapacity ? listMarginTop : 0);
// set list height (if is overflowing)
if (visualHeight > bounds.cappedHeight && listHeight.visual > _listAvailableHeight2) {
list.overflow = _listAvailableHeight2;
} else {
list.overflow = null;
}
// set container bounds (so pushes siblings downwards)
root.height = Math.min(
bounds.cappedHeight,
boundsHeight - listItemMargin.top - listItemMargin.bottom
);
} else {
// flexible height
// not a fixed height panel
var itemMargin = totalItems > 0 ? listItemMargin.top + listItemMargin.bottom : 0;
panel.scalable = true;
panel.height = Math.max(labelHeight, visualHeight - itemMargin);
// set container bounds (so pushes siblings downwards)
root.height = Math.max(labelHeight, boundsHeight - itemMargin);
}
// move credits to bottom
if (root.ref.credits && panel.heightCurrent)
root.ref.credits.style.transform = 'translateY(' + panel.heightCurrent + 'px)';
};
var calculateListItemMargin = function calculateListItemMargin(root) {
var item = root.ref.list.childViews[0].childViews[0];
return item
? {
top: item.rect.element.marginTop,
bottom: item.rect.element.marginBottom,
}
: {
top: 0,
bottom: 0,
};
};
var calculateListHeight = function calculateListHeight(root) {
var visual = 0;
var bounds = 0;
// get file list reference
var scrollList = root.ref.list;
var itemList = scrollList.childViews[0];
var visibleChildren = itemList.childViews.filter(function(child) {
return child.rect.element.height;
});
var children = root
.query('GET_ACTIVE_ITEMS')
.map(function(item) {
return visibleChildren.find(function(child) {
return child.id === item.id;
});
})
.filter(function(item) {
return item;
});
// no children, done!
if (children.length === 0) return { visual: visual, bounds: bounds };
var horizontalSpace = itemList.rect.element.width;
var dragIndex = getItemIndexByPosition(itemList, children, scrollList.dragCoordinates);
var childRect = children[0].rect.element;
var itemVerticalMargin = childRect.marginTop + childRect.marginBottom;
var itemHorizontalMargin = childRect.marginLeft + childRect.marginRight;
var itemWidth = childRect.width + itemHorizontalMargin;
var itemHeight = childRect.height + itemVerticalMargin;
var newItem = typeof dragIndex !== 'undefined' && dragIndex >= 0 ? 1 : 0;
var removedItem = children.find(function(child) {
return child.markedForRemoval && child.opacity < 0.45;
})
? -1
: 0;
var verticalItemCount = children.length + newItem + removedItem;
var itemsPerRow = getItemsPerRow(horizontalSpace, itemWidth);
// stack
if (itemsPerRow === 1) {
children.forEach(function(item) {
var height = item.rect.element.height + itemVerticalMargin;
bounds += height;
visual += height * item.opacity;
});
}
// grid
else {
bounds = Math.ceil(verticalItemCount / itemsPerRow) * itemHeight;
visual = bounds;
}
return { visual: visual, bounds: bounds };
};
var calculateRootBoundingBoxHeight = function calculateRootBoundingBoxHeight(root) {
var height = root.ref.measureHeight || null;
var cappedHeight = parseInt(root.style.maxHeight, 10) || null;
var fixedHeight = height === 0 ? null : height;
return {
cappedHeight: cappedHeight,
fixedHeight: fixedHeight,
};
};
var exceedsMaxFiles = function exceedsMaxFiles(root, items) {
var allowReplace = root.query('GET_ALLOW_REPLACE');
var allowMultiple = root.query('GET_ALLOW_MULTIPLE');
var totalItems = root.query('GET_TOTAL_ITEMS');
var maxItems = root.query('GET_MAX_FILES');
// total amount of items being dragged
var totalBrowseItems = items.length;
// if does not allow multiple items and dragging more than one item
if (!allowMultiple && totalBrowseItems > 1) {
return true;
}
// limit max items to one if not allowed to drop multiple items
maxItems = allowMultiple ? maxItems : allowReplace ? maxItems : 1;
// no more room?
var hasMaxItems = isInt(maxItems);
if (hasMaxItems && totalItems + totalBrowseItems > maxItems) {
root.dispatch('DID_THROW_MAX_FILES', {
source: items,
error: createResponse('warning', 0, 'Max files'),
});
return true;
}
return false;
};
var getDragIndex = function getDragIndex(list, children, position) {
var itemList = list.childViews[0];
return getItemIndexByPosition(itemList, children, {
left: position.scopeLeft - itemList.rect.element.left,
top:
position.scopeTop -
(list.rect.outer.top + list.rect.element.marginTop + list.rect.element.scrollTop),
});
};
/**
* Enable or disable file drop functionality
*/
var toggleDrop = function toggleDrop(root) {
var isAllowed = root.query('GET_ALLOW_DROP');
var isDisabled = root.query('GET_DISABLED');
var enabled = isAllowed && !isDisabled;
if (enabled && !root.ref.hopper) {
var hopper = createHopper(
root.element,
function(items) {
// allow quick validation of dropped items
var beforeDropFile =
root.query('GET_BEFORE_DROP_FILE') ||
function() {
return true;
};
// all items should be validated by all filters as valid
var dropValidation = root.query('GET_DROP_VALIDATION');
return dropValidation
? items.every(function(item) {
return (
applyFilters('ALLOW_HOPPER_ITEM', item, {
query: root.query,
}).every(function(result) {
return result === true;
}) && beforeDropFile(item)
);
})
: true;
},
{
filterItems: function filterItems(items) {
var ignoredFiles = root.query('GET_IGNORED_FILES');<|fim▁hole|> if (isFile(item)) {
return !ignoredFiles.includes(item.name.toLowerCase());
}
return true;
});
},
catchesDropsOnPage: root.query('GET_DROP_ON_PAGE'),
requiresDropOnElement: root.query('GET_DROP_ON_ELEMENT'),
}
);
hopper.onload = function(items, position) {
// get item children elements and sort based on list sort
var list = root.ref.list.childViews[0];
var visibleChildren = list.childViews.filter(function(child) {
return child.rect.element.height;
});
var children = root
.query('GET_ACTIVE_ITEMS')
.map(function(item) {
return visibleChildren.find(function(child) {
return child.id === item.id;
});
})
.filter(function(item) {
return item;
});
applyFilterChain('ADD_ITEMS', items, { dispatch: root.dispatch }).then(function(
queue
) {
// these files don't fit so stop here
if (exceedsMaxFiles(root, queue)) return false;
// go
root.dispatch('ADD_ITEMS', {
items: queue,
index: getDragIndex(root.ref.list, children, position),
interactionMethod: InteractionMethod.DROP,
});
});
root.dispatch('DID_DROP', { position: position });
root.dispatch('DID_END_DRAG', { position: position });
};
hopper.ondragstart = function(position) {
root.dispatch('DID_START_DRAG', { position: position });
};
hopper.ondrag = debounce(function(position) {
root.dispatch('DID_DRAG', { position: position });
});
hopper.ondragend = function(position) {
root.dispatch('DID_END_DRAG', { position: position });
};
root.ref.hopper = hopper;
root.ref.drip = root.appendChildView(root.createChildView(drip));
} else if (!enabled && root.ref.hopper) {
root.ref.hopper.destroy();
root.ref.hopper = null;
root.removeChildView(root.ref.drip);
}
};
/**
* Enable or disable browse functionality
*/
var toggleBrowse = function toggleBrowse(root, props) {
var isAllowed = root.query('GET_ALLOW_BROWSE');
var isDisabled = root.query('GET_DISABLED');
var enabled = isAllowed && !isDisabled;
if (enabled && !root.ref.browser) {
root.ref.browser = root.appendChildView(
root.createChildView(
browser,
Object.assign({}, props, {
onload: function onload(items) {
applyFilterChain('ADD_ITEMS', items, {
dispatch: root.dispatch,
}).then(function(queue) {
// these files don't fit so stop here
if (exceedsMaxFiles(root, queue)) return false;
// add items!
root.dispatch('ADD_ITEMS', {
items: queue,
index: -1,
interactionMethod: InteractionMethod.BROWSE,
});
});
},
})
),
0
);
} else if (!enabled && root.ref.browser) {
root.removeChildView(root.ref.browser);
root.ref.browser = null;
}
};
/**
* Enable or disable paste functionality
*/
var togglePaste = function togglePaste(root) {
var isAllowed = root.query('GET_ALLOW_PASTE');
var isDisabled = root.query('GET_DISABLED');
var enabled = isAllowed && !isDisabled;
if (enabled && !root.ref.paster) {
root.ref.paster = createPaster();
root.ref.paster.onload = function(items) {
applyFilterChain('ADD_ITEMS', items, { dispatch: root.dispatch }).then(function(
queue
) {
// these files don't fit so stop here
if (exceedsMaxFiles(root, queue)) return false;
// add items!
root.dispatch('ADD_ITEMS', {
items: queue,
index: -1,
interactionMethod: InteractionMethod.PASTE,
});
});
};
} else if (!enabled && root.ref.paster) {
root.ref.paster.destroy();
root.ref.paster = null;
}
};
/**
* Route actions
*/
var route$5 = createRoute({
DID_SET_ALLOW_BROWSE: function DID_SET_ALLOW_BROWSE(_ref5) {
var root = _ref5.root,
props = _ref5.props;
toggleBrowse(root, props);
},
DID_SET_ALLOW_DROP: function DID_SET_ALLOW_DROP(_ref6) {
var root = _ref6.root;
toggleDrop(root);
},
DID_SET_ALLOW_PASTE: function DID_SET_ALLOW_PASTE(_ref7) {
var root = _ref7.root;
togglePaste(root);
},
DID_SET_DISABLED: function DID_SET_DISABLED(_ref8) {
var root = _ref8.root,
props = _ref8.props;
toggleDrop(root);
togglePaste(root);
toggleBrowse(root, props);
var isDisabled = root.query('GET_DISABLED');
if (isDisabled) {
root.element.dataset.disabled = 'disabled';
} else {
// delete root.element.dataset.disabled; <= this does not work on iOS 10
root.element.removeAttribute('data-disabled');
}
},
});
var root = createView({
name: 'root',
read: function read(_ref9) {
var root = _ref9.root;
if (root.ref.measure) {
root.ref.measureHeight = root.ref.measure.offsetHeight;
}
},
create: create$e,
write: write$9,
destroy: function destroy(_ref10) {
var root = _ref10.root;
if (root.ref.paster) {
root.ref.paster.destroy();
}
if (root.ref.hopper) {
root.ref.hopper.destroy();
}
root.element.removeEventListener('touchmove', prevent);
root.element.removeEventListener('gesturestart', prevent);
},
mixins: {
styles: ['height'],
},
});
// creates the app
var createApp = function createApp() {
var initialOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
// let element
var originalElement = null;
// get default options
var defaultOptions = getOptions();
// create the data store, this will contain all our app info
var store = createStore(
// initial state (should be serializable)
createInitialState(defaultOptions),
// queries
[queries, createOptionQueries(defaultOptions)],
// action handlers
[actions, createOptionActions(defaultOptions)]
);
// set initial options
store.dispatch('SET_OPTIONS', { options: initialOptions });
// kick thread if visibility changes
var visibilityHandler = function visibilityHandler() {
if (document.hidden) return;
store.dispatch('KICK');
};
document.addEventListener('visibilitychange', visibilityHandler);
// re-render on window resize start and finish
var resizeDoneTimer = null;
var isResizing = false;
var isResizingHorizontally = false;
var initialWindowWidth = null;
var currentWindowWidth = null;
var resizeHandler = function resizeHandler() {
if (!isResizing) {
isResizing = true;
}
clearTimeout(resizeDoneTimer);
resizeDoneTimer = setTimeout(function() {
isResizing = false;
initialWindowWidth = null;
currentWindowWidth = null;
if (isResizingHorizontally) {
isResizingHorizontally = false;
store.dispatch('DID_STOP_RESIZE');
}
}, 500);
};
window.addEventListener('resize', resizeHandler);
// render initial view
var view = root(store, { id: getUniqueId() });
//
// PRIVATE API -------------------------------------------------------------------------------------
//
var isResting = false;
var isHidden = false;
var readWriteApi = {
// necessary for update loop
/**
* Reads from dom (never call manually)
* @private
*/
_read: function _read() {
// test if we're resizing horizontally
// TODO: see if we can optimize this by measuring root rect
if (isResizing) {
currentWindowWidth = window.innerWidth;
if (!initialWindowWidth) {
initialWindowWidth = currentWindowWidth;
}
if (!isResizingHorizontally && currentWindowWidth !== initialWindowWidth) {
store.dispatch('DID_START_RESIZE');
isResizingHorizontally = true;
}
}
if (isHidden && isResting) {
// test if is no longer hidden
isResting = view.element.offsetParent === null;
}
// if resting, no need to read as numbers will still all be correct
if (isResting) return;
// read view data
view._read();
// if is hidden we need to know so we exit rest mode when revealed
isHidden = view.rect.element.hidden;
},
/**
* Writes to dom (never call manually)
* @private
*/
_write: function _write(ts) {
// get all actions from store
var actions = store
.processActionQueue()
// filter out set actions (these will automatically trigger DID_SET)
.filter(function(action) {
return !/^SET_/.test(action.type);
});
// if was idling and no actions stop here
if (isResting && !actions.length) return;
// some actions might trigger events
routeActionsToEvents(actions);
// update the view
isResting = view._write(ts, actions, isResizingHorizontally);
// will clean up all archived items
removeReleasedItems(store.query('GET_ITEMS'));
// now idling
if (isResting) {
store.processDispatchQueue();
}
},
};
//
// EXPOSE EVENTS -------------------------------------------------------------------------------------
//
var createEvent = function createEvent(name) {
return function(data) {
// create default event
var event = {
type: name,
};
// no data to add
if (!data) {
return event;
}
// copy relevant props
if (data.hasOwnProperty('error')) {
event.error = data.error ? Object.assign({}, data.error) : null;
}
if (data.status) {
event.status = Object.assign({}, data.status);
}
if (data.file) {
event.output = data.file;
}
// only source is available, else add item if possible
if (data.source) {
event.file = data.source;
} else if (data.item || data.id) {
var item = data.item ? data.item : store.query('GET_ITEM', data.id);
event.file = item ? createItemAPI(item) : null;
}
// map all items in a possible items array
if (data.items) {
event.items = data.items.map(createItemAPI);
}
// if this is a progress event add the progress amount
if (/progress/.test(name)) {
event.progress = data.progress;
}
// copy relevant props
if (data.hasOwnProperty('origin') && data.hasOwnProperty('target')) {
event.origin = data.origin;
event.target = data.target;
}
return event;
};
};
var eventRoutes = {
DID_DESTROY: createEvent('destroy'),
DID_INIT: createEvent('init'),
DID_THROW_MAX_FILES: createEvent('warning'),
DID_INIT_ITEM: createEvent('initfile'),
DID_START_ITEM_LOAD: createEvent('addfilestart'),
DID_UPDATE_ITEM_LOAD_PROGRESS: createEvent('addfileprogress'),
DID_LOAD_ITEM: createEvent('addfile'),
DID_THROW_ITEM_INVALID: [createEvent('error'), createEvent('addfile')],
DID_THROW_ITEM_LOAD_ERROR: [createEvent('error'), createEvent('addfile')],
DID_THROW_ITEM_REMOVE_ERROR: [createEvent('error'), createEvent('removefile')],
DID_PREPARE_OUTPUT: createEvent('preparefile'),
DID_START_ITEM_PROCESSING: createEvent('processfilestart'),
DID_UPDATE_ITEM_PROCESS_PROGRESS: createEvent('processfileprogress'),
DID_ABORT_ITEM_PROCESSING: createEvent('processfileabort'),
DID_COMPLETE_ITEM_PROCESSING: createEvent('processfile'),
DID_COMPLETE_ITEM_PROCESSING_ALL: createEvent('processfiles'),
DID_REVERT_ITEM_PROCESSING: createEvent('processfilerevert'),
DID_THROW_ITEM_PROCESSING_ERROR: [createEvent('error'), createEvent('processfile')],
DID_REMOVE_ITEM: createEvent('removefile'),
DID_UPDATE_ITEMS: createEvent('updatefiles'),
DID_ACTIVATE_ITEM: createEvent('activatefile'),
DID_REORDER_ITEMS: createEvent('reorderfiles'),
};
var exposeEvent = function exposeEvent(event) {
// create event object to be dispatched
var detail = Object.assign({ pond: exports }, event);
delete detail.type;
view.element.dispatchEvent(
new CustomEvent('FilePond:' + event.type, {
// event info
detail: detail,
// event behaviour
bubbles: true,
cancelable: true,
composed: true, // triggers listeners outside of shadow root
})
);
// event object to params used for `on()` event handlers and callbacks `oninit()`
var params = [];
// if is possible error event, make it the first param
if (event.hasOwnProperty('error')) {
params.push(event.error);
}
// file is always section
if (event.hasOwnProperty('file')) {
params.push(event.file);
}
// append other props
var filtered = ['type', 'error', 'file'];
Object.keys(event)
.filter(function(key) {
return !filtered.includes(key);
})
.forEach(function(key) {
return params.push(event[key]);
});
// on(type, () => { })
exports.fire.apply(exports, [event.type].concat(params));
// oninit = () => {}
var handler = store.query('GET_ON' + event.type.toUpperCase());
if (handler) {
handler.apply(void 0, params);
}
};
var routeActionsToEvents = function routeActionsToEvents(actions) {
if (!actions.length) return;
actions
.filter(function(action) {
return eventRoutes[action.type];
})
.forEach(function(action) {
var routes = eventRoutes[action.type];
(Array.isArray(routes) ? routes : [routes]).forEach(function(route) {
// this isn't fantastic, but because of the stacking of settimeouts plugins can handle the did_load before the did_init
if (action.type === 'DID_INIT_ITEM') {
exposeEvent(route(action.data));
} else {
setTimeout(function() {
exposeEvent(route(action.data));
}, 0);
}
});
});
};
//
// PUBLIC API -------------------------------------------------------------------------------------
//
var setOptions = function setOptions(options) {
return store.dispatch('SET_OPTIONS', { options: options });
};
var getFile = function getFile(query) {
return store.query('GET_ACTIVE_ITEM', query);
};
var prepareFile = function prepareFile(query) {
return new Promise(function(resolve, reject) {
store.dispatch('REQUEST_ITEM_PREPARE', {
query: query,
success: function success(item) {
resolve(item);
},
failure: function failure(error) {
reject(error);
},
});
});
};
var addFile = function addFile(source) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return new Promise(function(resolve, reject) {
addFiles([{ source: source, options: options }], { index: options.index })
.then(function(items) {
return resolve(items && items[0]);
})
.catch(reject);
});
};
var isFilePondFile = function isFilePondFile(obj) {
return obj.file && obj.id;
};
var removeFile = function removeFile(query, options) {
// if only passed options
if (typeof query === 'object' && !isFilePondFile(query) && !options) {
options = query;
query = undefined;
}
// request item removal
store.dispatch('REMOVE_ITEM', Object.assign({}, options, { query: query }));
// see if item has been removed
return store.query('GET_ACTIVE_ITEM', query) === null;
};
var addFiles = function addFiles() {
for (
var _len = arguments.length, args = new Array(_len), _key = 0;
_key < _len;
_key++
) {
args[_key] = arguments[_key];
}
return new Promise(function(resolve, reject) {
var sources = [];
var options = {};
// user passed a sources array
if (isArray(args[0])) {
sources.push.apply(sources, args[0]);
Object.assign(options, args[1] || {});
} else {
// user passed sources as arguments, last one might be options object
var lastArgument = args[args.length - 1];
if (typeof lastArgument === 'object' && !(lastArgument instanceof Blob)) {
Object.assign(options, args.pop());
}
// add rest to sources
sources.push.apply(sources, args);
}
store.dispatch('ADD_ITEMS', {
items: sources,
index: options.index,
interactionMethod: InteractionMethod.API,
success: resolve,
failure: reject,
});
});
};
var getFiles = function getFiles() {
return store.query('GET_ACTIVE_ITEMS');
};
var processFile = function processFile(query) {
return new Promise(function(resolve, reject) {
store.dispatch('REQUEST_ITEM_PROCESSING', {
query: query,
success: function success(item) {
resolve(item);
},
failure: function failure(error) {
reject(error);
},
});
});
};
var prepareFiles = function prepareFiles() {
for (
var _len2 = arguments.length, args = new Array(_len2), _key2 = 0;
_key2 < _len2;
_key2++
) {
args[_key2] = arguments[_key2];
}
var queries = Array.isArray(args[0]) ? args[0] : args;
var items = queries.length ? queries : getFiles();
return Promise.all(items.map(prepareFile));
};
var processFiles = function processFiles() {
for (
var _len3 = arguments.length, args = new Array(_len3), _key3 = 0;
_key3 < _len3;
_key3++
) {
args[_key3] = arguments[_key3];
}
var queries = Array.isArray(args[0]) ? args[0] : args;
if (!queries.length) {
var files = getFiles().filter(function(item) {
return (
!(item.status === ItemStatus.IDLE && item.origin === FileOrigin.LOCAL) &&
item.status !== ItemStatus.PROCESSING &&
item.status !== ItemStatus.PROCESSING_COMPLETE &&
item.status !== ItemStatus.PROCESSING_REVERT_ERROR
);
});
return Promise.all(files.map(processFile));
}
return Promise.all(queries.map(processFile));
};
var removeFiles = function removeFiles() {
for (
var _len4 = arguments.length, args = new Array(_len4), _key4 = 0;
_key4 < _len4;
_key4++
) {
args[_key4] = arguments[_key4];
}
var queries = Array.isArray(args[0]) ? args[0] : args;
var options;
if (typeof queries[queries.length - 1] === 'object') {
options = queries.pop();
} else if (Array.isArray(args[0])) {
options = args[1];
}
var files = getFiles();
if (!queries.length)
return Promise.all(
files.map(function(file) {
return removeFile(file, options);
})
);
// when removing by index the indexes shift after each file removal so we need to convert indexes to ids
var mappedQueries = queries
.map(function(query) {
return isNumber(query) ? (files[query] ? files[query].id : null) : query;
})
.filter(function(query) {
return query;
});
return mappedQueries.map(function(q) {
return removeFile(q, options);
});
};
var exports = Object.assign(
{},
on(),
{},
readWriteApi,
{},
createOptionAPI(store, defaultOptions),
{
/**
* Override options defined in options object
* @param options
*/
setOptions: setOptions,
/**
* Load the given file
* @param source - the source of the file (either a File, base64 data uri or url)
* @param options - object, { index: 0 }
*/
addFile: addFile,
/**
* Load the given files
* @param sources - the sources of the files to load
* @param options - object, { index: 0 }
*/
addFiles: addFiles,
/**
* Returns the file objects matching the given query
* @param query { string, number, null }
*/
getFile: getFile,
/**
* Upload file with given name
* @param query { string, number, null }
*/
processFile: processFile,
/**
* Request prepare output for file with given name
* @param query { string, number, null }
*/
prepareFile: prepareFile,
/**
* Removes a file by its name
* @param query { string, number, null }
*/
removeFile: removeFile,
/**
* Moves a file to a new location in the files list
*/
moveFile: function moveFile(query, index) {
return store.dispatch('MOVE_ITEM', { query: query, index: index });
},
/**
* Returns all files (wrapped in public api)
*/
getFiles: getFiles,
/**
* Starts uploading all files
*/
processFiles: processFiles,
/**
* Clears all files from the files list
*/
removeFiles: removeFiles,
/**
* Starts preparing output of all files
*/
prepareFiles: prepareFiles,
/**
* Sort list of files
*/
sort: function sort(compare) {
return store.dispatch('SORT', { compare: compare });
},
/**
* Browse the file system for a file
*/
browse: function browse() {
// needs to be trigger directly as user action needs to be traceable (is not traceable in requestAnimationFrame)
var input = view.element.querySelector('input[type=file]');
if (input) {
input.click();
}
},
/**
* Destroys the app
*/
destroy: function destroy() {
// request destruction
exports.fire('destroy', view.element);
// stop active processes (file uploads, fetches, stuff like that)
// loop over items and depending on states call abort for ongoing processes
store.dispatch('ABORT_ALL');
// destroy view
view._destroy();
// stop listening to resize
window.removeEventListener('resize', resizeHandler);
// stop listening to the visiblitychange event
document.removeEventListener('visibilitychange', visibilityHandler);
// dispatch destroy
store.dispatch('DID_DESTROY');
},
/**
* Inserts the plugin before the target element
*/
insertBefore: function insertBefore$1(element) {
return insertBefore(view.element, element);
},
/**
* Inserts the plugin after the target element
*/
insertAfter: function insertAfter$1(element) {
return insertAfter(view.element, element);
},
/**
* Appends the plugin to the target element
*/
appendTo: function appendTo(element) {
return element.appendChild(view.element);
},
/**
* Replaces an element with the app
*/
replaceElement: function replaceElement(element) {
// insert the app before the element
insertBefore(view.element, element);
// remove the original element
element.parentNode.removeChild(element);
// remember original element
originalElement = element;
},
/**
* Restores the original element
*/
restoreElement: function restoreElement() {
if (!originalElement) {
return; // no element to restore
}
// restore original element
insertAfter(originalElement, view.element);
// remove our element
view.element.parentNode.removeChild(view.element);
// remove reference
originalElement = null;
},
/**
* Returns true if the app root is attached to given element
* @param element
*/
isAttachedTo: function isAttachedTo(element) {
return view.element === element || originalElement === element;
},
/**
* Returns the root element
*/
element: {
get: function get() {
return view.element;
},
},
/**
* Returns the current pond status
*/
status: {
get: function get() {
return store.query('GET_STATUS');
},
},
}
);
// Done!
store.dispatch('DID_INIT');
// create actual api object
return createObject(exports);
};
var createAppObject = function createAppObject() {
var customOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
// default options
var defaultOptions = {};
forin(getOptions(), function(key, value) {
defaultOptions[key] = value[0];
});
// set app options
var app = createApp(
Object.assign(
{},
defaultOptions,
{},
customOptions
)
);
// return the plugin instance
return app;
};
var lowerCaseFirstLetter = function lowerCaseFirstLetter(string) {
return string.charAt(0).toLowerCase() + string.slice(1);
};
var attributeNameToPropertyName = function attributeNameToPropertyName(attributeName) {
return toCamels(attributeName.replace(/^data-/, ''));
};
var mapObject = function mapObject(object, propertyMap) {
// remove unwanted
forin(propertyMap, function(selector, mapping) {
forin(object, function(property, value) {
// create regexp shortcut
var selectorRegExp = new RegExp(selector);
// tests if
var matches = selectorRegExp.test(property);
// no match, skip
if (!matches) {
return;
}
// if there's a mapping, the original property is always removed
delete object[property];
// should only remove, we done!
if (mapping === false) {
return;
}
// move value to new property
if (isString(mapping)) {
object[mapping] = value;
return;
}
// move to group
var group = mapping.group;
if (isObject(mapping) && !object[group]) {
object[group] = {};
}
object[group][lowerCaseFirstLetter(property.replace(selectorRegExp, ''))] = value;
});
// do submapping
if (mapping.mapping) {
mapObject(object[mapping.group], mapping.mapping);
}
});
};
var getAttributesAsObject = function getAttributesAsObject(node) {
var attributeMapping =
arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
// turn attributes into object
var attributes = [];
forin(node.attributes, function(index) {
attributes.push(node.attributes[index]);
});
var output = attributes
.filter(function(attribute) {
return attribute.name;
})
.reduce(function(obj, attribute) {
var value = attr(node, attribute.name);
obj[attributeNameToPropertyName(attribute.name)] =
value === attribute.name ? true : value;
return obj;
}, {});
// do mapping of object properties
mapObject(output, attributeMapping);
return output;
};
var createAppAtElement = function createAppAtElement(element) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
// how attributes of the input element are mapped to the options for the plugin
var attributeMapping = {
// translate to other name
'^class$': 'className',
'^multiple$': 'allowMultiple',
'^capture$': 'captureMethod',
'^webkitdirectory$': 'allowDirectoriesOnly',
// group under single property
'^server': {
group: 'server',
mapping: {
'^process': {
group: 'process',
},
'^revert': {
group: 'revert',
},
'^fetch': {
group: 'fetch',
},
'^restore': {
group: 'restore',
},
'^load': {
group: 'load',
},
},
},
// don't include in object
'^type$': false,
'^files$': false,
};
// add additional option translators
applyFilters('SET_ATTRIBUTE_TO_OPTION_MAP', attributeMapping);
// create final options object by setting options object and then overriding options supplied on element
var mergedOptions = Object.assign({}, options);
var attributeOptions = getAttributesAsObject(
element.nodeName === 'FIELDSET' ? element.querySelector('input[type=file]') : element,
attributeMapping
);
// merge with options object
Object.keys(attributeOptions).forEach(function(key) {
if (isObject(attributeOptions[key])) {
if (!isObject(mergedOptions[key])) {
mergedOptions[key] = {};
}
Object.assign(mergedOptions[key], attributeOptions[key]);
} else {
mergedOptions[key] = attributeOptions[key];
}
});
// if parent is a fieldset, get files from parent by selecting all input fields that are not file upload fields
// these will then be automatically set to the initial files
mergedOptions.files = (options.files || []).concat(
Array.from(element.querySelectorAll('input:not([type=file])')).map(function(input) {
return {
source: input.value,
options: {
type: input.dataset.type,
},
};
})
);
// build plugin
var app = createAppObject(mergedOptions);
// add already selected files
if (element.files) {
Array.from(element.files).forEach(function(file) {
app.addFile(file);
});
}
// replace the target element
app.replaceElement(element);
// expose
return app;
};
// if an element is passed, we create the instance at that element, if not, we just create an up object
var createApp$1 = function createApp() {
return isNode(arguments.length <= 0 ? undefined : arguments[0])
? createAppAtElement.apply(void 0, arguments)
: createAppObject.apply(void 0, arguments);
};
var PRIVATE_METHODS = ['fire', '_read', '_write'];
var createAppAPI = function createAppAPI(app) {
var api = {};
copyObjectPropertiesToObject(app, api, PRIVATE_METHODS);
return api;
};
/**
* Replaces placeholders in given string with replacements
* @param string - "Foo {bar}""
* @param replacements - { "bar": 10 }
*/
var replaceInString = function replaceInString(string, replacements) {
return string.replace(/(?:{([a-zA-Z]+)})/g, function(match, group) {
return replacements[group];
});
};
var createWorker = function createWorker(fn) {
var workerBlob = new Blob(['(', fn.toString(), ')()'], {
type: 'application/javascript',
});
var workerURL = URL.createObjectURL(workerBlob);
var worker = new Worker(workerURL);
return {
transfer: function transfer(message, cb) {},
post: function post(message, cb, transferList) {
var id = getUniqueId();
worker.onmessage = function(e) {
if (e.data.id === id) {
cb(e.data.message);
}
};
worker.postMessage(
{
id: id,
message: message,
},
transferList
);
},
terminate: function terminate() {
worker.terminate();
URL.revokeObjectURL(workerURL);
},
};
};
var loadImage = function loadImage(url) {
return new Promise(function(resolve, reject) {
var img = new Image();
img.onload = function() {
resolve(img);
};
img.onerror = function(e) {
reject(e);
};
img.src = url;
});
};
var renameFile = function renameFile(file, name) {
var renamedFile = file.slice(0, file.size, file.type);
renamedFile.lastModifiedDate = file.lastModifiedDate;
renamedFile.name = name;
return renamedFile;
};
var copyFile = function copyFile(file) {
return renameFile(file, file.name);
};
// already registered plugins (can't register twice)
var registeredPlugins = [];
// pass utils to plugin
var createAppPlugin = function createAppPlugin(plugin) {
// already registered
if (registeredPlugins.includes(plugin)) {
return;
}
// remember this plugin
registeredPlugins.push(plugin);
// setup!
var pluginOutline = plugin({
addFilter: addFilter,
utils: {
Type: Type,
forin: forin,
isString: isString,
isFile: isFile,
toNaturalFileSize: toNaturalFileSize,
replaceInString: replaceInString,
getExtensionFromFilename: getExtensionFromFilename,
getFilenameWithoutExtension: getFilenameWithoutExtension,
guesstimateMimeType: guesstimateMimeType,
getFileFromBlob: getFileFromBlob,
getFilenameFromURL: getFilenameFromURL,
createRoute: createRoute,
createWorker: createWorker,
createView: createView,
createItemAPI: createItemAPI,
loadImage: loadImage,
copyFile: copyFile,
renameFile: renameFile,
createBlob: createBlob,
applyFilterChain: applyFilterChain,
text: text,
getNumericAspectRatioFromString: getNumericAspectRatioFromString,
},
views: {
fileActionButton: fileActionButton,
},
});
// add plugin options to default options
extendDefaultOptions(pluginOutline.options);
};
// feature detection used by supported() method
var isOperaMini = function isOperaMini() {
return Object.prototype.toString.call(window.operamini) === '[object OperaMini]';
};
var hasPromises = function hasPromises() {
return 'Promise' in window;
};
var hasBlobSlice = function hasBlobSlice() {
return 'slice' in Blob.prototype;
};
var hasCreateObjectURL = function hasCreateObjectURL() {
return 'URL' in window && 'createObjectURL' in window.URL;
};
var hasVisibility = function hasVisibility() {
return 'visibilityState' in document;
};
var hasTiming = function hasTiming() {
return 'performance' in window;
}; // iOS 8.x
var hasCSSSupports = function hasCSSSupports() {
return 'supports' in (window.CSS || {});
}; // use to detect Safari 9+
var isIE11 = function isIE11() {
return /MSIE|Trident/.test(window.navigator.userAgent);
};
var supported = (function() {
// Runs immediately and then remembers result for subsequent calls
var isSupported =
// Has to be a browser
isBrowser() &&
// Can't run on Opera Mini due to lack of everything
!isOperaMini() &&
// Require these APIs to feature detect a modern browser
hasVisibility() &&
hasPromises() &&
hasBlobSlice() &&
hasCreateObjectURL() &&
hasTiming() &&
// doesn't need CSSSupports but is a good way to detect Safari 9+ (we do want to support IE11 though)
(hasCSSSupports() || isIE11());
return function() {
return isSupported;
};
})();
/**
* Plugin internal state (over all instances)
*/
var state = {
// active app instances, used to redraw the apps and to find the later
apps: [],
};
// plugin name
var name = 'filepond';
/**
* Public Plugin methods
*/
var fn = function fn() {};
exports.Status = {};
exports.FileStatus = {};
exports.FileOrigin = {};
exports.OptionTypes = {};
exports.create = fn;
exports.destroy = fn;
exports.parse = fn;
exports.find = fn;
exports.registerPlugin = fn;
exports.getOptions = fn;
exports.setOptions = fn;
// if not supported, no API
if (supported()) {
// start painter and fire load event
createPainter(
function() {
state.apps.forEach(function(app) {
return app._read();
});
},
function(ts) {
state.apps.forEach(function(app) {
return app._write(ts);
});
}
);
// fire loaded event so we know when FilePond is available
var dispatch = function dispatch() {
// let others know we have area ready
document.dispatchEvent(
new CustomEvent('FilePond:loaded', {
detail: {
supported: supported,
create: exports.create,
destroy: exports.destroy,
parse: exports.parse,
find: exports.find,
registerPlugin: exports.registerPlugin,
setOptions: exports.setOptions,
},
})
);
// clean up event
document.removeEventListener('DOMContentLoaded', dispatch);
};
if (document.readyState !== 'loading') {
// move to back of execution queue, FilePond should have been exported by then
setTimeout(function() {
return dispatch();
}, 0);
} else {
document.addEventListener('DOMContentLoaded', dispatch);
}
// updates the OptionTypes object based on the current options
var updateOptionTypes = function updateOptionTypes() {
return forin(getOptions(), function(key, value) {
exports.OptionTypes[key] = value[1];
});
};
exports.Status = Object.assign({}, Status);
exports.FileOrigin = Object.assign({}, FileOrigin);
exports.FileStatus = Object.assign({}, ItemStatus);
exports.OptionTypes = {};
updateOptionTypes();
// create method, creates apps and adds them to the app array
exports.create = function create() {
var app = createApp$1.apply(void 0, arguments);
app.on('destroy', exports.destroy);
state.apps.push(app);
return createAppAPI(app);
};
// destroys apps and removes them from the app array
exports.destroy = function destroy(hook) {
// returns true if the app was destroyed successfully
var indexToRemove = state.apps.findIndex(function(app) {
return app.isAttachedTo(hook);
});
if (indexToRemove >= 0) {
// remove from apps
var app = state.apps.splice(indexToRemove, 1)[0];
// restore original dom element
app.restoreElement();
return true;
}
return false;
};
// parses the given context for plugins (does not include the context element itself)
exports.parse = function parse(context) {
// get all possible hooks
var matchedHooks = Array.from(context.querySelectorAll('.' + name));
// filter out already active hooks
var newHooks = matchedHooks.filter(function(newHook) {
return !state.apps.find(function(app) {
return app.isAttachedTo(newHook);
});
});
// create new instance for each hook
return newHooks.map(function(hook) {
return exports.create(hook);
});
};
// returns an app based on the given element hook
exports.find = function find(hook) {
var app = state.apps.find(function(app) {
return app.isAttachedTo(hook);
});
if (!app) {
return null;
}
return createAppAPI(app);
};
// adds a plugin extension
exports.registerPlugin = function registerPlugin() {
for (
var _len = arguments.length, plugins = new Array(_len), _key = 0;
_key < _len;
_key++
) {
plugins[_key] = arguments[_key];
}
// register plugins
plugins.forEach(createAppPlugin);
// update OptionTypes, each plugin might have extended the default options
updateOptionTypes();
};
exports.getOptions = function getOptions$1() {
var opts = {};
forin(getOptions(), function(key, value) {
opts[key] = value[0];
});
return opts;
};
exports.setOptions = function setOptions$1(opts) {
if (isObject(opts)) {
// update existing plugins
state.apps.forEach(function(app) {
app.setOptions(opts);
});
// override defaults
setOptions(opts);
}
// return new options
return exports.getOptions();
};
}
exports.supported = supported;
Object.defineProperty(exports, '__esModule', { value: true });
});<|fim▁end|>
|
return items.filter(function(item) {
|
<|file_name|>cdn.js<|end_file_name|><|fim▁begin|>module.exports = cdn
var MaxCDN = require('maxcdn')
function cdn (self) {<|fim▁hole|> self.settings.maxcdn.consumerKey,
self.settings.maxcdn.consumerSecret
)
maxcdn.del('zones/pull.json/' + self.settings.maxcdn.zoneId + '/cache', function (err, res) {
console.log('MAXCDN: STATUS')
if (err) {
console.error('PURGE ERROR: ', err.stack || err.message || err)
return
} else if (res.code !== 200) {
console.error('PURGE ERROR: ', res.code)
return
}
console.log('PURGE SUCCESS')
})
}
}<|fim▁end|>
|
if (self.settings.maxcdn.zoneId) {
var maxcdn = new MaxCDN(
self.settings.maxcdn.companyAlias,
|
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>#[cfg(target_os = "windows")]
#[path = "schannel.rs"]
mod imp;
#[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "ios")))]
#[path = "openssl.rs"]
mod imp;
#[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "ios")))]
pub use self::imp::build_tls_from_pem;
use native_tls::TlsAcceptor;
use std::{fs::File, io::Read};
<|fim▁hole|> let mut buf = Vec::new();
pfx_file.read_to_end(&mut buf).unwrap();
imp::build_acceptor_from_pfx(&buf)
}<|fim▁end|>
|
#[allow(dead_code)]
pub fn build_tls_from_pfx(pfx_path: &str) -> TlsAcceptor {
let mut pfx_file = File::open(pfx_path).unwrap();
|
<|file_name|>lib.js<|end_file_name|><|fim▁begin|>/******/ (function(modules) { // webpackBootstrap
/******/ // install a JSONP callback for chunk loading
/******/ var parentJsonpFunction = window["webpackJsonp"];
/******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules) {
/******/ // add "moreModules" to the modules object,
/******/ // then flag all "chunkIds" as loaded and fire callback
/******/ var moduleId, chunkId, i = 0, callbacks = [];
/******/ for(;i < chunkIds.length; i++) {
/******/ chunkId = chunkIds[i];
/******/ if(installedChunks[chunkId])
/******/ callbacks.push.apply(callbacks, installedChunks[chunkId]);
/******/ installedChunks[chunkId] = 0;
/******/ }
/******/ for(moduleId in moreModules) {
/******/ modules[moduleId] = moreModules[moduleId];
/******/ }
/******/ if(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules);
/******/ while(callbacks.length)
/******/ callbacks.shift().call(null, __webpack_require__);
/******/ if(moreModules[0]) {
/******/ installedModules[0] = 0;
/******/ return __webpack_require__(0);
/******/ }
/******/ };
/******/ // The module cache
/******/ var installedModules = {};
/******/ // object to store loaded and loading chunks
/******/ // "0" means "already loaded"
/******/ // Array means "loading", array contains callbacks
/******/ var installedChunks = {
/******/ 0:0
/******/ };
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // This file contains only the entry chunk.
/******/ // The chunk loading function for additional chunks
/******/ __webpack_require__.e = function requireEnsure(chunkId, callback) {
/******/ // "0" is the signal for "already loaded"
/******/ if(installedChunks[chunkId] === 0)
/******/ return callback.call(null, __webpack_require__);
/******/ // an array means "currently loading".
/******/ if(installedChunks[chunkId] !== undefined) {
/******/ installedChunks[chunkId].push(callback);
/******/ } else {
/******/ // start chunk loading
/******/ installedChunks[chunkId] = [callback];
/******/ var head = document.getElementsByTagName('head')[0];
/******/ var script = document.createElement('script');
/******/ script.type = 'text/javascript';
/******/ script.charset = 'utf-8';
/******/ script.async = true;
/******/ script.src = __webpack_require__.p + "" + chunkId + ".index.bundle.js";
/******/ head.appendChild(script);
/******/ }
/******/ };
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(1);
module.exports = __webpack_require__(158);
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
module.exports = __webpack_require__(2);
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule React
*/
'use strict';
var ReactDOM = __webpack_require__(3);
var ReactDOMServer = __webpack_require__(148);
var ReactIsomorphic = __webpack_require__(152);
var assign = __webpack_require__(39);
var deprecated = __webpack_require__(157);
// `version` will be added here by ReactIsomorphic.
var React = {};
assign(React, ReactIsomorphic);
assign(React, {
// ReactDOM
findDOMNode: deprecated('findDOMNode', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.findDOMNode),
render: deprecated('render', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.render),
unmountComponentAtNode: deprecated('unmountComponentAtNode', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.unmountComponentAtNode),
// ReactDOMServer
renderToString: deprecated('renderToString', 'ReactDOMServer', 'react-dom/server', ReactDOMServer, ReactDOMServer.renderToString),
renderToStaticMarkup: deprecated('renderToStaticMarkup', 'ReactDOMServer', 'react-dom/server', ReactDOMServer, ReactDOMServer.renderToStaticMarkup)
});
React.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactDOM;
React.__SECRET_DOM_SERVER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactDOMServer;
module.exports = React;
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOM
*/
/* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/
'use strict';
var ReactCurrentOwner = __webpack_require__(5);
var ReactDOMTextComponent = __webpack_require__(6);
var ReactDefaultInjection = __webpack_require__(71);
var ReactInstanceHandles = __webpack_require__(45);
var ReactMount = __webpack_require__(28);
var ReactPerf = __webpack_require__(18);
var ReactReconciler = __webpack_require__(50);
var ReactUpdates = __webpack_require__(54);
var ReactVersion = __webpack_require__(146);
var findDOMNode = __webpack_require__(91);
var renderSubtreeIntoContainer = __webpack_require__(147);
var warning = __webpack_require__(25);
ReactDefaultInjection.inject();
var render = ReactPerf.measure('React', 'render', ReactMount.render);
var React = {
findDOMNode: findDOMNode,
render: render,
unmountComponentAtNode: ReactMount.unmountComponentAtNode,
version: ReactVersion,
/* eslint-disable camelcase */
unstable_batchedUpdates: ReactUpdates.batchedUpdates,
unstable_renderSubtreeIntoContainer: renderSubtreeIntoContainer
};
// Inject the runtime into a devtools global hook regardless of browser.
// Allows for debugging when the hook is injected on the page.
/* eslint-enable camelcase */
if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') {
__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({
CurrentOwner: ReactCurrentOwner,
InstanceHandles: ReactInstanceHandles,
Mount: ReactMount,
Reconciler: ReactReconciler,
TextComponent: ReactDOMTextComponent
});
}
if (process.env.NODE_ENV !== 'production') {
var ExecutionEnvironment = __webpack_require__(9);
if (ExecutionEnvironment.canUseDOM && window.top === window.self) {
// First check if devtools is not installed
if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
// If we're in Chrome or Firefox, provide a download link if not installed.
if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {
console.debug('Download the React DevTools for a better development experience: ' + 'https://fb.me/react-devtools');
}
}
// If we're in IE8, check to see if we are in compatibility mode and provide
// information on preventing compatibility mode
var ieCompatibilityMode = document.documentMode && document.documentMode < 8;
process.env.NODE_ENV !== 'production' ? warning(!ieCompatibilityMode, 'Internet Explorer is running in compatibility mode; please add the ' + 'following tag to your HTML to prevent this from happening: ' + '<meta http-equiv="X-UA-Compatible" content="IE=edge" />') : undefined;
var expectedFeatures = [
// shims
Array.isArray, Array.prototype.every, Array.prototype.forEach, Array.prototype.indexOf, Array.prototype.map, Date.now, Function.prototype.bind, Object.keys, String.prototype.split, String.prototype.trim,
// shams
Object.create, Object.freeze];
for (var i = 0; i < expectedFeatures.length; i++) {
if (!expectedFeatures[i]) {
console.error('One or more ES5 shim/shams expected by React are not available: ' + 'https://fb.me/react-warning-polyfills');
break;
}
}
}
}
module.exports = React;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 4 */
/***/ function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = setTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
clearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
setTimeout(drainQueue, 0);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ },
/* 5 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactCurrentOwner
*/
'use strict';
/**
* Keeps track of the current owner.
*
* The current owner is the component who should own any components that are
* currently being constructed.
*/
var ReactCurrentOwner = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
module.exports = ReactCurrentOwner;
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMTextComponent
* @typechecks static-only
*/
'use strict';
var DOMChildrenOperations = __webpack_require__(7);
var DOMPropertyOperations = __webpack_require__(22);
var ReactComponentBrowserEnvironment = __webpack_require__(26);
var ReactMount = __webpack_require__(28);
var assign = __webpack_require__(39);
var escapeTextContentForBrowser = __webpack_require__(21);
var setTextContent = __webpack_require__(20);
var validateDOMNesting = __webpack_require__(70);
/**
* Text nodes violate a couple assumptions that React makes about components:
*
* - When mounting text into the DOM, adjacent text nodes are merged.
* - Text nodes cannot be assigned a React root ID.
*
* This component is used to wrap strings in elements so that they can undergo
* the same reconciliation that is applied to elements.
*
* TODO: Investigate representing React components in the DOM with text nodes.
*
* @class ReactDOMTextComponent
* @extends ReactComponent
* @internal
*/
var ReactDOMTextComponent = function (props) {
// This constructor and its argument is currently used by mocks.
};
assign(ReactDOMTextComponent.prototype, {
/**
* @param {ReactText} text
* @internal
*/
construct: function (text) {
// TODO: This is really a ReactText (ReactNode), not a ReactElement
this._currentElement = text;
this._stringText = '' + text;
// Properties
this._rootNodeID = null;
this._mountIndex = 0;
},
/**
* Creates the markup for this text node. This node is not intended to have
* any features besides containing text content.
*
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @return {string} Markup for this text node.
* @internal
*/
mountComponent: function (rootID, transaction, context) {
if (process.env.NODE_ENV !== 'production') {
if (context[validateDOMNesting.ancestorInfoContextKey]) {
validateDOMNesting('span', null, context[validateDOMNesting.ancestorInfoContextKey]);
}
}
this._rootNodeID = rootID;
if (transaction.useCreateElement) {
var ownerDocument = context[ReactMount.ownerDocumentContextKey];
var el = ownerDocument.createElement('span');
DOMPropertyOperations.setAttributeForID(el, rootID);
// Populate node cache
ReactMount.getID(el);
setTextContent(el, this._stringText);
return el;
} else {
var escapedText = escapeTextContentForBrowser(this._stringText);
if (transaction.renderToStaticMarkup) {
// Normally we'd wrap this in a `span` for the reasons stated above, but
// since this is a situation where React won't take over (static pages),
// we can simply return the text as it is.
return escapedText;
}
return '<span ' + DOMPropertyOperations.createMarkupForID(rootID) + '>' + escapedText + '</span>';
}
},
/**
* Updates this component by updating the text content.
*
* @param {ReactText} nextText The next text content
* @param {ReactReconcileTransaction} transaction
* @internal
*/
receiveComponent: function (nextText, transaction) {
if (nextText !== this._currentElement) {
this._currentElement = nextText;
var nextStringText = '' + nextText;
if (nextStringText !== this._stringText) {
// TODO: Save this as pending props and use performUpdateIfNecessary
// and/or updateComponent to do the actual update for consistency with
// other component types?
this._stringText = nextStringText;
var node = ReactMount.getNode(this._rootNodeID);
DOMChildrenOperations.updateTextContent(node, nextStringText);
}
}
},
unmountComponent: function () {
ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID);
}
});
module.exports = ReactDOMTextComponent;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule DOMChildrenOperations
* @typechecks static-only
*/
'use strict';
var Danger = __webpack_require__(8);
var ReactMultiChildUpdateTypes = __webpack_require__(16);
var ReactPerf = __webpack_require__(18);
var setInnerHTML = __webpack_require__(19);
var setTextContent = __webpack_require__(20);
var invariant = __webpack_require__(13);
/**
* Inserts `childNode` as a child of `parentNode` at the `index`.
*
* @param {DOMElement} parentNode Parent node in which to insert.
* @param {DOMElement} childNode Child node to insert.
* @param {number} index Index at which to insert the child.
* @internal
*/
function insertChildAt(parentNode, childNode, index) {
// By exploiting arrays returning `undefined` for an undefined index, we can
// rely exclusively on `insertBefore(node, null)` instead of also using
// `appendChild(node)`. However, using `undefined` is not allowed by all
// browsers so we must replace it with `null`.
// fix render order error in safari
// IE8 will throw error when index out of list size.
var beforeChild = index >= parentNode.childNodes.length ? null : parentNode.childNodes.item(index);
parentNode.insertBefore(childNode, beforeChild);
}
/**
* Operations for updating with DOM children.
*/
var DOMChildrenOperations = {
dangerouslyReplaceNodeWithMarkup: Danger.dangerouslyReplaceNodeWithMarkup,
updateTextContent: setTextContent,
/**
* Updates a component's children by processing a series of updates. The
* update configurations are each expected to have a `parentNode` property.
*
* @param {array<object>} updates List of update configurations.
* @param {array<string>} markupList List of markup strings.
* @internal
*/
processUpdates: function (updates, markupList) {
var update;
// Mapping from parent IDs to initial child orderings.
var initialChildren = null;
// List of children that will be moved or removed.
var updatedChildren = null;
for (var i = 0; i < updates.length; i++) {
update = updates[i];
if (update.type === ReactMultiChildUpdateTypes.MOVE_EXISTING || update.type === ReactMultiChildUpdateTypes.REMOVE_NODE) {
var updatedIndex = update.fromIndex;
var updatedChild = update.parentNode.childNodes[updatedIndex];
var parentID = update.parentID;
!updatedChild ? process.env.NODE_ENV !== 'production' ? invariant(false, 'processUpdates(): Unable to find child %s of element. This ' + 'probably means the DOM was unexpectedly mutated (e.g., by the ' + 'browser), usually due to forgetting a <tbody> when using tables, ' + 'nesting tags like <form>, <p>, or <a>, or using non-SVG elements ' + 'in an <svg> parent. Try inspecting the child nodes of the element ' + 'with React ID `%s`.', updatedIndex, parentID) : invariant(false) : undefined;
initialChildren = initialChildren || {};
initialChildren[parentID] = initialChildren[parentID] || [];
initialChildren[parentID][updatedIndex] = updatedChild;
updatedChildren = updatedChildren || [];
updatedChildren.push(updatedChild);
}
}
var renderedMarkup;
// markupList is either a list of markup or just a list of elements
if (markupList.length && typeof markupList[0] === 'string') {
renderedMarkup = Danger.dangerouslyRenderMarkup(markupList);
} else {
renderedMarkup = markupList;
}
// Remove updated children first so that `toIndex` is consistent.
if (updatedChildren) {
for (var j = 0; j < updatedChildren.length; j++) {
updatedChildren[j].parentNode.removeChild(updatedChildren[j]);
}
}
for (var k = 0; k < updates.length; k++) {
update = updates[k];
switch (update.type) {
case ReactMultiChildUpdateTypes.INSERT_MARKUP:
insertChildAt(update.parentNode, renderedMarkup[update.markupIndex], update.toIndex);
break;
case ReactMultiChildUpdateTypes.MOVE_EXISTING:
insertChildAt(update.parentNode, initialChildren[update.parentID][update.fromIndex], update.toIndex);
break;
case ReactMultiChildUpdateTypes.SET_MARKUP:
setInnerHTML(update.parentNode, update.content);
break;
case ReactMultiChildUpdateTypes.TEXT_CONTENT:
setTextContent(update.parentNode, update.content);
break;
case ReactMultiChildUpdateTypes.REMOVE_NODE:
// Already removed by the for-loop above.
break;
}
}
}
};
ReactPerf.measureMethods(DOMChildrenOperations, 'DOMChildrenOperations', {
updateTextContent: 'updateTextContent'
});
module.exports = DOMChildrenOperations;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Danger
* @typechecks static-only
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(9);
var createNodesFromMarkup = __webpack_require__(10);
var emptyFunction = __webpack_require__(15);
var getMarkupWrap = __webpack_require__(14);
var invariant = __webpack_require__(13);
var OPEN_TAG_NAME_EXP = /^(<[^ \/>]+)/;
var RESULT_INDEX_ATTR = 'data-danger-index';
/**
* Extracts the `nodeName` from a string of markup.
*
* NOTE: Extracting the `nodeName` does not require a regular expression match
* because we make assumptions about React-generated markup (i.e. there are no
* spaces surrounding the opening tag and there is at least one attribute).
*
* @param {string} markup String of markup.
* @return {string} Node name of the supplied markup.
* @see http://jsperf.com/extract-nodename
*/
function getNodeName(markup) {
return markup.substring(1, markup.indexOf(' '));
}
var Danger = {
/**
* Renders markup into an array of nodes. The markup is expected to render
* into a list of root nodes. Also, the length of `resultList` and
* `markupList` should be the same.
*
* @param {array<string>} markupList List of markup strings to render.
* @return {array<DOMElement>} List of rendered nodes.
* @internal
*/
dangerouslyRenderMarkup: function (markupList) {
!ExecutionEnvironment.canUseDOM ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyRenderMarkup(...): Cannot render markup in a worker ' + 'thread. Make sure `window` and `document` are available globally ' + 'before requiring React when unit testing or use ' + 'ReactDOMServer.renderToString for server rendering.') : invariant(false) : undefined;
var nodeName;
var markupByNodeName = {};
// Group markup by `nodeName` if a wrap is necessary, else by '*'.
for (var i = 0; i < markupList.length; i++) {
!markupList[i] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyRenderMarkup(...): Missing markup.') : invariant(false) : undefined;
nodeName = getNodeName(markupList[i]);
nodeName = getMarkupWrap(nodeName) ? nodeName : '*';
markupByNodeName[nodeName] = markupByNodeName[nodeName] || [];
markupByNodeName[nodeName][i] = markupList[i];
}
var resultList = [];
var resultListAssignmentCount = 0;
for (nodeName in markupByNodeName) {
if (!markupByNodeName.hasOwnProperty(nodeName)) {
continue;
}
var markupListByNodeName = markupByNodeName[nodeName];
// This for-in loop skips the holes of the sparse array. The order of
// iteration should follow the order of assignment, which happens to match
// numerical index order, but we don't rely on that.
var resultIndex;
for (resultIndex in markupListByNodeName) {
if (markupListByNodeName.hasOwnProperty(resultIndex)) {
var markup = markupListByNodeName[resultIndex];
// Push the requested markup with an additional RESULT_INDEX_ATTR
// attribute. If the markup does not start with a < character, it
// will be discarded below (with an appropriate console.error).
markupListByNodeName[resultIndex] = markup.replace(OPEN_TAG_NAME_EXP,
// This index will be parsed back out below.
'$1 ' + RESULT_INDEX_ATTR + '="' + resultIndex + '" ');
}
}
// Render each group of markup with similar wrapping `nodeName`.
var renderNodes = createNodesFromMarkup(markupListByNodeName.join(''), emptyFunction // Do nothing special with <script> tags.
);
for (var j = 0; j < renderNodes.length; ++j) {
var renderNode = renderNodes[j];
if (renderNode.hasAttribute && renderNode.hasAttribute(RESULT_INDEX_ATTR)) {
resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR);
renderNode.removeAttribute(RESULT_INDEX_ATTR);
!!resultList.hasOwnProperty(resultIndex) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Danger: Assigning to an already-occupied result index.') : invariant(false) : undefined;
resultList[resultIndex] = renderNode;
// This should match resultList.length and markupList.length when
// we're done.
resultListAssignmentCount += 1;
} else if (process.env.NODE_ENV !== 'production') {
console.error('Danger: Discarding unexpected node:', renderNode);
}
}
}
// Although resultList was populated out of order, it should now be a dense
// array.
!(resultListAssignmentCount === resultList.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Danger: Did not assign to every index of resultList.') : invariant(false) : undefined;
!(resultList.length === markupList.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Danger: Expected markup to render %s nodes, but rendered %s.', markupList.length, resultList.length) : invariant(false) : undefined;
return resultList;
},
/**
* Replaces a node with a string of markup at its current position within its
* parent. The markup must render into a single root node.
*
* @param {DOMElement} oldChild Child node to replace.
* @param {string} markup Markup to render in place of the child node.
* @internal
*/
dangerouslyReplaceNodeWithMarkup: function (oldChild, markup) {
!ExecutionEnvironment.canUseDOM ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a ' + 'worker thread. Make sure `window` and `document` are available ' + 'globally before requiring React when unit testing or use ' + 'ReactDOMServer.renderToString() for server rendering.') : invariant(false) : undefined;
!markup ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : invariant(false) : undefined;
!(oldChild.tagName.toLowerCase() !== 'html') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the ' + '<html> node. This is because browser quirks make this unreliable ' + 'and/or slow. If you want to render to the root you must use ' + 'server rendering. See ReactDOMServer.renderToString().') : invariant(false) : undefined;
var newChild;
if (typeof markup === 'string') {
newChild = createNodesFromMarkup(markup, emptyFunction)[0];
} else {
newChild = markup;
}
oldChild.parentNode.replaceChild(newChild, oldChild);
}
};
module.exports = Danger;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 9 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ExecutionEnvironment
*/
'use strict';
var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
/**
* Simple, lightweight module assisting with the detection and context of
* Worker. Helps avoid circular dependencies and allows code to reason about
* whether or not they are in a Worker, even if they never include the main
* `ReactWorker` dependency.
*/
var ExecutionEnvironment = {
canUseDOM: canUseDOM,
canUseWorkers: typeof Worker !== 'undefined',
canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent),
canUseViewport: canUseDOM && !!window.screen,
isInWorker: !canUseDOM // For now, this is true - might change in the future.
};
module.exports = ExecutionEnvironment;
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule createNodesFromMarkup
* @typechecks
*/
/*eslint-disable fb-www/unsafe-html*/
'use strict';
var ExecutionEnvironment = __webpack_require__(9);
var createArrayFromMixed = __webpack_require__(11);
var getMarkupWrap = __webpack_require__(14);
var invariant = __webpack_require__(13);
/**
* Dummy container used to render all markup.
*/
var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null;
/**
* Pattern used by `getNodeName`.
*/
var nodeNamePattern = /^\s*<(\w+)/;
/**
* Extracts the `nodeName` of the first element in a string of markup.
*
* @param {string} markup String of markup.
* @return {?string} Node name of the supplied markup.
*/
function getNodeName(markup) {
var nodeNameMatch = markup.match(nodeNamePattern);
return nodeNameMatch && nodeNameMatch[1].toLowerCase();
}
/**
* Creates an array containing the nodes rendered from the supplied markup. The
* optionally supplied `handleScript` function will be invoked once for each
* <script> element that is rendered. If no `handleScript` function is supplied,
* an exception is thrown if any <script> elements are rendered.
*
* @param {string} markup A string of valid HTML markup.
* @param {?function} handleScript Invoked once for each rendered <script>.
* @return {array<DOMElement|DOMTextNode>} An array of rendered nodes.
*/
function createNodesFromMarkup(markup, handleScript) {
var node = dummyNode;
!!!dummyNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createNodesFromMarkup dummy not initialized') : invariant(false) : undefined;
var nodeName = getNodeName(markup);
var wrap = nodeName && getMarkupWrap(nodeName);
if (wrap) {
node.innerHTML = wrap[1] + markup + wrap[2];
var wrapDepth = wrap[0];
while (wrapDepth--) {
node = node.lastChild;
}
} else {
node.innerHTML = markup;
}
var scripts = node.getElementsByTagName('script');
if (scripts.length) {
!handleScript ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createNodesFromMarkup(...): Unexpected <script> element rendered.') : invariant(false) : undefined;
createArrayFromMixed(scripts).forEach(handleScript);
}
var nodes = createArrayFromMixed(node.childNodes);
while (node.lastChild) {
node.removeChild(node.lastChild);
}
return nodes;
}
module.exports = createNodesFromMarkup;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule createArrayFromMixed
* @typechecks
*/
'use strict';
var toArray = __webpack_require__(12);
/**
* Perform a heuristic test to determine if an object is "array-like".
*
* A monk asked Joshu, a Zen master, "Has a dog Buddha nature?"
* Joshu replied: "Mu."
*
* This function determines if its argument has "array nature": it returns
* true if the argument is an actual array, an `arguments' object, or an
* HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()).
*
* It will return false for other array-like objects like Filelist.
*
* @param {*} obj
* @return {boolean}
*/
function hasArrayNature(obj) {
return(
// not null/false
!!obj && (
// arrays are objects, NodeLists are functions in Safari
typeof obj == 'object' || typeof obj == 'function') &&
// quacks like an array
'length' in obj &&
// not window
!('setInterval' in obj) &&
// no DOM node should be considered an array-like
// a 'select' element has 'length' and 'item' properties on IE8
typeof obj.nodeType != 'number' && (
// a real array
Array.isArray(obj) ||
// arguments
'callee' in obj ||
// HTMLCollection/NodeList
'item' in obj)
);
}
/**
* Ensure that the argument is an array by wrapping it in an array if it is not.
* Creates a copy of the argument if it is already an array.
*
* This is mostly useful idiomatically:
*
* var createArrayFromMixed = require('createArrayFromMixed');
*
* function takesOneOrMoreThings(things) {
* things = createArrayFromMixed(things);
* ...
* }
*
* This allows you to treat `things' as an array, but accept scalars in the API.
*
* If you need to convert an array-like object, like `arguments`, into an array
* use toArray instead.
*
* @param {*} obj
* @return {array}
*/
function createArrayFromMixed(obj) {
if (!hasArrayNature(obj)) {
return [obj];
} else if (Array.isArray(obj)) {
return obj.slice();
} else {
return toArray(obj);
}
}
module.exports = createArrayFromMixed;
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule toArray
* @typechecks
*/
'use strict';
var invariant = __webpack_require__(13);
/**
* Convert array-like objects to arrays.
*
* This API assumes the caller knows the contents of the data type. For less
* well defined inputs use createArrayFromMixed.
*
* @param {object|function|filelist} obj
* @return {array}
*/
function toArray(obj) {
var length = obj.length;
// Some browse builtin objects can report typeof 'function' (e.g. NodeList in
// old versions of Safari).
!(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function')) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Array-like object expected') : invariant(false) : undefined;
!(typeof length === 'number') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object needs a length property') : invariant(false) : undefined;
!(length === 0 || length - 1 in obj) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object should have keys for indices') : invariant(false) : undefined;
// Old IE doesn't give collections access to hasOwnProperty. Assume inputs
// without method will throw during the slice call and skip straight to the
// fallback.
if (obj.hasOwnProperty) {
try {
return Array.prototype.slice.call(obj);
} catch (e) {
// IE < 9 does not support Array#slice on collections objects
}
}
// Fall back to copying key by key. This assumes all keys have a value,
// so will not preserve sparsely populated inputs.
var ret = Array(length);
for (var ii = 0; ii < length; ii++) {
ret[ii] = obj[ii];
}
return ret;
}
module.exports = toArray;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule invariant
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
function invariant(condition, format, a, b, c, d, e, f) {
if (process.env.NODE_ENV !== 'production') {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getMarkupWrap
*/
/*eslint-disable fb-www/unsafe-html */
'use strict';
var ExecutionEnvironment = __webpack_require__(9);
var invariant = __webpack_require__(13);
/**
* Dummy container used to detect which wraps are necessary.
*/
var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null;
/**
* Some browsers cannot use `innerHTML` to render certain elements standalone,
* so we wrap them, render the wrapped nodes, then extract the desired node.
*
* In IE8, certain elements cannot render alone, so wrap all elements ('*').
*/
var shouldWrap = {};
var selectWrap = [1, '<select multiple="true">', '</select>'];
var tableWrap = [1, '<table>', '</table>'];
var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>'];
var svgWrap = [1, '<svg xmlns="http://www.w3.org/2000/svg">', '</svg>'];
var markupWrap = {
'*': [1, '?<div>', '</div>'],
'area': [1, '<map>', '</map>'],
'col': [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'],
'legend': [1, '<fieldset>', '</fieldset>'],
'param': [1, '<object>', '</object>'],
'tr': [2, '<table><tbody>', '</tbody></table>'],
'optgroup': selectWrap,
'option': selectWrap,
'caption': tableWrap,
'colgroup': tableWrap,
'tbody': tableWrap,
'tfoot': tableWrap,
'thead': tableWrap,
'td': trWrap,
'th': trWrap
};
// Initialize the SVG elements since we know they'll always need to be wrapped
// consistently. If they are created inside a <div> they will be initialized in
// the wrong namespace (and will not display).
var svgElements = ['circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'text', 'tspan'];
svgElements.forEach(function (nodeName) {
markupWrap[nodeName] = svgWrap;
shouldWrap[nodeName] = true;
});
/**
* Gets the markup wrap configuration for the supplied `nodeName`.
*
* NOTE: This lazily detects which wraps are necessary for the current browser.
*
* @param {string} nodeName Lowercase `nodeName`.
* @return {?array} Markup wrap configuration, if applicable.
*/
function getMarkupWrap(nodeName) {
!!!dummyNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Markup wrapping node not initialized') : invariant(false) : undefined;
if (!markupWrap.hasOwnProperty(nodeName)) {
nodeName = '*';
}
if (!shouldWrap.hasOwnProperty(nodeName)) {
if (nodeName === '*') {
dummyNode.innerHTML = '<link />';
} else {
dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>';
}
shouldWrap[nodeName] = !dummyNode.firstChild;
}
return shouldWrap[nodeName] ? markupWrap[nodeName] : null;
}
module.exports = getMarkupWrap;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 15 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule emptyFunction
*/
"use strict";
function makeEmptyFunction(arg) {
return function () {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
function emptyFunction() {}
emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function () {
return this;
};
emptyFunction.thatReturnsArgument = function (arg) {
return arg;
};
module.exports = emptyFunction;
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactMultiChildUpdateTypes
*/
'use strict';
var keyMirror = __webpack_require__(17);
/**
* When a component's children are updated, a series of update configuration
* objects are created in order to batch and serialize the required changes.
*
* Enumerates all the possible types of update configurations.
*
* @internal
*/
var ReactMultiChildUpdateTypes = keyMirror({
INSERT_MARKUP: null,
MOVE_EXISTING: null,
REMOVE_NODE: null,
SET_MARKUP: null,
TEXT_CONTENT: null
});
module.exports = ReactMultiChildUpdateTypes;
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule keyMirror
* @typechecks static-only
*/
'use strict';
var invariant = __webpack_require__(13);
/**
* Constructs an enumeration with keys equal to their value.
*
* For example:
*
* var COLORS = keyMirror({blue: null, red: null});
* var myColor = COLORS.blue;
* var isColorValid = !!COLORS[myColor];
*
* The last line could not be performed if the values of the generated enum were
* not equal to their keys.
*
* Input: {key1: val1, key2: val2}
* Output: {key1: key1, key2: key2}
*
* @param {object} obj
* @return {object}
*/
var keyMirror = function (obj) {
var ret = {};
var key;
!(obj instanceof Object && !Array.isArray(obj)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'keyMirror(...): Argument must be an object.') : invariant(false) : undefined;
for (key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
ret[key] = key;
}
return ret;
};
module.exports = keyMirror;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactPerf
* @typechecks static-only
*/
'use strict';
/**
* ReactPerf is a general AOP system designed to measure performance. This
* module only has the hooks: see ReactDefaultPerf for the analysis tool.
*/
var ReactPerf = {
/**
* Boolean to enable/disable measurement. Set to false by default to prevent
* accidental logging and perf loss.
*/
enableMeasure: false,
/**
* Holds onto the measure function in use. By default, don't measure
* anything, but we'll override this if we inject a measure function.
*/
storedMeasure: _noMeasure,
/**
* @param {object} object
* @param {string} objectName
* @param {object<string>} methodNames
*/
measureMethods: function (object, objectName, methodNames) {
if (process.env.NODE_ENV !== 'production') {
for (var key in methodNames) {
if (!methodNames.hasOwnProperty(key)) {
continue;
}
object[key] = ReactPerf.measure(objectName, methodNames[key], object[key]);
}
}
},
/**
* Use this to wrap methods you want to measure. Zero overhead in production.
*
* @param {string} objName
* @param {string} fnName
* @param {function} func
* @return {function}
*/
measure: function (objName, fnName, func) {
if (process.env.NODE_ENV !== 'production') {
var measuredFunc = null;
var wrapper = function () {
if (ReactPerf.enableMeasure) {
if (!measuredFunc) {
measuredFunc = ReactPerf.storedMeasure(objName, fnName, func);
}
return measuredFunc.apply(this, arguments);
}
return func.apply(this, arguments);
};
wrapper.displayName = objName + '_' + fnName;
return wrapper;
}
return func;
},
injection: {
/**
* @param {function} measure
*/
injectMeasure: function (measure) {
ReactPerf.storedMeasure = measure;
}
}
};
/**
* Simply passes through the measured function, without measuring it.
*
* @param {string} objName
* @param {string} fnName
* @param {function} func
* @return {function}
*/
function _noMeasure(objName, fnName, func) {
return func;
}
module.exports = ReactPerf;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule setInnerHTML
*/
/* globals MSApp */
'use strict';
var ExecutionEnvironment = __webpack_require__(9);
var WHITESPACE_TEST = /^[ \r\n\t\f]/;
var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/;
/**
* Set the innerHTML property of a node, ensuring that whitespace is preserved
* even in IE8.
*
* @param {DOMElement} node
* @param {string} html
* @internal
*/
var setInnerHTML = function (node, html) {
node.innerHTML = html;
};
// Win8 apps: Allow all html to be inserted
if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {
setInnerHTML = function (node, html) {
MSApp.execUnsafeLocalFunction(function () {
node.innerHTML = html;
});
};
}
if (ExecutionEnvironment.canUseDOM) {
// IE8: When updating a just created node with innerHTML only leading
// whitespace is removed. When updating an existing node with innerHTML
// whitespace in root TextNodes is also collapsed.
// @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html
// Feature detection; only IE8 is known to behave improperly like this.
var testElement = document.createElement('div');
testElement.innerHTML = ' ';
if (testElement.innerHTML === '') {
setInnerHTML = function (node, html) {
// Magic theory: IE8 supposedly differentiates between added and updated
// nodes when processing innerHTML, innerHTML on updated nodes suffers
// from worse whitespace behavior. Re-adding a node like this triggers
// the initial and more favorable whitespace behavior.
// TODO: What to do on a detached node?
if (node.parentNode) {
node.parentNode.replaceChild(node, node);
}
// We also implement a workaround for non-visible tags disappearing into
// thin air on IE8, this only happens if there is no visible text
// in-front of the non-visible tags. Piggyback on the whitespace fix
// and simply check if any non-visible tags appear in the source.
if (WHITESPACE_TEST.test(html) || html[0] === '<' && NONVISIBLE_TEST.test(html)) {
// Recover leading whitespace by temporarily prepending any character.
// \uFEFF has the potential advantage of being zero-width/invisible.
// UglifyJS drops U+FEFF chars when parsing, so use String.fromCharCode
// in hopes that this is preserved even if "\uFEFF" is transformed to
// the actual Unicode character (by Babel, for example).
// https://github.com/mishoo/UglifyJS2/blob/v2.4.20/lib/parse.js#L216
node.innerHTML = String.fromCharCode(0xFEFF) + html;
// deleteData leaves an empty `TextNode` which offsets the index of all
// children. Definitely want to avoid this.
var textNode = node.firstChild;
if (textNode.data.length === 1) {
node.removeChild(textNode);
} else {
textNode.deleteData(0, 1);
}
} else {
node.innerHTML = html;
}
};
}
}
module.exports = setInnerHTML;
/***/ },
/* 20 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule setTextContent
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(9);
var escapeTextContentForBrowser = __webpack_require__(21);
var setInnerHTML = __webpack_require__(19);
/**
* Set the textContent property of a node, ensuring that whitespace is preserved
* even in IE8. innerText is a poor substitute for textContent and, among many
* issues, inserts <br> instead of the literal newline chars. innerHTML behaves
* as it should.
*
* @param {DOMElement} node
* @param {string} text
* @internal
*/
var setTextContent = function (node, text) {
node.textContent = text;
};
if (ExecutionEnvironment.canUseDOM) {
if (!('textContent' in document.documentElement)) {
setTextContent = function (node, text) {
setInnerHTML(node, escapeTextContentForBrowser(text));
};
}
}
module.exports = setTextContent;
/***/ },
/* 21 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule escapeTextContentForBrowser
*/
'use strict';
var ESCAPE_LOOKUP = {
'&': '&',
'>': '>',
'<': '<',
'"': '"',
'\'': '''
};
var ESCAPE_REGEX = /[&><"']/g;
function escaper(match) {
return ESCAPE_LOOKUP[match];
}
/**
* Escapes text to prevent scripting attacks.
*
* @param {*} text Text value to escape.
* @return {string} An escaped string.
*/
function escapeTextContentForBrowser(text) {
return ('' + text).replace(ESCAPE_REGEX, escaper);
}
module.exports = escapeTextContentForBrowser;
/***/ },
/* 22 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule DOMPropertyOperations
* @typechecks static-only
*/
'use strict';
var DOMProperty = __webpack_require__(23);
var ReactPerf = __webpack_require__(18);
var quoteAttributeValueForBrowser = __webpack_require__(24);
var warning = __webpack_require__(25);
// Simplified subset
var VALID_ATTRIBUTE_NAME_REGEX = /^[a-zA-Z_][\w\.\-]*$/;
var illegalAttributeNameCache = {};
var validatedAttributeNameCache = {};
function isAttributeNameSafe(attributeName) {
if (validatedAttributeNameCache.hasOwnProperty(attributeName)) {
return true;
}
if (illegalAttributeNameCache.hasOwnProperty(attributeName)) {
return false;
}
if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
validatedAttributeNameCache[attributeName] = true;
return true;
}
illegalAttributeNameCache[attributeName] = true;
process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid attribute name: `%s`', attributeName) : undefined;
return false;
}
function shouldIgnoreValue(propertyInfo, value) {
return value == null || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && isNaN(value) || propertyInfo.hasPositiveNumericValue && value < 1 || propertyInfo.hasOverloadedBooleanValue && value === false;
}
if (process.env.NODE_ENV !== 'production') {
var reactProps = {
children: true,
dangerouslySetInnerHTML: true,
key: true,
ref: true
};
var warnedProperties = {};
var warnUnknownProperty = function (name) {
if (reactProps.hasOwnProperty(name) && reactProps[name] || warnedProperties.hasOwnProperty(name) && warnedProperties[name]) {
return;
}
warnedProperties[name] = true;
var lowerCasedName = name.toLowerCase();
// data-* attributes should be lowercase; suggest the lowercase version
var standardName = DOMProperty.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null;
// For now, only warn when we have a suggested correction. This prevents
// logging too much when using transferPropsTo.
process.env.NODE_ENV !== 'production' ? warning(standardName == null, 'Unknown DOM property %s. Did you mean %s?', name, standardName) : undefined;
};
}
/**
* Operations for dealing with DOM properties.
*/
var DOMPropertyOperations = {
/**
* Creates markup for the ID property.
*
* @param {string} id Unescaped ID.
* @return {string} Markup string.
*/
createMarkupForID: function (id) {
return DOMProperty.ID_ATTRIBUTE_NAME + '=' + quoteAttributeValueForBrowser(id);
},
setAttributeForID: function (node, id) {
node.setAttribute(DOMProperty.ID_ATTRIBUTE_NAME, id);
},
/**
* Creates markup for a property.
*
* @param {string} name
* @param {*} value
* @return {?string} Markup string, or null if the property was invalid.
*/
createMarkupForProperty: function (name, value) {
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
if (propertyInfo) {
if (shouldIgnoreValue(propertyInfo, value)) {
return '';
}
var attributeName = propertyInfo.attributeName;
if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) {
return attributeName + '=""';
}
return attributeName + '=' + quoteAttributeValueForBrowser(value);
} else if (DOMProperty.isCustomAttribute(name)) {
if (value == null) {
return '';
}
return name + '=' + quoteAttributeValueForBrowser(value);
} else if (process.env.NODE_ENV !== 'production') {
warnUnknownProperty(name);
}
return null;
},
/**
* Creates markup for a custom property.
*
* @param {string} name
* @param {*} value
* @return {string} Markup string, or empty string if the property was invalid.
*/
createMarkupForCustomAttribute: function (name, value) {
if (!isAttributeNameSafe(name) || value == null) {
return '';
}
return name + '=' + quoteAttributeValueForBrowser(value);
},
/**
* Sets the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
* @param {*} value
*/
setValueForProperty: function (node, name, value) {
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
if (propertyInfo) {
var mutationMethod = propertyInfo.mutationMethod;
if (mutationMethod) {
mutationMethod(node, value);
} else if (shouldIgnoreValue(propertyInfo, value)) {
this.deleteValueForProperty(node, name);
} else if (propertyInfo.mustUseAttribute) {
var attributeName = propertyInfo.attributeName;
var namespace = propertyInfo.attributeNamespace;
// `setAttribute` with objects becomes only `[object]` in IE8/9,
// ('' + value) makes it output the correct toString()-value.
if (namespace) {
node.setAttributeNS(namespace, attributeName, '' + value);
} else if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) {
node.setAttribute(attributeName, '');
} else {
node.setAttribute(attributeName, '' + value);
}
} else {
var propName = propertyInfo.propertyName;
// Must explicitly cast values for HAS_SIDE_EFFECTS-properties to the
// property type before comparing; only `value` does and is string.
if (!propertyInfo.hasSideEffects || '' + node[propName] !== '' + value) {
// Contrary to `setAttribute`, object properties are properly
// `toString`ed by IE8/9.
node[propName] = value;
}
}
} else if (DOMProperty.isCustomAttribute(name)) {
DOMPropertyOperations.setValueForAttribute(node, name, value);
} else if (process.env.NODE_ENV !== 'production') {
warnUnknownProperty(name);
}
},
setValueForAttribute: function (node, name, value) {
if (!isAttributeNameSafe(name)) {
return;
}
if (value == null) {
node.removeAttribute(name);
} else {
node.setAttribute(name, '' + value);
}
},
/**
* Deletes the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
*/
deleteValueForProperty: function (node, name) {
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
if (propertyInfo) {
var mutationMethod = propertyInfo.mutationMethod;
if (mutationMethod) {
mutationMethod(node, undefined);
} else if (propertyInfo.mustUseAttribute) {
node.removeAttribute(propertyInfo.attributeName);
} else {
var propName = propertyInfo.propertyName;
var defaultValue = DOMProperty.getDefaultValueForProperty(node.nodeName, propName);
if (!propertyInfo.hasSideEffects || '' + node[propName] !== defaultValue) {
node[propName] = defaultValue;
}
}
} else if (DOMProperty.isCustomAttribute(name)) {
node.removeAttribute(name);
} else if (process.env.NODE_ENV !== 'production') {
warnUnknownProperty(name);
}
}
};
ReactPerf.measureMethods(DOMPropertyOperations, 'DOMPropertyOperations', {
setValueForProperty: 'setValueForProperty',
setValueForAttribute: 'setValueForAttribute',
deleteValueForProperty: 'deleteValueForProperty'
});
module.exports = DOMPropertyOperations;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule DOMProperty
* @typechecks static-only
*/
'use strict';
var invariant = __webpack_require__(13);
function checkMask(value, bitmask) {
return (value & bitmask) === bitmask;
}
var DOMPropertyInjection = {
/**
* Mapping from normalized, camelcased property names to a configuration that
* specifies how the associated DOM property should be accessed or rendered.
*/
MUST_USE_ATTRIBUTE: 0x1,
MUST_USE_PROPERTY: 0x2,
HAS_SIDE_EFFECTS: 0x4,
HAS_BOOLEAN_VALUE: 0x8,
HAS_NUMERIC_VALUE: 0x10,
HAS_POSITIVE_NUMERIC_VALUE: 0x20 | 0x10,
HAS_OVERLOADED_BOOLEAN_VALUE: 0x40,
/**
* Inject some specialized knowledge about the DOM. This takes a config object
* with the following properties:
*
* isCustomAttribute: function that given an attribute name will return true
* if it can be inserted into the DOM verbatim. Useful for data-* or aria-*
* attributes where it's impossible to enumerate all of the possible
* attribute names,
*
* Properties: object mapping DOM property name to one of the
* DOMPropertyInjection constants or null. If your attribute isn't in here,
* it won't get written to the DOM.
*
* DOMAttributeNames: object mapping React attribute name to the DOM
* attribute name. Attribute names not specified use the **lowercase**
* normalized name.
*
* DOMAttributeNamespaces: object mapping React attribute name to the DOM
* attribute namespace URL. (Attribute names not specified use no namespace.)
*
* DOMPropertyNames: similar to DOMAttributeNames but for DOM properties.
* Property names not specified use the normalized name.
*
* DOMMutationMethods: Properties that require special mutation methods. If
* `value` is undefined, the mutation method should unset the property.
*
* @param {object} domPropertyConfig the config as described above.
*/
injectDOMPropertyConfig: function (domPropertyConfig) {
var Injection = DOMPropertyInjection;
var Properties = domPropertyConfig.Properties || {};
var DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {};
var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {};
var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {};
var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {};
if (domPropertyConfig.isCustomAttribute) {
DOMProperty._isCustomAttributeFunctions.push(domPropertyConfig.isCustomAttribute);
}
for (var propName in Properties) {
!!DOMProperty.properties.hasOwnProperty(propName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property ' + '\'%s\' which has already been injected. You may be accidentally ' + 'injecting the same DOM property config twice, or you may be ' + 'injecting two configs that have conflicting property names.', propName) : invariant(false) : undefined;
var lowerCased = propName.toLowerCase();
var propConfig = Properties[propName];
var propertyInfo = {
attributeName: lowerCased,
attributeNamespace: null,
propertyName: propName,
mutationMethod: null,
mustUseAttribute: checkMask(propConfig, Injection.MUST_USE_ATTRIBUTE),
mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY),
hasSideEffects: checkMask(propConfig, Injection.HAS_SIDE_EFFECTS),
hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE),
hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE),
hasPositiveNumericValue: checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE),
hasOverloadedBooleanValue: checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE)
};
!(!propertyInfo.mustUseAttribute || !propertyInfo.mustUseProperty) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Cannot require using both attribute and property: %s', propName) : invariant(false) : undefined;
!(propertyInfo.mustUseProperty || !propertyInfo.hasSideEffects) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Properties that have side effects must use property: %s', propName) : invariant(false) : undefined;
!(propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Value can be one of boolean, overloaded boolean, or ' + 'numeric value, but not a combination: %s', propName) : invariant(false) : undefined;
if (process.env.NODE_ENV !== 'production') {
DOMProperty.getPossibleStandardName[lowerCased] = propName;
}
if (DOMAttributeNames.hasOwnProperty(propName)) {
var attributeName = DOMAttributeNames[propName];
propertyInfo.attributeName = attributeName;
if (process.env.NODE_ENV !== 'production') {
DOMProperty.getPossibleStandardName[attributeName] = propName;
}
}
if (DOMAttributeNamespaces.hasOwnProperty(propName)) {
propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName];
}
if (DOMPropertyNames.hasOwnProperty(propName)) {
propertyInfo.propertyName = DOMPropertyNames[propName];
}
if (DOMMutationMethods.hasOwnProperty(propName)) {
propertyInfo.mutationMethod = DOMMutationMethods[propName];
}
DOMProperty.properties[propName] = propertyInfo;
}
}
};
var defaultValueCache = {};
/**
* DOMProperty exports lookup objects that can be used like functions:
*
* > DOMProperty.isValid['id']
* true
* > DOMProperty.isValid['foobar']
* undefined
*
* Although this may be confusing, it performs better in general.
*
* @see http://jsperf.com/key-exists
* @see http://jsperf.com/key-missing
*/
var DOMProperty = {
ID_ATTRIBUTE_NAME: 'data-reactid',
/**
* Map from property "standard name" to an object with info about how to set
* the property in the DOM. Each object contains:
*
* attributeName:
* Used when rendering markup or with `*Attribute()`.
* attributeNamespace
* propertyName:
* Used on DOM node instances. (This includes properties that mutate due to
* external factors.)
* mutationMethod:
* If non-null, used instead of the property or `setAttribute()` after
* initial render.
* mustUseAttribute:
* Whether the property must be accessed and mutated using `*Attribute()`.
* (This includes anything that fails `<propName> in <element>`.)
* mustUseProperty:
* Whether the property must be accessed and mutated as an object property.
* hasSideEffects:
* Whether or not setting a value causes side effects such as triggering
* resources to be loaded or text selection changes. If true, we read from
* the DOM before updating to ensure that the value is only set if it has
* changed.
* hasBooleanValue:
* Whether the property should be removed when set to a falsey value.
* hasNumericValue:
* Whether the property must be numeric or parse as a numeric and should be
* removed when set to a falsey value.
* hasPositiveNumericValue:
* Whether the property must be positive numeric or parse as a positive
* numeric and should be removed when set to a falsey value.
* hasOverloadedBooleanValue:
* Whether the property can be used as a flag as well as with a value.
* Removed when strictly equal to false; present without a value when
* strictly equal to true; present with a value otherwise.
*/
properties: {},
/**
* Mapping from lowercase property names to the properly cased version, used
* to warn in the case of missing properties. Available only in __DEV__.
* @type {Object}
*/
getPossibleStandardName: process.env.NODE_ENV !== 'production' ? {} : null,
/**
* All of the isCustomAttribute() functions that have been injected.
*/
_isCustomAttributeFunctions: [],
/**
* Checks whether a property name is a custom attribute.
* @method
*/
isCustomAttribute: function (attributeName) {
for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) {
var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i];
if (isCustomAttributeFn(attributeName)) {
return true;
}
}
return false;
},
/**
* Returns the default property value for a DOM property (i.e., not an
* attribute). Most default values are '' or false, but not all. Worse yet,
* some (in particular, `type`) vary depending on the type of element.
*
* TODO: Is it better to grab all the possible properties when creating an
* element to avoid having to create the same element twice?
*/
getDefaultValueForProperty: function (nodeName, prop) {
var nodeDefaults = defaultValueCache[nodeName];
var testElement;
if (!nodeDefaults) {
defaultValueCache[nodeName] = nodeDefaults = {};
}
if (!(prop in nodeDefaults)) {
testElement = document.createElement(nodeName);
nodeDefaults[prop] = testElement[prop];
}
return nodeDefaults[prop];
},
injection: DOMPropertyInjection
};
module.exports = DOMProperty;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule quoteAttributeValueForBrowser
*/
'use strict';
var escapeTextContentForBrowser = __webpack_require__(21);
/**
* Escapes attribute value to prevent scripting attacks.
*
* @param {*} value Value to escape.
* @return {string} An escaped string.
*/
function quoteAttributeValueForBrowser(value) {
return '"' + escapeTextContentForBrowser(value) + '"';
}
module.exports = quoteAttributeValueForBrowser;
/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule warning
*/
'use strict';
var emptyFunction = __webpack_require__(15);
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var warning = emptyFunction;
if (process.env.NODE_ENV !== 'production') {
warning = function (condition, format) {
for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
if (format === undefined) {
throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (format.indexOf('Failed Composite propType: ') === 0) {
return; // Ignore CompositeComponent proptype check.
}
if (!condition) {
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
}
};
}
module.exports = warning;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactComponentBrowserEnvironment
*/
'use strict';
var ReactDOMIDOperations = __webpack_require__(27);
var ReactMount = __webpack_require__(28);
/**
* Abstracts away all functionality of the reconciler that requires knowledge of
* the browser context. TODO: These callers should be refactored to avoid the
* need for this injection.
*/
var ReactComponentBrowserEnvironment = {
processChildrenUpdates: ReactDOMIDOperations.dangerouslyProcessChildrenUpdates,
replaceNodeWithMarkupByID: ReactDOMIDOperations.dangerouslyReplaceNodeWithMarkupByID,
/**
* If a particular environment requires that some resources be cleaned up,
* specify this in the injected Mixin. In the DOM, we would likely want to
* purge any cached node ID lookups.
*
* @private
*/
unmountIDFromEnvironment: function (rootNodeID) {
ReactMount.purgeID(rootNodeID);
}
};
module.exports = ReactComponentBrowserEnvironment;
/***/ },
/* 27 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMIDOperations
* @typechecks static-only
*/
'use strict';
var DOMChildrenOperations = __webpack_require__(7);
var DOMPropertyOperations = __webpack_require__(22);
var ReactMount = __webpack_require__(28);
var ReactPerf = __webpack_require__(18);
var invariant = __webpack_require__(13);
/**
* Errors for properties that should not be updated with `updatePropertyByID()`.
*
* @type {object}
* @private
*/
var INVALID_PROPERTY_ERRORS = {
dangerouslySetInnerHTML: '`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.',
style: '`style` must be set using `updateStylesByID()`.'
};
/**
* Operations used to process updates to DOM nodes.
*/
var ReactDOMIDOperations = {
/**
* Updates a DOM node with new property values. This should only be used to
* update DOM properties in `DOMProperty`.
*
* @param {string} id ID of the node to update.
* @param {string} name A valid property name, see `DOMProperty`.
* @param {*} value New value of the property.
* @internal
*/
updatePropertyByID: function (id, name, value) {
var node = ReactMount.getNode(id);
!!INVALID_PROPERTY_ERRORS.hasOwnProperty(name) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'updatePropertyByID(...): %s', INVALID_PROPERTY_ERRORS[name]) : invariant(false) : undefined;
// If we're updating to null or undefined, we should remove the property
// from the DOM node instead of inadvertantly setting to a string. This
// brings us in line with the same behavior we have on initial render.
if (value != null) {
DOMPropertyOperations.setValueForProperty(node, name, value);
} else {
DOMPropertyOperations.deleteValueForProperty(node, name);
}
},
/**
* Replaces a DOM node that exists in the document with markup.
*
* @param {string} id ID of child to be replaced.
* @param {string} markup Dangerous markup to inject in place of child.
* @internal
* @see {Danger.dangerouslyReplaceNodeWithMarkup}
*/
dangerouslyReplaceNodeWithMarkupByID: function (id, markup) {
var node = ReactMount.getNode(id);
DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup(node, markup);
},
/**
* Updates a component's children by processing a series of updates.
*
* @param {array<object>} updates List of update configurations.
* @param {array<string>} markup List of markup strings.
* @internal
*/
dangerouslyProcessChildrenUpdates: function (updates, markup) {
for (var i = 0; i < updates.length; i++) {
updates[i].parentNode = ReactMount.getNode(updates[i].parentID);
}
DOMChildrenOperations.processUpdates(updates, markup);
}
};
ReactPerf.measureMethods(ReactDOMIDOperations, 'ReactDOMIDOperations', {
dangerouslyReplaceNodeWithMarkupByID: 'dangerouslyReplaceNodeWithMarkupByID',
dangerouslyProcessChildrenUpdates: 'dangerouslyProcessChildrenUpdates'
});
module.exports = ReactDOMIDOperations;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactMount
*/
'use strict';
var DOMProperty = __webpack_require__(23);
var ReactBrowserEventEmitter = __webpack_require__(29);
var ReactCurrentOwner = __webpack_require__(5);
var ReactDOMFeatureFlags = __webpack_require__(41);
var ReactElement = __webpack_require__(42);
var ReactEmptyComponentRegistry = __webpack_require__(44);
var ReactInstanceHandles = __webpack_require__(45);
var ReactInstanceMap = __webpack_require__(47);
var ReactMarkupChecksum = __webpack_require__(48);
var ReactPerf = __webpack_require__(18);
var ReactReconciler = __webpack_require__(50);
var ReactUpdateQueue = __webpack_require__(53);
var ReactUpdates = __webpack_require__(54);
var assign = __webpack_require__(39);
var emptyObject = __webpack_require__(58);
var containsNode = __webpack_require__(59);
var instantiateReactComponent = __webpack_require__(62);
var invariant = __webpack_require__(13);
var setInnerHTML = __webpack_require__(19);
var shouldUpdateReactComponent = __webpack_require__(67);
var validateDOMNesting = __webpack_require__(70);
var warning = __webpack_require__(25);
var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME;
var nodeCache = {};
var ELEMENT_NODE_TYPE = 1;
var DOC_NODE_TYPE = 9;
var DOCUMENT_FRAGMENT_NODE_TYPE = 11;
var ownerDocumentContextKey = '__ReactMount_ownerDocument$' + Math.random().toString(36).slice(2);
/** Mapping from reactRootID to React component instance. */
var instancesByReactRootID = {};
/** Mapping from reactRootID to `container` nodes. */
var containersByReactRootID = {};
if (process.env.NODE_ENV !== 'production') {
/** __DEV__-only mapping from reactRootID to root elements. */
var rootElementsByReactRootID = {};
}
// Used to store breadth-first search state in findComponentRoot.
var findComponentRootReusableArray = [];
/**
* Finds the index of the first character
* that's not common between the two given strings.
*
* @return {number} the index of the character where the strings diverge
*/
function firstDifferenceIndex(string1, string2) {
var minLen = Math.min(string1.length, string2.length);
for (var i = 0; i < minLen; i++) {
if (string1.charAt(i) !== string2.charAt(i)) {
return i;
}
}
return string1.length === string2.length ? -1 : minLen;
}
/**
* @param {DOMElement|DOMDocument} container DOM element that may contain
* a React component
* @return {?*} DOM element that may have the reactRoot ID, or null.
*/
function getReactRootElementInContainer(container) {
if (!container) {
return null;
}
if (container.nodeType === DOC_NODE_TYPE) {
return container.documentElement;
} else {
return container.firstChild;
}
}
/**
* @param {DOMElement} container DOM element that may contain a React component.
* @return {?string} A "reactRoot" ID, if a React component is rendered.
*/
function getReactRootID(container) {
var rootElement = getReactRootElementInContainer(container);
return rootElement && ReactMount.getID(rootElement);
}
/**
* Accessing node[ATTR_NAME] or calling getAttribute(ATTR_NAME) on a form
* element can return its control whose name or ID equals ATTR_NAME. All
* DOM nodes support `getAttributeNode` but this can also get called on
* other objects so just return '' if we're given something other than a
* DOM node (such as window).
*
* @param {?DOMElement|DOMWindow|DOMDocument|DOMTextNode} node DOM node.
* @return {string} ID of the supplied `domNode`.
*/
function getID(node) {
var id = internalGetID(node);
if (id) {
if (nodeCache.hasOwnProperty(id)) {
var cached = nodeCache[id];
if (cached !== node) {
!!isValid(cached, id) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactMount: Two valid but unequal nodes with the same `%s`: %s', ATTR_NAME, id) : invariant(false) : undefined;
nodeCache[id] = node;
}
} else {
nodeCache[id] = node;
}
}
return id;
}
function internalGetID(node) {
// If node is something like a window, document, or text node, none of
// which support attributes or a .getAttribute method, gracefully return
// the empty string, as if the attribute were missing.
return node && node.getAttribute && node.getAttribute(ATTR_NAME) || '';
}
/**
* Sets the React-specific ID of the given node.
*
* @param {DOMElement} node The DOM node whose ID will be set.
* @param {string} id The value of the ID attribute.
*/
function setID(node, id) {
var oldID = internalGetID(node);
if (oldID !== id) {
delete nodeCache[oldID];
}
node.setAttribute(ATTR_NAME, id);
nodeCache[id] = node;
}
/**
* Finds the node with the supplied React-generated DOM ID.
*
* @param {string} id A React-generated DOM ID.
* @return {DOMElement} DOM node with the suppled `id`.
* @internal
*/
function getNode(id) {
if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) {
nodeCache[id] = ReactMount.findReactNodeByID(id);
}
return nodeCache[id];
}
/**
* Finds the node with the supplied public React instance.
*
* @param {*} instance A public React instance.
* @return {?DOMElement} DOM node with the suppled `id`.
* @internal
*/
function getNodeFromInstance(instance) {
var id = ReactInstanceMap.get(instance)._rootNodeID;
if (ReactEmptyComponentRegistry.isNullComponentID(id)) {
return null;
}
if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) {
nodeCache[id] = ReactMount.findReactNodeByID(id);
}
return nodeCache[id];
}
/**
* A node is "valid" if it is contained by a currently mounted container.
*
* This means that the node does not have to be contained by a document in
* order to be considered valid.
*
* @param {?DOMElement} node The candidate DOM node.
* @param {string} id The expected ID of the node.
* @return {boolean} Whether the node is contained by a mounted container.
*/
function isValid(node, id) {
if (node) {
!(internalGetID(node) === id) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactMount: Unexpected modification of `%s`', ATTR_NAME) : invariant(false) : undefined;
var container = ReactMount.findReactContainerForID(id);
if (container && containsNode(container, node)) {
return true;
}
}
return false;
}
/**
* Causes the cache to forget about one React-specific ID.
*
* @param {string} id The ID to forget.
*/
function purgeID(id) {
delete nodeCache[id];
}
var deepestNodeSoFar = null;
function findDeepestCachedAncestorImpl(ancestorID) {
var ancestor = nodeCache[ancestorID];
if (ancestor && isValid(ancestor, ancestorID)) {
deepestNodeSoFar = ancestor;
} else {
// This node isn't populated in the cache, so presumably none of its
// descendants are. Break out of the loop.
return false;
}
}
/**
* Return the deepest cached node whose ID is a prefix of `targetID`.
*/
function findDeepestCachedAncestor(targetID) {
deepestNodeSoFar = null;
ReactInstanceHandles.traverseAncestors(targetID, findDeepestCachedAncestorImpl);
var foundNode = deepestNodeSoFar;
deepestNodeSoFar = null;
return foundNode;
}
/**
* Mounts this component and inserts it into the DOM.
*
* @param {ReactComponent} componentInstance The instance to mount.
* @param {string} rootID DOM ID of the root node.
* @param {DOMElement} container DOM element to mount into.
* @param {ReactReconcileTransaction} transaction
* @param {boolean} shouldReuseMarkup If true, do not insert markup
*/
function mountComponentIntoNode(componentInstance, rootID, container, transaction, shouldReuseMarkup, context) {
if (ReactDOMFeatureFlags.useCreateElement) {
context = assign({}, context);
if (container.nodeType === DOC_NODE_TYPE) {
context[ownerDocumentContextKey] = container;
} else {
context[ownerDocumentContextKey] = container.ownerDocument;
}
}
if (process.env.NODE_ENV !== 'production') {
if (context === emptyObject) {
context = {};
}
var tag = container.nodeName.toLowerCase();
context[validateDOMNesting.ancestorInfoContextKey] = validateDOMNesting.updatedAncestorInfo(null, tag, null);
}
var markup = ReactReconciler.mountComponent(componentInstance, rootID, transaction, context);
componentInstance._renderedComponent._topLevelWrapper = componentInstance;
ReactMount._mountImageIntoNode(markup, container, shouldReuseMarkup, transaction);
}
/**
* Batched mount.
*
* @param {ReactComponent} componentInstance The instance to mount.
* @param {string} rootID DOM ID of the root node.
* @param {DOMElement} container DOM element to mount into.
* @param {boolean} shouldReuseMarkup If true, do not insert markup
*/
function batchedMountComponentIntoNode(componentInstance, rootID, container, shouldReuseMarkup, context) {
var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(
/* forceHTML */shouldReuseMarkup);
transaction.perform(mountComponentIntoNode, null, componentInstance, rootID, container, transaction, shouldReuseMarkup, context);
ReactUpdates.ReactReconcileTransaction.release(transaction);
}
/**
* Unmounts a component and removes it from the DOM.
*
* @param {ReactComponent} instance React component instance.
* @param {DOMElement} container DOM element to unmount from.
* @final
* @internal
* @see {ReactMount.unmountComponentAtNode}
*/
function unmountComponentFromNode(instance, container) {
ReactReconciler.unmountComponent(instance);
if (container.nodeType === DOC_NODE_TYPE) {
container = container.documentElement;
}
// http://jsperf.com/emptying-a-node
while (container.lastChild) {
container.removeChild(container.lastChild);
}
}
/**
* True if the supplied DOM node has a direct React-rendered child that is
* not a React root element. Useful for warning in `render`,
* `unmountComponentAtNode`, etc.
*
* @param {?DOMElement} node The candidate DOM node.
* @return {boolean} True if the DOM element contains a direct child that was
* rendered by React but is not a root element.
* @internal
*/
function hasNonRootReactChild(node) {
var reactRootID = getReactRootID(node);
return reactRootID ? reactRootID !== ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID) : false;
}
/**
* Returns the first (deepest) ancestor of a node which is rendered by this copy
* of React.
*/
function findFirstReactDOMImpl(node) {
// This node might be from another React instance, so we make sure not to
// examine the node cache here
for (; node && node.parentNode !== node; node = node.parentNode) {
if (node.nodeType !== 1) {
// Not a DOMElement, therefore not a React component
continue;
}
var nodeID = internalGetID(node);
if (!nodeID) {
continue;
}
var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID);
// If containersByReactRootID contains the container we find by crawling up
// the tree, we know that this instance of React rendered the node.
// nb. isValid's strategy (with containsNode) does not work because render
// trees may be nested and we don't want a false positive in that case.
var current = node;
var lastID;
do {
lastID = internalGetID(current);
current = current.parentNode;
if (current == null) {
// The passed-in node has been detached from the container it was
// originally rendered into.
return null;
}
} while (lastID !== reactRootID);
if (current === containersByReactRootID[reactRootID]) {
return node;
}
}
return null;
}
/**
* Temporary (?) hack so that we can store all top-level pending updates on
* composites instead of having to worry about different types of components
* here.
*/
var TopLevelWrapper = function () {};
TopLevelWrapper.prototype.isReactComponent = {};
if (process.env.NODE_ENV !== 'production') {
TopLevelWrapper.displayName = 'TopLevelWrapper';
}
TopLevelWrapper.prototype.render = function () {
// this.props is actually a ReactElement
return this.props;
};
/**
* Mounting is the process of initializing a React component by creating its
* representative DOM elements and inserting them into a supplied `container`.
* Any prior content inside `container` is destroyed in the process.
*
* ReactMount.render(
* component,
* document.getElementById('container')
* );
*
* <div id="container"> <-- Supplied `container`.
* <div data-reactid=".3"> <-- Rendered reactRoot of React
* // ... component.
* </div>
* </div>
*
* Inside of `container`, the first element rendered is the "reactRoot".
*/
var ReactMount = {
TopLevelWrapper: TopLevelWrapper,
/** Exposed for debugging purposes **/
_instancesByReactRootID: instancesByReactRootID,
/**
* This is a hook provided to support rendering React components while
* ensuring that the apparent scroll position of its `container` does not
* change.
*
* @param {DOMElement} container The `container` being rendered into.
* @param {function} renderCallback This must be called once to do the render.
*/
scrollMonitor: function (container, renderCallback) {
renderCallback();
},
/**
* Take a component that's already mounted into the DOM and replace its props
* @param {ReactComponent} prevComponent component instance already in the DOM
* @param {ReactElement} nextElement component instance to render
* @param {DOMElement} container container to render into
* @param {?function} callback function triggered on completion
*/
_updateRootComponent: function (prevComponent, nextElement, container, callback) {
ReactMount.scrollMonitor(container, function () {
ReactUpdateQueue.enqueueElementInternal(prevComponent, nextElement);
if (callback) {
ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback);
}
});
if (process.env.NODE_ENV !== 'production') {
// Record the root element in case it later gets transplanted.
rootElementsByReactRootID[getReactRootID(container)] = getReactRootElementInContainer(container);
}
return prevComponent;
},
/**
* Register a component into the instance map and starts scroll value
* monitoring
* @param {ReactComponent} nextComponent component instance to render
* @param {DOMElement} container container to render into
* @return {string} reactRoot ID prefix
*/
_registerComponent: function (nextComponent, container) {
!(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '_registerComponent(...): Target container is not a DOM element.') : invariant(false) : undefined;
ReactBrowserEventEmitter.ensureScrollValueMonitoring();
var reactRootID = ReactMount.registerContainer(container);
instancesByReactRootID[reactRootID] = nextComponent;
return reactRootID;
},
/**
* Render a new component into the DOM.
* @param {ReactElement} nextElement element to render
* @param {DOMElement} container container to render into
* @param {boolean} shouldReuseMarkup if we should skip the markup insertion
* @return {ReactComponent} nextComponent
*/
_renderNewRootComponent: function (nextElement, container, shouldReuseMarkup, context) {
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case.
process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : undefined;
var componentInstance = instantiateReactComponent(nextElement, null);
var reactRootID = ReactMount._registerComponent(componentInstance, container);
// The initial render is synchronous but any updates that happen during
// rendering, in componentWillMount or componentDidMount, will be batched
// according to the current batching strategy.
ReactUpdates.batchedUpdates(batchedMountComponentIntoNode, componentInstance, reactRootID, container, shouldReuseMarkup, context);
if (process.env.NODE_ENV !== 'production') {
// Record the root element in case it later gets transplanted.
rootElementsByReactRootID[reactRootID] = getReactRootElementInContainer(container);
}
return componentInstance;
},
/**
* Renders a React component into the DOM in the supplied `container`.
*
* If the React component was previously rendered into `container`, this will
* perform an update on it and only mutate the DOM as necessary to reflect the
* latest React component.
*
* @param {ReactComponent} parentComponent The conceptual parent of this render tree.
* @param {ReactElement} nextElement Component element to render.
* @param {DOMElement} container DOM element to render into.
* @param {?function} callback function triggered on completion
* @return {ReactComponent} Component instance rendered in `container`.
*/
renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) {
!(parentComponent != null && parentComponent._reactInternalInstance != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'parentComponent must be a valid React Component') : invariant(false) : undefined;
return ReactMount._renderSubtreeIntoContainer(parentComponent, nextElement, container, callback);
},
_renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) {
!ReactElement.isValidElement(nextElement) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOM.render(): Invalid component element.%s', typeof nextElement === 'string' ? ' Instead of passing an element string, make sure to instantiate ' + 'it by passing it to React.createElement.' : typeof nextElement === 'function' ? ' Instead of passing a component class, make sure to instantiate ' + 'it by passing it to React.createElement.' :
// Check if it quacks like an element
nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : invariant(false) : undefined;
process.env.NODE_ENV !== 'production' ? warning(!container || !container.tagName || container.tagName.toUpperCase() !== 'BODY', 'render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.') : undefined;
var nextWrappedElement = new ReactElement(TopLevelWrapper, null, null, null, null, null, nextElement);
var prevComponent = instancesByReactRootID[getReactRootID(container)];
if (prevComponent) {
var prevWrappedElement = prevComponent._currentElement;
var prevElement = prevWrappedElement.props;
if (shouldUpdateReactComponent(prevElement, nextElement)) {
var publicInst = prevComponent._renderedComponent.getPublicInstance();
var updatedCallback = callback && function () {
callback.call(publicInst);
};
ReactMount._updateRootComponent(prevComponent, nextWrappedElement, container, updatedCallback);
return publicInst;
} else {
ReactMount.unmountComponentAtNode(container);
}
}
var reactRootElement = getReactRootElementInContainer(container);
var containerHasReactMarkup = reactRootElement && !!internalGetID(reactRootElement);
var containerHasNonRootReactChild = hasNonRootReactChild(container);
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(!containerHasNonRootReactChild, 'render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.') : undefined;
if (!containerHasReactMarkup || reactRootElement.nextSibling) {
var rootElementSibling = reactRootElement;
while (rootElementSibling) {
if (internalGetID(rootElementSibling)) {
process.env.NODE_ENV !== 'production' ? warning(false, 'render(): Target node has markup rendered by React, but there ' + 'are unrelated nodes as well. This is most commonly caused by ' + 'white-space inserted around server-rendered markup.') : undefined;
break;
}
rootElementSibling = rootElementSibling.nextSibling;
}
}
}
var shouldReuseMarkup = containerHasReactMarkup && !prevComponent && !containerHasNonRootReactChild;
var component = ReactMount._renderNewRootComponent(nextWrappedElement, container, shouldReuseMarkup, parentComponent != null ? parentComponent._reactInternalInstance._processChildContext(parentComponent._reactInternalInstance._context) : emptyObject)._renderedComponent.getPublicInstance();
if (callback) {
callback.call(component);
}
return component;
},
/**
* Renders a React component into the DOM in the supplied `container`.
*
* If the React component was previously rendered into `container`, this will
* perform an update on it and only mutate the DOM as necessary to reflect the
* latest React component.
*
* @param {ReactElement} nextElement Component element to render.
* @param {DOMElement} container DOM element to render into.
* @param {?function} callback function triggered on completion
* @return {ReactComponent} Component instance rendered in `container`.
*/
render: function (nextElement, container, callback) {
return ReactMount._renderSubtreeIntoContainer(null, nextElement, container, callback);
},
/**
* Registers a container node into which React components will be rendered.
* This also creates the "reactRoot" ID that will be assigned to the element
* rendered within.
*
* @param {DOMElement} container DOM element to register as a container.
* @return {string} The "reactRoot" ID of elements rendered within.
*/
registerContainer: function (container) {
var reactRootID = getReactRootID(container);
if (reactRootID) {
// If one exists, make sure it is a valid "reactRoot" ID.
reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID);
}
if (!reactRootID) {
// No valid "reactRoot" ID found, create one.
reactRootID = ReactInstanceHandles.createReactRootID();
}
containersByReactRootID[reactRootID] = container;
return reactRootID;
},
/**
* Unmounts and destroys the React component rendered in the `container`.
*
* @param {DOMElement} container DOM element containing a React component.
* @return {boolean} True if a component was found in and unmounted from
* `container`
*/
unmountComponentAtNode: function (container) {
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case. (Strictly speaking, unmounting won't cause a
// render but we still don't expect to be in a render call here.)
process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, 'unmountComponentAtNode(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from render ' + 'is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : undefined;
!(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'unmountComponentAtNode(...): Target container is not a DOM element.') : invariant(false) : undefined;
var reactRootID = getReactRootID(container);
var component = instancesByReactRootID[reactRootID];
if (!component) {
// Check if the node being unmounted was rendered by React, but isn't a
// root node.
var containerHasNonRootReactChild = hasNonRootReactChild(container);
// Check if the container itself is a React root node.
var containerID = internalGetID(container);
var isContainerReactRoot = containerID && containerID === ReactInstanceHandles.getReactRootIDFromNodeID(containerID);
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(!containerHasNonRootReactChild, 'unmountComponentAtNode(): The node you\'re attempting to unmount ' + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.') : undefined;
}
return false;
}
ReactUpdates.batchedUpdates(unmountComponentFromNode, component, container);
delete instancesByReactRootID[reactRootID];
delete containersByReactRootID[reactRootID];
if (process.env.NODE_ENV !== 'production') {
delete rootElementsByReactRootID[reactRootID];
}
return true;
},
/**
* Finds the container DOM element that contains React component to which the
* supplied DOM `id` belongs.
*
* @param {string} id The ID of an element rendered by a React component.
* @return {?DOMElement} DOM element that contains the `id`.
*/
findReactContainerForID: function (id) {
var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(id);
var container = containersByReactRootID[reactRootID];
if (process.env.NODE_ENV !== 'production') {
var rootElement = rootElementsByReactRootID[reactRootID];
if (rootElement && rootElement.parentNode !== container) {
process.env.NODE_ENV !== 'production' ? warning(
// Call internalGetID here because getID calls isValid which calls
// findReactContainerForID (this function).
internalGetID(rootElement) === reactRootID, 'ReactMount: Root element ID differed from reactRootID.') : undefined;
var containerChild = container.firstChild;
if (containerChild && reactRootID === internalGetID(containerChild)) {
// If the container has a new child with the same ID as the old
// root element, then rootElementsByReactRootID[reactRootID] is
// just stale and needs to be updated. The case that deserves a
// warning is when the container is empty.
rootElementsByReactRootID[reactRootID] = containerChild;
} else {
process.env.NODE_ENV !== 'production' ? warning(false, 'ReactMount: Root element has been removed from its original ' + 'container. New container: %s', rootElement.parentNode) : undefined;
}
}
}
return container;
},
/**
* Finds an element rendered by React with the supplied ID.
*
* @param {string} id ID of a DOM node in the React component.
* @return {DOMElement} Root DOM node of the React component.
*/
findReactNodeByID: function (id) {
var reactRoot = ReactMount.findReactContainerForID(id);
return ReactMount.findComponentRoot(reactRoot, id);
},
/**
* Traverses up the ancestors of the supplied node to find a node that is a
* DOM representation of a React component rendered by this copy of React.
*
* @param {*} node
* @return {?DOMEventTarget}
* @internal
*/
getFirstReactDOM: function (node) {
return findFirstReactDOMImpl(node);
},
/**
* Finds a node with the supplied `targetID` inside of the supplied
* `ancestorNode`. Exploits the ID naming scheme to perform the search
* quickly.
*
* @param {DOMEventTarget} ancestorNode Search from this root.
* @pararm {string} targetID ID of the DOM representation of the component.
* @return {DOMEventTarget} DOM node with the supplied `targetID`.
* @internal
*/
findComponentRoot: function (ancestorNode, targetID) {
var firstChildren = findComponentRootReusableArray;
var childIndex = 0;
var deepestAncestor = findDeepestCachedAncestor(targetID) || ancestorNode;
if (process.env.NODE_ENV !== 'production') {
// This will throw on the next line; give an early warning
process.env.NODE_ENV !== 'production' ? warning(deepestAncestor != null, 'React can\'t find the root component node for data-reactid value ' + '`%s`. If you\'re seeing this message, it probably means that ' + 'you\'ve loaded two copies of React on the page. At this time, only ' + 'a single copy of React can be loaded at a time.', targetID) : undefined;
}
firstChildren[0] = deepestAncestor.firstChild;
firstChildren.length = 1;
while (childIndex < firstChildren.length) {
var child = firstChildren[childIndex++];
var targetChild;
while (child) {
var childID = ReactMount.getID(child);
if (childID) {
// Even if we find the node we're looking for, we finish looping
// through its siblings to ensure they're cached so that we don't have
// to revisit this node again. Otherwise, we make n^2 calls to getID
// when visiting the many children of a single node in order.
if (targetID === childID) {
targetChild = child;
} else if (ReactInstanceHandles.isAncestorIDOf(childID, targetID)) {
// If we find a child whose ID is an ancestor of the given ID,
// then we can be sure that we only want to search the subtree
// rooted at this child, so we can throw out the rest of the
// search state.
firstChildren.length = childIndex = 0;
firstChildren.push(child.firstChild);
}
} else {
// If this child had no ID, then there's a chance that it was
// injected automatically by the browser, as when a `<table>`
// element sprouts an extra `<tbody>` child as a side effect of
// `.innerHTML` parsing. Optimistically continue down this
// branch, but not before examining the other siblings.
firstChildren.push(child.firstChild);
}
child = child.nextSibling;
}
if (targetChild) {
// Emptying firstChildren/findComponentRootReusableArray is
// not necessary for correctness, but it helps the GC reclaim
// any nodes that were left at the end of the search.
firstChildren.length = 0;
return targetChild;
}
}
firstChildren.length = 0;
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'findComponentRoot(..., %s): Unable to find element. This probably ' + 'means the DOM was unexpectedly mutated (e.g., by the browser), ' + 'usually due to forgetting a <tbody> when using tables, nesting tags ' + 'like <form>, <p>, or <a>, or using non-SVG elements in an <svg> ' + 'parent. ' + 'Try inspecting the child nodes of the element with React ID `%s`.', targetID, ReactMount.getID(ancestorNode)) : invariant(false) : undefined;
},
_mountImageIntoNode: function (markup, container, shouldReuseMarkup, transaction) {
!(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mountComponentIntoNode(...): Target container is not valid.') : invariant(false) : undefined;
if (shouldReuseMarkup) {
var rootElement = getReactRootElementInContainer(container);
if (ReactMarkupChecksum.canReuseMarkup(markup, rootElement)) {
return;
} else {
var checksum = rootElement.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
rootElement.removeAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
var rootMarkup = rootElement.outerHTML;
rootElement.setAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME, checksum);
var normalizedMarkup = markup;
if (process.env.NODE_ENV !== 'production') {
// because rootMarkup is retrieved from the DOM, various normalizations
// will have occurred which will not be present in `markup`. Here,
// insert markup into a <div> or <iframe> depending on the container
// type to perform the same normalizations before comparing.
var normalizer;
if (container.nodeType === ELEMENT_NODE_TYPE) {
normalizer = document.createElement('div');
normalizer.innerHTML = markup;
normalizedMarkup = normalizer.innerHTML;
} else {
normalizer = document.createElement('iframe');
document.body.appendChild(normalizer);
normalizer.contentDocument.write(markup);
normalizedMarkup = normalizer.contentDocument.documentElement.outerHTML;
document.body.removeChild(normalizer);
}
}
var diffIndex = firstDifferenceIndex(normalizedMarkup, rootMarkup);
var difference = ' (client) ' + normalizedMarkup.substring(diffIndex - 20, diffIndex + 20) + '\n (server) ' + rootMarkup.substring(diffIndex - 20, diffIndex + 20);
!(container.nodeType !== DOC_NODE_TYPE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You\'re trying to render a component to the document using ' + 'server rendering but the checksum was invalid. This usually ' + 'means you rendered a different component type or props on ' + 'the client from the one on the server, or your render() ' + 'methods are impure. React cannot handle this case due to ' + 'cross-browser quirks by rendering at the document root. You ' + 'should look for environment dependent code in your components ' + 'and ensure the props are the same client and server side:\n%s', difference) : invariant(false) : undefined;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(false, 'React attempted to reuse markup in a container but the ' + 'checksum was invalid. This generally means that you are ' + 'using server rendering and the markup generated on the ' + 'server was not what the client was expecting. React injected ' + 'new markup to compensate which works but you have lost many ' + 'of the benefits of server rendering. Instead, figure out ' + 'why the markup being generated is different on the client ' + 'or server:\n%s', difference) : undefined;
}
}
}
!(container.nodeType !== DOC_NODE_TYPE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You\'re trying to render a component to the document but ' + 'you didn\'t use server rendering. We can\'t do this ' + 'without using server rendering due to cross-browser quirks. ' + 'See ReactDOMServer.renderToString() for server rendering.') : invariant(false) : undefined;
if (transaction.useCreateElement) {
while (container.lastChild) {
container.removeChild(container.lastChild);
}
container.appendChild(markup);
} else {
setInnerHTML(container, markup);
}
},
ownerDocumentContextKey: ownerDocumentContextKey,
/**
* React ID utilities.
*/
getReactRootID: getReactRootID,
getID: getID,
setID: setID,
getNode: getNode,
getNodeFromInstance: getNodeFromInstance,
isValid: isValid,
purgeID: purgeID
};
ReactPerf.measureMethods(ReactMount, 'ReactMount', {
_renderNewRootComponent: '_renderNewRootComponent',
_mountImageIntoNode: '_mountImageIntoNode'
});
module.exports = ReactMount;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactBrowserEventEmitter
* @typechecks static-only
*/
'use strict';
var EventConstants = __webpack_require__(30);
var EventPluginHub = __webpack_require__(31);
var EventPluginRegistry = __webpack_require__(32);
var ReactEventEmitterMixin = __webpack_require__(37);
var ReactPerf = __webpack_require__(18);
var ViewportMetrics = __webpack_require__(38);
var assign = __webpack_require__(39);
var isEventSupported = __webpack_require__(40);
/**
* Summary of `ReactBrowserEventEmitter` event handling:
*
* - Top-level delegation is used to trap most native browser events. This
* may only occur in the main thread and is the responsibility of
* ReactEventListener, which is injected and can therefore support pluggable
* event sources. This is the only work that occurs in the main thread.
*
* - We normalize and de-duplicate events to account for browser quirks. This
* may be done in the worker thread.
*
* - Forward these native events (with the associated top-level type used to
* trap it) to `EventPluginHub`, which in turn will ask plugins if they want
* to extract any synthetic events.
*
* - The `EventPluginHub` will then process each event by annotating them with
* "dispatches", a sequence of listeners and IDs that care about that event.
*
* - The `EventPluginHub` then dispatches the events.
*
* Overview of React and the event system:
*
* +------------+ .
* | DOM | .
* +------------+ .
* | .
* v .
* +------------+ .
* | ReactEvent | .
* | Listener | .
* +------------+ . +-----------+
* | . +--------+|SimpleEvent|
* | . | |Plugin |
* +-----|------+ . v +-----------+
* | | | . +--------------+ +------------+
* | +-----------.--->|EventPluginHub| | Event |
* | | . | | +-----------+ | Propagators|
* | ReactEvent | . | | |TapEvent | |------------|
* | Emitter | . | |<---+|Plugin | |other plugin|
* | | . | | +-----------+ | utilities |
* | +-----------.--->| | +------------+
* | | | . +--------------+
* +-----|------+ . ^ +-----------+
* | . | |Enter/Leave|
* + . +-------+|Plugin |
* +-------------+ . +-----------+
* | application | .
* |-------------| .
* | | .
* | | .
* +-------------+ .
* .
* React Core . General Purpose Event Plugin System
*/
var alreadyListeningTo = {};
var isMonitoringScrollValue = false;
var reactTopListenersCounter = 0;
// For events like 'submit' which don't consistently bubble (which we trap at a
// lower node than `document`), binding at `document` would cause duplicate
// events so we don't include them here
var topEventMapping = {
topAbort: 'abort',
topBlur: 'blur',
topCanPlay: 'canplay',
topCanPlayThrough: 'canplaythrough',
topChange: 'change',
topClick: 'click',
topCompositionEnd: 'compositionend',
topCompositionStart: 'compositionstart',
topCompositionUpdate: 'compositionupdate',
topContextMenu: 'contextmenu',
topCopy: 'copy',
topCut: 'cut',
topDoubleClick: 'dblclick',
topDrag: 'drag',
topDragEnd: 'dragend',
topDragEnter: 'dragenter',
topDragExit: 'dragexit',
topDragLeave: 'dragleave',
topDragOver: 'dragover',
topDragStart: 'dragstart',
topDrop: 'drop',
topDurationChange: 'durationchange',
topEmptied: 'emptied',
topEncrypted: 'encrypted',
topEnded: 'ended',
topError: 'error',
topFocus: 'focus',
topInput: 'input',
topKeyDown: 'keydown',
topKeyPress: 'keypress',
topKeyUp: 'keyup',
topLoadedData: 'loadeddata',
topLoadedMetadata: 'loadedmetadata',
topLoadStart: 'loadstart',
topMouseDown: 'mousedown',
topMouseMove: 'mousemove',
topMouseOut: 'mouseout',
topMouseOver: 'mouseover',
topMouseUp: 'mouseup',
topPaste: 'paste',
topPause: 'pause',
topPlay: 'play',
topPlaying: 'playing',
topProgress: 'progress',
topRateChange: 'ratechange',
topScroll: 'scroll',
topSeeked: 'seeked',
topSeeking: 'seeking',
topSelectionChange: 'selectionchange',
topStalled: 'stalled',
topSuspend: 'suspend',
topTextInput: 'textInput',
topTimeUpdate: 'timeupdate',
topTouchCancel: 'touchcancel',
topTouchEnd: 'touchend',
topTouchMove: 'touchmove',
topTouchStart: 'touchstart',
topVolumeChange: 'volumechange',
topWaiting: 'waiting',
topWheel: 'wheel'
};
/**
* To ensure no conflicts with other potential React instances on the page
*/
var topListenersIDKey = '_reactListenersID' + String(Math.random()).slice(2);
function getListeningForDocument(mountAt) {
// In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty`
// directly.
if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) {
mountAt[topListenersIDKey] = reactTopListenersCounter++;
alreadyListeningTo[mountAt[topListenersIDKey]] = {};
}
return alreadyListeningTo[mountAt[topListenersIDKey]];
}
/**
* `ReactBrowserEventEmitter` is used to attach top-level event listeners. For
* example:
*
* ReactBrowserEventEmitter.putListener('myID', 'onClick', myFunction);
*
* This would allocate a "registration" of `('onClick', myFunction)` on 'myID'.
*
* @internal
*/
var ReactBrowserEventEmitter = assign({}, ReactEventEmitterMixin, {
/**
* Injectable event backend
*/
ReactEventListener: null,
injection: {
/**
* @param {object} ReactEventListener
*/
injectReactEventListener: function (ReactEventListener) {
ReactEventListener.setHandleTopLevel(ReactBrowserEventEmitter.handleTopLevel);
ReactBrowserEventEmitter.ReactEventListener = ReactEventListener;
}
},
/**
* Sets whether or not any created callbacks should be enabled.
*
* @param {boolean} enabled True if callbacks should be enabled.
*/
setEnabled: function (enabled) {
if (ReactBrowserEventEmitter.ReactEventListener) {
ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled);
}
},
/**
* @return {boolean} True if callbacks are enabled.
*/
isEnabled: function () {
return !!(ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled());
},
/**
* We listen for bubbled touch events on the document object.
*
* Firefox v8.01 (and possibly others) exhibited strange behavior when
* mounting `onmousemove` events at some node that was not the document
* element. The symptoms were that if your mouse is not moving over something
* contained within that mount point (for example on the background) the
* top-level listeners for `onmousemove` won't be called. However, if you
* register the `mousemove` on the document object, then it will of course
* catch all `mousemove`s. This along with iOS quirks, justifies restricting
* top-level listeners to the document object only, at least for these
* movement types of events and possibly all events.
*
* @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
*
* Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but
* they bubble to document.
*
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @param {object} contentDocumentHandle Document which owns the container
*/
listenTo: function (registrationName, contentDocumentHandle) {
var mountAt = contentDocumentHandle;
var isListening = getListeningForDocument(mountAt);
var dependencies = EventPluginRegistry.registrationNameDependencies[registrationName];
var topLevelTypes = EventConstants.topLevelTypes;
for (var i = 0; i < dependencies.length; i++) {
var dependency = dependencies[i];
if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) {
if (dependency === topLevelTypes.topWheel) {
if (isEventSupported('wheel')) {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'wheel', mountAt);
} else if (isEventSupported('mousewheel')) {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'mousewheel', mountAt);
} else {
// Firefox needs to capture a different mouse scroll event.
// @see http://www.quirksmode.org/dom/events/tests/scroll.html
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'DOMMouseScroll', mountAt);
}
} else if (dependency === topLevelTypes.topScroll) {
if (isEventSupported('scroll', true)) {
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topScroll, 'scroll', mountAt);
} else {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topScroll, 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE);
}
} else if (dependency === topLevelTypes.topFocus || dependency === topLevelTypes.topBlur) {
if (isEventSupported('focus', true)) {
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topFocus, 'focus', mountAt);
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topBlur, 'blur', mountAt);
} else if (isEventSupported('focusin')) {
// IE has `focusin` and `focusout` events which bubble.
// @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topFocus, 'focusin', mountAt);
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topBlur, 'focusout', mountAt);
}
// to make sure blur and focus event listeners are only attached once
isListening[topLevelTypes.topBlur] = true;
isListening[topLevelTypes.topFocus] = true;
} else if (topEventMapping.hasOwnProperty(dependency)) {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(dependency, topEventMapping[dependency], mountAt);
}
isListening[dependency] = true;
}
}
},
trapBubbledEvent: function (topLevelType, handlerBaseName, handle) {
return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelType, handlerBaseName, handle);
},
trapCapturedEvent: function (topLevelType, handlerBaseName, handle) {
return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelType, handlerBaseName, handle);
},
/**
* Listens to window scroll and resize events. We cache scroll values so that
* application code can access them without triggering reflows.
*
* NOTE: Scroll events do not bubble.
*
* @see http://www.quirksmode.org/dom/events/scroll.html
*/
ensureScrollValueMonitoring: function () {
if (!isMonitoringScrollValue) {
var refresh = ViewportMetrics.refreshScrollValues;
ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh);
isMonitoringScrollValue = true;
}
},
eventNameDispatchConfigs: EventPluginHub.eventNameDispatchConfigs,
registrationNameModules: EventPluginHub.registrationNameModules,
putListener: EventPluginHub.putListener,
getListener: EventPluginHub.getListener,
deleteListener: EventPluginHub.deleteListener,
deleteAllListeners: EventPluginHub.deleteAllListeners
});
ReactPerf.measureMethods(ReactBrowserEventEmitter, 'ReactBrowserEventEmitter', {
putListener: 'putListener',
deleteListener: 'deleteListener'
});
module.exports = ReactBrowserEventEmitter;
/***/ },
/* 30 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule EventConstants
*/
'use strict';
var keyMirror = __webpack_require__(17);
var PropagationPhases = keyMirror({ bubbled: null, captured: null });
/**
* Types of raw signals from the browser caught at the top level.
*/
var topLevelTypes = keyMirror({
topAbort: null,
topBlur: null,
topCanPlay: null,
topCanPlayThrough: null,
topChange: null,
topClick: null,
topCompositionEnd: null,
topCompositionStart: null,
topCompositionUpdate: null,
topContextMenu: null,
topCopy: null,
topCut: null,
topDoubleClick: null,
topDrag: null,
topDragEnd: null,
topDragEnter: null,
topDragExit: null,
topDragLeave: null,
topDragOver: null,
topDragStart: null,
topDrop: null,
topDurationChange: null,
topEmptied: null,
topEncrypted: null,
topEnded: null,
topError: null,
topFocus: null,
topInput: null,
topKeyDown: null,
topKeyPress: null,
topKeyUp: null,
topLoad: null,
topLoadedData: null,
topLoadedMetadata: null,
topLoadStart: null,
topMouseDown: null,
topMouseMove: null,
topMouseOut: null,
topMouseOver: null,
topMouseUp: null,
topPaste: null,
topPause: null,
topPlay: null,
topPlaying: null,
topProgress: null,
topRateChange: null,
topReset: null,
topScroll: null,
topSeeked: null,
topSeeking: null,
topSelectionChange: null,
topStalled: null,
topSubmit: null,
topSuspend: null,
topTextInput: null,
topTimeUpdate: null,
topTouchCancel: null,
topTouchEnd: null,
topTouchMove: null,
topTouchStart: null,
topVolumeChange: null,
topWaiting: null,
topWheel: null
});
var EventConstants = {
topLevelTypes: topLevelTypes,
PropagationPhases: PropagationPhases
};
module.exports = EventConstants;
/***/ },
/* 31 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule EventPluginHub
*/
'use strict';
var EventPluginRegistry = __webpack_require__(32);
var EventPluginUtils = __webpack_require__(33);
var ReactErrorUtils = __webpack_require__(34);
var accumulateInto = __webpack_require__(35);
var forEachAccumulated = __webpack_require__(36);
var invariant = __webpack_require__(13);
var warning = __webpack_require__(25);
/**
* Internal store for event listeners
*/
var listenerBank = {};
/**
* Internal queue of events that have accumulated their dispatches and are
* waiting to have their dispatches executed.
*/
var eventQueue = null;
/**
* Dispatches an event and releases it back into the pool, unless persistent.
*
* @param {?object} event Synthetic event to be dispatched.
* @param {boolean} simulated If the event is simulated (changes exn behavior)
* @private
*/
var executeDispatchesAndRelease = function (event, simulated) {
if (event) {
EventPluginUtils.executeDispatchesInOrder(event, simulated);
if (!event.isPersistent()) {
event.constructor.release(event);
}
}
};
var executeDispatchesAndReleaseSimulated = function (e) {
return executeDispatchesAndRelease(e, true);
};
var executeDispatchesAndReleaseTopLevel = function (e) {
return executeDispatchesAndRelease(e, false);
};
/**
* - `InstanceHandle`: [required] Module that performs logical traversals of DOM
* hierarchy given ids of the logical DOM elements involved.
*/
var InstanceHandle = null;
function validateInstanceHandle() {
var valid = InstanceHandle && InstanceHandle.traverseTwoPhase && InstanceHandle.traverseEnterLeave;
process.env.NODE_ENV !== 'production' ? warning(valid, 'InstanceHandle not injected before use!') : undefined;
}
/**
* This is a unified interface for event plugins to be installed and configured.
*
* Event plugins can implement the following properties:
*
* `extractEvents` {function(string, DOMEventTarget, string, object): *}
* Required. When a top-level event is fired, this method is expected to
* extract synthetic events that will in turn be queued and dispatched.
*
* `eventTypes` {object}
* Optional, plugins that fire events must publish a mapping of registration
* names that are used to register listeners. Values of this mapping must
* be objects that contain `registrationName` or `phasedRegistrationNames`.
*
* `executeDispatch` {function(object, function, string)}
* Optional, allows plugins to override how an event gets dispatched. By
* default, the listener is simply invoked.
*
* Each plugin that is injected into `EventsPluginHub` is immediately operable.
*
* @public
*/
var EventPluginHub = {
/**
* Methods for injecting dependencies.
*/
injection: {
/**
* @param {object} InjectedMount
* @public
*/
injectMount: EventPluginUtils.injection.injectMount,
/**
* @param {object} InjectedInstanceHandle
* @public
*/
injectInstanceHandle: function (InjectedInstanceHandle) {
InstanceHandle = InjectedInstanceHandle;
if (process.env.NODE_ENV !== 'production') {
validateInstanceHandle();
}
},
getInstanceHandle: function () {
if (process.env.NODE_ENV !== 'production') {
validateInstanceHandle();
}
return InstanceHandle;
},
/**
* @param {array} InjectedEventPluginOrder
* @public
*/
injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder,
/**
* @param {object} injectedNamesToPlugins Map from names to plugin modules.
*/
injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName
},
eventNameDispatchConfigs: EventPluginRegistry.eventNameDispatchConfigs,
registrationNameModules: EventPluginRegistry.registrationNameModules,
/**
* Stores `listener` at `listenerBank[registrationName][id]`. Is idempotent.
*
* @param {string} id ID of the DOM element.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @param {?function} listener The callback to store.
*/
putListener: function (id, registrationName, listener) {
!(typeof listener === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener) : invariant(false) : undefined;
var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {});
bankForRegistrationName[id] = listener;
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
if (PluginModule && PluginModule.didPutListener) {
PluginModule.didPutListener(id, registrationName, listener);
}
},
/**
* @param {string} id ID of the DOM element.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @return {?function} The stored callback.
*/
getListener: function (id, registrationName) {
var bankForRegistrationName = listenerBank[registrationName];
return bankForRegistrationName && bankForRegistrationName[id];
},
/**
* Deletes a listener from the registration bank.
*
* @param {string} id ID of the DOM element.
* @param {string} registrationName Name of listener (e.g. `onClick`).
*/
deleteListener: function (id, registrationName) {
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
if (PluginModule && PluginModule.willDeleteListener) {
PluginModule.willDeleteListener(id, registrationName);
}
var bankForRegistrationName = listenerBank[registrationName];
// TODO: This should never be null -- when is it?
if (bankForRegistrationName) {
delete bankForRegistrationName[id];
}
},
/**
* Deletes all listeners for the DOM element with the supplied ID.
*
* @param {string} id ID of the DOM element.
*/
deleteAllListeners: function (id) {
for (var registrationName in listenerBank) {
if (!listenerBank[registrationName][id]) {
continue;
}
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
if (PluginModule && PluginModule.willDeleteListener) {
PluginModule.willDeleteListener(id, registrationName);
}
delete listenerBank[registrationName][id];
}
},
/**
* Allows registered plugins an opportunity to extract events from top-level
* native browser events.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @internal
*/
extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
var events;
var plugins = EventPluginRegistry.plugins;
for (var i = 0; i < plugins.length; i++) {
// Not every plugin in the ordering may be loaded at runtime.
var possiblePlugin = plugins[i];
if (possiblePlugin) {
var extractedEvents = possiblePlugin.extractEvents(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget);
if (extractedEvents) {
events = accumulateInto(events, extractedEvents);
}
}
}
return events;
},
/**
* Enqueues a synthetic event that should be dispatched when
* `processEventQueue` is invoked.
*
* @param {*} events An accumulation of synthetic events.
* @internal
*/
enqueueEvents: function (events) {
if (events) {
eventQueue = accumulateInto(eventQueue, events);
}
},
/**
* Dispatches all synthetic events on the event queue.
*
* @internal
*/
processEventQueue: function (simulated) {
// Set `eventQueue` to null before processing it so that we can tell if more
// events get enqueued while processing.
var processingEventQueue = eventQueue;
eventQueue = null;
if (simulated) {
forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated);
} else {
forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel);
}
!!eventQueue ? process.env.NODE_ENV !== 'production' ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing ' + 'an event queue. Support for this has not yet been implemented.') : invariant(false) : undefined;
// This would be a good time to rethrow if any of the event handlers threw.
ReactErrorUtils.rethrowCaughtError();
},
/**
* These are needed for tests only. Do not use!
*/
__purge: function () {
listenerBank = {};
},
__getListenerBank: function () {
return listenerBank;
}
};
module.exports = EventPluginHub;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 32 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule EventPluginRegistry
* @typechecks static-only
*/
'use strict';
var invariant = __webpack_require__(13);
/**
* Injectable ordering of event plugins.
*/
var EventPluginOrder = null;
/**
* Injectable mapping from names to event plugin modules.
*/
var namesToPlugins = {};
/**
* Recomputes the plugin list using the injected plugins and plugin ordering.
*
* @private
*/
function recomputePluginOrdering() {
if (!EventPluginOrder) {
// Wait until an `EventPluginOrder` is injected.
return;
}
for (var pluginName in namesToPlugins) {
var PluginModule = namesToPlugins[pluginName];
var pluginIndex = EventPluginOrder.indexOf(pluginName);
!(pluginIndex > -1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in ' + 'the plugin ordering, `%s`.', pluginName) : invariant(false) : undefined;
if (EventPluginRegistry.plugins[pluginIndex]) {
continue;
}
!PluginModule.extractEvents ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` ' + 'method, but `%s` does not.', pluginName) : invariant(false) : undefined;
EventPluginRegistry.plugins[pluginIndex] = PluginModule;
var publishedEvents = PluginModule.eventTypes;
for (var eventName in publishedEvents) {
!publishEventForPlugin(publishedEvents[eventName], PluginModule, eventName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : invariant(false) : undefined;
}
}
}
/**
* Publishes an event so that it can be dispatched by the supplied plugin.
*
* @param {object} dispatchConfig Dispatch configuration for the event.
* @param {object} PluginModule Plugin publishing the event.
* @return {boolean} True if the event was successfully published.
* @private
*/
function publishEventForPlugin(dispatchConfig, PluginModule, eventName) {
!!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same ' + 'event name, `%s`.', eventName) : invariant(false) : undefined;
EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig;
var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;
if (phasedRegistrationNames) {
for (var phaseName in phasedRegistrationNames) {
if (phasedRegistrationNames.hasOwnProperty(phaseName)) {
var phasedRegistrationName = phasedRegistrationNames[phaseName];
publishRegistrationName(phasedRegistrationName, PluginModule, eventName);
}
}
return true;
} else if (dispatchConfig.registrationName) {
publishRegistrationName(dispatchConfig.registrationName, PluginModule, eventName);
return true;
}
return false;
}
/**
* Publishes a registration name that is used to identify dispatched events and
* can be used with `EventPluginHub.putListener` to register listeners.
*
* @param {string} registrationName Registration name to add.
* @param {object} PluginModule Plugin publishing the event.
* @private
*/
function publishRegistrationName(registrationName, PluginModule, eventName) {
!!EventPluginRegistry.registrationNameModules[registrationName] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName) : invariant(false) : undefined;
EventPluginRegistry.registrationNameModules[registrationName] = PluginModule;
EventPluginRegistry.registrationNameDependencies[registrationName] = PluginModule.eventTypes[eventName].dependencies;
}
/**
* Registers plugins so that they can extract and dispatch events.
*
* @see {EventPluginHub}
*/
var EventPluginRegistry = {
/**
* Ordered list of injected plugins.
*/
plugins: [],
/**
* Mapping from event name to dispatch config
*/
eventNameDispatchConfigs: {},
/**
* Mapping from registration name to plugin module
*/
registrationNameModules: {},
/**
* Mapping from registration name to event name
*/
registrationNameDependencies: {},
/**
* Injects an ordering of plugins (by plugin name). This allows the ordering
* to be decoupled from injection of the actual plugins so that ordering is
* always deterministic regardless of packaging, on-the-fly injection, etc.
*
* @param {array} InjectedEventPluginOrder
* @internal
* @see {EventPluginHub.injection.injectEventPluginOrder}
*/
injectEventPluginOrder: function (InjectedEventPluginOrder) {
!!EventPluginOrder ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than ' + 'once. You are likely trying to load more than one copy of React.') : invariant(false) : undefined;
// Clone the ordering so it cannot be dynamically mutated.
EventPluginOrder = Array.prototype.slice.call(InjectedEventPluginOrder);
recomputePluginOrdering();
},
/**
* Injects plugins to be used by `EventPluginHub`. The plugin names must be
* in the ordering injected by `injectEventPluginOrder`.
*
* Plugins can be injected as part of page initialization or on-the-fly.
*
* @param {object} injectedNamesToPlugins Map from names to plugin modules.
* @internal
* @see {EventPluginHub.injection.injectEventPluginsByName}
*/
injectEventPluginsByName: function (injectedNamesToPlugins) {
var isOrderingDirty = false;
for (var pluginName in injectedNamesToPlugins) {
if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) {
continue;
}
var PluginModule = injectedNamesToPlugins[pluginName];
if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== PluginModule) {
!!namesToPlugins[pluginName] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins ' + 'using the same name, `%s`.', pluginName) : invariant(false) : undefined;
namesToPlugins[pluginName] = PluginModule;
isOrderingDirty = true;
}
}
if (isOrderingDirty) {
recomputePluginOrdering();
}
},
/**
* Looks up the plugin for the supplied event.
*
* @param {object} event A synthetic event.
* @return {?object} The plugin that created the supplied event.
* @internal
*/
getPluginModuleForEvent: function (event) {
var dispatchConfig = event.dispatchConfig;
if (dispatchConfig.registrationName) {
return EventPluginRegistry.registrationNameModules[dispatchConfig.registrationName] || null;
}
for (var phase in dispatchConfig.phasedRegistrationNames) {
if (!dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) {
continue;
}
var PluginModule = EventPluginRegistry.registrationNameModules[dispatchConfig.phasedRegistrationNames[phase]];
if (PluginModule) {
return PluginModule;
}
}
return null;
},
/**
* Exposed for unit testing.
* @private
*/
_resetEventPlugins: function () {
EventPluginOrder = null;
for (var pluginName in namesToPlugins) {
if (namesToPlugins.hasOwnProperty(pluginName)) {
delete namesToPlugins[pluginName];
}
}
EventPluginRegistry.plugins.length = 0;
var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs;
for (var eventName in eventNameDispatchConfigs) {
if (eventNameDispatchConfigs.hasOwnProperty(eventName)) {
delete eventNameDispatchConfigs[eventName];
}
}
var registrationNameModules = EventPluginRegistry.registrationNameModules;
for (var registrationName in registrationNameModules) {
if (registrationNameModules.hasOwnProperty(registrationName)) {
delete registrationNameModules[registrationName];
}
}
}
};
module.exports = EventPluginRegistry;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 33 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule EventPluginUtils
*/
'use strict';
var EventConstants = __webpack_require__(30);
var ReactErrorUtils = __webpack_require__(34);
var invariant = __webpack_require__(13);
var warning = __webpack_require__(25);
/**
* Injected dependencies:
*/
/**
* - `Mount`: [required] Module that can convert between React dom IDs and
* actual node references.
*/
var injection = {
Mount: null,
injectMount: function (InjectedMount) {
injection.Mount = InjectedMount;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(InjectedMount && InjectedMount.getNode && InjectedMount.getID, 'EventPluginUtils.injection.injectMount(...): Injected Mount ' + 'module is missing getNode or getID.') : undefined;
}
}
};
var topLevelTypes = EventConstants.topLevelTypes;
function isEndish(topLevelType) {
return topLevelType === topLevelTypes.topMouseUp || topLevelType === topLevelTypes.topTouchEnd || topLevelType === topLevelTypes.topTouchCancel;
}
function isMoveish(topLevelType) {
return topLevelType === topLevelTypes.topMouseMove || topLevelType === topLevelTypes.topTouchMove;
}
function isStartish(topLevelType) {
return topLevelType === topLevelTypes.topMouseDown || topLevelType === topLevelTypes.topTouchStart;
}
var validateEventDispatches;
if (process.env.NODE_ENV !== 'production') {
validateEventDispatches = function (event) {
var dispatchListeners = event._dispatchListeners;
var dispatchIDs = event._dispatchIDs;
var listenersIsArr = Array.isArray(dispatchListeners);
var idsIsArr = Array.isArray(dispatchIDs);
var IDsLen = idsIsArr ? dispatchIDs.length : dispatchIDs ? 1 : 0;
var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0;
process.env.NODE_ENV !== 'production' ? warning(idsIsArr === listenersIsArr && IDsLen === listenersLen, 'EventPluginUtils: Invalid `event`.') : undefined;
};
}
/**
* Dispatch the event to the listener.
* @param {SyntheticEvent} event SyntheticEvent to handle
* @param {boolean} simulated If the event is simulated (changes exn behavior)
* @param {function} listener Application-level callback
* @param {string} domID DOM id to pass to the callback.
*/
function executeDispatch(event, simulated, listener, domID) {
var type = event.type || 'unknown-event';
event.currentTarget = injection.Mount.getNode(domID);
if (simulated) {
ReactErrorUtils.invokeGuardedCallbackWithCatch(type, listener, event, domID);
} else {
ReactErrorUtils.invokeGuardedCallback(type, listener, event, domID);
}
event.currentTarget = null;
}
/**
* Standard/simple iteration through an event's collected dispatches.
*/
function executeDispatchesInOrder(event, simulated) {
var dispatchListeners = event._dispatchListeners;
var dispatchIDs = event._dispatchIDs;
if (process.env.NODE_ENV !== 'production') {
validateEventDispatches(event);
}
if (Array.isArray(dispatchListeners)) {
for (var i = 0; i < dispatchListeners.length; i++) {
if (event.isPropagationStopped()) {
break;
}
// Listeners and IDs are two parallel arrays that are always in sync.
executeDispatch(event, simulated, dispatchListeners[i], dispatchIDs[i]);
}
} else if (dispatchListeners) {
executeDispatch(event, simulated, dispatchListeners, dispatchIDs);
}
event._dispatchListeners = null;
event._dispatchIDs = null;
}
/**
* Standard/simple iteration through an event's collected dispatches, but stops
* at the first dispatch execution returning true, and returns that id.
*
* @return {?string} id of the first dispatch execution who's listener returns
* true, or null if no listener returned true.
*/
function executeDispatchesInOrderStopAtTrueImpl(event) {
var dispatchListeners = event._dispatchListeners;
var dispatchIDs = event._dispatchIDs;
if (process.env.NODE_ENV !== 'production') {
validateEventDispatches(event);
}
if (Array.isArray(dispatchListeners)) {
for (var i = 0; i < dispatchListeners.length; i++) {
if (event.isPropagationStopped()) {
break;
}
// Listeners and IDs are two parallel arrays that are always in sync.
if (dispatchListeners[i](event, dispatchIDs[i])) {
return dispatchIDs[i];
}
}
} else if (dispatchListeners) {
if (dispatchListeners(event, dispatchIDs)) {
return dispatchIDs;
}
}
return null;
}
/**
* @see executeDispatchesInOrderStopAtTrueImpl
*/
function executeDispatchesInOrderStopAtTrue(event) {
var ret = executeDispatchesInOrderStopAtTrueImpl(event);
event._dispatchIDs = null;
event._dispatchListeners = null;
return ret;
}
/**
* Execution of a "direct" dispatch - there must be at most one dispatch
* accumulated on the event or it is considered an error. It doesn't really make
* sense for an event with multiple dispatches (bubbled) to keep track of the
* return values at each dispatch execution, but it does tend to make sense when
* dealing with "direct" dispatches.
*
* @return {*} The return value of executing the single dispatch.
*/
function executeDirectDispatch(event) {
if (process.env.NODE_ENV !== 'production') {
validateEventDispatches(event);
}
var dispatchListener = event._dispatchListeners;
var dispatchID = event._dispatchIDs;
!!Array.isArray(dispatchListener) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'executeDirectDispatch(...): Invalid `event`.') : invariant(false) : undefined;
var res = dispatchListener ? dispatchListener(event, dispatchID) : null;
event._dispatchListeners = null;
event._dispatchIDs = null;
return res;
}
/**
* @param {SyntheticEvent} event
* @return {boolean} True iff number of dispatches accumulated is greater than 0.
*/
function hasDispatches(event) {
return !!event._dispatchListeners;
}
/**
* General utilities that are useful in creating custom Event Plugins.
*/
var EventPluginUtils = {
isEndish: isEndish,
isMoveish: isMoveish,
isStartish: isStartish,
executeDirectDispatch: executeDirectDispatch,
executeDispatchesInOrder: executeDispatchesInOrder,
executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue,
hasDispatches: hasDispatches,
getNode: function (id) {
return injection.Mount.getNode(id);
},
getID: function (node) {
return injection.Mount.getID(node);
},
injection: injection
};
module.exports = EventPluginUtils;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 34 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactErrorUtils
* @typechecks
*/
'use strict';
var caughtError = null;
/**
* Call a function while guarding against errors that happens within it.
*
* @param {?String} name of the guard to use for logging or debugging
* @param {Function} func The function to invoke
* @param {*} a First argument
* @param {*} b Second argument
*/
function invokeGuardedCallback(name, func, a, b) {
try {
return func(a, b);
} catch (x) {
if (caughtError === null) {
caughtError = x;
}
return undefined;
}
}
var ReactErrorUtils = {
invokeGuardedCallback: invokeGuardedCallback,
/**
* Invoked by ReactTestUtils.Simulate so that any errors thrown by the event
* handler are sure to be rethrown by rethrowCaughtError.
*/
invokeGuardedCallbackWithCatch: invokeGuardedCallback,
/**
* During execution of guarded functions we will capture the first error which
* we will rethrow to be handled by the top level error handler.
*/
rethrowCaughtError: function () {
if (caughtError) {
var error = caughtError;
caughtError = null;
throw error;
}
}
};
if (process.env.NODE_ENV !== 'production') {
/**
* To help development we can get better devtools integration by simulating a
* real browser event.
*/
if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
var fakeNode = document.createElement('react');
ReactErrorUtils.invokeGuardedCallback = function (name, func, a, b) {
var boundFunc = func.bind(null, a, b);
var evtType = 'react-' + name;
fakeNode.addEventListener(evtType, boundFunc, false);
var evt = document.createEvent('Event');
evt.initEvent(evtType, false, false);
fakeNode.dispatchEvent(evt);
fakeNode.removeEventListener(evtType, boundFunc, false);
};
}
}
module.exports = ReactErrorUtils;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule accumulateInto
*/
'use strict';
var invariant = __webpack_require__(13);
/**
*
* Accumulates items that must not be null or undefined into the first one. This
* is used to conserve memory by avoiding array allocations, and thus sacrifices
* API cleanness. Since `current` can be null before being passed in and not
* null after this function, make sure to assign it back to `current`:
*
* `a = accumulateInto(a, b);`
*
* This API should be sparingly used. Try `accumulate` for something cleaner.
*
* @return {*|array<*>} An accumulation of items.
*/
function accumulateInto(current, next) {
!(next != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : invariant(false) : undefined;
if (current == null) {
return next;
}
// Both are not empty. Warning: Never call x.concat(y) when you are not
// certain that x is an Array (x could be a string with concat method).
var currentIsArray = Array.isArray(current);
var nextIsArray = Array.isArray(next);
if (currentIsArray && nextIsArray) {
current.push.apply(current, next);
return current;
}
if (currentIsArray) {
current.push(next);
return current;
}
if (nextIsArray) {
// A bit too dangerous to mutate `next`.
return [current].concat(next);
}
return [current, next];
}
module.exports = accumulateInto;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 36 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule forEachAccumulated
*/
'use strict';
/**
* @param {array} arr an "accumulation" of items which is either an Array or
* a single item. Useful when paired with the `accumulate` module. This is a
* simple utility that allows us to reason about a collection of items, but
* handling the case when there is exactly one item (and we do not need to
* allocate an array).
*/
var forEachAccumulated = function (arr, cb, scope) {
if (Array.isArray(arr)) {
arr.forEach(cb, scope);
} else if (arr) {
cb.call(scope, arr);
}
};
module.exports = forEachAccumulated;
/***/ },
/* 37 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactEventEmitterMixin
*/
'use strict';
var EventPluginHub = __webpack_require__(31);
function runEventQueueInBatch(events) {
EventPluginHub.enqueueEvents(events);
EventPluginHub.processEventQueue(false);
}
var ReactEventEmitterMixin = {
/**
* Streams a fired top-level event to `EventPluginHub` where plugins have the
* opportunity to create `ReactEvent`s to be dispatched.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {object} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native environment event.
*/
handleTopLevel: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
var events = EventPluginHub.extractEvents(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget);
runEventQueueInBatch(events);
}
};
module.exports = ReactEventEmitterMixin;
/***/ },
/* 38 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ViewportMetrics
*/
'use strict';
var ViewportMetrics = {
currentScrollLeft: 0,
currentScrollTop: 0,
refreshScrollValues: function (scrollPosition) {
ViewportMetrics.currentScrollLeft = scrollPosition.x;
ViewportMetrics.currentScrollTop = scrollPosition.y;
}
};
module.exports = ViewportMetrics;
/***/ },
/* 39 */
/***/ function(module, exports) {
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Object.assign
*/
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign
'use strict';
function assign(target, sources) {
if (target == null) {
throw new TypeError('Object.assign target cannot be null or undefined');
}
var to = Object(target);
var hasOwnProperty = Object.prototype.hasOwnProperty;
for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) {
var nextSource = arguments[nextIndex];
if (nextSource == null) {
continue;
}
var from = Object(nextSource);
// We don't currently support accessors nor proxies. Therefore this
// copy cannot throw. If we ever supported this then we must handle
// exceptions and side-effects. We don't support symbols so they won't
// be transferred.
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
}
return to;
}
module.exports = assign;
/***/ },
/* 40 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule isEventSupported
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(9);
var useHasFeature;
if (ExecutionEnvironment.canUseDOM) {
useHasFeature = document.implementation && document.implementation.hasFeature &&
// always returns true in newer browsers as per the standard.
// @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature
document.implementation.hasFeature('', '') !== true;
}
/**
* Checks if an event is supported in the current execution environment.
*
* NOTE: This will not work correctly for non-generic events such as `change`,
* `reset`, `load`, `error`, and `select`.
*
* Borrows from Modernizr.
*
* @param {string} eventNameSuffix Event name, e.g. "click".
* @param {?boolean} capture Check if the capture phase is supported.
* @return {boolean} True if the event is supported.
* @internal
* @license Modernizr 3.0.0pre (Custom Build) | MIT
*/
function isEventSupported(eventNameSuffix, capture) {
if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) {
return false;
}
var eventName = 'on' + eventNameSuffix;
var isSupported = (eventName in document);
if (!isSupported) {
var element = document.createElement('div');
element.setAttribute(eventName, 'return;');
isSupported = typeof element[eventName] === 'function';
}
if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') {
// This is the only way to test support for the `wheel` event in IE9+.
isSupported = document.implementation.hasFeature('Events.wheel', '3.0');
}
return isSupported;
}
module.exports = isEventSupported;
/***/ },
/* 41 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMFeatureFlags
*/
'use strict';
var ReactDOMFeatureFlags = {
useCreateElement: false
};
module.exports = ReactDOMFeatureFlags;
/***/ },
/* 42 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactElement
*/
'use strict';
var ReactCurrentOwner = __webpack_require__(5);
var assign = __webpack_require__(39);
var canDefineProperty = __webpack_require__(43);
// The Symbol used to tag the ReactElement type. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7;
var RESERVED_PROPS = {
key: true,
ref: true,
__self: true,
__source: true
};
/**
* Base constructor for all React elements. This is only used to make this
* work with a dynamic instanceof check. Nothing should live on this prototype.
*
* @param {*} type
* @param {*} key
* @param {string|object} ref
* @param {*} self A *temporary* helper to detect places where `this` is
* different from the `owner` when React.createElement is called, so that we
* can warn. We want to get rid of owner and replace string `ref`s with arrow
* functions, and as long as `this` and owner are the same, there will be no
* change in behavior.
* @param {*} source An annotation object (added by a transpiler or otherwise)
* indicating filename, line number, and/or other information.
* @param {*} owner
* @param {*} props
* @internal
*/
var ReactElement = function (type, key, ref, self, source, owner, props) {
var element = {
// This tag allow us to uniquely identify this as a React Element
$$typeof: REACT_ELEMENT_TYPE,
// Built-in properties that belong on the element
type: type,
key: key,
ref: ref,
props: props,
// Record the component responsible for creating this element.
_owner: owner
};
if (process.env.NODE_ENV !== 'production') {
// The validation flag is currently mutative. We put it on
// an external backing store so that we can freeze the whole object.
// This can be replaced with a WeakMap once they are implemented in
// commonly used development environments.
element._store = {};
// To make comparing ReactElements easier for testing purposes, we make
// the validation flag non-enumerable (where possible, which should
// include every environment we run tests in), so the test framework
// ignores it.
if (canDefineProperty) {
Object.defineProperty(element._store, 'validated', {
configurable: false,
enumerable: false,
writable: true,
value: false
});
// self and source are DEV only properties.
Object.defineProperty(element, '_self', {
configurable: false,
enumerable: false,
writable: false,
value: self
});
// Two elements created in two different places should be considered
// equal for testing purposes and therefore we hide it from enumeration.
Object.defineProperty(element, '_source', {
configurable: false,
enumerable: false,
writable: false,
value: source
});
} else {
element._store.validated = false;
element._self = self;
element._source = source;
}
Object.freeze(element.props);
Object.freeze(element);
}
return element;
};
ReactElement.createElement = function (type, config, children) {
var propName;
// Reserved names are extracted
var props = {};
var key = null;
var ref = null;
var self = null;
var source = null;
if (config != null) {
ref = config.ref === undefined ? null : config.ref;
key = config.key === undefined ? null : '' + config.key;
self = config.__self === undefined ? null : config.__self;
source = config.__source === undefined ? null : config.__source;
// Remaining properties are added to a new props object
for (propName in config) {
if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
props[propName] = config[propName];
}
}
}
// Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
props.children = childArray;
}
// Resolve default props
if (type && type.defaultProps) {
var defaultProps = type.defaultProps;
for (propName in defaultProps) {
if (typeof props[propName] === 'undefined') {
props[propName] = defaultProps[propName];
}
}
}
return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
};
ReactElement.createFactory = function (type) {
var factory = ReactElement.createElement.bind(null, type);
// Expose the type on the factory and the prototype so that it can be
// easily accessed on elements. E.g. `<Foo />.type === Foo`.
// This should not be named `constructor` since this may not be the function
// that created the element, and it may not even be a constructor.
// Legacy hook TODO: Warn if this is accessed
factory.type = type;
return factory;
};
ReactElement.cloneAndReplaceKey = function (oldElement, newKey) {
var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);
return newElement;
};
ReactElement.cloneAndReplaceProps = function (oldElement, newProps) {
var newElement = ReactElement(oldElement.type, oldElement.key, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, newProps);
if (process.env.NODE_ENV !== 'production') {
// If the key on the original is valid, then the clone is valid
newElement._store.validated = oldElement._store.validated;
}
return newElement;
};
ReactElement.cloneElement = function (element, config, children) {
var propName;
// Original props are copied
var props = assign({}, element.props);
// Reserved names are extracted
var key = element.key;
var ref = element.ref;
// Self is preserved since the owner is preserved.
var self = element._self;
// Source is preserved since cloneElement is unlikely to be targeted by a
// transpiler, and the original source is probably a better indicator of the
// true owner.
var source = element._source;
// Owner will be preserved, unless ref is overridden
var owner = element._owner;
if (config != null) {
if (config.ref !== undefined) {
// Silently steal the ref from the parent.
ref = config.ref;
owner = ReactCurrentOwner.current;
}
if (config.key !== undefined) {
key = '' + config.key;
}
// Remaining properties override existing props
for (propName in config) {
if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
props[propName] = config[propName];
}
}
}
// Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
props.children = childArray;
}
return ReactElement(element.type, key, ref, self, source, owner, props);
};
/**
* @param {?object} object
* @return {boolean} True if `object` is a valid component.
* @final
*/
ReactElement.isValidElement = function (object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
};
module.exports = ReactElement;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 43 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule canDefineProperty
*/
'use strict';
var canDefineProperty = false;
if (process.env.NODE_ENV !== 'production') {
try {
Object.defineProperty({}, 'x', { get: function () {} });
canDefineProperty = true;
} catch (x) {
// IE will fail on defineProperty
}
}
module.exports = canDefineProperty;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 44 */
/***/ function(module, exports) {
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactEmptyComponentRegistry
*/
'use strict';
// This registry keeps track of the React IDs of the components that rendered to
// `null` (in reality a placeholder such as `noscript`)
var nullComponentIDsRegistry = {};
/**
* @param {string} id Component's `_rootNodeID`.
* @return {boolean} True if the component is rendered to null.
*/
function isNullComponentID(id) {
return !!nullComponentIDsRegistry[id];
}
/**
* Mark the component as having rendered to null.
* @param {string} id Component's `_rootNodeID`.
*/
function registerNullComponentID(id) {
nullComponentIDsRegistry[id] = true;
}
/**
* Unmark the component as having rendered to null: it renders to something now.
* @param {string} id Component's `_rootNodeID`.
*/
function deregisterNullComponentID(id) {
delete nullComponentIDsRegistry[id];
}
var ReactEmptyComponentRegistry = {
isNullComponentID: isNullComponentID,
registerNullComponentID: registerNullComponentID,
deregisterNullComponentID: deregisterNullComponentID
};
module.exports = ReactEmptyComponentRegistry;
/***/ },
/* 45 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactInstanceHandles
* @typechecks static-only
*/
'use strict';
var ReactRootIndex = __webpack_require__(46);
var invariant = __webpack_require__(13);
var SEPARATOR = '.';
var SEPARATOR_LENGTH = SEPARATOR.length;
/**
* Maximum depth of traversals before we consider the possibility of a bad ID.
*/
var MAX_TREE_DEPTH = 10000;
/**
* Creates a DOM ID prefix to use when mounting React components.
*
* @param {number} index A unique integer
* @return {string} React root ID.
* @internal
*/
function getReactRootIDString(index) {
return SEPARATOR + index.toString(36);
}
/**
* Checks if a character in the supplied ID is a separator or the end.
*
* @param {string} id A React DOM ID.
* @param {number} index Index of the character to check.
* @return {boolean} True if the character is a separator or end of the ID.
* @private
*/
function isBoundary(id, index) {
return id.charAt(index) === SEPARATOR || index === id.length;
}
/**
* Checks if the supplied string is a valid React DOM ID.
*
* @param {string} id A React DOM ID, maybe.
* @return {boolean} True if the string is a valid React DOM ID.
* @private
*/
function isValidID(id) {
return id === '' || id.charAt(0) === SEPARATOR && id.charAt(id.length - 1) !== SEPARATOR;
}
/**
* Checks if the first ID is an ancestor of or equal to the second ID.
*
* @param {string} ancestorID
* @param {string} descendantID
* @return {boolean} True if `ancestorID` is an ancestor of `descendantID`.
* @internal
*/
function isAncestorIDOf(ancestorID, descendantID) {
return descendantID.indexOf(ancestorID) === 0 && isBoundary(descendantID, ancestorID.length);
}
/**
* Gets the parent ID of the supplied React DOM ID, `id`.
*
* @param {string} id ID of a component.
* @return {string} ID of the parent, or an empty string.
* @private
*/
function getParentID(id) {
return id ? id.substr(0, id.lastIndexOf(SEPARATOR)) : '';
}
/**
* Gets the next DOM ID on the tree path from the supplied `ancestorID` to the
* supplied `destinationID`. If they are equal, the ID is returned.
*
* @param {string} ancestorID ID of an ancestor node of `destinationID`.
* @param {string} destinationID ID of the destination node.
* @return {string} Next ID on the path from `ancestorID` to `destinationID`.
* @private
*/
function getNextDescendantID(ancestorID, destinationID) {
!(isValidID(ancestorID) && isValidID(destinationID)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNextDescendantID(%s, %s): Received an invalid React DOM ID.', ancestorID, destinationID) : invariant(false) : undefined;
!isAncestorIDOf(ancestorID, destinationID) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNextDescendantID(...): React has made an invalid assumption about ' + 'the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.', ancestorID, destinationID) : invariant(false) : undefined;
if (ancestorID === destinationID) {
return ancestorID;
}
// Skip over the ancestor and the immediate separator. Traverse until we hit
// another separator or we reach the end of `destinationID`.
var start = ancestorID.length + SEPARATOR_LENGTH;
var i;
for (i = start; i < destinationID.length; i++) {
if (isBoundary(destinationID, i)) {
break;
}
}
return destinationID.substr(0, i);
}
/**
* Gets the nearest common ancestor ID of two IDs.
*
* Using this ID scheme, the nearest common ancestor ID is the longest common
* prefix of the two IDs that immediately preceded a "marker" in both strings.
*
* @param {string} oneID
* @param {string} twoID
* @return {string} Nearest common ancestor ID, or the empty string if none.
* @private
*/
function getFirstCommonAncestorID(oneID, twoID) {
var minLength = Math.min(oneID.length, twoID.length);
if (minLength === 0) {
return '';
}
var lastCommonMarkerIndex = 0;
// Use `<=` to traverse until the "EOL" of the shorter string.
for (var i = 0; i <= minLength; i++) {
if (isBoundary(oneID, i) && isBoundary(twoID, i)) {
lastCommonMarkerIndex = i;
} else if (oneID.charAt(i) !== twoID.charAt(i)) {
break;
}
}
var longestCommonID = oneID.substr(0, lastCommonMarkerIndex);
!isValidID(longestCommonID) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s', oneID, twoID, longestCommonID) : invariant(false) : undefined;
return longestCommonID;
}
/**
* Traverses the parent path between two IDs (either up or down). The IDs must
* not be the same, and there must exist a parent path between them. If the
* callback returns `false`, traversal is stopped.
*
* @param {?string} start ID at which to start traversal.
* @param {?string} stop ID at which to end traversal.
* @param {function} cb Callback to invoke each ID with.
* @param {*} arg Argument to invoke the callback with.
* @param {?boolean} skipFirst Whether or not to skip the first node.
* @param {?boolean} skipLast Whether or not to skip the last node.
* @private
*/
function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) {
start = start || '';
stop = stop || '';
!(start !== stop) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.', start) : invariant(false) : undefined;
var traverseUp = isAncestorIDOf(stop, start);
!(traverseUp || isAncestorIDOf(start, stop)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do ' + 'not have a parent path.', start, stop) : invariant(false) : undefined;
// Traverse from `start` to `stop` one depth at a time.
var depth = 0;
var traverse = traverseUp ? getParentID : getNextDescendantID;
for (var id = start;; /* until break */id = traverse(id, stop)) {
var ret;
if ((!skipFirst || id !== start) && (!skipLast || id !== stop)) {
ret = cb(id, traverseUp, arg);
}
if (ret === false || id === stop) {
// Only break //after// visiting `stop`.
break;
}
!(depth++ < MAX_TREE_DEPTH) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'traverseParentPath(%s, %s, ...): Detected an infinite loop while ' + 'traversing the React DOM ID tree. This may be due to malformed IDs: %s', start, stop, id) : invariant(false) : undefined;
}
}
/**
* Manages the IDs assigned to DOM representations of React components. This
* uses a specific scheme in order to traverse the DOM efficiently (e.g. in
* order to simulate events).
*
* @internal
*/
var ReactInstanceHandles = {
/**
* Constructs a React root ID
* @return {string} A React root ID.
*/
createReactRootID: function () {
return getReactRootIDString(ReactRootIndex.createReactRootIndex());
},
/**
* Constructs a React ID by joining a root ID with a name.
*
* @param {string} rootID Root ID of a parent component.
* @param {string} name A component's name (as flattened children).
* @return {string} A React ID.
* @internal
*/
createReactID: function (rootID, name) {
return rootID + name;
},
/**
* Gets the DOM ID of the React component that is the root of the tree that
* contains the React component with the supplied DOM ID.
*
* @param {string} id DOM ID of a React component.
* @return {?string} DOM ID of the React component that is the root.
* @internal
*/
getReactRootIDFromNodeID: function (id) {
if (id && id.charAt(0) === SEPARATOR && id.length > 1) {
var index = id.indexOf(SEPARATOR, 1);
return index > -1 ? id.substr(0, index) : id;
}
return null;
},
/**
* Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
* should would receive a `mouseEnter` or `mouseLeave` event.
*
* NOTE: Does not invoke the callback on the nearest common ancestor because
* nothing "entered" or "left" that element.
*
* @param {string} leaveID ID being left.
* @param {string} enterID ID being entered.
* @param {function} cb Callback to invoke on each entered/left ID.
* @param {*} upArg Argument to invoke the callback with on left IDs.
* @param {*} downArg Argument to invoke the callback with on entered IDs.
* @internal
*/
traverseEnterLeave: function (leaveID, enterID, cb, upArg, downArg) {
var ancestorID = getFirstCommonAncestorID(leaveID, enterID);
if (ancestorID !== leaveID) {
traverseParentPath(leaveID, ancestorID, cb, upArg, false, true);
}
if (ancestorID !== enterID) {
traverseParentPath(ancestorID, enterID, cb, downArg, true, false);
}
},
/**
* Simulates the traversal of a two-phase, capture/bubble event dispatch.
*
* NOTE: This traversal happens on IDs without touching the DOM.
*
* @param {string} targetID ID of the target node.
* @param {function} cb Callback to invoke.
* @param {*} arg Argument to invoke the callback with.
* @internal
*/
traverseTwoPhase: function (targetID, cb, arg) {
if (targetID) {
traverseParentPath('', targetID, cb, arg, true, false);
traverseParentPath(targetID, '', cb, arg, false, true);
}
},
/**
* Same as `traverseTwoPhase` but skips the `targetID`.
*/
traverseTwoPhaseSkipTarget: function (targetID, cb, arg) {
if (targetID) {
traverseParentPath('', targetID, cb, arg, true, true);
traverseParentPath(targetID, '', cb, arg, true, true);
}
},
/**
* Traverse a node ID, calling the supplied `cb` for each ancestor ID. For
* example, passing `.0.$row-0.1` would result in `cb` getting called
* with `.0`, `.0.$row-0`, and `.0.$row-0.1`.
*
* NOTE: This traversal happens on IDs without touching the DOM.
*
* @param {string} targetID ID of the target node.
* @param {function} cb Callback to invoke.
* @param {*} arg Argument to invoke the callback with.
* @internal
*/
traverseAncestors: function (targetID, cb, arg) {
traverseParentPath('', targetID, cb, arg, true, false);
},
getFirstCommonAncestorID: getFirstCommonAncestorID,
/**
* Exposed for unit testing.
* @private
*/
_getNextDescendantID: getNextDescendantID,
isAncestorIDOf: isAncestorIDOf,
SEPARATOR: SEPARATOR
};
module.exports = ReactInstanceHandles;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 46 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactRootIndex
* @typechecks
*/
'use strict';
var ReactRootIndexInjection = {
/**
* @param {function} _createReactRootIndex
*/
injectCreateReactRootIndex: function (_createReactRootIndex) {
ReactRootIndex.createReactRootIndex = _createReactRootIndex;
}
};
var ReactRootIndex = {
createReactRootIndex: null,
injection: ReactRootIndexInjection
};
module.exports = ReactRootIndex;
/***/ },
/* 47 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactInstanceMap
*/
'use strict';
/**
* `ReactInstanceMap` maintains a mapping from a public facing stateful
* instance (key) and the internal representation (value). This allows public
* methods to accept the user facing instance as an argument and map them back
* to internal methods.
*/
// TODO: Replace this with ES6: var ReactInstanceMap = new Map();
var ReactInstanceMap = {
/**
* This API should be called `delete` but we'd have to make sure to always
* transform these to strings for IE support. When this transform is fully
* supported we can rename it.
*/
remove: function (key) {
key._reactInternalInstance = undefined;
},
get: function (key) {
return key._reactInternalInstance;
},
has: function (key) {
return key._reactInternalInstance !== undefined;
},
set: function (key, value) {
key._reactInternalInstance = value;
}
};
module.exports = ReactInstanceMap;
/***/ },
/* 48 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactMarkupChecksum
*/
'use strict';
var adler32 = __webpack_require__(49);
var TAG_END = /\/?>/;
var ReactMarkupChecksum = {
CHECKSUM_ATTR_NAME: 'data-react-checksum',
/**
* @param {string} markup Markup string
* @return {string} Markup string with checksum attribute attached
*/
addChecksumToMarkup: function (markup) {
var checksum = adler32(markup);
// Add checksum (handle both parent tags and self-closing tags)
return markup.replace(TAG_END, ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '"$&');
},
/**
* @param {string} markup to use
* @param {DOMElement} element root React element
* @returns {boolean} whether or not the markup is the same
*/
canReuseMarkup: function (markup, element) {
var existingChecksum = element.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
existingChecksum = existingChecksum && parseInt(existingChecksum, 10);
var markupChecksum = adler32(markup);
return markupChecksum === existingChecksum;
}
};
module.exports = ReactMarkupChecksum;
/***/ },
/* 49 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule adler32
*/
'use strict';
var MOD = 65521;
// adler32 is not cryptographically strong, and is only used to sanity check that
// markup generated on the server matches the markup generated on the client.
// This implementation (a modified version of the SheetJS version) has been optimized
// for our use case, at the expense of conforming to the adler32 specification
// for non-ascii inputs.
function adler32(data) {
var a = 1;
var b = 0;
var i = 0;
var l = data.length;
var m = l & ~0x3;
while (i < m) {
for (; i < Math.min(i + 4096, m); i += 4) {
b += (a += data.charCodeAt(i)) + (a += data.charCodeAt(i + 1)) + (a += data.charCodeAt(i + 2)) + (a += data.charCodeAt(i + 3));
}
a %= MOD;
b %= MOD;
}
for (; i < l; i++) {
b += a += data.charCodeAt(i);
}
a %= MOD;
b %= MOD;
return a | b << 16;
}
module.exports = adler32;
/***/ },
/* 50 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactReconciler
*/
'use strict';
var ReactRef = __webpack_require__(51);
/**
* Helper to call ReactRef.attachRefs with this composite component, split out
* to avoid allocations in the transaction mount-ready queue.
*/
function attachRefs() {
ReactRef.attachRefs(this, this._currentElement);
}
var ReactReconciler = {
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {ReactComponent} internalInstance
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: function (internalInstance, rootID, transaction, context) {
var markup = internalInstance.mountComponent(rootID, transaction, context);
if (internalInstance._currentElement && internalInstance._currentElement.ref != null) {
transaction.getReactMountReady().enqueue(attachRefs, internalInstance);
}
return markup;
},
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function (internalInstance) {
ReactRef.detachRefs(internalInstance, internalInstance._currentElement);
internalInstance.unmountComponent();
},
/**
* Update a component using a new element.
*
* @param {ReactComponent} internalInstance
* @param {ReactElement} nextElement
* @param {ReactReconcileTransaction} transaction
* @param {object} context
* @internal
*/
receiveComponent: function (internalInstance, nextElement, transaction, context) {
var prevElement = internalInstance._currentElement;
if (nextElement === prevElement && context === internalInstance._context) {
// Since elements are immutable after the owner is rendered,
// we can do a cheap identity compare here to determine if this is a
// superfluous reconcile. It's possible for state to be mutable but such
// change should trigger an update of the owner which would recreate
// the element. We explicitly check for the existence of an owner since
// it's possible for an element created outside a composite to be
// deeply mutated and reused.
// TODO: Bailing out early is just a perf optimization right?
// TODO: Removing the return statement should affect correctness?
return;
}
var refsChanged = ReactRef.shouldUpdateRefs(prevElement, nextElement);
if (refsChanged) {
ReactRef.detachRefs(internalInstance, prevElement);
}
internalInstance.receiveComponent(nextElement, transaction, context);
if (refsChanged && internalInstance._currentElement && internalInstance._currentElement.ref != null) {
transaction.getReactMountReady().enqueue(attachRefs, internalInstance);
}
},
/**
* Flush any dirty changes in a component.
*
* @param {ReactComponent} internalInstance
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function (internalInstance, transaction) {
internalInstance.performUpdateIfNecessary(transaction);
}
};
module.exports = ReactReconciler;
/***/ },
/* 51 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactRef
*/
'use strict';
var ReactOwner = __webpack_require__(52);
var ReactRef = {};
function attachRef(ref, component, owner) {
if (typeof ref === 'function') {
ref(component.getPublicInstance());
} else {
// Legacy ref
ReactOwner.addComponentAsRefTo(component, ref, owner);
}
}
function detachRef(ref, component, owner) {
if (typeof ref === 'function') {
ref(null);
} else {
// Legacy ref
ReactOwner.removeComponentAsRefFrom(component, ref, owner);
}
}
ReactRef.attachRefs = function (instance, element) {
if (element === null || element === false) {
return;
}
var ref = element.ref;
if (ref != null) {
attachRef(ref, instance, element._owner);
}
};
ReactRef.shouldUpdateRefs = function (prevElement, nextElement) {
// If either the owner or a `ref` has changed, make sure the newest owner
// has stored a reference to `this`, and the previous owner (if different)
// has forgotten the reference to `this`. We use the element instead
// of the public this.props because the post processing cannot determine
// a ref. The ref conceptually lives on the element.
// TODO: Should this even be possible? The owner cannot change because
// it's forbidden by shouldUpdateReactComponent. The ref can change
// if you swap the keys of but not the refs. Reconsider where this check
// is made. It probably belongs where the key checking and
// instantiateReactComponent is done.
var prevEmpty = prevElement === null || prevElement === false;
var nextEmpty = nextElement === null || nextElement === false;
return(
// This has a few false positives w/r/t empty components.
prevEmpty || nextEmpty || nextElement._owner !== prevElement._owner || nextElement.ref !== prevElement.ref
);
};
ReactRef.detachRefs = function (instance, element) {
if (element === null || element === false) {
return;
}
var ref = element.ref;
if (ref != null) {
detachRef(ref, instance, element._owner);
}
};
module.exports = ReactRef;
/***/ },
/* 52 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactOwner
*/
'use strict';
var invariant = __webpack_require__(13);
/**
* ReactOwners are capable of storing references to owned components.
*
* All components are capable of //being// referenced by owner components, but
* only ReactOwner components are capable of //referencing// owned components.
* The named reference is known as a "ref".
*
* Refs are available when mounted and updated during reconciliation.
*
* var MyComponent = React.createClass({
* render: function() {
* return (
* <div onClick={this.handleClick}>
* <CustomComponent ref="custom" />
* </div>
* );
* },
* handleClick: function() {
* this.refs.custom.handleClick();
* },
* componentDidMount: function() {
* this.refs.custom.initialize();
* }
* });
*
* Refs should rarely be used. When refs are used, they should only be done to
* control data that is not handled by React's data flow.
*
* @class ReactOwner
*/
var ReactOwner = {
/**
* @param {?object} object
* @return {boolean} True if `object` is a valid owner.
* @final
*/
isValidOwner: function (object) {
return !!(object && typeof object.attachRef === 'function' && typeof object.detachRef === 'function');
},
/**
* Adds a component by ref to an owner component.
*
* @param {ReactComponent} component Component to reference.
* @param {string} ref Name by which to refer to the component.
* @param {ReactOwner} owner Component on which to record the ref.
* @final
* @internal
*/
addComponentAsRefTo: function (component, ref, owner) {
!ReactOwner.isValidOwner(owner) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'addComponentAsRefTo(...): Only a ReactOwner can have refs. You might ' + 'be adding a ref to a component that was not created inside a component\'s ' + '`render` method, or you have multiple copies of React loaded ' + '(details: https://fb.me/react-refs-must-have-owner).') : invariant(false) : undefined;
owner.attachRef(ref, component);
},
/**
* Removes a component by ref from an owner component.
*
* @param {ReactComponent} component Component to dereference.
* @param {string} ref Name of the ref to remove.
* @param {ReactOwner} owner Component on which the ref is recorded.
* @final
* @internal
*/
removeComponentAsRefFrom: function (component, ref, owner) {
!ReactOwner.isValidOwner(owner) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might ' + 'be removing a ref to a component that was not created inside a component\'s ' + '`render` method, or you have multiple copies of React loaded ' + '(details: https://fb.me/react-refs-must-have-owner).') : invariant(false) : undefined;
// Check that `component` is still the current ref because we do not want to
// detach the ref if another component stole it.
if (owner.getPublicInstance().refs[ref] === component.getPublicInstance()) {
owner.detachRef(ref);
}
}
};
module.exports = ReactOwner;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 53 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactUpdateQueue
*/
'use strict';
var ReactCurrentOwner = __webpack_require__(5);
var ReactElement = __webpack_require__(42);
var ReactInstanceMap = __webpack_require__(47);
var ReactUpdates = __webpack_require__(54);
var assign = __webpack_require__(39);
var invariant = __webpack_require__(13);
var warning = __webpack_require__(25);
function enqueueUpdate(internalInstance) {
ReactUpdates.enqueueUpdate(internalInstance);
}
function getInternalInstanceReadyForUpdate(publicInstance, callerName) {
var internalInstance = ReactInstanceMap.get(publicInstance);
if (!internalInstance) {
if (process.env.NODE_ENV !== 'production') {
// Only warn when we have a callerName. Otherwise we should be silent.
// We're probably calling from enqueueCallback. We don't want to warn
// there because we already warned for the corresponding lifecycle method.
process.env.NODE_ENV !== 'production' ? warning(!callerName, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, publicInstance.constructor.displayName) : undefined;
}
return null;
}
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '%s(...): Cannot update during an existing state transition ' + '(such as within `render`). Render methods should be a pure function ' + 'of props and state.', callerName) : undefined;
}
return internalInstance;
}
/**
* ReactUpdateQueue allows for state updates to be scheduled into a later
* reconciliation step.
*/
var ReactUpdateQueue = {
/**
* Checks whether or not this composite component is mounted.
* @param {ReactClass} publicInstance The instance we want to test.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function (publicInstance) {
if (process.env.NODE_ENV !== 'production') {
var owner = ReactCurrentOwner.current;
if (owner !== null) {
process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : undefined;
owner._warnedAboutRefsInRender = true;
}
}
var internalInstance = ReactInstanceMap.get(publicInstance);
if (internalInstance) {
// During componentWillMount and render this will still be null but after
// that will always render to something. At least for now. So we can use
// this hack.
return !!internalInstance._renderedComponent;
} else {
return false;
}
},
/**
* Enqueue a callback that will be executed after all the pending updates
* have processed.
*
* @param {ReactClass} publicInstance The instance to use as `this` context.
* @param {?function} callback Called after state is updated.
* @internal
*/
enqueueCallback: function (publicInstance, callback) {
!(typeof callback === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.') : invariant(false) : undefined;
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance);
// Previously we would throw an error if we didn't have an internal
// instance. Since we want to make it a no-op instead, we mirror the same
// behavior we have in other enqueue* methods.
// We also need to ignore callbacks in componentWillMount. See
// enqueueUpdates.
if (!internalInstance) {
return null;
}
if (internalInstance._pendingCallbacks) {
internalInstance._pendingCallbacks.push(callback);
} else {
internalInstance._pendingCallbacks = [callback];
}
// TODO: The callback here is ignored when setState is called from
// componentWillMount. Either fix it or disallow doing so completely in
// favor of getInitialState. Alternatively, we can disallow
// componentWillMount during server-side rendering.
enqueueUpdate(internalInstance);
},
enqueueCallbackInternal: function (internalInstance, callback) {
!(typeof callback === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.') : invariant(false) : undefined;
if (internalInstance._pendingCallbacks) {
internalInstance._pendingCallbacks.push(callback);
} else {
internalInstance._pendingCallbacks = [callback];
}
enqueueUpdate(internalInstance);
},
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @internal
*/
enqueueForceUpdate: function (publicInstance) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'forceUpdate');
if (!internalInstance) {
return;
}
internalInstance._pendingForceUpdate = true;
enqueueUpdate(internalInstance);
},
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} completeState Next state.
* @internal
*/
enqueueReplaceState: function (publicInstance, completeState) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceState');
if (!internalInstance) {
return;
}
internalInstance._pendingStateQueue = [completeState];
internalInstance._pendingReplaceState = true;
enqueueUpdate(internalInstance);
},
/**
* Sets a subset of the state. This only exists because _pendingState is
* internal. This provides a merging strategy that is not available to deep
* properties which is confusing. TODO: Expose pendingState or don't use it
* during the merge.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialState Next partial state to be merged with state.
* @internal
*/
enqueueSetState: function (publicInstance, partialState) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setState');
if (!internalInstance) {
return;
}
var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []);
queue.push(partialState);
enqueueUpdate(internalInstance);
},
/**
* Sets a subset of the props.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialProps Subset of the next props.
* @internal
*/
enqueueSetProps: function (publicInstance, partialProps) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setProps');
if (!internalInstance) {
return;
}
ReactUpdateQueue.enqueueSetPropsInternal(internalInstance, partialProps);
},
enqueueSetPropsInternal: function (internalInstance, partialProps) {
var topLevelWrapper = internalInstance._topLevelWrapper;
!topLevelWrapper ? process.env.NODE_ENV !== 'production' ? invariant(false, 'setProps(...): You called `setProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.') : invariant(false) : undefined;
// Merge with the pending element if it exists, otherwise with existing
// element props.
var wrapElement = topLevelWrapper._pendingElement || topLevelWrapper._currentElement;
var element = wrapElement.props;
var props = assign({}, element.props, partialProps);
topLevelWrapper._pendingElement = ReactElement.cloneAndReplaceProps(wrapElement, ReactElement.cloneAndReplaceProps(element, props));
enqueueUpdate(topLevelWrapper);
},
/**
* Replaces all of the props.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} props New props.
* @internal
*/
enqueueReplaceProps: function (publicInstance, props) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceProps');
if (!internalInstance) {
return;
}
ReactUpdateQueue.enqueueReplacePropsInternal(internalInstance, props);
},
enqueueReplacePropsInternal: function (internalInstance, props) {
var topLevelWrapper = internalInstance._topLevelWrapper;
!topLevelWrapper ? process.env.NODE_ENV !== 'production' ? invariant(false, 'replaceProps(...): You called `replaceProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.') : invariant(false) : undefined;
// Merge with the pending element if it exists, otherwise with existing
// element props.
var wrapElement = topLevelWrapper._pendingElement || topLevelWrapper._currentElement;
var element = wrapElement.props;
topLevelWrapper._pendingElement = ReactElement.cloneAndReplaceProps(wrapElement, ReactElement.cloneAndReplaceProps(element, props));
enqueueUpdate(topLevelWrapper);
},
enqueueElementInternal: function (internalInstance, newElement) {
internalInstance._pendingElement = newElement;
enqueueUpdate(internalInstance);
}
};
module.exports = ReactUpdateQueue;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 54 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactUpdates
*/
'use strict';
var CallbackQueue = __webpack_require__(55);
var PooledClass = __webpack_require__(56);
var ReactPerf = __webpack_require__(18);
var ReactReconciler = __webpack_require__(50);
var Transaction = __webpack_require__(57);
var assign = __webpack_require__(39);
var invariant = __webpack_require__(13);
var dirtyComponents = [];
var asapCallbackQueue = CallbackQueue.getPooled();
var asapEnqueued = false;
var batchingStrategy = null;
function ensureInjected() {
!(ReactUpdates.ReactReconcileTransaction && batchingStrategy) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must inject a reconcile transaction class and batching ' + 'strategy') : invariant(false) : undefined;
}
var NESTED_UPDATES = {
initialize: function () {
this.dirtyComponentsLength = dirtyComponents.length;
},
close: function () {
if (this.dirtyComponentsLength !== dirtyComponents.length) {
// Additional updates were enqueued by componentDidUpdate handlers or
// similar; before our own UPDATE_QUEUEING wrapper closes, we want to run
// these new updates so that if A's componentDidUpdate calls setState on
// B, B will update before the callback A's updater provided when calling
// setState.
dirtyComponents.splice(0, this.dirtyComponentsLength);
flushBatchedUpdates();
} else {
dirtyComponents.length = 0;
}
}
};
var UPDATE_QUEUEING = {
initialize: function () {
this.callbackQueue.reset();
},
close: function () {
this.callbackQueue.notifyAll();
}
};
var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING];
function ReactUpdatesFlushTransaction() {
this.reinitializeTransaction();
this.dirtyComponentsLength = null;
this.callbackQueue = CallbackQueue.getPooled();
this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* forceHTML */false);
}
assign(ReactUpdatesFlushTransaction.prototype, Transaction.Mixin, {
getTransactionWrappers: function () {
return TRANSACTION_WRAPPERS;
},
destructor: function () {
this.dirtyComponentsLength = null;
CallbackQueue.release(this.callbackQueue);
this.callbackQueue = null;
ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction);
this.reconcileTransaction = null;
},
perform: function (method, scope, a) {
// Essentially calls `this.reconcileTransaction.perform(method, scope, a)`
// with this transaction's wrappers around it.
return Transaction.Mixin.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a);
}
});
PooledClass.addPoolingTo(ReactUpdatesFlushTransaction);
function batchedUpdates(callback, a, b, c, d, e) {
ensureInjected();
batchingStrategy.batchedUpdates(callback, a, b, c, d, e);
}
/**
* Array comparator for ReactComponents by mount ordering.
*
* @param {ReactComponent} c1 first component you're comparing
* @param {ReactComponent} c2 second component you're comparing
* @return {number} Return value usable by Array.prototype.sort().
*/
function mountOrderComparator(c1, c2) {
return c1._mountOrder - c2._mountOrder;
}
function runBatchedUpdates(transaction) {
var len = transaction.dirtyComponentsLength;
!(len === dirtyComponents.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected flush transaction\'s stored dirty-components length (%s) to ' + 'match dirty-components array length (%s).', len, dirtyComponents.length) : invariant(false) : undefined;
// Since reconciling a component higher in the owner hierarchy usually (not
// always -- see shouldComponentUpdate()) will reconcile children, reconcile
// them before their children by sorting the array.
dirtyComponents.sort(mountOrderComparator);
for (var i = 0; i < len; i++) {
// If a component is unmounted before pending changes apply, it will still
// be here, but we assume that it has cleared its _pendingCallbacks and
// that performUpdateIfNecessary is a noop.
var component = dirtyComponents[i];
// If performUpdateIfNecessary happens to enqueue any new updates, we
// shouldn't execute the callbacks until the next render happens, so
// stash the callbacks first
var callbacks = component._pendingCallbacks;
component._pendingCallbacks = null;
ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction);
if (callbacks) {
for (var j = 0; j < callbacks.length; j++) {
transaction.callbackQueue.enqueue(callbacks[j], component.getPublicInstance());
}
}
}
}
var flushBatchedUpdates = function () {
// ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents
// array and perform any updates enqueued by mount-ready handlers (i.e.,
// componentDidUpdate) but we need to check here too in order to catch
// updates enqueued by setState callbacks and asap calls.
while (dirtyComponents.length || asapEnqueued) {
if (dirtyComponents.length) {
var transaction = ReactUpdatesFlushTransaction.getPooled();
transaction.perform(runBatchedUpdates, null, transaction);
ReactUpdatesFlushTransaction.release(transaction);
}
if (asapEnqueued) {
asapEnqueued = false;
var queue = asapCallbackQueue;
asapCallbackQueue = CallbackQueue.getPooled();
queue.notifyAll();
CallbackQueue.release(queue);
}
}
};
flushBatchedUpdates = ReactPerf.measure('ReactUpdates', 'flushBatchedUpdates', flushBatchedUpdates);
/**
* Mark a component as needing a rerender, adding an optional callback to a
* list of functions which will be executed once the rerender occurs.
*/
function enqueueUpdate(component) {
ensureInjected();
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case. (This is called by each top-level update
// function, like setProps, setState, forceUpdate, etc.; creation and
// destruction of top-level components is guarded in ReactMount.)
if (!batchingStrategy.isBatchingUpdates) {
batchingStrategy.batchedUpdates(enqueueUpdate, component);
return;
}
dirtyComponents.push(component);
}
/**
* Enqueue a callback to be run at the end of the current batching cycle. Throws
* if no updates are currently being performed.
*/
function asap(callback, context) {
!batchingStrategy.isBatchingUpdates ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context where' + 'updates are not being batched.') : invariant(false) : undefined;
asapCallbackQueue.enqueue(callback, context);
asapEnqueued = true;
}
var ReactUpdatesInjection = {
injectReconcileTransaction: function (ReconcileTransaction) {
!ReconcileTransaction ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a reconcile transaction class') : invariant(false) : undefined;
ReactUpdates.ReactReconcileTransaction = ReconcileTransaction;
},
injectBatchingStrategy: function (_batchingStrategy) {
!_batchingStrategy ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batching strategy') : invariant(false) : undefined;
!(typeof _batchingStrategy.batchedUpdates === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batchedUpdates() function') : invariant(false) : undefined;
!(typeof _batchingStrategy.isBatchingUpdates === 'boolean') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide an isBatchingUpdates boolean attribute') : invariant(false) : undefined;
batchingStrategy = _batchingStrategy;
}
};
var ReactUpdates = {
/**
* React references `ReactReconcileTransaction` using this property in order
* to allow dependency injection.
*
* @internal
*/
ReactReconcileTransaction: null,
batchedUpdates: batchedUpdates,
enqueueUpdate: enqueueUpdate,
flushBatchedUpdates: flushBatchedUpdates,
injection: ReactUpdatesInjection,
asap: asap
};
module.exports = ReactUpdates;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 55 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule CallbackQueue
*/
'use strict';
var PooledClass = __webpack_require__(56);
var assign = __webpack_require__(39);
var invariant = __webpack_require__(13);
/**
* A specialized pseudo-event module to help keep track of components waiting to
* be notified when their DOM representations are available for use.
*
* This implements `PooledClass`, so you should never need to instantiate this.
* Instead, use `CallbackQueue.getPooled()`.
*
* @class ReactMountReady
* @implements PooledClass
* @internal
*/
function CallbackQueue() {
this._callbacks = null;
this._contexts = null;
}
assign(CallbackQueue.prototype, {
/**
* Enqueues a callback to be invoked when `notifyAll` is invoked.
*
* @param {function} callback Invoked when `notifyAll` is invoked.
* @param {?object} context Context to call `callback` with.
* @internal
*/
enqueue: function (callback, context) {
this._callbacks = this._callbacks || [];
this._contexts = this._contexts || [];
this._callbacks.push(callback);
this._contexts.push(context);
},
/**
* Invokes all enqueued callbacks and clears the queue. This is invoked after
* the DOM representation of a component has been created or updated.
*
* @internal
*/
notifyAll: function () {
var callbacks = this._callbacks;
var contexts = this._contexts;
if (callbacks) {
!(callbacks.length === contexts.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Mismatched list of contexts in callback queue') : invariant(false) : undefined;
this._callbacks = null;
this._contexts = null;
for (var i = 0; i < callbacks.length; i++) {
callbacks[i].call(contexts[i]);
}
callbacks.length = 0;
contexts.length = 0;
}
},
/**
* Resets the internal queue.
*
* @internal
*/
reset: function () {
this._callbacks = null;
this._contexts = null;
},
/**
* `PooledClass` looks for this.
*/
destructor: function () {
this.reset();
}
});
PooledClass.addPoolingTo(CallbackQueue);
module.exports = CallbackQueue;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 56 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule PooledClass
*/
'use strict';
var invariant = __webpack_require__(13);
/**
* Static poolers. Several custom versions for each potential number of
* arguments. A completely generic pooler is easy to implement, but would
* require accessing the `arguments` object. In each of these, `this` refers to
* the Class itself, not an instance. If any others are needed, simply add them
* here, or in their own files.
*/
var oneArgumentPooler = function (copyFieldsFrom) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, copyFieldsFrom);
return instance;
} else {
return new Klass(copyFieldsFrom);
}
};
var twoArgumentPooler = function (a1, a2) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2);
return instance;
} else {
return new Klass(a1, a2);
}
};
var threeArgumentPooler = function (a1, a2, a3) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3);
return instance;
} else {
return new Klass(a1, a2, a3);
}
};
var fourArgumentPooler = function (a1, a2, a3, a4) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3, a4);
return instance;
} else {
return new Klass(a1, a2, a3, a4);
}
};
var fiveArgumentPooler = function (a1, a2, a3, a4, a5) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3, a4, a5);
return instance;
} else {
return new Klass(a1, a2, a3, a4, a5);
}
};
var standardReleaser = function (instance) {
var Klass = this;
!(instance instanceof Klass) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : invariant(false) : undefined;
instance.destructor();
if (Klass.instancePool.length < Klass.poolSize) {
Klass.instancePool.push(instance);
}
};
var DEFAULT_POOL_SIZE = 10;
var DEFAULT_POOLER = oneArgumentPooler;
/**
* Augments `CopyConstructor` to be a poolable class, augmenting only the class
* itself (statically) not adding any prototypical fields. Any CopyConstructor
* you give this may have a `poolSize` property, and will look for a
* prototypical `destructor` on instances (optional).
*
* @param {Function} CopyConstructor Constructor that can be used to reset.
* @param {Function} pooler Customizable pooler.
*/
var addPoolingTo = function (CopyConstructor, pooler) {
var NewKlass = CopyConstructor;
NewKlass.instancePool = [];
NewKlass.getPooled = pooler || DEFAULT_POOLER;
if (!NewKlass.poolSize) {
NewKlass.poolSize = DEFAULT_POOL_SIZE;
}
NewKlass.release = standardReleaser;
return NewKlass;
};
var PooledClass = {
addPoolingTo: addPoolingTo,
oneArgumentPooler: oneArgumentPooler,
twoArgumentPooler: twoArgumentPooler,
threeArgumentPooler: threeArgumentPooler,
fourArgumentPooler: fourArgumentPooler,
fiveArgumentPooler: fiveArgumentPooler
};
module.exports = PooledClass;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 57 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Transaction
*/
'use strict';
var invariant = __webpack_require__(13);
/**
* `Transaction` creates a black box that is able to wrap any method such that
* certain invariants are maintained before and after the method is invoked
* (Even if an exception is thrown while invoking the wrapped method). Whoever
* instantiates a transaction can provide enforcers of the invariants at
* creation time. The `Transaction` class itself will supply one additional
* automatic invariant for you - the invariant that any transaction instance
* should not be run while it is already being run. You would typically create a
* single instance of a `Transaction` for reuse multiple times, that potentially
* is used to wrap several different methods. Wrappers are extremely simple -
* they only require implementing two methods.
*
* <pre>
* wrappers (injected at creation time)
* + +
* | |
* +-----------------|--------|--------------+
* | v | |
* | +---------------+ | |
* | +--| wrapper1 |---|----+ |
* | | +---------------+ v | |
* | | +-------------+ | |
* | | +----| wrapper2 |--------+ |
* | | | +-------------+ | | |
* | | | | | |
* | v v v v | wrapper
* | +---+ +---+ +---------+ +---+ +---+ | invariants
* perform(anyMethod) | | | | | | | | | | | | maintained
* +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|-------->
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | +---+ +---+ +---------+ +---+ +---+ |
* | initialize close |
* +-----------------------------------------+
* </pre>
*
* Use cases:
* - Preserving the input selection ranges before/after reconciliation.
* Restoring selection even in the event of an unexpected error.
* - Deactivating events while rearranging the DOM, preventing blurs/focuses,
* while guaranteeing that afterwards, the event system is reactivated.
* - Flushing a queue of collected DOM mutations to the main UI thread after a
* reconciliation takes place in a worker thread.
* - Invoking any collected `componentDidUpdate` callbacks after rendering new
* content.
* - (Future use case): Wrapping particular flushes of the `ReactWorker` queue
* to preserve the `scrollTop` (an automatic scroll aware DOM).
* - (Future use case): Layout calculations before and after DOM updates.
*
* Transactional plugin API:
* - A module that has an `initialize` method that returns any precomputation.
* - and a `close` method that accepts the precomputation. `close` is invoked
* when the wrapped process is completed, or has failed.
*
* @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules
* that implement `initialize` and `close`.
* @return {Transaction} Single transaction for reuse in thread.
*
* @class Transaction
*/
var Mixin = {
/**
* Sets up this instance so that it is prepared for collecting metrics. Does
* so such that this setup method may be used on an instance that is already
* initialized, in a way that does not consume additional memory upon reuse.
* That can be useful if you decide to make your subclass of this mixin a
* "PooledClass".
*/
reinitializeTransaction: function () {
this.transactionWrappers = this.getTransactionWrappers();
if (this.wrapperInitData) {
this.wrapperInitData.length = 0;
} else {
this.wrapperInitData = [];
}
this._isInTransaction = false;
},
_isInTransaction: false,
/**
* @abstract
* @return {Array<TransactionWrapper>} Array of transaction wrappers.
*/
getTransactionWrappers: null,
isInTransaction: function () {
return !!this._isInTransaction;
},
/**
* Executes the function within a safety window. Use this for the top level
* methods that result in large amounts of computation/mutations that would
* need to be safety checked. The optional arguments helps prevent the need
* to bind in many cases.
*
* @param {function} method Member of scope to call.
* @param {Object} scope Scope to invoke from.
* @param {Object?=} a Argument to pass to the method.
* @param {Object?=} b Argument to pass to the method.
* @param {Object?=} c Argument to pass to the method.
* @param {Object?=} d Argument to pass to the method.
* @param {Object?=} e Argument to pass to the method.
* @param {Object?=} f Argument to pass to the method.
*
* @return {*} Return value from `method`.
*/
perform: function (method, scope, a, b, c, d, e, f) {
!!this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.perform(...): Cannot initialize a transaction when there ' + 'is already an outstanding transaction.') : invariant(false) : undefined;
var errorThrown;
var ret;
try {
this._isInTransaction = true;
// Catching errors makes debugging more difficult, so we start with
// errorThrown set to true before setting it to false after calling
// close -- if it's still set to true in the finally block, it means
// one of these calls threw.
errorThrown = true;
this.initializeAll(0);
ret = method.call(scope, a, b, c, d, e, f);
errorThrown = false;
} finally {
try {
if (errorThrown) {
// If `method` throws, prefer to show that stack trace over any thrown
// by invoking `closeAll`.
try {
this.closeAll(0);
} catch (err) {}
} else {
// Since `method` didn't throw, we don't want to silence the exception
// here.
this.closeAll(0);
}
} finally {
this._isInTransaction = false;
}
}
return ret;
},
initializeAll: function (startIndex) {
var transactionWrappers = this.transactionWrappers;
for (var i = startIndex; i < transactionWrappers.length; i++) {
var wrapper = transactionWrappers[i];
try {
// Catching errors makes debugging more difficult, so we start with the
// OBSERVED_ERROR state before overwriting it with the real return value
// of initialize -- if it's still set to OBSERVED_ERROR in the finally
// block, it means wrapper.initialize threw.
this.wrapperInitData[i] = Transaction.OBSERVED_ERROR;
this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null;
} finally {
if (this.wrapperInitData[i] === Transaction.OBSERVED_ERROR) {
// The initializer for wrapper i threw an error; initialize the
// remaining wrappers but silence any exceptions from them to ensure
// that the first error is the one to bubble up.
try {
this.initializeAll(i + 1);
} catch (err) {}
}
}
}
},
/**
* Invokes each of `this.transactionWrappers.close[i]` functions, passing into
* them the respective return values of `this.transactionWrappers.init[i]`
* (`close`rs that correspond to initializers that failed will not be
* invoked).
*/
closeAll: function (startIndex) {
!this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.closeAll(): Cannot close transaction when none are open.') : invariant(false) : undefined;
var transactionWrappers = this.transactionWrappers;
for (var i = startIndex; i < transactionWrappers.length; i++) {
var wrapper = transactionWrappers[i];
var initData = this.wrapperInitData[i];
var errorThrown;
try {
// Catching errors makes debugging more difficult, so we start with
// errorThrown set to true before setting it to false after calling
// close -- if it's still set to true in the finally block, it means
// wrapper.close threw.
errorThrown = true;
if (initData !== Transaction.OBSERVED_ERROR && wrapper.close) {
wrapper.close.call(this, initData);
}
errorThrown = false;
} finally {
if (errorThrown) {
// The closer for wrapper i threw an error; close the remaining
// wrappers but silence any exceptions from them to ensure that the
// first error is the one to bubble up.
try {
this.closeAll(i + 1);
} catch (e) {}
}
}
}
this.wrapperInitData.length = 0;
}
};
var Transaction = {
Mixin: Mixin,
/**
* Token to look for to determine if an error occurred.
*/
OBSERVED_ERROR: {}
};
module.exports = Transaction;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 58 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule emptyObject
*/
'use strict';
var emptyObject = {};
if (process.env.NODE_ENV !== 'production') {
Object.freeze(emptyObject);
}
module.exports = emptyObject;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 59 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule containsNode
* @typechecks
*/
'use strict';
var isTextNode = __webpack_require__(60);
/*eslint-disable no-bitwise */
/**
* Checks if a given DOM node contains or is another DOM node.
*
* @param {?DOMNode} outerNode Outer DOM node.
* @param {?DOMNode} innerNode Inner DOM node.
* @return {boolean} True if `outerNode` contains or is `innerNode`.
*/
function containsNode(_x, _x2) {
var _again = true;
_function: while (_again) {
var outerNode = _x,
innerNode = _x2;
_again = false;
if (!outerNode || !innerNode) {
return false;
} else if (outerNode === innerNode) {
return true;
} else if (isTextNode(outerNode)) {
return false;
} else if (isTextNode(innerNode)) {
_x = outerNode;
_x2 = innerNode.parentNode;
_again = true;
continue _function;
} else if (outerNode.contains) {
return outerNode.contains(innerNode);
} else if (outerNode.compareDocumentPosition) {
return !!(outerNode.compareDocumentPosition(innerNode) & 16);
} else {
return false;
}
}
}
module.exports = containsNode;
/***/ },
/* 60 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule isTextNode
* @typechecks
*/
'use strict';
var isNode = __webpack_require__(61);
/**
* @param {*} object The object to check.
* @return {boolean} Whether or not the object is a DOM text node.
*/
function isTextNode(object) {
return isNode(object) && object.nodeType == 3;
}
module.exports = isTextNode;
/***/ },
/* 61 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule isNode
* @typechecks
*/
/**
* @param {*} object The object to check.
* @return {boolean} Whether or not the object is a DOM node.
*/
'use strict';
function isNode(object) {
return !!(object && (typeof Node === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string'));
}
module.exports = isNode;
/***/ },
/* 62 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule instantiateReactComponent
* @typechecks static-only
*/
'use strict';
var ReactCompositeComponent = __webpack_require__(63);
var ReactEmptyComponent = __webpack_require__(68);
var ReactNativeComponent = __webpack_require__(69);
var assign = __webpack_require__(39);
var invariant = __webpack_require__(13);
var warning = __webpack_require__(25);
// To avoid a cyclic dependency, we create the final class in this module
var ReactCompositeComponentWrapper = function () {};
assign(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent.Mixin, {
_instantiateReactComponent: instantiateReactComponent
});
function getDeclarationErrorAddendum(owner) {
if (owner) {
var name = owner.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
/**
* Check if the type reference is a known internal type. I.e. not a user
* provided composite type.
*
* @param {function} type
* @return {boolean} Returns true if this is a valid internal type.
*/
function isInternalComponentType(type) {
return typeof type === 'function' && typeof type.prototype !== 'undefined' && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function';
}
/**
* Given a ReactNode, create an instance that will actually be mounted.
*
* @param {ReactNode} node
* @return {object} A new instance of the element's constructor.
* @protected
*/
function instantiateReactComponent(node) {
var instance;
if (node === null || node === false) {
instance = new ReactEmptyComponent(instantiateReactComponent);
} else if (typeof node === 'object') {
var element = node;
!(element && (typeof element.type === 'function' || typeof element.type === 'string')) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Element type is invalid: expected a string (for built-in components) ' + 'or a class/function (for composite components) but got: %s.%s', element.type == null ? element.type : typeof element.type, getDeclarationErrorAddendum(element._owner)) : invariant(false) : undefined;
// Special case string values
if (typeof element.type === 'string') {
instance = ReactNativeComponent.createInternalComponent(element);
} else if (isInternalComponentType(element.type)) {
// This is temporarily available for custom components that are not string
// representations. I.e. ART. Once those are updated to use the string
// representation, we can drop this code path.
instance = new element.type(element);
} else {
instance = new ReactCompositeComponentWrapper();
}
} else if (typeof node === 'string' || typeof node === 'number') {
instance = ReactNativeComponent.createInstanceForText(node);
} else {
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Encountered invalid React node of type %s', typeof node) : invariant(false) : undefined;
}
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(typeof instance.construct === 'function' && typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.') : undefined;
}
// Sets up the instance. This can probably just move into the constructor now.
instance.construct(node);
// These two fields are used by the DOM and ART diffing algorithms
// respectively. Instead of using expandos on components, we should be
// storing the state needed by the diffing algorithms elsewhere.
instance._mountIndex = 0;
instance._mountImage = null;
if (process.env.NODE_ENV !== 'production') {
instance._isOwnerNecessary = false;
instance._warnedAboutRefsInRender = false;
}
// Internal instances should fully constructed at this point, so they should
// not get any new fields added to them at this point.
if (process.env.NODE_ENV !== 'production') {
if (Object.preventExtensions) {
Object.preventExtensions(instance);
}
}
return instance;
}
module.exports = instantiateReactComponent;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 63 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactCompositeComponent
*/
'use strict';
var ReactComponentEnvironment = __webpack_require__(64);
var ReactCurrentOwner = __webpack_require__(5);
var ReactElement = __webpack_require__(42);
var ReactInstanceMap = __webpack_require__(47);
var ReactPerf = __webpack_require__(18);
var ReactPropTypeLocations = __webpack_require__(65);
var ReactPropTypeLocationNames = __webpack_require__(66);
var ReactReconciler = __webpack_require__(50);
var ReactUpdateQueue = __webpack_require__(53);
var assign = __webpack_require__(39);
var emptyObject = __webpack_require__(58);
var invariant = __webpack_require__(13);
var shouldUpdateReactComponent = __webpack_require__(67);
var warning = __webpack_require__(25);
function getDeclarationErrorAddendum(component) {
var owner = component._currentElement._owner || null;
if (owner) {
var name = owner.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
function StatelessComponent(Component) {}
StatelessComponent.prototype.render = function () {
var Component = ReactInstanceMap.get(this)._currentElement.type;
return Component(this.props, this.context, this.updater);
};
/**
* ------------------ The Life-Cycle of a Composite Component ------------------
*
* - constructor: Initialization of state. The instance is now retained.
* - componentWillMount
* - render
* - [children's constructors]
* - [children's componentWillMount and render]
* - [children's componentDidMount]
* - componentDidMount
*
* Update Phases:
* - componentWillReceiveProps (only called if parent updated)
* - shouldComponentUpdate
* - componentWillUpdate
* - render
* - [children's constructors or receive props phases]
* - componentDidUpdate
*
* - componentWillUnmount
* - [children's componentWillUnmount]
* - [children destroyed]
* - (destroyed): The instance is now blank, released by React and ready for GC.
*
* -----------------------------------------------------------------------------
*/
/**
* An incrementing ID assigned to each component when it is mounted. This is
* used to enforce the order in which `ReactUpdates` updates dirty components.
*
* @private
*/
var nextMountID = 1;
/**
* @lends {ReactCompositeComponent.prototype}
*/
var ReactCompositeComponentMixin = {
/**
* Base constructor for all composite component.
*
* @param {ReactElement} element
* @final
* @internal
*/
construct: function (element) {
this._currentElement = element;
this._rootNodeID = null;
this._instance = null;
// See ReactUpdateQueue
this._pendingElement = null;
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
this._renderedComponent = null;
this._context = null;
this._mountOrder = 0;
this._topLevelWrapper = null;
// See ReactUpdates and ReactUpdateQueue.
this._pendingCallbacks = null;
},
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: function (rootID, transaction, context) {
this._context = context;
this._mountOrder = nextMountID++;
this._rootNodeID = rootID;
var publicProps = this._processProps(this._currentElement.props);
var publicContext = this._processContext(context);
var Component = this._currentElement.type;
// Initialize the public class
var inst;
var renderedElement;
// This is a way to detect if Component is a stateless arrow function
// component, which is not newable. It might not be 100% reliable but is
// something we can do until we start detecting that Component extends
// React.Component. We already assume that typeof Component === 'function'.
var canInstantiate = ('prototype' in Component);
if (canInstantiate) {
if (process.env.NODE_ENV !== 'production') {
ReactCurrentOwner.current = this;
try {
inst = new Component(publicProps, publicContext, ReactUpdateQueue);
} finally {
ReactCurrentOwner.current = null;
}
} else {
inst = new Component(publicProps, publicContext, ReactUpdateQueue);
}
}
if (!canInstantiate || inst === null || inst === false || ReactElement.isValidElement(inst)) {
renderedElement = inst;
inst = new StatelessComponent(Component);
}
if (process.env.NODE_ENV !== 'production') {
// This will throw later in _renderValidatedComponent, but add an early
// warning now to help debugging
if (inst.render == null) {
process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`, returned ' + 'null/false from a stateless component, or tried to render an ' + 'element whose type is a function that isn\'t a React component.', Component.displayName || Component.name || 'Component') : undefined;
} else {
// We support ES6 inheriting from React.Component, the module pattern,
// and stateless components, but not ES6 classes that don't extend
process.env.NODE_ENV !== 'production' ? warning(Component.prototype && Component.prototype.isReactComponent || !canInstantiate || !(inst instanceof Component), '%s(...): React component classes must extend React.Component.', Component.displayName || Component.name || 'Component') : undefined;
}
}
// These should be set up in the constructor, but as a convenience for
// simpler class abstractions, we set them up after the fact.
inst.props = publicProps;
inst.context = publicContext;
inst.refs = emptyObject;
inst.updater = ReactUpdateQueue;
this._instance = inst;
// Store a reference from the instance back to the internal representation
ReactInstanceMap.set(inst, this);
if (process.env.NODE_ENV !== 'production') {
// Since plain JS classes are defined without any special initialization
// logic, we can not catch common errors early. Therefore, we have to
// catch them here, at initialization time, instead.
process.env.NODE_ENV !== 'production' ? warning(!inst.getInitialState || inst.getInitialState.isReactClassApproved, 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', this.getName() || 'a component') : undefined;
process.env.NODE_ENV !== 'production' ? warning(!inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved, 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', this.getName() || 'a component') : undefined;
process.env.NODE_ENV !== 'production' ? warning(!inst.propTypes, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', this.getName() || 'a component') : undefined;
process.env.NODE_ENV !== 'production' ? warning(!inst.contextTypes, 'contextTypes was defined as an instance property on %s. Use a ' + 'static property to define contextTypes instead.', this.getName() || 'a component') : undefined;
process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentShouldUpdate !== 'function', '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', this.getName() || 'A component') : undefined;
process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentDidUnmount !== 'function', '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', this.getName() || 'A component') : undefined;
process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentWillRecieveProps !== 'function', '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', this.getName() || 'A component') : undefined;
}
var initialState = inst.state;
if (initialState === undefined) {
inst.state = initialState = null;
}
!(typeof initialState === 'object' && !Array.isArray(initialState)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.state: must be set to an object or null', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined;
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
if (inst.componentWillMount) {
inst.componentWillMount();
// When mounting, calls to `setState` by `componentWillMount` will set
// `this._pendingStateQueue` without triggering a re-render.
if (this._pendingStateQueue) {
inst.state = this._processPendingState(inst.props, inst.context);
}
}
// If not a stateless component, we now render
if (renderedElement === undefined) {
renderedElement = this._renderValidatedComponent();
}
this._renderedComponent = this._instantiateReactComponent(renderedElement);
var markup = ReactReconciler.mountComponent(this._renderedComponent, rootID, transaction, this._processChildContext(context));
if (inst.componentDidMount) {
transaction.getReactMountReady().enqueue(inst.componentDidMount, inst);
}
return markup;
},
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function () {
var inst = this._instance;
if (inst.componentWillUnmount) {
inst.componentWillUnmount();
}
ReactReconciler.unmountComponent(this._renderedComponent);
this._renderedComponent = null;
this._instance = null;
// Reset pending fields
// Even if this component is scheduled for another update in ReactUpdates,
// it would still be ignored because these fields are reset.
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
this._pendingCallbacks = null;
this._pendingElement = null;
// These fields do not really need to be reset since this object is no
// longer accessible.
this._context = null;
this._rootNodeID = null;
this._topLevelWrapper = null;
// Delete the reference from the instance to this internal representation
// which allow the internals to be properly cleaned up even if the user
// leaks a reference to the public instance.
ReactInstanceMap.remove(inst);
// Some existing components rely on inst.props even after they've been
// destroyed (in event handlers).
// TODO: inst.props = null;
// TODO: inst.state = null;
// TODO: inst.context = null;
},
/**
* Filters the context object to only contain keys specified in
* `contextTypes`
*
* @param {object} context
* @return {?object}
* @private
*/
_maskContext: function (context) {
var maskedContext = null;
var Component = this._currentElement.type;
var contextTypes = Component.contextTypes;
if (!contextTypes) {
return emptyObject;
}
maskedContext = {};
for (var contextName in contextTypes) {
maskedContext[contextName] = context[contextName];
}
return maskedContext;
},
/**
* Filters the context object to only contain keys specified in
* `contextTypes`, and asserts that they are valid.
*
* @param {object} context
* @return {?object}
* @private
*/
_processContext: function (context) {
var maskedContext = this._maskContext(context);
if (process.env.NODE_ENV !== 'production') {
var Component = this._currentElement.type;
if (Component.contextTypes) {
this._checkPropTypes(Component.contextTypes, maskedContext, ReactPropTypeLocations.context);
}
}
return maskedContext;
},
/**
* @param {object} currentContext
* @return {object}
* @private
*/
_processChildContext: function (currentContext) {
var Component = this._currentElement.type;
var inst = this._instance;
var childContext = inst.getChildContext && inst.getChildContext();
if (childContext) {
!(typeof Component.childContextTypes === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined;
if (process.env.NODE_ENV !== 'production') {
this._checkPropTypes(Component.childContextTypes, childContext, ReactPropTypeLocations.childContext);
}
for (var name in childContext) {
!(name in Component.childContextTypes) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || 'ReactCompositeComponent', name) : invariant(false) : undefined;
}
return assign({}, currentContext, childContext);
}
return currentContext;
},
/**
* Processes props by setting default values for unspecified props and
* asserting that the props are valid. Does not mutate its argument; returns
* a new props object with defaults merged in.
*
* @param {object} newProps
* @return {object}
* @private
*/
_processProps: function (newProps) {
if (process.env.NODE_ENV !== 'production') {
var Component = this._currentElement.type;
if (Component.propTypes) {
this._checkPropTypes(Component.propTypes, newProps, ReactPropTypeLocations.prop);
}
}
return newProps;
},
/**
* Assert that the props are valid
*
* @param {object} propTypes Map of prop name to a ReactPropType
* @param {object} props
* @param {string} location e.g. "prop", "context", "child context"
* @private
*/
_checkPropTypes: function (propTypes, props, location) {
// TODO: Stop validating prop types here and only use the element
// validation.
var componentName = this.getName();
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error;
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
!(typeof propTypes[propName] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually ' + 'from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName) : invariant(false) : undefined;
error = propTypes[propName](props, propName, componentName, location);
} catch (ex) {
error = ex;
}
if (error instanceof Error) {
// We may want to extend this logic for similar errors in
// top-level render calls, so I'm abstracting it away into
// a function to minimize refactoring in the future
var addendum = getDeclarationErrorAddendum(this);
if (location === ReactPropTypeLocations.prop) {
// Preface gives us something to blacklist in warning module
process.env.NODE_ENV !== 'production' ? warning(false, 'Failed Composite propType: %s%s', error.message, addendum) : undefined;
} else {
process.env.NODE_ENV !== 'production' ? warning(false, 'Failed Context Types: %s%s', error.message, addendum) : undefined;
}
}
}
}
},
receiveComponent: function (nextElement, transaction, nextContext) {
var prevElement = this._currentElement;
var prevContext = this._context;
this._pendingElement = null;
this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext);
},
/**
* If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate`
* is set, update the component.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function (transaction) {
if (this._pendingElement != null) {
ReactReconciler.receiveComponent(this, this._pendingElement || this._currentElement, transaction, this._context);
}
if (this._pendingStateQueue !== null || this._pendingForceUpdate) {
this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context);
}
},
/**
* Perform an update to a mounted component. The componentWillReceiveProps and
* shouldComponentUpdate methods are called, then (assuming the update isn't
* skipped) the remaining update lifecycle methods are called and the DOM
* representation is updated.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @param {ReactElement} prevParentElement
* @param {ReactElement} nextParentElement
* @internal
* @overridable
*/
updateComponent: function (transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) {
var inst = this._instance;
var nextContext = this._context === nextUnmaskedContext ? inst.context : this._processContext(nextUnmaskedContext);
var nextProps;
// Distinguish between a props update versus a simple state update
if (prevParentElement === nextParentElement) {
// Skip checking prop types again -- we don't read inst.props to avoid
// warning for DOM component props in this upgrade
nextProps = nextParentElement.props;
} else {
nextProps = this._processProps(nextParentElement.props);
// An update here will schedule an update but immediately set
// _pendingStateQueue which will ensure that any state updates gets
// immediately reconciled instead of waiting for the next batch.
if (inst.componentWillReceiveProps) {
inst.componentWillReceiveProps(nextProps, nextContext);
}
}
var nextState = this._processPendingState(nextProps, nextContext);
var shouldUpdate = this._pendingForceUpdate || !inst.shouldComponentUpdate || inst.shouldComponentUpdate(nextProps, nextState, nextContext);
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(typeof shouldUpdate !== 'undefined', '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', this.getName() || 'ReactCompositeComponent') : undefined;
}
if (shouldUpdate) {
this._pendingForceUpdate = false;
// Will set `this.props`, `this.state` and `this.context`.
this._performComponentUpdate(nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext);
} else {
// If it's determined that a component should not update, we still want
// to set props and state but we shortcut the rest of the update.
this._currentElement = nextParentElement;
this._context = nextUnmaskedContext;
inst.props = nextProps;
inst.state = nextState;
inst.context = nextContext;
}
},
_processPendingState: function (props, context) {
var inst = this._instance;
var queue = this._pendingStateQueue;
var replace = this._pendingReplaceState;
this._pendingReplaceState = false;
this._pendingStateQueue = null;
if (!queue) {
return inst.state;
}
if (replace && queue.length === 1) {
return queue[0];
}
var nextState = assign({}, replace ? queue[0] : inst.state);
for (var i = replace ? 1 : 0; i < queue.length; i++) {
var partial = queue[i];
assign(nextState, typeof partial === 'function' ? partial.call(inst, nextState, props, context) : partial);
}
return nextState;
},
/**
* Merges new props and state, notifies delegate methods of update and
* performs update.
*
* @param {ReactElement} nextElement Next element
* @param {object} nextProps Next public object to set as properties.
* @param {?object} nextState Next object to set as state.
* @param {?object} nextContext Next public object to set as context.
* @param {ReactReconcileTransaction} transaction
* @param {?object} unmaskedContext
* @private
*/
_performComponentUpdate: function (nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) {
var inst = this._instance;
var hasComponentDidUpdate = Boolean(inst.componentDidUpdate);
var prevProps;
var prevState;
var prevContext;
if (hasComponentDidUpdate) {
prevProps = inst.props;
prevState = inst.state;
prevContext = inst.context;
}
if (inst.componentWillUpdate) {
inst.componentWillUpdate(nextProps, nextState, nextContext);
}
this._currentElement = nextElement;
this._context = unmaskedContext;
inst.props = nextProps;
inst.state = nextState;
inst.context = nextContext;
this._updateRenderedComponent(transaction, unmaskedContext);
if (hasComponentDidUpdate) {
transaction.getReactMountReady().enqueue(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), inst);
}
},
/**
* Call the component's `render` method and update the DOM accordingly.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
_updateRenderedComponent: function (transaction, context) {
var prevComponentInstance = this._renderedComponent;
var prevRenderedElement = prevComponentInstance._currentElement;
var nextRenderedElement = this._renderValidatedComponent();
if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) {
ReactReconciler.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context));
} else {
// These two IDs are actually the same! But nothing should rely on that.
var thisID = this._rootNodeID;
var prevComponentID = prevComponentInstance._rootNodeID;
ReactReconciler.unmountComponent(prevComponentInstance);
this._renderedComponent = this._instantiateReactComponent(nextRenderedElement);
var nextMarkup = ReactReconciler.mountComponent(this._renderedComponent, thisID, transaction, this._processChildContext(context));
this._replaceNodeWithMarkupByID(prevComponentID, nextMarkup);
}
},
/**
* @protected
*/
_replaceNodeWithMarkupByID: function (prevComponentID, nextMarkup) {
ReactComponentEnvironment.replaceNodeWithMarkupByID(prevComponentID, nextMarkup);
},
/**
* @protected
*/
_renderValidatedComponentWithoutOwnerOrContext: function () {
var inst = this._instance;
var renderedComponent = inst.render();
if (process.env.NODE_ENV !== 'production') {
// We allow auto-mocks to proceed as if they're returning null.
if (typeof renderedComponent === 'undefined' && inst.render._isMockFunction) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
renderedComponent = null;
}
}
return renderedComponent;
},
/**
* @private
*/
_renderValidatedComponent: function () {
var renderedComponent;
ReactCurrentOwner.current = this;
try {
renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext();
} finally {
ReactCurrentOwner.current = null;
}
!(
// TODO: An `isValidNode` function would probably be more appropriate
renderedComponent === null || renderedComponent === false || ReactElement.isValidElement(renderedComponent)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.render(): A valid ReactComponent must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined;
return renderedComponent;
},
/**
* Lazily allocates the refs object and stores `component` as `ref`.
*
* @param {string} ref Reference name.
* @param {component} component Component to store as `ref`.
* @final
* @private
*/
attachRef: function (ref, component) {
var inst = this.getPublicInstance();
!(inst != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Stateless function components cannot have refs.') : invariant(false) : undefined;
var publicComponentInstance = component.getPublicInstance();
if (process.env.NODE_ENV !== 'production') {
var componentName = component && component.getName ? component.getName() : 'a component';
process.env.NODE_ENV !== 'production' ? warning(publicComponentInstance != null, 'Stateless function components cannot be given refs ' + '(See ref "%s" in %s created by %s). ' + 'Attempts to access this ref will fail.', ref, componentName, this.getName()) : undefined;
}
var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs;
refs[ref] = publicComponentInstance;
},
/**
* Detaches a reference name.
*
* @param {string} ref Name to dereference.
* @final
* @private
*/
detachRef: function (ref) {
var refs = this.getPublicInstance().refs;
delete refs[ref];
},
/**
* Get a text description of the component that can be used to identify it
* in error messages.
* @return {string} The name or null.
* @internal
*/
getName: function () {
var type = this._currentElement.type;
var constructor = this._instance && this._instance.constructor;
return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null;
},
/**
* Get the publicly accessible representation of this component - i.e. what
* is exposed by refs and returned by render. Can be null for stateless
* components.
*
* @return {ReactComponent} the public component instance.
* @internal
*/
getPublicInstance: function () {
var inst = this._instance;
if (inst instanceof StatelessComponent) {
return null;
}
return inst;
},
// Stub
_instantiateReactComponent: null
};
ReactPerf.measureMethods(ReactCompositeComponentMixin, 'ReactCompositeComponent', {
mountComponent: 'mountComponent',
updateComponent: 'updateComponent',
_renderValidatedComponent: '_renderValidatedComponent'
});
var ReactCompositeComponent = {
Mixin: ReactCompositeComponentMixin
};
module.exports = ReactCompositeComponent;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 64 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactComponentEnvironment
*/
'use strict';
var invariant = __webpack_require__(13);
var injected = false;
var ReactComponentEnvironment = {
/**
* Optionally injectable environment dependent cleanup hook. (server vs.
* browser etc). Example: A browser system caches DOM nodes based on component
* ID and must remove that cache entry when this instance is unmounted.
*/
unmountIDFromEnvironment: null,
/**
* Optionally injectable hook for swapping out mount images in the middle of
* the tree.
*/
replaceNodeWithMarkupByID: null,
/**
* Optionally injectable hook for processing a queue of child updates. Will
* later move into MultiChildComponents.
*/
processChildrenUpdates: null,
injection: {
injectEnvironment: function (environment) {
!!injected ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactCompositeComponent: injectEnvironment() can only be called once.') : invariant(false) : undefined;
ReactComponentEnvironment.unmountIDFromEnvironment = environment.unmountIDFromEnvironment;
ReactComponentEnvironment.replaceNodeWithMarkupByID = environment.replaceNodeWithMarkupByID;
ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates;
injected = true;
}
}
};
module.exports = ReactComponentEnvironment;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 65 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactPropTypeLocations
*/
'use strict';
var keyMirror = __webpack_require__(17);
var ReactPropTypeLocations = keyMirror({
prop: null,
context: null,
childContext: null
});
module.exports = ReactPropTypeLocations;
/***/ },
/* 66 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactPropTypeLocationNames
*/
'use strict';
var ReactPropTypeLocationNames = {};
if (process.env.NODE_ENV !== 'production') {
ReactPropTypeLocationNames = {
prop: 'prop',
context: 'context',
childContext: 'child context'
};
}
module.exports = ReactPropTypeLocationNames;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 67 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule shouldUpdateReactComponent
* @typechecks static-only
*/
'use strict';
/**
* Given a `prevElement` and `nextElement`, determines if the existing
* instance should be updated as opposed to being destroyed or replaced by a new
* instance. Both arguments are elements. This ensures that this logic can
* operate on stateless trees without any backing instance.
*
* @param {?object} prevElement
* @param {?object} nextElement
* @return {boolean} True if the existing instance should be updated.
* @protected
*/
function shouldUpdateReactComponent(prevElement, nextElement) {
var prevEmpty = prevElement === null || prevElement === false;
var nextEmpty = nextElement === null || nextElement === false;
if (prevEmpty || nextEmpty) {
return prevEmpty === nextEmpty;
}
var prevType = typeof prevElement;
var nextType = typeof nextElement;
if (prevType === 'string' || prevType === 'number') {
return nextType === 'string' || nextType === 'number';
} else {
return nextType === 'object' && prevElement.type === nextElement.type && prevElement.key === nextElement.key;
}
return false;
}
module.exports = shouldUpdateReactComponent;
/***/ },
/* 68 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactEmptyComponent
*/
'use strict';
var ReactElement = __webpack_require__(42);
var ReactEmptyComponentRegistry = __webpack_require__(44);
var ReactReconciler = __webpack_require__(50);
var assign = __webpack_require__(39);
var placeholderElement;
var ReactEmptyComponentInjection = {
injectEmptyComponent: function (component) {
placeholderElement = ReactElement.createElement(component);
}
};
var ReactEmptyComponent = function (instantiate) {
this._currentElement = null;
this._rootNodeID = null;
this._renderedComponent = instantiate(placeholderElement);
};
assign(ReactEmptyComponent.prototype, {
construct: function (element) {},
mountComponent: function (rootID, transaction, context) {
ReactEmptyComponentRegistry.registerNullComponentID(rootID);
this._rootNodeID = rootID;
return ReactReconciler.mountComponent(this._renderedComponent, rootID, transaction, context);
},
receiveComponent: function () {},
unmountComponent: function (rootID, transaction, context) {
ReactReconciler.unmountComponent(this._renderedComponent);
ReactEmptyComponentRegistry.deregisterNullComponentID(this._rootNodeID);
this._rootNodeID = null;
this._renderedComponent = null;
}
});
ReactEmptyComponent.injection = ReactEmptyComponentInjection;
module.exports = ReactEmptyComponent;
/***/ },
/* 69 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactNativeComponent
*/
'use strict';
var assign = __webpack_require__(39);
var invariant = __webpack_require__(13);
var autoGenerateWrapperClass = null;
var genericComponentClass = null;
// This registry keeps track of wrapper classes around native tags.
var tagToComponentClass = {};
var textComponentClass = null;
var ReactNativeComponentInjection = {
// This accepts a class that receives the tag string. This is a catch all
// that can render any kind of tag.
injectGenericComponentClass: function (componentClass) {
genericComponentClass = componentClass;
},
// This accepts a text component class that takes the text string to be
// rendered as props.
injectTextComponentClass: function (componentClass) {
textComponentClass = componentClass;
},
// This accepts a keyed object with classes as values. Each key represents a
// tag. That particular tag will use this class instead of the generic one.
injectComponentClasses: function (componentClasses) {
assign(tagToComponentClass, componentClasses);
}
};
/**
* Get a composite component wrapper class for a specific tag.
*
* @param {ReactElement} element The tag for which to get the class.
* @return {function} The React class constructor function.
*/
function getComponentClassForElement(element) {
if (typeof element.type === 'function') {
return element.type;
}
var tag = element.type;
var componentClass = tagToComponentClass[tag];
if (componentClass == null) {
tagToComponentClass[tag] = componentClass = autoGenerateWrapperClass(tag);
}
return componentClass;
}
/**
* Get a native internal component class for a specific tag.
*
* @param {ReactElement} element The element to create.
* @return {function} The internal class constructor function.
*/
function createInternalComponent(element) {
!genericComponentClass ? process.env.NODE_ENV !== 'production' ? invariant(false, 'There is no registered component for the tag %s', element.type) : invariant(false) : undefined;
return new genericComponentClass(element.type, element.props);
}
/**
* @param {ReactText} text
* @return {ReactComponent}
*/
function createInstanceForText(text) {
return new textComponentClass(text);
}
/**
* @param {ReactComponent} component
* @return {boolean}
*/
function isTextComponent(component) {
return component instanceof textComponentClass;
}
var ReactNativeComponent = {
getComponentClassForElement: getComponentClassForElement,
createInternalComponent: createInternalComponent,
createInstanceForText: createInstanceForText,
isTextComponent: isTextComponent,
injection: ReactNativeComponentInjection
};
module.exports = ReactNativeComponent;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 70 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule validateDOMNesting
*/
'use strict';
var assign = __webpack_require__(39);
var emptyFunction = __webpack_require__(15);
var warning = __webpack_require__(25);
var validateDOMNesting = emptyFunction;
if (process.env.NODE_ENV !== 'production') {
// This validation code was written based on the HTML5 parsing spec:
// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
//
// Note: this does not catch all invalid nesting, nor does it try to (as it's
// not clear what practical benefit doing so provides); instead, we warn only
// for cases where the parser will give a parse tree differing from what React
// intended. For example, <b><div></div></b> is invalid but we don't warn
// because it still parses correctly; we do warn for other cases like nested
// <p> tags where the beginning of the second element implicitly closes the
// first, causing a confusing mess.
// https://html.spec.whatwg.org/multipage/syntax.html#special
var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp'];
// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template',
// https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
// TODO: Distinguish by namespace here -- for <title>, including it here
// errs on the side of fewer warnings
'foreignObject', 'desc', 'title'];
// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
var buttonScopeTags = inScopeTags.concat(['button']);
// https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'];
var emptyAncestorInfo = {
parentTag: null,
formTag: null,
aTagInScope: null,
buttonTagInScope: null,
nobrTagInScope: null,
pTagInButtonScope: null,
listItemTagAutoclosing: null,
dlItemTagAutoclosing: null
};
var updatedAncestorInfo = function (oldInfo, tag, instance) {
var ancestorInfo = assign({}, oldInfo || emptyAncestorInfo);
var info = { tag: tag, instance: instance };
if (inScopeTags.indexOf(tag) !== -1) {
ancestorInfo.aTagInScope = null;
ancestorInfo.buttonTagInScope = null;
ancestorInfo.nobrTagInScope = null;
}
if (buttonScopeTags.indexOf(tag) !== -1) {
ancestorInfo.pTagInButtonScope = null;
}
// See rules for 'li', 'dd', 'dt' start tags in
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') {
ancestorInfo.listItemTagAutoclosing = null;
ancestorInfo.dlItemTagAutoclosing = null;
}
ancestorInfo.parentTag = info;
if (tag === 'form') {
ancestorInfo.formTag = info;
}
if (tag === 'a') {
ancestorInfo.aTagInScope = info;
}
if (tag === 'button') {
ancestorInfo.buttonTagInScope = info;
}
if (tag === 'nobr') {
ancestorInfo.nobrTagInScope = info;
}
if (tag === 'p') {
ancestorInfo.pTagInButtonScope = info;
}
if (tag === 'li') {
ancestorInfo.listItemTagAutoclosing = info;
}
if (tag === 'dd' || tag === 'dt') {
ancestorInfo.dlItemTagAutoclosing = info;
}
return ancestorInfo;
};
/**
* Returns whether
*/
var isTagValidWithParent = function (tag, parentTag) {
// First, let's check if we're in an unusual parsing mode...
switch (parentTag) {
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
case 'select':
return tag === 'option' || tag === 'optgroup' || tag === '#text';
case 'optgroup':
return tag === 'option' || tag === '#text';
// Strictly speaking, seeing an <option> doesn't mean we're in a <select>
// but
case 'option':
return tag === '#text';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
// No special behavior since these rules fall back to "in body" mode for
// all except special table nodes which cause bad parsing behavior anyway.
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr
case 'tr':
return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody
case 'tbody':
case 'thead':
case 'tfoot':
return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup
case 'colgroup':
return tag === 'col' || tag === 'template';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable
case 'table':
return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead
case 'head':
return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template';
// https://html.spec.whatwg.org/multipage/semantics.html#the-html-element
case 'html':
return tag === 'head' || tag === 'body';
}
// Probably in the "in body" parsing mode, so we outlaw only tag combos
// where the parsing rules cause implicit opens or closes to be added.
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
switch (tag) {
case 'h1':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6':
return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6';
case 'rp':
case 'rt':
return impliedEndTags.indexOf(parentTag) === -1;
case 'caption':
case 'col':
case 'colgroup':
case 'frame':
case 'head':
case 'tbody':
case 'td':
case 'tfoot':
case 'th':
case 'thead':
case 'tr':
// These tags are only valid with a few parents that have special child
// parsing rules -- if we're down here, then none of those matched and
// so we allow it only if we don't know what the parent is, as all other
// cases are invalid.
return parentTag == null;
}
return true;
};
/**
* Returns whether
*/
var findInvalidAncestorForTag = function (tag, ancestorInfo) {
switch (tag) {
case 'address':
case 'article':
case 'aside':
case 'blockquote':
case 'center':
case 'details':
case 'dialog':
case 'dir':
case 'div':
case 'dl':
case 'fieldset':
case 'figcaption':
case 'figure':
case 'footer':
case 'header':
case 'hgroup':
case 'main':
case 'menu':
case 'nav':
case 'ol':
case 'p':
case 'section':
case 'summary':
case 'ul':
case 'pre':
case 'listing':
case 'table':
case 'hr':
case 'xmp':
case 'h1':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6':
return ancestorInfo.pTagInButtonScope;
case 'form':
return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;
case 'li':
return ancestorInfo.listItemTagAutoclosing;
case 'dd':
case 'dt':
return ancestorInfo.dlItemTagAutoclosing;
case 'button':
return ancestorInfo.buttonTagInScope;
case 'a':
// Spec says something about storing a list of markers, but it sounds
// equivalent to this check.
return ancestorInfo.aTagInScope;
case 'nobr':
return ancestorInfo.nobrTagInScope;
}
return null;
};
/**
* Given a ReactCompositeComponent instance, return a list of its recursive
* owners, starting at the root and ending with the instance itself.
*/
var findOwnerStack = function (instance) {
if (!instance) {
return [];
}
var stack = [];
/*eslint-disable space-after-keywords */
do {
/*eslint-enable space-after-keywords */
stack.push(instance);
} while (instance = instance._currentElement._owner);
stack.reverse();
return stack;
};
var didWarn = {};
validateDOMNesting = function (childTag, childInstance, ancestorInfo) {
ancestorInfo = ancestorInfo || emptyAncestorInfo;
var parentInfo = ancestorInfo.parentTag;
var parentTag = parentInfo && parentInfo.tag;
var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
var problematic = invalidParent || invalidAncestor;
if (problematic) {
var ancestorTag = problematic.tag;
var ancestorInstance = problematic.instance;
var childOwner = childInstance && childInstance._currentElement._owner;
var ancestorOwner = ancestorInstance && ancestorInstance._currentElement._owner;
var childOwners = findOwnerStack(childOwner);
var ancestorOwners = findOwnerStack(ancestorOwner);
var minStackLen = Math.min(childOwners.length, ancestorOwners.length);
var i;
var deepestCommon = -1;
for (i = 0; i < minStackLen; i++) {
if (childOwners[i] === ancestorOwners[i]) {
deepestCommon = i;
} else {
break;
}
}
var UNKNOWN = '(unknown)';
var childOwnerNames = childOwners.slice(deepestCommon + 1).map(function (inst) {
return inst.getName() || UNKNOWN;
});
var ancestorOwnerNames = ancestorOwners.slice(deepestCommon + 1).map(function (inst) {
return inst.getName() || UNKNOWN;
});
var ownerInfo = [].concat(
// If the parent and child instances have a common owner ancestor, start
// with that -- otherwise we just start with the parent's owners.
deepestCommon !== -1 ? childOwners[deepestCommon].getName() || UNKNOWN : [], ancestorOwnerNames, ancestorTag,
// If we're warning about an invalid (non-parent) ancestry, add '...'
invalidAncestor ? ['...'] : [], childOwnerNames, childTag).join(' > ');
var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + ownerInfo;
if (didWarn[warnKey]) {
return;
}
didWarn[warnKey] = true;
if (invalidParent) {
var info = '';
if (ancestorTag === 'table' && childTag === 'tr') {
info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.';
}
process.env.NODE_ENV !== 'production' ? warning(false, 'validateDOMNesting(...): <%s> cannot appear as a child of <%s>. ' + 'See %s.%s', childTag, ancestorTag, ownerInfo, info) : undefined;
} else {
process.env.NODE_ENV !== 'production' ? warning(false, 'validateDOMNesting(...): <%s> cannot appear as a descendant of ' + '<%s>. See %s.', childTag, ancestorTag, ownerInfo) : undefined;
}
}
};
validateDOMNesting.ancestorInfoContextKey = '__validateDOMNesting_ancestorInfo$' + Math.random().toString(36).slice(2);
validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo;
// For testing
validateDOMNesting.isTagValidInContext = function (tag, ancestorInfo) {
ancestorInfo = ancestorInfo || emptyAncestorInfo;
var parentInfo = ancestorInfo.parentTag;
var parentTag = parentInfo && parentInfo.tag;
return isTagValidWithParent(tag, parentTag) && !findInvalidAncestorForTag(tag, ancestorInfo);
};
}
module.exports = validateDOMNesting;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 71 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDefaultInjection
*/
'use strict';
var BeforeInputEventPlugin = __webpack_require__(72);
var ChangeEventPlugin = __webpack_require__(80);
var ClientReactRootIndex = __webpack_require__(83);
var DefaultEventPluginOrder = __webpack_require__(84);
var EnterLeaveEventPlugin = __webpack_require__(85);
var ExecutionEnvironment = __webpack_require__(9);
var HTMLDOMPropertyConfig = __webpack_require__(89);
var ReactBrowserComponentMixin = __webpack_require__(90);
var ReactComponentBrowserEnvironment = __webpack_require__(26);
var ReactDefaultBatchingStrategy = __webpack_require__(92);
var ReactDOMComponent = __webpack_require__(93);
var ReactDOMTextComponent = __webpack_require__(6);
var ReactEventListener = __webpack_require__(118);
var ReactInjection = __webpack_require__(121);
var ReactInstanceHandles = __webpack_require__(45);
var ReactMount = __webpack_require__(28);
var ReactReconcileTransaction = __webpack_require__(125);
var SelectEventPlugin = __webpack_require__(130);
var ServerReactRootIndex = __webpack_require__(131);
var SimpleEventPlugin = __webpack_require__(132);
var SVGDOMPropertyConfig = __webpack_require__(141);
var alreadyInjected = false;
function inject() {
if (alreadyInjected) {
// TODO: This is currently true because these injections are shared between
// the client and the server package. They should be built independently
// and not share any injection state. Then this problem will be solved.
return;
}
alreadyInjected = true;
ReactInjection.EventEmitter.injectReactEventListener(ReactEventListener);
/**
* Inject modules for resolving DOM hierarchy and plugin ordering.
*/
ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder);
ReactInjection.EventPluginHub.injectInstanceHandle(ReactInstanceHandles);
ReactInjection.EventPluginHub.injectMount(ReactMount);
/**
* Some important event plugins included by default (without having to require
* them).
*/
ReactInjection.EventPluginHub.injectEventPluginsByName({
SimpleEventPlugin: SimpleEventPlugin,
EnterLeaveEventPlugin: EnterLeaveEventPlugin,
ChangeEventPlugin: ChangeEventPlugin,
SelectEventPlugin: SelectEventPlugin,
BeforeInputEventPlugin: BeforeInputEventPlugin
});
ReactInjection.NativeComponent.injectGenericComponentClass(ReactDOMComponent);
ReactInjection.NativeComponent.injectTextComponentClass(ReactDOMTextComponent);
ReactInjection.Class.injectMixin(ReactBrowserComponentMixin);
ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig);
ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig);
ReactInjection.EmptyComponent.injectEmptyComponent('noscript');
ReactInjection.Updates.injectReconcileTransaction(ReactReconcileTransaction);
ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy);
ReactInjection.RootIndex.injectCreateReactRootIndex(ExecutionEnvironment.canUseDOM ? ClientReactRootIndex.createReactRootIndex : ServerReactRootIndex.createReactRootIndex);
ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment);
if (process.env.NODE_ENV !== 'production') {
var url = ExecutionEnvironment.canUseDOM && window.location.href || '';
if (/[?&]react_perf\b/.test(url)) {
var ReactDefaultPerf = __webpack_require__(142);
ReactDefaultPerf.start();
}
}
}
module.exports = {
inject: inject
};
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 72 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015 Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule BeforeInputEventPlugin
* @typechecks static-only
*/
'use strict';
var EventConstants = __webpack_require__(30);
var EventPropagators = __webpack_require__(73);
var ExecutionEnvironment = __webpack_require__(9);
var FallbackCompositionState = __webpack_require__(74);
var SyntheticCompositionEvent = __webpack_require__(76);
var SyntheticInputEvent = __webpack_require__(78);
var keyOf = __webpack_require__(79);
var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
var START_KEYCODE = 229;
var canUseCompositionEvent = ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window;
var documentMode = null;
if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) {
documentMode = document.documentMode;
}
// Webkit offers a very useful `textInput` event that can be used to
// directly represent `beforeInput`. The IE `textinput` event is not as
// useful, so we don't use it.
var canUseTextInputEvent = ExecutionEnvironment.canUseDOM && 'TextEvent' in window && !documentMode && !isPresto();
// In IE9+, we have access to composition events, but the data supplied
// by the native compositionend event may be incorrect. Japanese ideographic
// spaces, for instance (\u3000) are not recorded correctly.
var useFallbackCompositionData = ExecutionEnvironment.canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);
/**
* Opera <= 12 includes TextEvent in window, but does not fire
* text input events. Rely on keypress instead.
*/
function isPresto() {
var opera = window.opera;
return typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12;
}
var SPACEBAR_CODE = 32;
var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE);
var topLevelTypes = EventConstants.topLevelTypes;
// Events and their corresponding property names.
var eventTypes = {
beforeInput: {
phasedRegistrationNames: {
bubbled: keyOf({ onBeforeInput: null }),
captured: keyOf({ onBeforeInputCapture: null })
},
dependencies: [topLevelTypes.topCompositionEnd, topLevelTypes.topKeyPress, topLevelTypes.topTextInput, topLevelTypes.topPaste]
},
compositionEnd: {
phasedRegistrationNames: {
bubbled: keyOf({ onCompositionEnd: null }),
captured: keyOf({ onCompositionEndCapture: null })
},
dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionEnd, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown]
},
compositionStart: {
phasedRegistrationNames: {
bubbled: keyOf({ onCompositionStart: null }),
captured: keyOf({ onCompositionStartCapture: null })
},
dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionStart, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown]
},
compositionUpdate: {
phasedRegistrationNames: {
bubbled: keyOf({ onCompositionUpdate: null }),
captured: keyOf({ onCompositionUpdateCapture: null })
},
dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionUpdate, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown]
}
};
// Track whether we've ever handled a keypress on the space key.
var hasSpaceKeypress = false;
/**
* Return whether a native keypress event is assumed to be a command.
* This is required because Firefox fires `keypress` events for key commands
* (cut, copy, select-all, etc.) even though no character is inserted.
*/
function isKeypressCommand(nativeEvent) {
return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) &&
// ctrlKey && altKey is equivalent to AltGr, and is not a command.
!(nativeEvent.ctrlKey && nativeEvent.altKey);
}
/**
* Translate native top level events into event types.
*
* @param {string} topLevelType
* @return {object}
*/
function getCompositionEventType(topLevelType) {
switch (topLevelType) {
case topLevelTypes.topCompositionStart:
return eventTypes.compositionStart;
case topLevelTypes.topCompositionEnd:
return eventTypes.compositionEnd;
case topLevelTypes.topCompositionUpdate:
return eventTypes.compositionUpdate;
}
}
/**
* Does our fallback best-guess model think this event signifies that
* composition has begun?
*
* @param {string} topLevelType
* @param {object} nativeEvent
* @return {boolean}
*/
function isFallbackCompositionStart(topLevelType, nativeEvent) {
return topLevelType === topLevelTypes.topKeyDown && nativeEvent.keyCode === START_KEYCODE;
}
/**
* Does our fallback mode think that this event is the end of composition?
*
* @param {string} topLevelType
* @param {object} nativeEvent
* @return {boolean}
*/
function isFallbackCompositionEnd(topLevelType, nativeEvent) {
switch (topLevelType) {
case topLevelTypes.topKeyUp:
// Command keys insert or clear IME input.
return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
case topLevelTypes.topKeyDown:
// Expect IME keyCode on each keydown. If we get any other
// code we must have exited earlier.
return nativeEvent.keyCode !== START_KEYCODE;
case topLevelTypes.topKeyPress:
case topLevelTypes.topMouseDown:
case topLevelTypes.topBlur:
// Events are not possible without cancelling IME.
return true;
default:
return false;
}
}
/**
* Google Input Tools provides composition data via a CustomEvent,
* with the `data` property populated in the `detail` object. If this
* is available on the event object, use it. If not, this is a plain
* composition event and we have nothing special to extract.
*
* @param {object} nativeEvent
* @return {?string}
*/
function getDataFromCustomEvent(nativeEvent) {
var detail = nativeEvent.detail;
if (typeof detail === 'object' && 'data' in detail) {
return detail.data;
}
return null;
}
// Track the current IME composition fallback object, if any.
var currentComposition = null;
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {?object} A SyntheticCompositionEvent.
*/
function extractCompositionEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
var eventType;
var fallbackData;
if (canUseCompositionEvent) {
eventType = getCompositionEventType(topLevelType);
} else if (!currentComposition) {
if (isFallbackCompositionStart(topLevelType, nativeEvent)) {
eventType = eventTypes.compositionStart;
}
} else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) {
eventType = eventTypes.compositionEnd;
}
if (!eventType) {
return null;
}
if (useFallbackCompositionData) {
// The current composition is stored statically and must not be
// overwritten while composition continues.
if (!currentComposition && eventType === eventTypes.compositionStart) {
currentComposition = FallbackCompositionState.getPooled(topLevelTarget);
} else if (eventType === eventTypes.compositionEnd) {
if (currentComposition) {
fallbackData = currentComposition.getData();
}
}
}
var event = SyntheticCompositionEvent.getPooled(eventType, topLevelTargetID, nativeEvent, nativeEventTarget);
if (fallbackData) {
// Inject data generated from fallback path into the synthetic event.
// This matches the property of native CompositionEventInterface.
event.data = fallbackData;
} else {
var customData = getDataFromCustomEvent(nativeEvent);
if (customData !== null) {
event.data = customData;
}
}
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {object} nativeEvent Native browser event.
* @return {?string} The string corresponding to this `beforeInput` event.
*/
function getNativeBeforeInputChars(topLevelType, nativeEvent) {
switch (topLevelType) {
case topLevelTypes.topCompositionEnd:
return getDataFromCustomEvent(nativeEvent);
case topLevelTypes.topKeyPress:
/**
* If native `textInput` events are available, our goal is to make
* use of them. However, there is a special case: the spacebar key.
* In Webkit, preventing default on a spacebar `textInput` event
* cancels character insertion, but it *also* causes the browser
* to fall back to its default spacebar behavior of scrolling the
* page.
*
* Tracking at:
* https://code.google.com/p/chromium/issues/detail?id=355103
*
* To avoid this issue, use the keypress event as if no `textInput`
* event is available.
*/
var which = nativeEvent.which;
if (which !== SPACEBAR_CODE) {
return null;
}
hasSpaceKeypress = true;
return SPACEBAR_CHAR;
case topLevelTypes.topTextInput:
// Record the characters to be added to the DOM.
var chars = nativeEvent.data;
// If it's a spacebar character, assume that we have already handled
// it at the keypress level and bail immediately. Android Chrome
// doesn't give us keycodes, so we need to blacklist it.
if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
return null;
}
return chars;
default:
// For other native event types, do nothing.
return null;
}
}
/**
* For browsers that do not provide the `textInput` event, extract the
* appropriate string to use for SyntheticInputEvent.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {object} nativeEvent Native browser event.
* @return {?string} The fallback string for this `beforeInput` event.
*/
function getFallbackBeforeInputChars(topLevelType, nativeEvent) {
// If we are currently composing (IME) and using a fallback to do so,
// try to extract the composed characters from the fallback object.
if (currentComposition) {
if (topLevelType === topLevelTypes.topCompositionEnd || isFallbackCompositionEnd(topLevelType, nativeEvent)) {
var chars = currentComposition.getData();
FallbackCompositionState.release(currentComposition);
currentComposition = null;
return chars;
}
return null;
}
switch (topLevelType) {
case topLevelTypes.topPaste:
// If a paste event occurs after a keypress, throw out the input
// chars. Paste events should not lead to BeforeInput events.
return null;
case topLevelTypes.topKeyPress:
/**
* As of v27, Firefox may fire keypress events even when no character
* will be inserted. A few possibilities:
*
* - `which` is `0`. Arrow keys, Esc key, etc.
*
* - `which` is the pressed key code, but no char is available.
* Ex: 'AltGr + d` in Polish. There is no modified character for
* this key combination and no character is inserted into the
* document, but FF fires the keypress for char code `100` anyway.
* No `input` event will occur.
*
* - `which` is the pressed key code, but a command combination is
* being used. Ex: `Cmd+C`. No character is inserted, and no
* `input` event will occur.
*/
if (nativeEvent.which && !isKeypressCommand(nativeEvent)) {
return String.fromCharCode(nativeEvent.which);
}
return null;
case topLevelTypes.topCompositionEnd:
return useFallbackCompositionData ? null : nativeEvent.data;
default:
return null;
}
}
/**
* Extract a SyntheticInputEvent for `beforeInput`, based on either native
* `textInput` or fallback behavior.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {?object} A SyntheticInputEvent.
*/
function extractBeforeInputEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
var chars;
if (canUseTextInputEvent) {
chars = getNativeBeforeInputChars(topLevelType, nativeEvent);
} else {
chars = getFallbackBeforeInputChars(topLevelType, nativeEvent);
}
// If no characters are being inserted, no BeforeInput event should
// be fired.
if (!chars) {
return null;
}
var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, topLevelTargetID, nativeEvent, nativeEventTarget);
event.data = chars;
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
/**
* Create an `onBeforeInput` event to match
* http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
*
* This event plugin is based on the native `textInput` event
* available in Chrome, Safari, Opera, and IE. This event fires after
* `onKeyPress` and `onCompositionEnd`, but before `onInput`.
*
* `beforeInput` is spec'd but not implemented in any browsers, and
* the `input` event does not provide any useful information about what has
* actually been added, contrary to the spec. Thus, `textInput` is the best
* available event to identify the characters that have actually been inserted
* into the target node.
*
* This plugin is also responsible for emitting `composition` events, thus
* allowing us to share composition fallback code for both `beforeInput` and
* `composition` event types.
*/
var BeforeInputEventPlugin = {
eventTypes: eventTypes,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
return [extractCompositionEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget), extractBeforeInputEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget)];
}
};
module.exports = BeforeInputEventPlugin;
/***/ },
/* 73 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule EventPropagators
*/
'use strict';
var EventConstants = __webpack_require__(30);
var EventPluginHub = __webpack_require__(31);
var warning = __webpack_require__(25);
var accumulateInto = __webpack_require__(35);
var forEachAccumulated = __webpack_require__(36);
var PropagationPhases = EventConstants.PropagationPhases;
var getListener = EventPluginHub.getListener;
/**
* Some event types have a notion of different registration names for different
* "phases" of propagation. This finds listeners by a given phase.
*/
function listenerAtPhase(id, event, propagationPhase) {
var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];
return getListener(id, registrationName);
}
/**
* Tags a `SyntheticEvent` with dispatched listeners. Creating this function
* here, allows us to not have to bind or create functions for each event.
* Mutating the event's members allows us to not have to create a wrapping
* "dispatch" object that pairs the event with the listener.
*/
function accumulateDirectionalDispatches(domID, upwards, event) {
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(domID, 'Dispatching id must not be null') : undefined;
}
var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured;
var listener = listenerAtPhase(domID, event, phase);
if (listener) {
event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
event._dispatchIDs = accumulateInto(event._dispatchIDs, domID);
}
}
/**
* Collect dispatches (must be entirely collected before dispatching - see unit
* tests). Lazily allocate the array to conserve memory. We must loop through
* each event and perform the traversal for each one. We cannot perform a
* single traversal for the entire collection of events because each event may
* have a different target.
*/
function accumulateTwoPhaseDispatchesSingle(event) {
if (event && event.dispatchConfig.phasedRegistrationNames) {
EventPluginHub.injection.getInstanceHandle().traverseTwoPhase(event.dispatchMarker, accumulateDirectionalDispatches, event);
}
}
/**
* Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID.
*/
function accumulateTwoPhaseDispatchesSingleSkipTarget(event) {
if (event && event.dispatchConfig.phasedRegistrationNames) {
EventPluginHub.injection.getInstanceHandle().traverseTwoPhaseSkipTarget(event.dispatchMarker, accumulateDirectionalDispatches, event);
}
}
/**
* Accumulates without regard to direction, does not look for phased
* registration names. Same as `accumulateDirectDispatchesSingle` but without
* requiring that the `dispatchMarker` be the same as the dispatched ID.
*/
function accumulateDispatches(id, ignoredDirection, event) {
if (event && event.dispatchConfig.registrationName) {
var registrationName = event.dispatchConfig.registrationName;
var listener = getListener(id, registrationName);
if (listener) {
event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
event._dispatchIDs = accumulateInto(event._dispatchIDs, id);
}
}
}
/**
* Accumulates dispatches on an `SyntheticEvent`, but only for the
* `dispatchMarker`.
* @param {SyntheticEvent} event
*/
function accumulateDirectDispatchesSingle(event) {
if (event && event.dispatchConfig.registrationName) {
accumulateDispatches(event.dispatchMarker, null, event);
}
}
function accumulateTwoPhaseDispatches(events) {
forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
}
function accumulateTwoPhaseDispatchesSkipTarget(events) {
forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget);
}
function accumulateEnterLeaveDispatches(leave, enter, fromID, toID) {
EventPluginHub.injection.getInstanceHandle().traverseEnterLeave(fromID, toID, accumulateDispatches, leave, enter);
}
function accumulateDirectDispatches(events) {
forEachAccumulated(events, accumulateDirectDispatchesSingle);
}
/**
* A small set of propagation patterns, each of which will accept a small amount
* of information, and generate a set of "dispatch ready event objects" - which
* are sets of events that have already been annotated with a set of dispatched
* listener functions/ids. The API is designed this way to discourage these
* propagation strategies from actually executing the dispatches, since we
* always want to collect the entire set of dispatches before executing event a
* single one.
*
* @constructor EventPropagators
*/
var EventPropagators = {
accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches,
accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget,
accumulateDirectDispatches: accumulateDirectDispatches,
accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches
};
module.exports = EventPropagators;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 74 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule FallbackCompositionState
* @typechecks static-only
*/
'use strict';
var PooledClass = __webpack_require__(56);
var assign = __webpack_require__(39);
var getTextContentAccessor = __webpack_require__(75);
/**
* This helper class stores information about text content of a target node,
* allowing comparison of content before and after a given event.
*
* Identify the node where selection currently begins, then observe
* both its text content and its current position in the DOM. Since the
* browser may natively replace the target node during composition, we can
* use its position to find its replacement.
*
* @param {DOMEventTarget} root
*/
function FallbackCompositionState(root) {
this._root = root;
this._startText = this.getText();
this._fallbackText = null;
}
assign(FallbackCompositionState.prototype, {
destructor: function () {
this._root = null;
this._startText = null;
this._fallbackText = null;
},
/**
* Get current text of input.
*
* @return {string}
*/
getText: function () {
if ('value' in this._root) {
return this._root.value;
}
return this._root[getTextContentAccessor()];
},
/**
* Determine the differing substring between the initially stored
* text content and the current content.
*
* @return {string}
*/
getData: function () {
if (this._fallbackText) {
return this._fallbackText;
}
var start;
var startValue = this._startText;
var startLength = startValue.length;
var end;
var endValue = this.getText();
var endLength = endValue.length;
for (start = 0; start < startLength; start++) {
if (startValue[start] !== endValue[start]) {
break;
}
}
var minEnd = startLength - start;
for (end = 1; end <= minEnd; end++) {
if (startValue[startLength - end] !== endValue[endLength - end]) {
break;
}
}
var sliceTail = end > 1 ? 1 - end : undefined;
this._fallbackText = endValue.slice(start, sliceTail);
return this._fallbackText;
}
});
PooledClass.addPoolingTo(FallbackCompositionState);
module.exports = FallbackCompositionState;
/***/ },
/* 75 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getTextContentAccessor
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(9);
var contentKey = null;
/**
* Gets the key used to access text content on a DOM node.
*
* @return {?string} Key used to access text content.
* @internal
*/
function getTextContentAccessor() {
if (!contentKey && ExecutionEnvironment.canUseDOM) {
// Prefer textContent to innerText because many browsers support both but
// SVG <text> elements don't support innerText even when <div> does.
contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText';
}
return contentKey;
}
module.exports = getTextContentAccessor;
/***/ },
/* 76 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticCompositionEvent
* @typechecks static-only
*/
'use strict';
var SyntheticEvent = __webpack_require__(77);
/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
*/
var CompositionEventInterface = {
data: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticCompositionEvent, CompositionEventInterface);
module.exports = SyntheticCompositionEvent;
/***/ },
/* 77 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticEvent
* @typechecks static-only
*/
'use strict';
var PooledClass = __webpack_require__(56);
var assign = __webpack_require__(39);
var emptyFunction = __webpack_require__(15);
var warning = __webpack_require__(25);
/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var EventInterface = {
type: null,
// currentTarget is set when dispatching; no use in copying it here
currentTarget: emptyFunction.thatReturnsNull,
eventPhase: null,
bubbles: null,
cancelable: null,
timeStamp: function (event) {
return event.timeStamp || Date.now();
},
defaultPrevented: null,
isTrusted: null
};
/**
* Synthetic events are dispatched by event plugins, typically in response to a
* top-level event delegation handler.
*
* These systems should generally use pooling to reduce the frequency of garbage
* collection. The system should check `isPersistent` to determine whether the
* event should be released into the pool after being dispatched. Users that
* need a persisted event should invoke `persist`.
*
* Synthetic events (and subclasses) implement the DOM Level 3 Events API by
* normalizing browser quirks. Subclasses do not necessarily have to implement a
* DOM interface; custom application-specific events can also subclass this.
*
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
*/
function SyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
this.dispatchConfig = dispatchConfig;
this.dispatchMarker = dispatchMarker;
this.nativeEvent = nativeEvent;
this.target = nativeEventTarget;
this.currentTarget = nativeEventTarget;
var Interface = this.constructor.Interface;
for (var propName in Interface) {
if (!Interface.hasOwnProperty(propName)) {
continue;
}
var normalize = Interface[propName];
if (normalize) {
this[propName] = normalize(nativeEvent);
} else {
this[propName] = nativeEvent[propName];
}
}
var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
if (defaultPrevented) {
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
} else {
this.isDefaultPrevented = emptyFunction.thatReturnsFalse;
}
this.isPropagationStopped = emptyFunction.thatReturnsFalse;
}
assign(SyntheticEvent.prototype, {
preventDefault: function () {
this.defaultPrevented = true;
var event = this.nativeEvent;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(event, 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re calling `preventDefault` on a ' + 'released/nullified synthetic event. This is a no-op. See ' + 'https://fb.me/react-event-pooling for more information.') : undefined;
}
if (!event) {
return;
}
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
},
stopPropagation: function () {
var event = this.nativeEvent;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(event, 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re calling `stopPropagation` on a ' + 'released/nullified synthetic event. This is a no-op. See ' + 'https://fb.me/react-event-pooling for more information.') : undefined;
}
if (!event) {
return;
}
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
this.isPropagationStopped = emptyFunction.thatReturnsTrue;
},
/**
* We release all dispatched `SyntheticEvent`s after each event loop, adding
* them back into the pool. This allows a way to hold onto a reference that
* won't be added back into the pool.
*/
persist: function () {
this.isPersistent = emptyFunction.thatReturnsTrue;
},
/**
* Checks if this event should be released back into the pool.
*
* @return {boolean} True if this should not be released, false otherwise.
*/
isPersistent: emptyFunction.thatReturnsFalse,
/**
* `PooledClass` looks for `destructor` on each instance it releases.
*/
destructor: function () {
var Interface = this.constructor.Interface;
for (var propName in Interface) {
this[propName] = null;
}
this.dispatchConfig = null;
this.dispatchMarker = null;
this.nativeEvent = null;
}
});
SyntheticEvent.Interface = EventInterface;
/**
* Helper to reduce boilerplate when creating subclasses.
*
* @param {function} Class
* @param {?object} Interface
*/
SyntheticEvent.augmentClass = function (Class, Interface) {
var Super = this;
var prototype = Object.create(Super.prototype);
assign(prototype, Class.prototype);
Class.prototype = prototype;
Class.prototype.constructor = Class;
Class.Interface = assign({}, Super.Interface, Interface);
Class.augmentClass = Super.augmentClass;
PooledClass.addPoolingTo(Class, PooledClass.fourArgumentPooler);
};
PooledClass.addPoolingTo(SyntheticEvent, PooledClass.fourArgumentPooler);
module.exports = SyntheticEvent;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 78 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticInputEvent
* @typechecks static-only
*/
'use strict';
var SyntheticEvent = __webpack_require__(77);
/**
* @interface Event
* @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
* /#events-inputevents
*/
var InputEventInterface = {
data: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface);
module.exports = SyntheticInputEvent;
/***/ },
/* 79 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule keyOf
*/
/**
* Allows extraction of a minified key. Let's the build system minify keys
* without losing the ability to dynamically use key strings as values
* themselves. Pass in an object with a single key/val pair and it will return
* you the string key of that single record. Suppose you want to grab the
* value for a key 'className' inside of an object. Key/val minification may
* have aliased that key to be 'xa12'. keyOf({className: null}) will return
* 'xa12' in that case. Resolve keys you want to use once at startup time, then
* reuse those resolutions.
*/
"use strict";
var keyOf = function (oneKeyObj) {
var key;
for (key in oneKeyObj) {
if (!oneKeyObj.hasOwnProperty(key)) {
continue;
}
return key;
}
return null;
};
module.exports = keyOf;
/***/ },
/* 80 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ChangeEventPlugin
*/
'use strict';
var EventConstants = __webpack_require__(30);
var EventPluginHub = __webpack_require__(31);
var EventPropagators = __webpack_require__(73);
var ExecutionEnvironment = __webpack_require__(9);
var ReactUpdates = __webpack_require__(54);
var SyntheticEvent = __webpack_require__(77);
var getEventTarget = __webpack_require__(81);
var isEventSupported = __webpack_require__(40);
var isTextInputElement = __webpack_require__(82);
var keyOf = __webpack_require__(79);
var topLevelTypes = EventConstants.topLevelTypes;
var eventTypes = {
change: {
phasedRegistrationNames: {
bubbled: keyOf({ onChange: null }),
captured: keyOf({ onChangeCapture: null })
},
dependencies: [topLevelTypes.topBlur, topLevelTypes.topChange, topLevelTypes.topClick, topLevelTypes.topFocus, topLevelTypes.topInput, topLevelTypes.topKeyDown, topLevelTypes.topKeyUp, topLevelTypes.topSelectionChange]
}
};
/**
* For IE shims
*/
var activeElement = null;
var activeElementID = null;
var activeElementValue = null;
var activeElementValueProp = null;
/**
* SECTION: handle `change` event
*/
function shouldUseChangeEvent(elem) {
var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
return nodeName === 'select' || nodeName === 'input' && elem.type === 'file';
}
var doesChangeEventBubble = false;
if (ExecutionEnvironment.canUseDOM) {
// See `handleChange` comment below
doesChangeEventBubble = isEventSupported('change') && (!('documentMode' in document) || document.documentMode > 8);
}
function manualDispatchChangeEvent(nativeEvent) {
var event = SyntheticEvent.getPooled(eventTypes.change, activeElementID, nativeEvent, getEventTarget(nativeEvent));
EventPropagators.accumulateTwoPhaseDispatches(event);
// If change and propertychange bubbled, we'd just bind to it like all the
// other events and have it go through ReactBrowserEventEmitter. Since it
// doesn't, we manually listen for the events and so we have to enqueue and
// process the abstract event manually.
//
// Batching is necessary here in order to ensure that all event handlers run
// before the next rerender (including event handlers attached to ancestor
// elements instead of directly on the input). Without this, controlled
// components don't work properly in conjunction with event bubbling because
// the component is rerendered and the value reverted before all the event
// handlers can run. See https://github.com/facebook/react/issues/708.
ReactUpdates.batchedUpdates(runEventInBatch, event);
}
function runEventInBatch(event) {
EventPluginHub.enqueueEvents(event);
EventPluginHub.processEventQueue(false);
}
function startWatchingForChangeEventIE8(target, targetID) {
activeElement = target;
activeElementID = targetID;
activeElement.attachEvent('onchange', manualDispatchChangeEvent);
}
function stopWatchingForChangeEventIE8() {
if (!activeElement) {
return;
}
activeElement.detachEvent('onchange', manualDispatchChangeEvent);
activeElement = null;
activeElementID = null;
}
function getTargetIDForChangeEvent(topLevelType, topLevelTarget, topLevelTargetID) {
if (topLevelType === topLevelTypes.topChange) {
return topLevelTargetID;
}
}
function handleEventsForChangeEventIE8(topLevelType, topLevelTarget, topLevelTargetID) {
if (topLevelType === topLevelTypes.topFocus) {
// stopWatching() should be a noop here but we call it just in case we
// missed a blur event somehow.
stopWatchingForChangeEventIE8();
startWatchingForChangeEventIE8(topLevelTarget, topLevelTargetID);
} else if (topLevelType === topLevelTypes.topBlur) {
stopWatchingForChangeEventIE8();
}
}
/**
* SECTION: handle `input` event
*/
var isInputEventSupported = false;
if (ExecutionEnvironment.canUseDOM) {
// IE9 claims to support the input event but fails to trigger it when
// deleting text, so we ignore its input events
isInputEventSupported = isEventSupported('input') && (!('documentMode' in document) || document.documentMode > 9);
}
/**
* (For old IE.) Replacement getter/setter for the `value` property that gets
* set on the active element.
*/
var newValueProp = {
get: function () {
return activeElementValueProp.get.call(this);
},
set: function (val) {
// Cast to a string so we can do equality checks.
activeElementValue = '' + val;
activeElementValueProp.set.call(this, val);
}
};
/**
* (For old IE.) Starts tracking propertychange events on the passed-in element
* and override the value property so that we can distinguish user events from
* value changes in JS.
*/
function startWatchingForValueChange(target, targetID) {
activeElement = target;
activeElementID = targetID;
activeElementValue = target.value;
activeElementValueProp = Object.getOwnPropertyDescriptor(target.constructor.prototype, 'value');
// Not guarded in a canDefineProperty check: IE8 supports defineProperty only
// on DOM elements
Object.defineProperty(activeElement, 'value', newValueProp);
activeElement.attachEvent('onpropertychange', handlePropertyChange);
}
/**
* (For old IE.) Removes the event listeners from the currently-tracked element,
* if any exists.
*/
function stopWatchingForValueChange() {
if (!activeElement) {
return;
}
// delete restores the original property definition
delete activeElement.value;
activeElement.detachEvent('onpropertychange', handlePropertyChange);
activeElement = null;
activeElementID = null;
activeElementValue = null;
activeElementValueProp = null;
}
/**
* (For old IE.) Handles a propertychange event, sending a `change` event if
* the value of the active element has changed.
*/
function handlePropertyChange(nativeEvent) {
if (nativeEvent.propertyName !== 'value') {
return;
}
var value = nativeEvent.srcElement.value;
if (value === activeElementValue) {
return;
}
activeElementValue = value;
manualDispatchChangeEvent(nativeEvent);
}
/**
* If a `change` event should be fired, returns the target's ID.
*/
function getTargetIDForInputEvent(topLevelType, topLevelTarget, topLevelTargetID) {
if (topLevelType === topLevelTypes.topInput) {
// In modern browsers (i.e., not IE8 or IE9), the input event is exactly
// what we want so fall through here and trigger an abstract event
return topLevelTargetID;
}
}
// For IE8 and IE9.
function handleEventsForInputEventIE(topLevelType, topLevelTarget, topLevelTargetID) {
if (topLevelType === topLevelTypes.topFocus) {
// In IE8, we can capture almost all .value changes by adding a
// propertychange handler and looking for events with propertyName
// equal to 'value'
// In IE9, propertychange fires for most input events but is buggy and
// doesn't fire when text is deleted, but conveniently, selectionchange
// appears to fire in all of the remaining cases so we catch those and
// forward the event if the value has changed
// In either case, we don't want to call the event handler if the value
// is changed from JS so we redefine a setter for `.value` that updates
// our activeElementValue variable, allowing us to ignore those changes
//
// stopWatching() should be a noop here but we call it just in case we
// missed a blur event somehow.
stopWatchingForValueChange();
startWatchingForValueChange(topLevelTarget, topLevelTargetID);
} else if (topLevelType === topLevelTypes.topBlur) {
stopWatchingForValueChange();
}
}
// For IE8 and IE9.
function getTargetIDForInputEventIE(topLevelType, topLevelTarget, topLevelTargetID) {
if (topLevelType === topLevelTypes.topSelectionChange || topLevelType === topLevelTypes.topKeyUp || topLevelType === topLevelTypes.topKeyDown) {
// On the selectionchange event, the target is just document which isn't
// helpful for us so just check activeElement instead.
//
// 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
// propertychange on the first input event after setting `value` from a
// script and fires only keydown, keypress, keyup. Catching keyup usually
// gets it and catching keydown lets us fire an event for the first
// keystroke if user does a key repeat (it'll be a little delayed: right
// before the second keystroke). Other input methods (e.g., paste) seem to
// fire selectionchange normally.
if (activeElement && activeElement.value !== activeElementValue) {
activeElementValue = activeElement.value;
return activeElementID;
}
}
}
/**
* SECTION: handle `click` event
*/
function shouldUseClickEvent(elem) {
// Use the `click` event to detect changes to checkbox and radio inputs.
// This approach works across all browsers, whereas `change` does not fire
// until `blur` in IE8.
return elem.nodeName && elem.nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio');
}
function getTargetIDForClickEvent(topLevelType, topLevelTarget, topLevelTargetID) {
if (topLevelType === topLevelTypes.topClick) {
return topLevelTargetID;
}
}
/**
* This plugin creates an `onChange` event that normalizes change events
* across form elements. This event fires at a time when it's possible to
* change the element's value without seeing a flicker.
*
* Supported elements are:
* - input (see `isTextInputElement`)
* - textarea
* - select
*/
var ChangeEventPlugin = {
eventTypes: eventTypes,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
var getTargetIDFunc, handleEventFunc;
if (shouldUseChangeEvent(topLevelTarget)) {
if (doesChangeEventBubble) {
getTargetIDFunc = getTargetIDForChangeEvent;
} else {
handleEventFunc = handleEventsForChangeEventIE8;
}
} else if (isTextInputElement(topLevelTarget)) {
if (isInputEventSupported) {
getTargetIDFunc = getTargetIDForInputEvent;
} else {
getTargetIDFunc = getTargetIDForInputEventIE;
handleEventFunc = handleEventsForInputEventIE;
}
} else if (shouldUseClickEvent(topLevelTarget)) {
getTargetIDFunc = getTargetIDForClickEvent;
}
if (getTargetIDFunc) {
var targetID = getTargetIDFunc(topLevelType, topLevelTarget, topLevelTargetID);
if (targetID) {
var event = SyntheticEvent.getPooled(eventTypes.change, targetID, nativeEvent, nativeEventTarget);
event.type = 'change';
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
}
if (handleEventFunc) {
handleEventFunc(topLevelType, topLevelTarget, topLevelTargetID);
}
}
};
module.exports = ChangeEventPlugin;
/***/ },
/* 81 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getEventTarget
* @typechecks static-only
*/
'use strict';
/**
* Gets the target node from a native browser event by accounting for
* inconsistencies in browser DOM APIs.
*
* @param {object} nativeEvent Native browser event.
* @return {DOMEventTarget} Target node.
*/
function getEventTarget(nativeEvent) {
var target = nativeEvent.target || nativeEvent.srcElement || window;
// Safari may fire events on text nodes (Node.TEXT_NODE is 3).
// @see http://www.quirksmode.org/js/events_properties.html
return target.nodeType === 3 ? target.parentNode : target;
}
module.exports = getEventTarget;
/***/ },
/* 82 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule isTextInputElement
*/
'use strict';
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
*/
var supportedInputTypes = {
'color': true,
'date': true,
'datetime': true,
'datetime-local': true,
'email': true,
'month': true,
'number': true,
'password': true,
'range': true,
'search': true,
'tel': true,
'text': true,
'time': true,
'url': true,
'week': true
};
function isTextInputElement(elem) {
var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
return nodeName && (nodeName === 'input' && supportedInputTypes[elem.type] || nodeName === 'textarea');
}
module.exports = isTextInputElement;
/***/ },
/* 83 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ClientReactRootIndex
* @typechecks
*/
'use strict';
var nextReactRootIndex = 0;
var ClientReactRootIndex = {
createReactRootIndex: function () {
return nextReactRootIndex++;
}
};
module.exports = ClientReactRootIndex;
/***/ },
/* 84 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule DefaultEventPluginOrder
*/
'use strict';
var keyOf = __webpack_require__(79);
/**
* Module that is injectable into `EventPluginHub`, that specifies a
* deterministic ordering of `EventPlugin`s. A convenient way to reason about
* plugins, without having to package every one of them. This is better than
* having plugins be ordered in the same order that they are injected because
* that ordering would be influenced by the packaging order.
* `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that
* preventing default on events is convenient in `SimpleEventPlugin` handlers.
*/
var DefaultEventPluginOrder = [keyOf({ ResponderEventPlugin: null }), keyOf({ SimpleEventPlugin: null }), keyOf({ TapEventPlugin: null }), keyOf({ EnterLeaveEventPlugin: null }), keyOf({ ChangeEventPlugin: null }), keyOf({ SelectEventPlugin: null }), keyOf({ BeforeInputEventPlugin: null })];
module.exports = DefaultEventPluginOrder;
/***/ },
/* 85 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule EnterLeaveEventPlugin
* @typechecks static-only
*/
'use strict';
var EventConstants = __webpack_require__(30);
var EventPropagators = __webpack_require__(73);
var SyntheticMouseEvent = __webpack_require__(86);
var ReactMount = __webpack_require__(28);
var keyOf = __webpack_require__(79);
var topLevelTypes = EventConstants.topLevelTypes;
var getFirstReactDOM = ReactMount.getFirstReactDOM;
var eventTypes = {
mouseEnter: {
registrationName: keyOf({ onMouseEnter: null }),
dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver]
},
mouseLeave: {
registrationName: keyOf({ onMouseLeave: null }),
dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver]
}
};
var extractedEvents = [null, null];
var EnterLeaveEventPlugin = {
eventTypes: eventTypes,
/**
* For almost every interaction we care about, there will be both a top-level
* `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
* we do not extract duplicate events. However, moving the mouse into the
* browser from outside will not fire a `mouseout` event. In this case, we use
* the `mouseover` top-level event.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
if (topLevelType === topLevelTypes.topMouseOver && (nativeEvent.relatedTarget || nativeEvent.fromElement)) {
return null;
}
if (topLevelType !== topLevelTypes.topMouseOut && topLevelType !== topLevelTypes.topMouseOver) {
// Must not be a mouse in or mouse out - ignoring.
return null;
}
var win;
if (topLevelTarget.window === topLevelTarget) {
// `topLevelTarget` is probably a window object.
win = topLevelTarget;
} else {
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
var doc = topLevelTarget.ownerDocument;
if (doc) {
win = doc.defaultView || doc.parentWindow;
} else {
win = window;
}
}
var from;
var to;
var fromID = '';
var toID = '';
if (topLevelType === topLevelTypes.topMouseOut) {
from = topLevelTarget;
fromID = topLevelTargetID;
to = getFirstReactDOM(nativeEvent.relatedTarget || nativeEvent.toElement);
if (to) {
toID = ReactMount.getID(to);
} else {
to = win;
}
to = to || win;
} else {
from = win;
to = topLevelTarget;
toID = topLevelTargetID;
}
if (from === to) {
// Nothing pertains to our managed components.
return null;
}
var leave = SyntheticMouseEvent.getPooled(eventTypes.mouseLeave, fromID, nativeEvent, nativeEventTarget);
leave.type = 'mouseleave';
leave.target = from;
leave.relatedTarget = to;
var enter = SyntheticMouseEvent.getPooled(eventTypes.mouseEnter, toID, nativeEvent, nativeEventTarget);
enter.type = 'mouseenter';
enter.target = to;
enter.relatedTarget = from;
EventPropagators.accumulateEnterLeaveDispatches(leave, enter, fromID, toID);
extractedEvents[0] = leave;
extractedEvents[1] = enter;
return extractedEvents;
}
};
module.exports = EnterLeaveEventPlugin;
/***/ },
/* 86 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticMouseEvent
* @typechecks static-only
*/
'use strict';
var SyntheticUIEvent = __webpack_require__(87);
var ViewportMetrics = __webpack_require__(38);
var getEventModifierState = __webpack_require__(88);
/**
* @interface MouseEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var MouseEventInterface = {
screenX: null,
screenY: null,
clientX: null,
clientY: null,
ctrlKey: null,
shiftKey: null,
altKey: null,
metaKey: null,
getModifierState: getEventModifierState,
button: function (event) {
// Webkit, Firefox, IE9+
// which: 1 2 3
// button: 0 1 2 (standard)
var button = event.button;
if ('which' in event) {
return button;
}
// IE<9
// which: undefined
// button: 0 0 0
// button: 1 4 2 (onmouseup)
return button === 2 ? 2 : button === 4 ? 1 : 0;
},
buttons: null,
relatedTarget: function (event) {
return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement);
},
// "Proprietary" Interface.
pageX: function (event) {
return 'pageX' in event ? event.pageX : event.clientX + ViewportMetrics.currentScrollLeft;
},
pageY: function (event) {
return 'pageY' in event ? event.pageY : event.clientY + ViewportMetrics.currentScrollTop;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface);
module.exports = SyntheticMouseEvent;
/***/ },
/* 87 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticUIEvent
* @typechecks static-only
*/
'use strict';
var SyntheticEvent = __webpack_require__(77);
var getEventTarget = __webpack_require__(81);
/**
* @interface UIEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var UIEventInterface = {
view: function (event) {
if (event.view) {
return event.view;
}
var target = getEventTarget(event);
if (target != null && target.window === target) {
// target is a window object
return target;
}
var doc = target.ownerDocument;
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
if (doc) {
return doc.defaultView || doc.parentWindow;
} else {
return window;
}
},
detail: function (event) {
return event.detail || 0;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticEvent}
*/
function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface);
module.exports = SyntheticUIEvent;
/***/ },
/* 88 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getEventModifierState
* @typechecks static-only
*/
'use strict';
/**
* Translation from modifier key to the associated property in the event.
* @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
*/
var modifierKeyToProp = {
'Alt': 'altKey',
'Control': 'ctrlKey',
'Meta': 'metaKey',
'Shift': 'shiftKey'
};
// IE8 does not implement getModifierState so we simply map it to the only
// modifier keys exposed by the event itself, does not support Lock-keys.
// Currently, all major browsers except Chrome seems to support Lock-keys.
function modifierStateGetter(keyArg) {
var syntheticEvent = this;
var nativeEvent = syntheticEvent.nativeEvent;
if (nativeEvent.getModifierState) {
return nativeEvent.getModifierState(keyArg);
}
var keyProp = modifierKeyToProp[keyArg];
return keyProp ? !!nativeEvent[keyProp] : false;
}
function getEventModifierState(nativeEvent) {
return modifierStateGetter;
}
module.exports = getEventModifierState;
/***/ },
/* 89 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule HTMLDOMPropertyConfig
*/
'use strict';
var DOMProperty = __webpack_require__(23);
var ExecutionEnvironment = __webpack_require__(9);
var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE;
var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY;
var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE;
var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS;
var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE;
var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE;
var HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE;
var hasSVG;
if (ExecutionEnvironment.canUseDOM) {
var implementation = document.implementation;
hasSVG = implementation && implementation.hasFeature && implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#BasicStructure', '1.1');
}
var HTMLDOMPropertyConfig = {
isCustomAttribute: RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/),
Properties: {
/**
* Standard Properties
*/
accept: null,
acceptCharset: null,
accessKey: null,
action: null,
allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
allowTransparency: MUST_USE_ATTRIBUTE,
alt: null,
async: HAS_BOOLEAN_VALUE,
autoComplete: null,
// autoFocus is polyfilled/normalized by AutoFocusUtils
// autoFocus: HAS_BOOLEAN_VALUE,
autoPlay: HAS_BOOLEAN_VALUE,
capture: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
cellPadding: null,
cellSpacing: null,
charSet: MUST_USE_ATTRIBUTE,
challenge: MUST_USE_ATTRIBUTE,
checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
classID: MUST_USE_ATTRIBUTE,
// To set className on SVG elements, it's necessary to use .setAttribute;
// this works on HTML elements too in all browsers except IE8. Conveniently,
// IE8 doesn't support SVG and so we can simply use the attribute in
// browsers that support SVG and the property in browsers that don't,
// regardless of whether the element is HTML or SVG.
className: hasSVG ? MUST_USE_ATTRIBUTE : MUST_USE_PROPERTY,
cols: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
colSpan: null,
content: null,
contentEditable: null,
contextMenu: MUST_USE_ATTRIBUTE,
controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
coords: null,
crossOrigin: null,
data: null, // For `<object />` acts as `src`.
dateTime: MUST_USE_ATTRIBUTE,
'default': HAS_BOOLEAN_VALUE,
defer: HAS_BOOLEAN_VALUE,
dir: null,
disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
download: HAS_OVERLOADED_BOOLEAN_VALUE,
draggable: null,
encType: null,
form: MUST_USE_ATTRIBUTE,
formAction: MUST_USE_ATTRIBUTE,
formEncType: MUST_USE_ATTRIBUTE,
formMethod: MUST_USE_ATTRIBUTE,
formNoValidate: HAS_BOOLEAN_VALUE,
formTarget: MUST_USE_ATTRIBUTE,
frameBorder: MUST_USE_ATTRIBUTE,
headers: null,
height: MUST_USE_ATTRIBUTE,
hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
high: null,
href: null,
hrefLang: null,
htmlFor: null,
httpEquiv: null,
icon: null,
id: MUST_USE_PROPERTY,
inputMode: MUST_USE_ATTRIBUTE,
integrity: null,
is: MUST_USE_ATTRIBUTE,
keyParams: MUST_USE_ATTRIBUTE,
keyType: MUST_USE_ATTRIBUTE,
kind: null,
label: null,
lang: null,
list: MUST_USE_ATTRIBUTE,
loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
low: null,
manifest: MUST_USE_ATTRIBUTE,
marginHeight: null,
marginWidth: null,
max: null,
maxLength: MUST_USE_ATTRIBUTE,
media: MUST_USE_ATTRIBUTE,
mediaGroup: null,
method: null,
min: null,
minLength: MUST_USE_ATTRIBUTE,
multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
name: null,
nonce: MUST_USE_ATTRIBUTE,
noValidate: HAS_BOOLEAN_VALUE,
open: HAS_BOOLEAN_VALUE,
optimum: null,
pattern: null,
placeholder: null,
poster: null,
preload: null,
radioGroup: null,
readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
rel: null,
required: HAS_BOOLEAN_VALUE,
reversed: HAS_BOOLEAN_VALUE,
role: MUST_USE_ATTRIBUTE,
rows: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
rowSpan: null,
sandbox: null,
scope: null,
scoped: HAS_BOOLEAN_VALUE,
scrolling: null,
seamless: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
shape: null,
size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
sizes: MUST_USE_ATTRIBUTE,
span: HAS_POSITIVE_NUMERIC_VALUE,
spellCheck: null,
src: null,
srcDoc: MUST_USE_PROPERTY,
srcLang: null,
srcSet: MUST_USE_ATTRIBUTE,
start: HAS_NUMERIC_VALUE,
step: null,
style: null,
summary: null,
tabIndex: null,
target: null,
title: null,
type: null,
useMap: null,
value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS,
width: MUST_USE_ATTRIBUTE,
wmode: MUST_USE_ATTRIBUTE,
wrap: null,
/**
* RDFa Properties
*/
about: MUST_USE_ATTRIBUTE,
datatype: MUST_USE_ATTRIBUTE,
inlist: MUST_USE_ATTRIBUTE,
prefix: MUST_USE_ATTRIBUTE,
// property is also supported for OpenGraph in meta tags.
property: MUST_USE_ATTRIBUTE,
resource: MUST_USE_ATTRIBUTE,
'typeof': MUST_USE_ATTRIBUTE,
vocab: MUST_USE_ATTRIBUTE,
/**
* Non-standard Properties
*/
// autoCapitalize and autoCorrect are supported in Mobile Safari for
// keyboard hints.
autoCapitalize: MUST_USE_ATTRIBUTE,
autoCorrect: MUST_USE_ATTRIBUTE,
// autoSave allows WebKit/Blink to persist values of input fields on page reloads
autoSave: null,
// color is for Safari mask-icon link
color: null,
// itemProp, itemScope, itemType are for
// Microdata support. See http://schema.org/docs/gs.html
itemProp: MUST_USE_ATTRIBUTE,
itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
itemType: MUST_USE_ATTRIBUTE,
// itemID and itemRef are for Microdata support as well but
// only specified in the the WHATWG spec document. See
// https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api
itemID: MUST_USE_ATTRIBUTE,
itemRef: MUST_USE_ATTRIBUTE,
// results show looking glass icon and recent searches on input
// search fields in WebKit/Blink
results: null,
// IE-only attribute that specifies security restrictions on an iframe
// as an alternative to the sandbox attribute on IE<10
security: MUST_USE_ATTRIBUTE,
// IE-only attribute that controls focus behavior
unselectable: MUST_USE_ATTRIBUTE
},
DOMAttributeNames: {
acceptCharset: 'accept-charset',
className: 'class',
htmlFor: 'for',
httpEquiv: 'http-equiv'
},
DOMPropertyNames: {
autoComplete: 'autocomplete',
autoFocus: 'autofocus',
autoPlay: 'autoplay',
autoSave: 'autosave',
// `encoding` is equivalent to `enctype`, IE8 lacks an `enctype` setter.
// http://www.w3.org/TR/html5/forms.html#dom-fs-encoding
encType: 'encoding',
hrefLang: 'hreflang',
radioGroup: 'radiogroup',
spellCheck: 'spellcheck',
srcDoc: 'srcdoc',
srcSet: 'srcset'
}
};
module.exports = HTMLDOMPropertyConfig;
/***/ },
/* 90 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactBrowserComponentMixin
*/
'use strict';
var ReactInstanceMap = __webpack_require__(47);
var findDOMNode = __webpack_require__(91);
var warning = __webpack_require__(25);
var didWarnKey = '_getDOMNodeDidWarn';
var ReactBrowserComponentMixin = {
/**
* Returns the DOM node rendered by this component.
*
* @return {DOMElement} The root node of this component.
* @final
* @protected
*/
getDOMNode: function () {
process.env.NODE_ENV !== 'production' ? warning(this.constructor[didWarnKey], '%s.getDOMNode(...) is deprecated. Please use ' + 'ReactDOM.findDOMNode(instance) instead.', ReactInstanceMap.get(this).getName() || this.tagName || 'Unknown') : undefined;
this.constructor[didWarnKey] = true;
return findDOMNode(this);
}
};
module.exports = ReactBrowserComponentMixin;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 91 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule findDOMNode
* @typechecks static-only
*/
'use strict';
var ReactCurrentOwner = __webpack_require__(5);
var ReactInstanceMap = __webpack_require__(47);
var ReactMount = __webpack_require__(28);
var invariant = __webpack_require__(13);
var warning = __webpack_require__(25);
/**
* Returns the DOM node rendered by this element.
*
* @param {ReactComponent|DOMElement} componentOrElement
* @return {?DOMElement} The root node of this element.
*/
function findDOMNode(componentOrElement) {
if (process.env.NODE_ENV !== 'production') {
var owner = ReactCurrentOwner.current;
if (owner !== null) {
process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing getDOMNode or findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : undefined;
owner._warnedAboutRefsInRender = true;
}
}
if (componentOrElement == null) {
return null;
}
if (componentOrElement.nodeType === 1) {
return componentOrElement;
}
if (ReactInstanceMap.has(componentOrElement)) {
return ReactMount.getNodeFromInstance(componentOrElement);
}
!(componentOrElement.render == null || typeof componentOrElement.render !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : invariant(false) : undefined;
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : invariant(false) : undefined;
}
module.exports = findDOMNode;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 92 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDefaultBatchingStrategy
*/
'use strict';
var ReactUpdates = __webpack_require__(54);
var Transaction = __webpack_require__(57);
var assign = __webpack_require__(39);
var emptyFunction = __webpack_require__(15);
var RESET_BATCHED_UPDATES = {
initialize: emptyFunction,
close: function () {
ReactDefaultBatchingStrategy.isBatchingUpdates = false;
}
};
var FLUSH_BATCHED_UPDATES = {
initialize: emptyFunction,
close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates)
};
var TRANSACTION_WRAPPERS = [FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES];
function ReactDefaultBatchingStrategyTransaction() {
this.reinitializeTransaction();
}
assign(ReactDefaultBatchingStrategyTransaction.prototype, Transaction.Mixin, {
getTransactionWrappers: function () {
return TRANSACTION_WRAPPERS;
}
});
var transaction = new ReactDefaultBatchingStrategyTransaction();
var ReactDefaultBatchingStrategy = {
isBatchingUpdates: false,
/**
* Call the provided function in a context within which calls to `setState`
* and friends are batched such that components aren't updated unnecessarily.
*/
batchedUpdates: function (callback, a, b, c, d, e) {
var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates;
ReactDefaultBatchingStrategy.isBatchingUpdates = true;
// The code is written this way to avoid extra allocations
if (alreadyBatchingUpdates) {
callback(a, b, c, d, e);
} else {
transaction.perform(callback, null, a, b, c, d, e);
}
}
};
module.exports = ReactDefaultBatchingStrategy;
/***/ },
/* 93 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMComponent
* @typechecks static-only
*/
/* global hasOwnProperty:true */
'use strict';
var AutoFocusUtils = __webpack_require__(94);
var CSSPropertyOperations = __webpack_require__(96);
var DOMProperty = __webpack_require__(23);
var DOMPropertyOperations = __webpack_require__(22);
var EventConstants = __webpack_require__(30);
var ReactBrowserEventEmitter = __webpack_require__(29);
var ReactComponentBrowserEnvironment = __webpack_require__(26);
var ReactDOMButton = __webpack_require__(104);
var ReactDOMInput = __webpack_require__(105);
var ReactDOMOption = __webpack_require__(109);
var ReactDOMSelect = __webpack_require__(112);
var ReactDOMTextarea = __webpack_require__(113);
var ReactMount = __webpack_require__(28);
var ReactMultiChild = __webpack_require__(114);
var ReactPerf = __webpack_require__(18);
var ReactUpdateQueue = __webpack_require__(53);
var assign = __webpack_require__(39);
var canDefineProperty = __webpack_require__(43);
var escapeTextContentForBrowser = __webpack_require__(21);
var invariant = __webpack_require__(13);
var isEventSupported = __webpack_require__(40);
var keyOf = __webpack_require__(79);
var setInnerHTML = __webpack_require__(19);
var setTextContent = __webpack_require__(20);
var shallowEqual = __webpack_require__(117);
var validateDOMNesting = __webpack_require__(70);
var warning = __webpack_require__(25);
var deleteListener = ReactBrowserEventEmitter.deleteListener;
var listenTo = ReactBrowserEventEmitter.listenTo;
var registrationNameModules = ReactBrowserEventEmitter.registrationNameModules;
// For quickly matching children type, to test if can be treated as content.
var CONTENT_TYPES = { 'string': true, 'number': true };
var CHILDREN = keyOf({ children: null });
var STYLE = keyOf({ style: null });
var HTML = keyOf({ __html: null });
var ELEMENT_NODE_TYPE = 1;
function getDeclarationErrorAddendum(internalInstance) {
if (internalInstance) {
var owner = internalInstance._currentElement._owner || null;
if (owner) {
var name = owner.getName();
if (name) {
return ' This DOM node was rendered by `' + name + '`.';
}
}
}
return '';
}
var legacyPropsDescriptor;
if (process.env.NODE_ENV !== 'production') {
legacyPropsDescriptor = {
props: {
enumerable: false,
get: function () {
var component = this._reactInternalComponent;
process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .props of a DOM node; instead, ' + 'recreate the props as `render` did originally or read the DOM ' + 'properties/attributes directly from this node (e.g., ' + 'this.refs.box.className).%s', getDeclarationErrorAddendum(component)) : undefined;
return component._currentElement.props;
}
}
};
}
function legacyGetDOMNode() {
if (process.env.NODE_ENV !== 'production') {
var component = this._reactInternalComponent;
process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .getDOMNode() of a DOM node; ' + 'instead, use the node directly.%s', getDeclarationErrorAddendum(component)) : undefined;
}
return this;
}
function legacyIsMounted() {
var component = this._reactInternalComponent;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .isMounted() of a DOM node.%s', getDeclarationErrorAddendum(component)) : undefined;
}
return !!component;
}
function legacySetStateEtc() {
if (process.env.NODE_ENV !== 'production') {
var component = this._reactInternalComponent;
process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .setState(), .replaceState(), or ' + '.forceUpdate() of a DOM node. This is a no-op.%s', getDeclarationErrorAddendum(component)) : undefined;
}
}
function legacySetProps(partialProps, callback) {
var component = this._reactInternalComponent;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .setProps() of a DOM node. ' + 'Instead, call ReactDOM.render again at the top level.%s', getDeclarationErrorAddendum(component)) : undefined;
}
if (!component) {
return;
}
ReactUpdateQueue.enqueueSetPropsInternal(component, partialProps);
if (callback) {
ReactUpdateQueue.enqueueCallbackInternal(component, callback);
}
}
function legacyReplaceProps(partialProps, callback) {
var component = this._reactInternalComponent;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .replaceProps() of a DOM node. ' + 'Instead, call ReactDOM.render again at the top level.%s', getDeclarationErrorAddendum(component)) : undefined;
}
if (!component) {
return;
}
ReactUpdateQueue.enqueueReplacePropsInternal(component, partialProps);
if (callback) {
ReactUpdateQueue.enqueueCallbackInternal(component, callback);
}
}
function friendlyStringify(obj) {
if (typeof obj === 'object') {
if (Array.isArray(obj)) {
return '[' + obj.map(friendlyStringify).join(', ') + ']';
} else {
var pairs = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var keyEscaped = /^[a-z$_][\w$_]*$/i.test(key) ? key : JSON.stringify(key);
pairs.push(keyEscaped + ': ' + friendlyStringify(obj[key]));
}
}
return '{' + pairs.join(', ') + '}';
}
} else if (typeof obj === 'string') {
return JSON.stringify(obj);
} else if (typeof obj === 'function') {
return '[function object]';
}
// Differs from JSON.stringify in that undefined becauses undefined and that
// inf and nan don't become null
return String(obj);
}
var styleMutationWarning = {};
function checkAndWarnForMutatedStyle(style1, style2, component) {
if (style1 == null || style2 == null) {
return;
}
if (shallowEqual(style1, style2)) {
return;
}
var componentName = component._tag;
var owner = component._currentElement._owner;
var ownerName;
if (owner) {
ownerName = owner.getName();
}
var hash = ownerName + '|' + componentName;
if (styleMutationWarning.hasOwnProperty(hash)) {
return;
}
styleMutationWarning[hash] = true;
process.env.NODE_ENV !== 'production' ? warning(false, '`%s` was passed a style object that has previously been mutated. ' + 'Mutating `style` is deprecated. Consider cloning it beforehand. Check ' + 'the `render` %s. Previous style: %s. Mutated style: %s.', componentName, owner ? 'of `' + ownerName + '`' : 'using <' + componentName + '>', friendlyStringify(style1), friendlyStringify(style2)) : undefined;
}
/**
* @param {object} component
* @param {?object} props
*/
function assertValidProps(component, props) {
if (!props) {
return;
}
// Note the use of `==` which checks for null or undefined.
if (process.env.NODE_ENV !== 'production') {
if (voidElementTags[component._tag]) {
process.env.NODE_ENV !== 'production' ? warning(props.children == null && props.dangerouslySetInnerHTML == null, '%s is a void element tag and must not have `children` or ' + 'use `props.dangerouslySetInnerHTML`.%s', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : undefined;
}
}
if (props.dangerouslySetInnerHTML != null) {
!(props.children == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : invariant(false) : undefined;
!(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://fb.me/react-invariant-dangerously-set-inner-html ' + 'for more information.') : invariant(false) : undefined;
}
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(props.innerHTML == null, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.') : undefined;
process.env.NODE_ENV !== 'production' ? warning(!props.contentEditable || props.children == null, 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.') : undefined;
}
!(props.style == null || typeof props.style === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The `style` prop expects a mapping from style properties to values, ' + 'not a string. For example, style={{marginRight: spacing + \'em\'}} when ' + 'using JSX.%s', getDeclarationErrorAddendum(component)) : invariant(false) : undefined;
}
function enqueuePutListener(id, registrationName, listener, transaction) {
if (process.env.NODE_ENV !== 'production') {
// IE8 has no API for event capturing and the `onScroll` event doesn't
// bubble.
process.env.NODE_ENV !== 'production' ? warning(registrationName !== 'onScroll' || isEventSupported('scroll', true), 'This browser doesn\'t support the `onScroll` event') : undefined;
}
var container = ReactMount.findReactContainerForID(id);
if (container) {
var doc = container.nodeType === ELEMENT_NODE_TYPE ? container.ownerDocument : container;
listenTo(registrationName, doc);
}
transaction.getReactMountReady().enqueue(putListener, {
id: id,
registrationName: registrationName,
listener: listener
});
}
function putListener() {
var listenerToPut = this;
ReactBrowserEventEmitter.putListener(listenerToPut.id, listenerToPut.registrationName, listenerToPut.listener);
}
// There are so many media events, it makes sense to just
// maintain a list rather than create a `trapBubbledEvent` for each
var mediaEvents = {
topAbort: 'abort',
topCanPlay: 'canplay',
topCanPlayThrough: 'canplaythrough',
topDurationChange: 'durationchange',
topEmptied: 'emptied',
topEncrypted: 'encrypted',
topEnded: 'ended',
topError: 'error',
topLoadedData: 'loadeddata',
topLoadedMetadata: 'loadedmetadata',
topLoadStart: 'loadstart',
topPause: 'pause',
topPlay: 'play',
topPlaying: 'playing',
topProgress: 'progress',
topRateChange: 'ratechange',
topSeeked: 'seeked',
topSeeking: 'seeking',
topStalled: 'stalled',
topSuspend: 'suspend',
topTimeUpdate: 'timeupdate',
topVolumeChange: 'volumechange',
topWaiting: 'waiting'
};
function trapBubbledEventsLocal() {
var inst = this;
// If a component renders to null or if another component fatals and causes
// the state of the tree to be corrupted, `node` here can be null.
!inst._rootNodeID ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Must be mounted to trap events') : invariant(false) : undefined;
var node = ReactMount.getNode(inst._rootNodeID);
!node ? process.env.NODE_ENV !== 'production' ? invariant(false, 'trapBubbledEvent(...): Requires node to be rendered.') : invariant(false) : undefined;
switch (inst._tag) {
case 'iframe':
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)];
break;
case 'video':
case 'audio':
inst._wrapperState.listeners = [];
// create listener for each media event
for (var event in mediaEvents) {
if (mediaEvents.hasOwnProperty(event)) {
inst._wrapperState.listeners.push(ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes[event], mediaEvents[event], node));
}
}
break;
case 'img':
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topError, 'error', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)];
break;
case 'form':
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topReset, 'reset', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topSubmit, 'submit', node)];
break;
}
}
function mountReadyInputWrapper() {
ReactDOMInput.mountReadyWrapper(this);
}
function postUpdateSelectWrapper() {
ReactDOMSelect.postUpdateWrapper(this);
}
// For HTML, certain tags should omit their close tag. We keep a whitelist for
// those special cased tags.
var omittedCloseTags = {
'area': true,
'base': true,
'br': true,
'col': true,
'embed': true,
'hr': true,
'img': true,
'input': true,
'keygen': true,
'link': true,
'meta': true,
'param': true,
'source': true,
'track': true,
'wbr': true
};
// NOTE: menuitem's close tag should be omitted, but that causes problems.
var newlineEatingTags = {
'listing': true,
'pre': true,
'textarea': true
};
// For HTML, certain tags cannot have children. This has the same purpose as
// `omittedCloseTags` except that `menuitem` should still have its closing tag.
var voidElementTags = assign({
'menuitem': true
}, omittedCloseTags);
// We accept any tag to be rendered but since this gets injected into arbitrary
// HTML, we want to make sure that it's a safe tag.
// http://www.w3.org/TR/REC-xml/#NT-Name
var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset
var validatedTagCache = {};
var hasOwnProperty = ({}).hasOwnProperty;
function validateDangerousTag(tag) {
if (!hasOwnProperty.call(validatedTagCache, tag)) {
!VALID_TAG_REGEX.test(tag) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Invalid tag: %s', tag) : invariant(false) : undefined;
validatedTagCache[tag] = true;
}
}
function processChildContextDev(context, inst) {
// Pass down our tag name to child components for validation purposes
context = assign({}, context);
var info = context[validateDOMNesting.ancestorInfoContextKey];
context[validateDOMNesting.ancestorInfoContextKey] = validateDOMNesting.updatedAncestorInfo(info, inst._tag, inst);
return context;
}
function isCustomComponent(tagName, props) {
return tagName.indexOf('-') >= 0 || props.is != null;
}
/**
* Creates a new React class that is idempotent and capable of containing other
* React components. It accepts event listeners and DOM properties that are
* valid according to `DOMProperty`.
*
* - Event listeners: `onClick`, `onMouseDown`, etc.
* - DOM properties: `className`, `name`, `title`, etc.
*
* The `style` property functions differently from the DOM API. It accepts an
* object mapping of style properties to values.
*
* @constructor ReactDOMComponent
* @extends ReactMultiChild
*/
function ReactDOMComponent(tag) {
validateDangerousTag(tag);
this._tag = tag.toLowerCase();
this._renderedChildren = null;
this._previousStyle = null;
this._previousStyleCopy = null;
this._rootNodeID = null;
this._wrapperState = null;
this._topLevelWrapper = null;
this._nodeWithLegacyProperties = null;
if (process.env.NODE_ENV !== 'production') {
this._unprocessedContextDev = null;
this._processedContextDev = null;
}
}
ReactDOMComponent.displayName = 'ReactDOMComponent';
ReactDOMComponent.Mixin = {
construct: function (element) {
this._currentElement = element;
},
/**
* Generates root tag markup then recurses. This method has side effects and
* is not idempotent.
*
* @internal
* @param {string} rootID The root DOM ID for this node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {object} context
* @return {string} The computed markup.
*/
mountComponent: function (rootID, transaction, context) {
this._rootNodeID = rootID;
var props = this._currentElement.props;
switch (this._tag) {
case 'iframe':
case 'img':
case 'form':
case 'video':
case 'audio':
this._wrapperState = {
listeners: null
};
transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
break;
case 'button':
props = ReactDOMButton.getNativeProps(this, props, context);
break;
case 'input':
ReactDOMInput.mountWrapper(this, props, context);
props = ReactDOMInput.getNativeProps(this, props, context);
break;
case 'option':
ReactDOMOption.mountWrapper(this, props, context);
props = ReactDOMOption.getNativeProps(this, props, context);
break;
case 'select':
ReactDOMSelect.mountWrapper(this, props, context);
props = ReactDOMSelect.getNativeProps(this, props, context);
context = ReactDOMSelect.processChildContext(this, props, context);
break;
case 'textarea':
ReactDOMTextarea.mountWrapper(this, props, context);
props = ReactDOMTextarea.getNativeProps(this, props, context);
break;
}
assertValidProps(this, props);
if (process.env.NODE_ENV !== 'production') {
if (context[validateDOMNesting.ancestorInfoContextKey]) {
validateDOMNesting(this._tag, this, context[validateDOMNesting.ancestorInfoContextKey]);
}
}
if (process.env.NODE_ENV !== 'production') {
this._unprocessedContextDev = context;
this._processedContextDev = processChildContextDev(context, this);
context = this._processedContextDev;
}
var mountImage;
if (transaction.useCreateElement) {
var ownerDocument = context[ReactMount.ownerDocumentContextKey];
var el = ownerDocument.createElement(this._currentElement.type);
DOMPropertyOperations.setAttributeForID(el, this._rootNodeID);
// Populate node cache
ReactMount.getID(el);
this._updateDOMProperties({}, props, transaction, el);
this._createInitialChildren(transaction, props, context, el);
mountImage = el;
} else {
var tagOpen = this._createOpenTagMarkupAndPutListeners(transaction, props);
var tagContent = this._createContentMarkup(transaction, props, context);
if (!tagContent && omittedCloseTags[this._tag]) {
mountImage = tagOpen + '/>';
} else {
mountImage = tagOpen + '>' + tagContent + '</' + this._currentElement.type + '>';
}
}
switch (this._tag) {
case 'input':
transaction.getReactMountReady().enqueue(mountReadyInputWrapper, this);
// falls through
case 'button':
case 'select':
case 'textarea':
if (props.autoFocus) {
transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this);
}
break;
}
return mountImage;
},
/**
* Creates markup for the open tag and all attributes.
*
* This method has side effects because events get registered.
*
* Iterating over object properties is faster than iterating over arrays.
* @see http://jsperf.com/obj-vs-arr-iteration
*
* @private
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {object} props
* @return {string} Markup of opening tag.
*/
_createOpenTagMarkupAndPutListeners: function (transaction, props) {
var ret = '<' + this._currentElement.type;
for (var propKey in props) {
if (!props.hasOwnProperty(propKey)) {
continue;
}
var propValue = props[propKey];
if (propValue == null) {
continue;
}
if (registrationNameModules.hasOwnProperty(propKey)) {
if (propValue) {
enqueuePutListener(this._rootNodeID, propKey, propValue, transaction);
}
} else {
if (propKey === STYLE) {
if (propValue) {
if (process.env.NODE_ENV !== 'production') {
// See `_updateDOMProperties`. style block
this._previousStyle = propValue;
}
propValue = this._previousStyleCopy = assign({}, props.style);
}
propValue = CSSPropertyOperations.createMarkupForStyles(propValue);
}
var markup = null;
if (this._tag != null && isCustomComponent(this._tag, props)) {
if (propKey !== CHILDREN) {
markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue);
}
} else {
markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue);
}
if (markup) {
ret += ' ' + markup;
}
}
}
// For static pages, no need to put React ID and checksum. Saves lots of
// bytes.
if (transaction.renderToStaticMarkup) {
return ret;
}
var markupForID = DOMPropertyOperations.createMarkupForID(this._rootNodeID);
return ret + ' ' + markupForID;
},
/**
* Creates markup for the content between the tags.
*
* @private
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {object} props
* @param {object} context
* @return {string} Content markup.
*/
_createContentMarkup: function (transaction, props, context) {
var ret = '';
// Intentional use of != to avoid catching zero/false.
var innerHTML = props.dangerouslySetInnerHTML;
if (innerHTML != null) {
if (innerHTML.__html != null) {
ret = innerHTML.__html;
}
} else {
var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null;
var childrenToUse = contentToUse != null ? null : props.children;
if (contentToUse != null) {
// TODO: Validate that text is allowed as a child of this node
ret = escapeTextContentForBrowser(contentToUse);
} else if (childrenToUse != null) {
var mountImages = this.mountChildren(childrenToUse, transaction, context);
ret = mountImages.join('');
}
}
if (newlineEatingTags[this._tag] && ret.charAt(0) === '\n') {
// text/html ignores the first character in these tags if it's a newline
// Prefer to break application/xml over text/html (for now) by adding
// a newline specifically to get eaten by the parser. (Alternately for
// textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
// \r is normalized out by HTMLTextAreaElement#value.)
// See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
// See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
// See: <http://www.w3.org/TR/html5/syntax.html#newlines>
// See: Parsing of "textarea" "listing" and "pre" elements
// from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
return '\n' + ret;
} else {
return ret;
}
},
_createInitialChildren: function (transaction, props, context, el) {
// Intentional use of != to avoid catching zero/false.
var innerHTML = props.dangerouslySetInnerHTML;
if (innerHTML != null) {
if (innerHTML.__html != null) {
setInnerHTML(el, innerHTML.__html);
}
} else {
var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null;
var childrenToUse = contentToUse != null ? null : props.children;
if (contentToUse != null) {
// TODO: Validate that text is allowed as a child of this node
setTextContent(el, contentToUse);
} else if (childrenToUse != null) {
var mountImages = this.mountChildren(childrenToUse, transaction, context);
for (var i = 0; i < mountImages.length; i++) {
el.appendChild(mountImages[i]);
}
}
}
},
/**
* Receives a next element and updates the component.
*
* @internal
* @param {ReactElement} nextElement
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {object} context
*/
receiveComponent: function (nextElement, transaction, context) {
var prevElement = this._currentElement;
this._currentElement = nextElement;
this.updateComponent(transaction, prevElement, nextElement, context);
},
/**
* Updates a native DOM component after it has already been allocated and
* attached to the DOM. Reconciles the root DOM node, then recurses.
*
* @param {ReactReconcileTransaction} transaction
* @param {ReactElement} prevElement
* @param {ReactElement} nextElement
* @internal
* @overridable
*/
updateComponent: function (transaction, prevElement, nextElement, context) {
var lastProps = prevElement.props;
var nextProps = this._currentElement.props;
switch (this._tag) {
case 'button':
lastProps = ReactDOMButton.getNativeProps(this, lastProps);
nextProps = ReactDOMButton.getNativeProps(this, nextProps);
break;
case 'input':
ReactDOMInput.updateWrapper(this);
lastProps = ReactDOMInput.getNativeProps(this, lastProps);
nextProps = ReactDOMInput.getNativeProps(this, nextProps);
break;
case 'option':
lastProps = ReactDOMOption.getNativeProps(this, lastProps);
nextProps = ReactDOMOption.getNativeProps(this, nextProps);
break;
case 'select':
lastProps = ReactDOMSelect.getNativeProps(this, lastProps);
nextProps = ReactDOMSelect.getNativeProps(this, nextProps);
break;
case 'textarea':
ReactDOMTextarea.updateWrapper(this);
lastProps = ReactDOMTextarea.getNativeProps(this, lastProps);
nextProps = ReactDOMTextarea.getNativeProps(this, nextProps);
break;
}
if (process.env.NODE_ENV !== 'production') {
// If the context is reference-equal to the old one, pass down the same
// processed object so the update bailout in ReactReconciler behaves
// correctly (and identically in dev and prod). See #5005.
if (this._unprocessedContextDev !== context) {
this._unprocessedContextDev = context;
this._processedContextDev = processChildContextDev(context, this);
}
context = this._processedContextDev;
}
assertValidProps(this, nextProps);
this._updateDOMProperties(lastProps, nextProps, transaction, null);
this._updateDOMChildren(lastProps, nextProps, transaction, context);
if (!canDefineProperty && this._nodeWithLegacyProperties) {
this._nodeWithLegacyProperties.props = nextProps;
}
if (this._tag === 'select') {
// <select> value update needs to occur after <option> children
// reconciliation
transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this);
}
},
/**
* Reconciles the properties by detecting differences in property values and
* updating the DOM as necessary. This function is probably the single most
* critical path for performance optimization.
*
* TODO: Benchmark whether checking for changed values in memory actually
* improves performance (especially statically positioned elements).
* TODO: Benchmark the effects of putting this at the top since 99% of props
* do not change for a given reconciliation.
* TODO: Benchmark areas that can be improved with caching.
*
* @private
* @param {object} lastProps
* @param {object} nextProps
* @param {ReactReconcileTransaction} transaction
* @param {?DOMElement} node
*/
_updateDOMProperties: function (lastProps, nextProps, transaction, node) {
var propKey;
var styleName;
var styleUpdates;
for (propKey in lastProps) {
if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey)) {
continue;
}
if (propKey === STYLE) {
var lastStyle = this._previousStyleCopy;
for (styleName in lastStyle) {
if (lastStyle.hasOwnProperty(styleName)) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = '';
}
}
this._previousStyleCopy = null;
} else if (registrationNameModules.hasOwnProperty(propKey)) {
if (lastProps[propKey]) {
// Only call deleteListener if there was a listener previously or
// else willDeleteListener gets called when there wasn't actually a
// listener (e.g., onClick={null})
deleteListener(this._rootNodeID, propKey);
}
} else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) {
if (!node) {
node = ReactMount.getNode(this._rootNodeID);
}
DOMPropertyOperations.deleteValueForProperty(node, propKey);
}
}
for (propKey in nextProps) {
var nextProp = nextProps[propKey];
var lastProp = propKey === STYLE ? this._previousStyleCopy : lastProps[propKey];
if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp) {
continue;
}
if (propKey === STYLE) {
if (nextProp) {
if (process.env.NODE_ENV !== 'production') {
checkAndWarnForMutatedStyle(this._previousStyleCopy, this._previousStyle, this);
this._previousStyle = nextProp;
}
nextProp = this._previousStyleCopy = assign({}, nextProp);
} else {
this._previousStyleCopy = null;
}
if (lastProp) {
// Unset styles on `lastProp` but not on `nextProp`.
for (styleName in lastProp) {
if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = '';
}
}
// Update styles that changed since `lastProp`.
for (styleName in nextProp) {
if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = nextProp[styleName];
}
}
} else {
// Relies on `updateStylesByID` not mutating `styleUpdates`.
styleUpdates = nextProp;
}
} else if (registrationNameModules.hasOwnProperty(propKey)) {
if (nextProp) {
enqueuePutListener(this._rootNodeID, propKey, nextProp, transaction);
} else if (lastProp) {
deleteListener(this._rootNodeID, propKey);
}
} else if (isCustomComponent(this._tag, nextProps)) {
if (!node) {
node = ReactMount.getNode(this._rootNodeID);
}
if (propKey === CHILDREN) {
nextProp = null;
}
DOMPropertyOperations.setValueForAttribute(node, propKey, nextProp);
} else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) {
if (!node) {
node = ReactMount.getNode(this._rootNodeID);
}
// If we're updating to null or undefined, we should remove the property
// from the DOM node instead of inadvertantly setting to a string. This
// brings us in line with the same behavior we have on initial render.
if (nextProp != null) {
DOMPropertyOperations.setValueForProperty(node, propKey, nextProp);
} else {
DOMPropertyOperations.deleteValueForProperty(node, propKey);
}
}
}
if (styleUpdates) {
if (!node) {
node = ReactMount.getNode(this._rootNodeID);
}
CSSPropertyOperations.setValueForStyles(node, styleUpdates);
}
},
/**
* Reconciles the children with the various properties that affect the
* children content.
*
* @param {object} lastProps
* @param {object} nextProps
* @param {ReactReconcileTransaction} transaction
* @param {object} context
*/
_updateDOMChildren: function (lastProps, nextProps, transaction, context) {
var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null;
var nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null;
var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html;
var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html;
// Note the use of `!=` which checks for null or undefined.
var lastChildren = lastContent != null ? null : lastProps.children;
var nextChildren = nextContent != null ? null : nextProps.children;
// If we're switching from children to content/html or vice versa, remove
// the old content
var lastHasContentOrHtml = lastContent != null || lastHtml != null;
var nextHasContentOrHtml = nextContent != null || nextHtml != null;
if (lastChildren != null && nextChildren == null) {
this.updateChildren(null, transaction, context);
} else if (lastHasContentOrHtml && !nextHasContentOrHtml) {
this.updateTextContent('');
}
if (nextContent != null) {
if (lastContent !== nextContent) {
this.updateTextContent('' + nextContent);
}
} else if (nextHtml != null) {
if (lastHtml !== nextHtml) {
this.updateMarkup('' + nextHtml);
}
} else if (nextChildren != null) {
this.updateChildren(nextChildren, transaction, context);
}
},
/**
* Destroys all event registrations for this instance. Does not remove from
* the DOM. That must be done by the parent.
*
* @internal
*/
unmountComponent: function () {
switch (this._tag) {
case 'iframe':
case 'img':
case 'form':
case 'video':
case 'audio':
var listeners = this._wrapperState.listeners;
if (listeners) {
for (var i = 0; i < listeners.length; i++) {
listeners[i].remove();
}
}
break;
case 'input':
ReactDOMInput.unmountWrapper(this);
break;
case 'html':
case 'head':
case 'body':
/**
* Components like <html> <head> and <body> can't be removed or added
* easily in a cross-browser way, however it's valuable to be able to
* take advantage of React's reconciliation for styling and <title>
* management. So we just document it and throw in dangerous cases.
*/
true ? process.env.NODE_ENV !== 'production' ? invariant(false, '<%s> tried to unmount. Because of cross-browser quirks it is ' + 'impossible to unmount some top-level components (eg <html>, ' + '<head>, and <body>) reliably and efficiently. To fix this, have a ' + 'single top-level component that never unmounts render these ' + 'elements.', this._tag) : invariant(false) : undefined;
break;
}
this.unmountChildren();
ReactBrowserEventEmitter.deleteAllListeners(this._rootNodeID);
ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID);
this._rootNodeID = null;
this._wrapperState = null;
if (this._nodeWithLegacyProperties) {
var node = this._nodeWithLegacyProperties;
node._reactInternalComponent = null;
this._nodeWithLegacyProperties = null;
}
},
getPublicInstance: function () {
if (!this._nodeWithLegacyProperties) {
var node = ReactMount.getNode(this._rootNodeID);
node._reactInternalComponent = this;
node.getDOMNode = legacyGetDOMNode;
node.isMounted = legacyIsMounted;
node.setState = legacySetStateEtc;
node.replaceState = legacySetStateEtc;
node.forceUpdate = legacySetStateEtc;
node.setProps = legacySetProps;
node.replaceProps = legacyReplaceProps;
if (process.env.NODE_ENV !== 'production') {
if (canDefineProperty) {
Object.defineProperties(node, legacyPropsDescriptor);
} else {
// updateComponent will update this property on subsequent renders
node.props = this._currentElement.props;
}
} else {
// updateComponent will update this property on subsequent renders
node.props = this._currentElement.props;
}
this._nodeWithLegacyProperties = node;
}
return this._nodeWithLegacyProperties;
}
};
ReactPerf.measureMethods(ReactDOMComponent, 'ReactDOMComponent', {
mountComponent: 'mountComponent',
updateComponent: 'updateComponent'
});
assign(ReactDOMComponent.prototype, ReactDOMComponent.Mixin, ReactMultiChild.Mixin);
module.exports = ReactDOMComponent;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 94 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule AutoFocusUtils
* @typechecks static-only
*/
'use strict';
var ReactMount = __webpack_require__(28);
var findDOMNode = __webpack_require__(91);
var focusNode = __webpack_require__(95);
var Mixin = {
componentDidMount: function () {
if (this.props.autoFocus) {
focusNode(findDOMNode(this));
}
}
};
var AutoFocusUtils = {
Mixin: Mixin,
focusDOMComponent: function () {
focusNode(ReactMount.getNode(this._rootNodeID));
}
};
module.exports = AutoFocusUtils;
/***/ },
/* 95 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule focusNode
*/
'use strict';
/**
* @param {DOMElement} node input/textarea to focus
*/
function focusNode(node) {
// IE8 can throw "Can't move focus to the control because it is invisible,
// not enabled, or of a type that does not accept the focus." for all kinds of
// reasons that are too expensive and fragile to test.
try {
node.focus();
} catch (e) {}
}
module.exports = focusNode;
/***/ },
/* 96 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule CSSPropertyOperations
* @typechecks static-only
*/
'use strict';
var CSSProperty = __webpack_require__(97);
var ExecutionEnvironment = __webpack_require__(9);
var ReactPerf = __webpack_require__(18);
var camelizeStyleName = __webpack_require__(98);
var dangerousStyleValue = __webpack_require__(100);
var hyphenateStyleName = __webpack_require__(101);
var memoizeStringOnly = __webpack_require__(103);
var warning = __webpack_require__(25);
var processStyleName = memoizeStringOnly(function (styleName) {
return hyphenateStyleName(styleName);
});
var hasShorthandPropertyBug = false;
var styleFloatAccessor = 'cssFloat';
if (ExecutionEnvironment.canUseDOM) {
var tempStyle = document.createElement('div').style;
try {
// IE8 throws "Invalid argument." if resetting shorthand style properties.
tempStyle.font = '';
} catch (e) {
hasShorthandPropertyBug = true;
}
// IE8 only supports accessing cssFloat (standard) as styleFloat
if (document.documentElement.style.cssFloat === undefined) {
styleFloatAccessor = 'styleFloat';
}
}
if (process.env.NODE_ENV !== 'production') {
// 'msTransform' is correct, but the other prefixes should be capitalized
var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
// style values shouldn't contain a semicolon
var badStyleValueWithSemicolonPattern = /;\s*$/;
var warnedStyleNames = {};
var warnedStyleValues = {};
var warnHyphenatedStyleName = function (name) {
if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
return;
}
warnedStyleNames[name] = true;
process.env.NODE_ENV !== 'production' ? warning(false, 'Unsupported style property %s. Did you mean %s?', name, camelizeStyleName(name)) : undefined;
};
var warnBadVendoredStyleName = function (name) {
if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
return;
}
warnedStyleNames[name] = true;
process.env.NODE_ENV !== 'production' ? warning(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1)) : undefined;
};
var warnStyleValueWithSemicolon = function (name, value) {
if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
return;
}
warnedStyleValues[value] = true;
process.env.NODE_ENV !== 'production' ? warning(false, 'Style property values shouldn\'t contain a semicolon. ' + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, '')) : undefined;
};
/**
* @param {string} name
* @param {*} value
*/
var warnValidStyle = function (name, value) {
if (name.indexOf('-') > -1) {
warnHyphenatedStyleName(name);
} else if (badVendoredStyleNamePattern.test(name)) {
warnBadVendoredStyleName(name);
} else if (badStyleValueWithSemicolonPattern.test(value)) {
warnStyleValueWithSemicolon(name, value);
}
};
}
/**
* Operations for dealing with CSS properties.
*/
var CSSPropertyOperations = {
/**
* Serializes a mapping of style properties for use as inline styles:
*
* > createMarkupForStyles({width: '200px', height: 0})
* "width:200px;height:0;"
*
* Undefined values are ignored so that declarative programming is easier.
* The result should be HTML-escaped before insertion into the DOM.
*
* @param {object} styles
* @return {?string}
*/
createMarkupForStyles: function (styles) {
var serialized = '';
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
var styleValue = styles[styleName];
if (process.env.NODE_ENV !== 'production') {
warnValidStyle(styleName, styleValue);
}
if (styleValue != null) {
serialized += processStyleName(styleName) + ':';
serialized += dangerousStyleValue(styleName, styleValue) + ';';
}
}
return serialized || null;
},
/**
* Sets the value for multiple styles on a node. If a value is specified as
* '' (empty string), the corresponding style property will be unset.
*
* @param {DOMElement} node
* @param {object} styles
*/
setValueForStyles: function (node, styles) {
var style = node.style;
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
if (process.env.NODE_ENV !== 'production') {
warnValidStyle(styleName, styles[styleName]);
}
var styleValue = dangerousStyleValue(styleName, styles[styleName]);
if (styleName === 'float') {
styleName = styleFloatAccessor;
}
if (styleValue) {
style[styleName] = styleValue;
} else {
var expansion = hasShorthandPropertyBug && CSSProperty.shorthandPropertyExpansions[styleName];
if (expansion) {
// Shorthand property that IE8 won't like unsetting, so unset each
// component to placate it
for (var individualStyleName in expansion) {
style[individualStyleName] = '';
}
} else {
style[styleName] = '';
}
}
}
}
};
ReactPerf.measureMethods(CSSPropertyOperations, 'CSSPropertyOperations', {
setValueForStyles: 'setValueForStyles'
});
module.exports = CSSPropertyOperations;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 97 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule CSSProperty
*/
'use strict';
/**
* CSS properties which accept numbers but are not in units of "px".
*/
var isUnitlessNumber = {
animationIterationCount: true,
boxFlex: true,
boxFlexGroup: true,
boxOrdinalGroup: true,
columnCount: true,
flex: true,
flexGrow: true,
flexPositive: true,
flexShrink: true,
flexNegative: true,
flexOrder: true,
fontWeight: true,
lineClamp: true,
lineHeight: true,
opacity: true,
order: true,
orphans: true,
tabSize: true,
widows: true,
zIndex: true,
zoom: true,
// SVG-related properties
fillOpacity: true,
stopOpacity: true,
strokeDashoffset: true,
strokeOpacity: true,
strokeWidth: true
};
/**
* @param {string} prefix vendor-specific prefix, eg: Webkit
* @param {string} key style name, eg: transitionDuration
* @return {string} style name prefixed with `prefix`, properly camelCased, eg:
* WebkitTransitionDuration
*/
function prefixKey(prefix, key) {
return prefix + key.charAt(0).toUpperCase() + key.substring(1);
}
/**
* Support style names that may come passed in prefixed by adding permutations
* of vendor prefixes.
*/
var prefixes = ['Webkit', 'ms', 'Moz', 'O'];
// Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
// infinite loop, because it iterates over the newly added props too.
Object.keys(isUnitlessNumber).forEach(function (prop) {
prefixes.forEach(function (prefix) {
isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
});
});
/**
* Most style properties can be unset by doing .style[prop] = '' but IE8
* doesn't like doing that with shorthand properties so for the properties that
* IE8 breaks on, which are listed here, we instead unset each of the
* individual properties. See http://bugs.jquery.com/ticket/12385.
* The 4-value 'clock' properties like margin, padding, border-width seem to
* behave without any problems. Curiously, list-style works too without any
* special prodding.
*/
var shorthandPropertyExpansions = {
background: {
backgroundAttachment: true,
backgroundColor: true,
backgroundImage: true,
backgroundPositionX: true,
backgroundPositionY: true,
backgroundRepeat: true
},
backgroundPosition: {
backgroundPositionX: true,
backgroundPositionY: true
},
border: {
borderWidth: true,
borderStyle: true,
borderColor: true
},
borderBottom: {
borderBottomWidth: true,
borderBottomStyle: true,
borderBottomColor: true
},
borderLeft: {
borderLeftWidth: true,
borderLeftStyle: true,
borderLeftColor: true
},
borderRight: {
borderRightWidth: true,
borderRightStyle: true,
borderRightColor: true
},
borderTop: {
borderTopWidth: true,
borderTopStyle: true,
borderTopColor: true
},
font: {
fontStyle: true,
fontVariant: true,
fontWeight: true,
fontSize: true,
lineHeight: true,
fontFamily: true
},
outline: {
outlineWidth: true,
outlineStyle: true,
outlineColor: true
}
};
var CSSProperty = {
isUnitlessNumber: isUnitlessNumber,
shorthandPropertyExpansions: shorthandPropertyExpansions
};
module.exports = CSSProperty;
/***/ },
/* 98 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule camelizeStyleName
* @typechecks
*/
'use strict';
var camelize = __webpack_require__(99);
var msPattern = /^-ms-/;
/**
* Camelcases a hyphenated CSS property name, for example:
*
* > camelizeStyleName('background-color')
* < "backgroundColor"
* > camelizeStyleName('-moz-transition')
* < "MozTransition"
* > camelizeStyleName('-ms-transition')
* < "msTransition"
*
* As Andi Smith suggests
* (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
* is converted to lowercase `ms`.
*
* @param {string} string
* @return {string}
*/
function camelizeStyleName(string) {
return camelize(string.replace(msPattern, 'ms-'));
}
module.exports = camelizeStyleName;
/***/ },
/* 99 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule camelize
* @typechecks
*/
"use strict";
var _hyphenPattern = /-(.)/g;
/**
* Camelcases a hyphenated string, for example:
*
* > camelize('background-color')
* < "backgroundColor"
*
* @param {string} string
* @return {string}
*/
function camelize(string) {
return string.replace(_hyphenPattern, function (_, character) {
return character.toUpperCase();
});
}
module.exports = camelize;
/***/ },
/* 100 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule dangerousStyleValue
* @typechecks static-only
*/
'use strict';
var CSSProperty = __webpack_require__(97);
var isUnitlessNumber = CSSProperty.isUnitlessNumber;
/**
* Convert a value into the proper css writable value. The style name `name`
* should be logical (no hyphens), as specified
* in `CSSProperty.isUnitlessNumber`.
*
* @param {string} name CSS property name such as `topMargin`.
* @param {*} value CSS property value such as `10px`.
* @return {string} Normalized style value with dimensions applied.
*/
function dangerousStyleValue(name, value) {
// Note that we've removed escapeTextForBrowser() calls here since the
// whole string will be escaped when the attribute is injected into
// the markup. If you provide unsafe user data here they can inject
// arbitrary CSS which may be problematic (I couldn't repro this):
// https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
// http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
// This is not an XSS hole but instead a potential CSS injection issue
// which has lead to a greater discussion about how we're going to
// trust URLs moving forward. See #2115901
var isEmpty = value == null || typeof value === 'boolean' || value === '';
if (isEmpty) {
return '';
}
var isNonNumeric = isNaN(value);
if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) {
return '' + value; // cast to string
}
if (typeof value === 'string') {
value = value.trim();
}
return value + 'px';
}
module.exports = dangerousStyleValue;
/***/ },
/* 101 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule hyphenateStyleName
* @typechecks
*/
'use strict';
var hyphenate = __webpack_require__(102);
var msPattern = /^ms-/;
/**
* Hyphenates a camelcased CSS property name, for example:
*
* > hyphenateStyleName('backgroundColor')
* < "background-color"
* > hyphenateStyleName('MozTransition')
* < "-moz-transition"
* > hyphenateStyleName('msTransition')
* < "-ms-transition"
*
* As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
* is converted to `-ms-`.
*
* @param {string} string
* @return {string}
*/
function hyphenateStyleName(string) {
return hyphenate(string).replace(msPattern, '-ms-');
}
module.exports = hyphenateStyleName;
/***/ },
/* 102 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule hyphenate
* @typechecks
*/
'use strict';
var _uppercasePattern = /([A-Z])/g;
/**
* Hyphenates a camelcased string, for example:
*
* > hyphenate('backgroundColor')
* < "background-color"
*
* For CSS style names, use `hyphenateStyleName` instead which works properly
* with all vendor prefixes, including `ms`.
*
* @param {string} string
* @return {string}
*/
function hyphenate(string) {
return string.replace(_uppercasePattern, '-$1').toLowerCase();
}
module.exports = hyphenate;
/***/ },
/* 103 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule memoizeStringOnly
* @typechecks static-only
*/
'use strict';
/**
* Memoizes the return value of a function that accepts one string argument.
*
* @param {function} callback
* @return {function}
*/
function memoizeStringOnly(callback) {
var cache = {};
return function (string) {
if (!cache.hasOwnProperty(string)) {
cache[string] = callback.call(this, string);
}
return cache[string];
};
}
module.exports = memoizeStringOnly;
/***/ },
/* 104 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMButton
*/
'use strict';
var mouseListenerNames = {
onClick: true,
onDoubleClick: true,
onMouseDown: true,
onMouseMove: true,
onMouseUp: true,
onClickCapture: true,
onDoubleClickCapture: true,
onMouseDownCapture: true,
onMouseMoveCapture: true,
onMouseUpCapture: true
};
/**
* Implements a <button> native component that does not receive mouse events
* when `disabled` is set.
*/
var ReactDOMButton = {
getNativeProps: function (inst, props, context) {
if (!props.disabled) {
return props;
}
// Copy the props, except the mouse listeners
var nativeProps = {};
for (var key in props) {
if (props.hasOwnProperty(key) && !mouseListenerNames[key]) {
nativeProps[key] = props[key];
}
}
return nativeProps;
}
};
module.exports = ReactDOMButton;
/***/ },
/* 105 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMInput
*/
'use strict';
var ReactDOMIDOperations = __webpack_require__(27);
var LinkedValueUtils = __webpack_require__(106);
var ReactMount = __webpack_require__(28);
var ReactUpdates = __webpack_require__(54);
var assign = __webpack_require__(39);
var invariant = __webpack_require__(13);
var instancesByReactID = {};
function forceUpdateIfMounted() {
if (this._rootNodeID) {
// DOM component is still mounted; update
ReactDOMInput.updateWrapper(this);
}
}
/**
* Implements an <input> native component that allows setting these optional
* props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
*
* If `checked` or `value` are not supplied (or null/undefined), user actions
* that affect the checked state or value will trigger updates to the element.
*
* If they are supplied (and not null/undefined), the rendered element will not
* trigger updates to the element. Instead, the props must change in order for
* the rendered element to be updated.
*
* The rendered element will be initialized as unchecked (or `defaultChecked`)
* with an empty value (or `defaultValue`).
*
* @see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
*/
var ReactDOMInput = {
getNativeProps: function (inst, props, context) {
var value = LinkedValueUtils.getValue(props);
var checked = LinkedValueUtils.getChecked(props);
var nativeProps = assign({}, props, {
defaultChecked: undefined,
defaultValue: undefined,
value: value != null ? value : inst._wrapperState.initialValue,
checked: checked != null ? checked : inst._wrapperState.initialChecked,
onChange: inst._wrapperState.onChange
});
return nativeProps;
},
mountWrapper: function (inst, props) {
if (process.env.NODE_ENV !== 'production') {
LinkedValueUtils.checkPropTypes('input', props, inst._currentElement._owner);
}
var defaultValue = props.defaultValue;
inst._wrapperState = {
initialChecked: props.defaultChecked || false,
initialValue: defaultValue != null ? defaultValue : null,
onChange: _handleChange.bind(inst)
};
},
mountReadyWrapper: function (inst) {
// Can't be in mountWrapper or else server rendering leaks.
instancesByReactID[inst._rootNodeID] = inst;
},
unmountWrapper: function (inst) {
delete instancesByReactID[inst._rootNodeID];
},
updateWrapper: function (inst) {
var props = inst._currentElement.props;
// TODO: Shouldn't this be getChecked(props)?
var checked = props.checked;
if (checked != null) {
ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'checked', checked || false);
}
var value = LinkedValueUtils.getValue(props);
if (value != null) {
// Cast `value` to a string to ensure the value is set correctly. While
// browsers typically do this as necessary, jsdom doesn't.
ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'value', '' + value);
}
}
};
function _handleChange(event) {
var props = this._currentElement.props;
var returnValue = LinkedValueUtils.executeOnChange(props, event);
// Here we use asap to wait until all updates have propagated, which
// is important when using controlled components within layers:
// https://github.com/facebook/react/issues/1698
ReactUpdates.asap(forceUpdateIfMounted, this);
var name = props.name;
if (props.type === 'radio' && name != null) {
var rootNode = ReactMount.getNode(this._rootNodeID);
var queryRoot = rootNode;
while (queryRoot.parentNode) {
queryRoot = queryRoot.parentNode;
}
// If `rootNode.form` was non-null, then we could try `form.elements`,
// but that sometimes behaves strangely in IE8. We could also try using
// `form.getElementsByName`, but that will only return direct children
// and won't include inputs that use the HTML5 `form=` attribute. Since
// the input might not even be in a form, let's just use the global
// `querySelectorAll` to ensure we don't miss anything.
var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]');
for (var i = 0; i < group.length; i++) {
var otherNode = group[i];
if (otherNode === rootNode || otherNode.form !== rootNode.form) {
continue;
}
// This will throw if radio buttons rendered by different copies of React
// and the same name are rendered into the same form (same as #1939).
// That's probably okay; we don't support it just as we don't support
// mixing React with non-React.
var otherID = ReactMount.getID(otherNode);
!otherID ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the ' + 'same `name` is not supported.') : invariant(false) : undefined;
var otherInstance = instancesByReactID[otherID];
!otherInstance ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOMInput: Unknown radio button ID %s.', otherID) : invariant(false) : undefined;
// If this is a controlled radio button group, forcing the input that
// was previously checked to update will cause it to be come re-checked
// as appropriate.
ReactUpdates.asap(forceUpdateIfMounted, otherInstance);
}
}
return returnValue;
}
module.exports = ReactDOMInput;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 106 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule LinkedValueUtils
* @typechecks static-only
*/
'use strict';
var ReactPropTypes = __webpack_require__(107);
var ReactPropTypeLocations = __webpack_require__(65);
var invariant = __webpack_require__(13);
var warning = __webpack_require__(25);
var hasReadOnlyValue = {
'button': true,
'checkbox': true,
'image': true,
'hidden': true,
'radio': true,
'reset': true,
'submit': true
};
function _assertSingleLink(inputProps) {
!(inputProps.checkedLink == null || inputProps.valueLink == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a valueLink. If you want to use ' + 'checkedLink, you probably don\'t want to use valueLink and vice versa.') : invariant(false) : undefined;
}
function _assertValueLink(inputProps) {
_assertSingleLink(inputProps);
!(inputProps.value == null && inputProps.onChange == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a valueLink and a value or onChange event. If you want ' + 'to use value or onChange, you probably don\'t want to use valueLink.') : invariant(false) : undefined;
}
function _assertCheckedLink(inputProps) {
_assertSingleLink(inputProps);
!(inputProps.checked == null && inputProps.onChange == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a checked property or onChange event. ' + 'If you want to use checked or onChange, you probably don\'t want to ' + 'use checkedLink') : invariant(false) : undefined;
}
var propTypes = {
value: function (props, propName, componentName) {
if (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) {
return null;
}
return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
},
checked: function (props, propName, componentName) {
if (!props[propName] || props.onChange || props.readOnly || props.disabled) {
return null;
}
return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
},
onChange: ReactPropTypes.func
};
var loggedTypeFailures = {};
function getDeclarationErrorAddendum(owner) {
if (owner) {
var name = owner.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
/**
* Provide a linked `value` attribute for controlled forms. You should not use
* this outside of the ReactDOM controlled form components.
*/
var LinkedValueUtils = {
checkPropTypes: function (tagName, props, owner) {
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error = propTypes[propName](props, propName, tagName, ReactPropTypeLocations.prop);
}
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var addendum = getDeclarationErrorAddendum(owner);
process.env.NODE_ENV !== 'production' ? warning(false, 'Failed form propType: %s%s', error.message, addendum) : undefined;
}
}
},
/**
* @param {object} inputProps Props for form component
* @return {*} current value of the input either from value prop or link.
*/
getValue: function (inputProps) {
if (inputProps.valueLink) {
_assertValueLink(inputProps);
return inputProps.valueLink.value;
}
return inputProps.value;
},
/**
* @param {object} inputProps Props for form component
* @return {*} current checked status of the input either from checked prop
* or link.
*/
getChecked: function (inputProps) {
if (inputProps.checkedLink) {
_assertCheckedLink(inputProps);
return inputProps.checkedLink.value;
}
return inputProps.checked;
},
/**
* @param {object} inputProps Props for form component
* @param {SyntheticEvent} event change event to handle
*/
executeOnChange: function (inputProps, event) {
if (inputProps.valueLink) {
_assertValueLink(inputProps);
return inputProps.valueLink.requestChange(event.target.value);
} else if (inputProps.checkedLink) {
_assertCheckedLink(inputProps);
return inputProps.checkedLink.requestChange(event.target.checked);
} else if (inputProps.onChange) {
return inputProps.onChange.call(undefined, event);
}
}
};
module.exports = LinkedValueUtils;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 107 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactPropTypes
*/
'use strict';
var ReactElement = __webpack_require__(42);
var ReactPropTypeLocationNames = __webpack_require__(66);
var emptyFunction = __webpack_require__(15);
var getIteratorFn = __webpack_require__(108);
/**
* Collection of methods that allow declaration and validation of props that are
* supplied to React components. Example usage:
*
* var Props = require('ReactPropTypes');
* var MyArticle = React.createClass({
* propTypes: {
* // An optional string prop named "description".
* description: Props.string,
*
* // A required enum prop named "category".
* category: Props.oneOf(['News','Photos']).isRequired,
*
* // A prop named "dialog" that requires an instance of Dialog.
* dialog: Props.instanceOf(Dialog).isRequired
* },
* render: function() { ... }
* });
*
* A more formal specification of how these methods are used:
*
* type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
* decl := ReactPropTypes.{type}(.isRequired)?
*
* Each and every declaration produces a function with the same signature. This
* allows the creation of custom validation functions. For example:
*
* var MyLink = React.createClass({
* propTypes: {
* // An optional string or URI prop named "href".
* href: function(props, propName, componentName) {
* var propValue = props[propName];
* if (propValue != null && typeof propValue !== 'string' &&
* !(propValue instanceof URI)) {
* return new Error(
* 'Expected a string or an URI for ' + propName + ' in ' +
* componentName
* );
* }
* }
* },
* render: function() {...}
* });
*
* @internal
*/
var ANONYMOUS = '<<anonymous>>';
var ReactPropTypes = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker
};
function createChainableTypeChecker(validate) {
function checkType(isRequired, props, propName, componentName, location, propFullName) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (props[propName] == null) {
var locationName = ReactPropTypeLocationNames[location];
if (isRequired) {
return new Error('Required ' + locationName + ' `' + propFullName + '` was not specified in ' + ('`' + componentName + '`.'));
}
return null;
} else {
return validate(props, propName, componentName, location, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== expectedType) {
var locationName = ReactPropTypeLocationNames[location];
// `propValue` being instance of, say, date/regexp, pass the 'object'
// check, but we can offer a more precise error message here rather than
// 'of type `object`'.
var preciseType = getPreciseType(propValue);
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunction.thatReturns(null));
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var locationName = ReactPropTypeLocationNames[location];
var propType = getPropType(propValue);
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
}
for (var i = 0; i < propValue.length; i++) {
var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']');
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!ReactElement.isValidElement(props[propName])) {
var locationName = ReactPropTypeLocationNames[location];
return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a single ReactElement.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location, propFullName) {
if (!(props[propName] instanceof expectedClass)) {
var locationName = ReactPropTypeLocationNames[location];
var expectedClassName = expectedClass.name || ANONYMOUS;
var actualClassName = getClassName(props[propName]);
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
if (!Array.isArray(expectedValues)) {
return createChainableTypeChecker(function () {
return new Error('Invalid argument supplied to oneOf, expected an instance of array.');
});
}
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (propValue === expectedValues[i]) {
return null;
}
}
var locationName = ReactPropTypeLocationNames[location];
var valuesString = JSON.stringify(expectedValues);
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
var locationName = ReactPropTypeLocationNames[location];
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
}
for (var key in propValue) {
if (propValue.hasOwnProperty(key)) {
var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key);
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
return createChainableTypeChecker(function () {
return new Error('Invalid argument supplied to oneOfType, expected an instance of array.');
});
}
function validate(props, propName, componentName, location, propFullName) {
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (checker(props, propName, componentName, location, propFullName) == null) {
return null;
}
}
var locationName = ReactPropTypeLocationNames[location];
return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
}
return createChainableTypeChecker(validate);
}
function createNodeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!isNode(props[propName])) {
var locationName = ReactPropTypeLocationNames[location];
return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
var locationName = ReactPropTypeLocationNames[location];
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (!checker) {
continue;
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(propValue) {
switch (typeof propValue) {
case 'number':
case 'string':
case 'undefined':
return true;
case 'boolean':
return !propValue;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isNode);
}
if (propValue === null || ReactElement.isValidElement(propValue)) {
return true;
}
var iteratorFn = getIteratorFn(propValue);
if (iteratorFn) {
var iterator = iteratorFn.call(propValue);
var step;
if (iteratorFn !== propValue.entries) {
while (!(step = iterator.next()).done) {
if (!isNode(step.value)) {
return false;
}
}
} else {
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
if (!isNode(entry[1])) {
return false;
}
}
}
}
} else {
return false;
}
return true;
default:
return false;
}
}
// Equivalent of `typeof` but with special handling for array and regexp.
function getPropType(propValue) {
var propType = typeof propValue;
if (Array.isArray(propValue)) {
return 'array';
}
if (propValue instanceof RegExp) {
// Old webkits (at least until Android 4.0) return 'function' rather than
// 'object' for typeof a RegExp. We'll normalize this here so that /bla/
// passes PropTypes.object.
return 'object';
}
return propType;
}
// This handles more types than `getPropType`. Only used for error messages.
// See `createPrimitiveTypeChecker`.
function getPreciseType(propValue) {
var propType = getPropType(propValue);
if (propType === 'object') {
if (propValue instanceof Date) {
return 'date';
} else if (propValue instanceof RegExp) {
return 'regexp';
}
}
return propType;
}
// Returns class name of the object, if any.
function getClassName(propValue) {
if (!propValue.constructor || !propValue.constructor.name) {
return '<<anonymous>>';
}
return propValue.constructor.name;
}
module.exports = ReactPropTypes;
/***/ },
/* 108 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getIteratorFn
* @typechecks static-only
*/
'use strict';
/* global Symbol */
var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
/**
* Returns the iterator method function contained on the iterable object.
*
* Be sure to invoke the function with the iterable as context:
*
* var iteratorFn = getIteratorFn(myIterable);
* if (iteratorFn) {
* var iterator = iteratorFn.call(myIterable);
* ...
* }
*
* @param {?object} maybeIterable
* @return {?function}
*/
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
module.exports = getIteratorFn;
/***/ },
/* 109 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMOption
*/
'use strict';
var ReactChildren = __webpack_require__(110);
var ReactDOMSelect = __webpack_require__(112);
var assign = __webpack_require__(39);
var warning = __webpack_require__(25);
var valueContextKey = ReactDOMSelect.valueContextKey;
/**
* Implements an <option> native component that warns when `selected` is set.
*/
var ReactDOMOption = {
mountWrapper: function (inst, props, context) {
// TODO (yungsters): Remove support for `selected` in <option>.
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(props.selected == null, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.') : undefined;
}
// Look up whether this option is 'selected' via context
var selectValue = context[valueContextKey];
// If context key is null (e.g., no specified value or after initial mount)
// or missing (e.g., for <datalist>), we don't change props.selected
var selected = null;
if (selectValue != null) {
selected = false;
if (Array.isArray(selectValue)) {
// multiple
for (var i = 0; i < selectValue.length; i++) {
if ('' + selectValue[i] === '' + props.value) {
selected = true;
break;
}
}
} else {
selected = '' + selectValue === '' + props.value;
}
}
inst._wrapperState = { selected: selected };
},
getNativeProps: function (inst, props, context) {
var nativeProps = assign({ selected: undefined, children: undefined }, props);
// Read state only from initial mount because <select> updates value
// manually; we need the initial state only for server rendering
if (inst._wrapperState.selected != null) {
nativeProps.selected = inst._wrapperState.selected;
}
var content = '';
// Flatten children and warn if they aren't strings or numbers;
// invalid types are ignored.
ReactChildren.forEach(props.children, function (child) {
if (child == null) {
return;
}
if (typeof child === 'string' || typeof child === 'number') {
content += child;
} else {
process.env.NODE_ENV !== 'production' ? warning(false, 'Only strings and numbers are supported as <option> children.') : undefined;
}
});
nativeProps.children = content;
return nativeProps;
}
};
module.exports = ReactDOMOption;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 110 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactChildren
*/
'use strict';
var PooledClass = __webpack_require__(56);
var ReactElement = __webpack_require__(42);
var emptyFunction = __webpack_require__(15);
var traverseAllChildren = __webpack_require__(111);
var twoArgumentPooler = PooledClass.twoArgumentPooler;
var fourArgumentPooler = PooledClass.fourArgumentPooler;
var userProvidedKeyEscapeRegex = /\/(?!\/)/g;
function escapeUserProvidedKey(text) {
return ('' + text).replace(userProvidedKeyEscapeRegex, '//');
}
/**
* PooledClass representing the bookkeeping associated with performing a child
* traversal. Allows avoiding binding callbacks.
*
* @constructor ForEachBookKeeping
* @param {!function} forEachFunction Function to perform traversal with.
* @param {?*} forEachContext Context to perform context with.
*/
function ForEachBookKeeping(forEachFunction, forEachContext) {
this.func = forEachFunction;
this.context = forEachContext;
this.count = 0;
}
ForEachBookKeeping.prototype.destructor = function () {
this.func = null;
this.context = null;
this.count = 0;
};
PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler);
function forEachSingleChild(bookKeeping, child, name) {
var func = bookKeeping.func;
var context = bookKeeping.context;
func.call(context, child, bookKeeping.count++);
}
/**
* Iterates through children that are typically specified as `props.children`.
*
* The provided forEachFunc(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} forEachFunc
* @param {*} forEachContext Context for forEachContext.
*/
function forEachChildren(children, forEachFunc, forEachContext) {
if (children == null) {
return children;
}
var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext);
traverseAllChildren(children, forEachSingleChild, traverseContext);
ForEachBookKeeping.release(traverseContext);
}
/**
* PooledClass representing the bookkeeping associated with performing a child
* mapping. Allows avoiding binding callbacks.
*
* @constructor MapBookKeeping
* @param {!*} mapResult Object containing the ordered map of results.
* @param {!function} mapFunction Function to perform mapping with.
* @param {?*} mapContext Context to perform mapping with.
*/
function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) {
this.result = mapResult;
this.keyPrefix = keyPrefix;
this.func = mapFunction;
this.context = mapContext;
this.count = 0;
}
MapBookKeeping.prototype.destructor = function () {
this.result = null;
this.keyPrefix = null;
this.func = null;
this.context = null;
this.count = 0;
};
PooledClass.addPoolingTo(MapBookKeeping, fourArgumentPooler);
function mapSingleChildIntoContext(bookKeeping, child, childKey) {
var result = bookKeeping.result;
var keyPrefix = bookKeeping.keyPrefix;
var func = bookKeeping.func;
var context = bookKeeping.context;
var mappedChild = func.call(context, child, bookKeeping.count++);
if (Array.isArray(mappedChild)) {
mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, emptyFunction.thatReturnsArgument);
} else if (mappedChild != null) {
if (ReactElement.isValidElement(mappedChild)) {
mappedChild = ReactElement.cloneAndReplaceKey(mappedChild,
// Keep both the (mapped) and old keys if they differ, just as
// traverseAllChildren used to do for objects as children
keyPrefix + (mappedChild !== child ? escapeUserProvidedKey(mappedChild.key || '') + '/' : '') + childKey);
}
result.push(mappedChild);
}
}
function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) {
var escapedPrefix = '';
if (prefix != null) {
escapedPrefix = escapeUserProvidedKey(prefix) + '/';
}
var traverseContext = MapBookKeeping.getPooled(array, escapedPrefix, func, context);
traverseAllChildren(children, mapSingleChildIntoContext, traverseContext);
MapBookKeeping.release(traverseContext);
}
/**
* Maps children that are typically specified as `props.children`.
*
* The provided mapFunction(child, key, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func The map function.
* @param {*} context Context for mapFunction.
* @return {object} Object containing the ordered map of results.
*/
function mapChildren(children, func, context) {
if (children == null) {
return children;
}
var result = [];
mapIntoWithKeyPrefixInternal(children, result, null, func, context);
return result;
}
function forEachSingleChildDummy(traverseContext, child, name) {
return null;
}
/**
* Count the number of children that are typically specified as
* `props.children`.
*
* @param {?*} children Children tree container.
* @return {number} The number of children.
*/
function countChildren(children, context) {
return traverseAllChildren(children, forEachSingleChildDummy, null);
}
/**
* Flatten a children object (typically specified as `props.children`) and
* return an array with appropriately re-keyed children.
*/
function toArray(children) {
var result = [];
mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument);
return result;
}
var ReactChildren = {
forEach: forEachChildren,
map: mapChildren,
mapIntoWithKeyPrefixInternal: mapIntoWithKeyPrefixInternal,
count: countChildren,
toArray: toArray
};
module.exports = ReactChildren;
/***/ },
/* 111 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule traverseAllChildren
*/
'use strict';
var ReactCurrentOwner = __webpack_require__(5);
var ReactElement = __webpack_require__(42);
var ReactInstanceHandles = __webpack_require__(45);
var getIteratorFn = __webpack_require__(108);
var invariant = __webpack_require__(13);
var warning = __webpack_require__(25);
var SEPARATOR = ReactInstanceHandles.SEPARATOR;
var SUBSEPARATOR = ':';
/**
* TODO: Test that a single child and an array with one item have the same key
* pattern.
*/
var userProvidedKeyEscaperLookup = {
'=': '=0',
'.': '=1',
':': '=2'
};
var userProvidedKeyEscapeRegex = /[=.:]/g;
var didWarnAboutMaps = false;
function userProvidedKeyEscaper(match) {
return userProvidedKeyEscaperLookup[match];
}
/**
* Generate a key string that identifies a component within a set.
*
* @param {*} component A component that could contain a manual key.
* @param {number} index Index that is used if a manual key is not provided.
* @return {string}
*/
function getComponentKey(component, index) {
if (component && component.key != null) {
// Explicit key
return wrapUserProvidedKey(component.key);
}
// Implicit key determined by the index in the set
return index.toString(36);
}
/**
* Escape a component key so that it is safe to use in a reactid.
*
* @param {*} text Component key to be escaped.
* @return {string} An escaped string.
*/
function escapeUserProvidedKey(text) {
return ('' + text).replace(userProvidedKeyEscapeRegex, userProvidedKeyEscaper);
}
/**
* Wrap a `key` value explicitly provided by the user to distinguish it from
* implicitly-generated keys generated by a component's index in its parent.
*
* @param {string} key Value of a user-provided `key` attribute
* @return {string}
*/
function wrapUserProvidedKey(key) {
return '$' + escapeUserProvidedKey(key);
}
/**
* @param {?*} children Children tree container.
* @param {!string} nameSoFar Name of the key path so far.
* @param {!function} callback Callback to invoke with each child found.
* @param {?*} traverseContext Used to pass information throughout the traversal
* process.
* @return {!number} The number of children in this subtree.
*/
function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) {
var type = typeof children;
if (type === 'undefined' || type === 'boolean') {
// All of the above are perceived as null.
children = null;
}
if (children === null || type === 'string' || type === 'number' || ReactElement.isValidElement(children)) {
callback(traverseContext, children,
// If it's the only child, treat the name as if it was wrapped in an array
// so that it's consistent if the number of children grows.
nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar);
return 1;
}
var child;
var nextName;
var subtreeCount = 0; // Count of children found in the current subtree.
var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
child = children[i];
nextName = nextNamePrefix + getComponentKey(child, i);
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
}
} else {
var iteratorFn = getIteratorFn(children);
if (iteratorFn) {
var iterator = iteratorFn.call(children);
var step;
if (iteratorFn !== children.entries) {
var ii = 0;
while (!(step = iterator.next()).done) {
child = step.value;
nextName = nextNamePrefix + getComponentKey(child, ii++);
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
}
} else {
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.') : undefined;
didWarnAboutMaps = true;
}
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
child = entry[1];
nextName = nextNamePrefix + wrapUserProvidedKey(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0);
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
}
}
}
} else if (type === 'object') {
var addendum = '';
if (process.env.NODE_ENV !== 'production') {
addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.';
if (children._isReactElement) {
addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.';
}
if (ReactCurrentOwner.current) {
var name = ReactCurrentOwner.current.getName();
if (name) {
addendum += ' Check the render method of `' + name + '`.';
}
}
}
var childrenString = String(children);
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : invariant(false) : undefined;
}
}
return subtreeCount;
}
/**
* Traverses children that are typically specified as `props.children`, but
* might also be specified through attributes:
*
* - `traverseAllChildren(this.props.children, ...)`
* - `traverseAllChildren(this.props.leftPanelChildren, ...)`
*
* The `traverseContext` is an optional argument that is passed through the
* entire traversal. It can be used to store accumulations or anything else that
* the callback might find relevant.
*
* @param {?*} children Children tree object.
* @param {!function} callback To invoke upon traversing each child.
* @param {?*} traverseContext Context for traversal.
* @return {!number} The number of children in this subtree.
*/
function traverseAllChildren(children, callback, traverseContext) {
if (children == null) {
return 0;
}
return traverseAllChildrenImpl(children, '', callback, traverseContext);
}
module.exports = traverseAllChildren;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 112 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMSelect
*/
'use strict';
var LinkedValueUtils = __webpack_require__(106);
var ReactMount = __webpack_require__(28);
var ReactUpdates = __webpack_require__(54);
var assign = __webpack_require__(39);
var warning = __webpack_require__(25);
var valueContextKey = '__ReactDOMSelect_value$' + Math.random().toString(36).slice(2);
function updateOptionsIfPendingUpdateAndMounted() {
if (this._rootNodeID && this._wrapperState.pendingUpdate) {
this._wrapperState.pendingUpdate = false;
var props = this._currentElement.props;
var value = LinkedValueUtils.getValue(props);
if (value != null) {
updateOptions(this, Boolean(props.multiple), value);
}
}
}
function getDeclarationErrorAddendum(owner) {
if (owner) {
var name = owner.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
var valuePropNames = ['value', 'defaultValue'];
/**
* Validation function for `value` and `defaultValue`.
* @private
*/
function checkSelectPropTypes(inst, props) {
var owner = inst._currentElement._owner;
LinkedValueUtils.checkPropTypes('select', props, owner);
for (var i = 0; i < valuePropNames.length; i++) {
var propName = valuePropNames[i];
if (props[propName] == null) {
continue;
}
if (props.multiple) {
process.env.NODE_ENV !== 'production' ? warning(Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum(owner)) : undefined;
} else {
process.env.NODE_ENV !== 'production' ? warning(!Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum(owner)) : undefined;
}
}
}
/**
* @param {ReactDOMComponent} inst
* @param {boolean} multiple
* @param {*} propValue A stringable (with `multiple`, a list of stringables).
* @private
*/
function updateOptions(inst, multiple, propValue) {
var selectedValue, i;
var options = ReactMount.getNode(inst._rootNodeID).options;
if (multiple) {
selectedValue = {};
for (i = 0; i < propValue.length; i++) {
selectedValue['' + propValue[i]] = true;
}
for (i = 0; i < options.length; i++) {
var selected = selectedValue.hasOwnProperty(options[i].value);
if (options[i].selected !== selected) {
options[i].selected = selected;
}
}
} else {
// Do not set `select.value` as exact behavior isn't consistent across all
// browsers for all cases.
selectedValue = '' + propValue;
for (i = 0; i < options.length; i++) {
if (options[i].value === selectedValue) {
options[i].selected = true;
return;
}
}
if (options.length) {
options[0].selected = true;
}
}
}
/**
* Implements a <select> native component that allows optionally setting the
* props `value` and `defaultValue`. If `multiple` is false, the prop must be a
* stringable. If `multiple` is true, the prop must be an array of stringables.
*
* If `value` is not supplied (or null/undefined), user actions that change the
* selected option will trigger updates to the rendered options.
*
* If it is supplied (and not null/undefined), the rendered options will not
* update in response to user actions. Instead, the `value` prop must change in
* order for the rendered options to update.
*
* If `defaultValue` is provided, any options with the supplied values will be
* selected.
*/
var ReactDOMSelect = {
valueContextKey: valueContextKey,
getNativeProps: function (inst, props, context) {
return assign({}, props, {
onChange: inst._wrapperState.onChange,
value: undefined
});
},
mountWrapper: function (inst, props) {
if (process.env.NODE_ENV !== 'production') {
checkSelectPropTypes(inst, props);
}
var value = LinkedValueUtils.getValue(props);
inst._wrapperState = {
pendingUpdate: false,
initialValue: value != null ? value : props.defaultValue,
onChange: _handleChange.bind(inst),
wasMultiple: Boolean(props.multiple)
};
},
processChildContext: function (inst, props, context) {
// Pass down initial value so initial generated markup has correct
// `selected` attributes
var childContext = assign({}, context);
childContext[valueContextKey] = inst._wrapperState.initialValue;
return childContext;
},
postUpdateWrapper: function (inst) {
var props = inst._currentElement.props;
// After the initial mount, we control selected-ness manually so don't pass
// the context value down
inst._wrapperState.initialValue = undefined;
var wasMultiple = inst._wrapperState.wasMultiple;
inst._wrapperState.wasMultiple = Boolean(props.multiple);
var value = LinkedValueUtils.getValue(props);
if (value != null) {
inst._wrapperState.pendingUpdate = false;
updateOptions(inst, Boolean(props.multiple), value);
} else if (wasMultiple !== Boolean(props.multiple)) {
// For simplicity, reapply `defaultValue` if `multiple` is toggled.
if (props.defaultValue != null) {
updateOptions(inst, Boolean(props.multiple), props.defaultValue);
} else {
// Revert the select back to its default unselected state.
updateOptions(inst, Boolean(props.multiple), props.multiple ? [] : '');
}
}
}
};
function _handleChange(event) {
var props = this._currentElement.props;
var returnValue = LinkedValueUtils.executeOnChange(props, event);
this._wrapperState.pendingUpdate = true;
ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this);
return returnValue;
}
module.exports = ReactDOMSelect;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 113 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMTextarea
*/
'use strict';
var LinkedValueUtils = __webpack_require__(106);
var ReactDOMIDOperations = __webpack_require__(27);
var ReactUpdates = __webpack_require__(54);
var assign = __webpack_require__(39);
var invariant = __webpack_require__(13);
var warning = __webpack_require__(25);
function forceUpdateIfMounted() {
if (this._rootNodeID) {
// DOM component is still mounted; update
ReactDOMTextarea.updateWrapper(this);
}
}
/**
* Implements a <textarea> native component that allows setting `value`, and
* `defaultValue`. This differs from the traditional DOM API because value is
* usually set as PCDATA children.
*
* If `value` is not supplied (or null/undefined), user actions that affect the
* value will trigger updates to the element.
*
* If `value` is supplied (and not null/undefined), the rendered element will
* not trigger updates to the element. Instead, the `value` prop must change in
* order for the rendered element to be updated.
*
* The rendered element will be initialized with an empty value, the prop
* `defaultValue` if specified, or the children content (deprecated).
*/
var ReactDOMTextarea = {
getNativeProps: function (inst, props, context) {
!(props.dangerouslySetInnerHTML == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : invariant(false) : undefined;
// Always set children to the same thing. In IE9, the selection range will
// get reset if `textContent` is mutated.
var nativeProps = assign({}, props, {
defaultValue: undefined,
value: undefined,
children: inst._wrapperState.initialValue,
onChange: inst._wrapperState.onChange
});
return nativeProps;
},
mountWrapper: function (inst, props) {
if (process.env.NODE_ENV !== 'production') {
LinkedValueUtils.checkPropTypes('textarea', props, inst._currentElement._owner);
}
var defaultValue = props.defaultValue;
// TODO (yungsters): Remove support for children content in <textarea>.
var children = props.children;
if (children != null) {
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.') : undefined;
}
!(defaultValue == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : invariant(false) : undefined;
if (Array.isArray(children)) {
!(children.length <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, '<textarea> can only have at most one child.') : invariant(false) : undefined;
children = children[0];
}
defaultValue = '' + children;
}
if (defaultValue == null) {
defaultValue = '';
}
var value = LinkedValueUtils.getValue(props);
inst._wrapperState = {
// We save the initial value so that `ReactDOMComponent` doesn't update
// `textContent` (unnecessary since we update value).
// The initial value can be a boolean or object so that's why it's
// forced to be a string.
initialValue: '' + (value != null ? value : defaultValue),
onChange: _handleChange.bind(inst)
};
},
updateWrapper: function (inst) {
var props = inst._currentElement.props;
var value = LinkedValueUtils.getValue(props);
if (value != null) {
// Cast `value` to a string to ensure the value is set correctly. While
// browsers typically do this as necessary, jsdom doesn't.
ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'value', '' + value);
}
}
};
function _handleChange(event) {
var props = this._currentElement.props;
var returnValue = LinkedValueUtils.executeOnChange(props, event);
ReactUpdates.asap(forceUpdateIfMounted, this);
return returnValue;
}
module.exports = ReactDOMTextarea;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 114 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactMultiChild
* @typechecks static-only
*/
'use strict';
var ReactComponentEnvironment = __webpack_require__(64);
var ReactMultiChildUpdateTypes = __webpack_require__(16);
var ReactCurrentOwner = __webpack_require__(5);
var ReactReconciler = __webpack_require__(50);
var ReactChildReconciler = __webpack_require__(115);
var flattenChildren = __webpack_require__(116);
/**
* Updating children of a component may trigger recursive updates. The depth is
* used to batch recursive updates to render markup more efficiently.
*
* @type {number}
* @private
*/
var updateDepth = 0;
/**
* Queue of update configuration objects.
*
* Each object has a `type` property that is in `ReactMultiChildUpdateTypes`.
*
* @type {array<object>}
* @private
*/
var updateQueue = [];
/**
* Queue of markup to be rendered.
*
* @type {array<string>}
* @private
*/
var markupQueue = [];
/**
* Enqueues markup to be rendered and inserted at a supplied index.
*
* @param {string} parentID ID of the parent component.
* @param {string} markup Markup that renders into an element.
* @param {number} toIndex Destination index.
* @private
*/
function enqueueInsertMarkup(parentID, markup, toIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.INSERT_MARKUP,
markupIndex: markupQueue.push(markup) - 1,
content: null,
fromIndex: null,
toIndex: toIndex
});
}
/**
* Enqueues moving an existing element to another index.
*
* @param {string} parentID ID of the parent component.
* @param {number} fromIndex Source index of the existing element.
* @param {number} toIndex Destination index of the element.
* @private
*/
function enqueueMove(parentID, fromIndex, toIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.MOVE_EXISTING,
markupIndex: null,
content: null,
fromIndex: fromIndex,
toIndex: toIndex
});
}
/**
* Enqueues removing an element at an index.
*
* @param {string} parentID ID of the parent component.
* @param {number} fromIndex Index of the element to remove.
* @private
*/
function enqueueRemove(parentID, fromIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.REMOVE_NODE,
markupIndex: null,
content: null,
fromIndex: fromIndex,
toIndex: null
});
}
/**
* Enqueues setting the markup of a node.
*
* @param {string} parentID ID of the parent component.
* @param {string} markup Markup that renders into an element.
* @private
*/
function enqueueSetMarkup(parentID, markup) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.SET_MARKUP,
markupIndex: null,
content: markup,
fromIndex: null,
toIndex: null
});
}
/**
* Enqueues setting the text content.
*
* @param {string} parentID ID of the parent component.
* @param {string} textContent Text content to set.
* @private
*/
function enqueueTextContent(parentID, textContent) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.TEXT_CONTENT,
markupIndex: null,
content: textContent,
fromIndex: null,
toIndex: null
});
}
/**
* Processes any enqueued updates.
*
* @private
*/
function processQueue() {
if (updateQueue.length) {
ReactComponentEnvironment.processChildrenUpdates(updateQueue, markupQueue);
clearQueue();
}
}
/**
* Clears any enqueued updates.
*
* @private
*/
function clearQueue() {
updateQueue.length = 0;
markupQueue.length = 0;
}
/**
* ReactMultiChild are capable of reconciling multiple children.
*
* @class ReactMultiChild
* @internal
*/
var ReactMultiChild = {
/**
* Provides common functionality for components that must reconcile multiple
* children. This is used by `ReactDOMComponent` to mount, update, and
* unmount child components.
*
* @lends {ReactMultiChild.prototype}
*/
Mixin: {
_reconcilerInstantiateChildren: function (nestedChildren, transaction, context) {
if (process.env.NODE_ENV !== 'production') {
if (this._currentElement) {
try {
ReactCurrentOwner.current = this._currentElement._owner;
return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context);
} finally {
ReactCurrentOwner.current = null;
}
}
}
return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context);
},
_reconcilerUpdateChildren: function (prevChildren, nextNestedChildrenElements, transaction, context) {
var nextChildren;
if (process.env.NODE_ENV !== 'production') {
if (this._currentElement) {
try {
ReactCurrentOwner.current = this._currentElement._owner;
nextChildren = flattenChildren(nextNestedChildrenElements);
} finally {
ReactCurrentOwner.current = null;
}
return ReactChildReconciler.updateChildren(prevChildren, nextChildren, transaction, context);
}
}
nextChildren = flattenChildren(nextNestedChildrenElements);
return ReactChildReconciler.updateChildren(prevChildren, nextChildren, transaction, context);
},
/**
* Generates a "mount image" for each of the supplied children. In the case
* of `ReactDOMComponent`, a mount image is a string of markup.
*
* @param {?object} nestedChildren Nested child maps.
* @return {array} An array of mounted representations.
* @internal
*/
mountChildren: function (nestedChildren, transaction, context) {
var children = this._reconcilerInstantiateChildren(nestedChildren, transaction, context);
this._renderedChildren = children;
var mountImages = [];
var index = 0;
for (var name in children) {
if (children.hasOwnProperty(name)) {
var child = children[name];
// Inlined for performance, see `ReactInstanceHandles.createReactID`.
var rootID = this._rootNodeID + name;
var mountImage = ReactReconciler.mountComponent(child, rootID, transaction, context);
child._mountIndex = index++;
mountImages.push(mountImage);
}
}
return mountImages;
},
/**
* Replaces any rendered children with a text content string.
*
* @param {string} nextContent String of content.
* @internal
*/
updateTextContent: function (nextContent) {
updateDepth++;
var errorThrown = true;
try {
var prevChildren = this._renderedChildren;
// Remove any rendered children.
ReactChildReconciler.unmountChildren(prevChildren);
// TODO: The setTextContent operation should be enough
for (var name in prevChildren) {
if (prevChildren.hasOwnProperty(name)) {
this._unmountChild(prevChildren[name]);
}
}
// Set new text content.
this.setTextContent(nextContent);
errorThrown = false;
} finally {
updateDepth--;
if (!updateDepth) {
if (errorThrown) {
clearQueue();
} else {
processQueue();
}
}
}
},
/**
* Replaces any rendered children with a markup string.
*
* @param {string} nextMarkup String of markup.
* @internal
*/
updateMarkup: function (nextMarkup) {
updateDepth++;
var errorThrown = true;
try {
var prevChildren = this._renderedChildren;
// Remove any rendered children.
ReactChildReconciler.unmountChildren(prevChildren);
for (var name in prevChildren) {
if (prevChildren.hasOwnProperty(name)) {
this._unmountChildByName(prevChildren[name], name);
}
}
this.setMarkup(nextMarkup);
errorThrown = false;
} finally {
updateDepth--;
if (!updateDepth) {
if (errorThrown) {
clearQueue();
} else {
processQueue();
}
}
}
},
/**
* Updates the rendered children with new children.
*
* @param {?object} nextNestedChildrenElements Nested child element maps.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
updateChildren: function (nextNestedChildrenElements, transaction, context) {
updateDepth++;
var errorThrown = true;
try {
this._updateChildren(nextNestedChildrenElements, transaction, context);
errorThrown = false;
} finally {
updateDepth--;
if (!updateDepth) {
if (errorThrown) {
clearQueue();
} else {
processQueue();
}
}
}
},
/**
* Improve performance by isolating this hot code path from the try/catch
* block in `updateChildren`.
*
* @param {?object} nextNestedChildrenElements Nested child element maps.
* @param {ReactReconcileTransaction} transaction
* @final
* @protected
*/
_updateChildren: function (nextNestedChildrenElements, transaction, context) {
var prevChildren = this._renderedChildren;
var nextChildren = this._reconcilerUpdateChildren(prevChildren, nextNestedChildrenElements, transaction, context);
this._renderedChildren = nextChildren;
if (!nextChildren && !prevChildren) {
return;
}
var name;
// `nextIndex` will increment for each child in `nextChildren`, but
// `lastIndex` will be the last index visited in `prevChildren`.
var lastIndex = 0;
var nextIndex = 0;
for (name in nextChildren) {
if (!nextChildren.hasOwnProperty(name)) {
continue;
}
var prevChild = prevChildren && prevChildren[name];
var nextChild = nextChildren[name];
if (prevChild === nextChild) {
this.moveChild(prevChild, nextIndex, lastIndex);
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
prevChild._mountIndex = nextIndex;
} else {
if (prevChild) {
// Update `lastIndex` before `_mountIndex` gets unset by unmounting.
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
this._unmountChild(prevChild);
}
// The child must be instantiated before it's mounted.
this._mountChildByNameAtIndex(nextChild, name, nextIndex, transaction, context);
}
nextIndex++;
}
// Remove children that are no longer present.
for (name in prevChildren) {
if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) {
this._unmountChild(prevChildren[name]);
}
}
},
/**
* Unmounts all rendered children. This should be used to clean up children
* when this component is unmounted.
*
* @internal
*/
unmountChildren: function () {
var renderedChildren = this._renderedChildren;
ReactChildReconciler.unmountChildren(renderedChildren);
this._renderedChildren = null;
},
/**
* Moves a child component to the supplied index.
*
* @param {ReactComponent} child Component to move.
* @param {number} toIndex Destination index of the element.
* @param {number} lastIndex Last index visited of the siblings of `child`.
* @protected
*/
moveChild: function (child, toIndex, lastIndex) {
// If the index of `child` is less than `lastIndex`, then it needs to
// be moved. Otherwise, we do not need to move it because a child will be
// inserted or moved before `child`.
if (child._mountIndex < lastIndex) {
enqueueMove(this._rootNodeID, child._mountIndex, toIndex);
}
},
/**
* Creates a child component.
*
* @param {ReactComponent} child Component to create.
* @param {string} mountImage Markup to insert.
* @protected
*/
createChild: function (child, mountImage) {
enqueueInsertMarkup(this._rootNodeID, mountImage, child._mountIndex);
},
/**
* Removes a child component.
*
* @param {ReactComponent} child Child to remove.
* @protected
*/
removeChild: function (child) {
enqueueRemove(this._rootNodeID, child._mountIndex);
},
/**
* Sets this text content string.
*
* @param {string} textContent Text content to set.
* @protected
*/
setTextContent: function (textContent) {
enqueueTextContent(this._rootNodeID, textContent);
},
/**
* Sets this markup string.
*
* @param {string} markup Markup to set.
* @protected
*/
setMarkup: function (markup) {
enqueueSetMarkup(this._rootNodeID, markup);
},
/**
* Mounts a child with the supplied name.
*
* NOTE: This is part of `updateChildren` and is here for readability.
*
* @param {ReactComponent} child Component to mount.
* @param {string} name Name of the child.
* @param {number} index Index at which to insert the child.
* @param {ReactReconcileTransaction} transaction
* @private
*/
_mountChildByNameAtIndex: function (child, name, index, transaction, context) {
// Inlined for performance, see `ReactInstanceHandles.createReactID`.
var rootID = this._rootNodeID + name;
var mountImage = ReactReconciler.mountComponent(child, rootID, transaction, context);
child._mountIndex = index;
this.createChild(child, mountImage);
},
/**
* Unmounts a rendered child.
*
* NOTE: This is part of `updateChildren` and is here for readability.
*
* @param {ReactComponent} child Component to unmount.
* @private
*/
_unmountChild: function (child) {
this.removeChild(child);
child._mountIndex = null;
}
}
};
module.exports = ReactMultiChild;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 115 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactChildReconciler
* @typechecks static-only
*/
'use strict';
var ReactReconciler = __webpack_require__(50);
var instantiateReactComponent = __webpack_require__(62);
var shouldUpdateReactComponent = __webpack_require__(67);
var traverseAllChildren = __webpack_require__(111);
var warning = __webpack_require__(25);
function instantiateChild(childInstances, child, name) {
// We found a component instance.
var keyUnique = childInstances[name] === undefined;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name) : undefined;
}
if (child != null && keyUnique) {
childInstances[name] = instantiateReactComponent(child, null);
}
}
/**
* ReactChildReconciler provides helpers for initializing or updating a set of
* children. Its output is suitable for passing it onto ReactMultiChild which
* does diffed reordering and insertion.
*/
var ReactChildReconciler = {
/**
* Generates a "mount image" for each of the supplied children. In the case
* of `ReactDOMComponent`, a mount image is a string of markup.
*
* @param {?object} nestedChildNodes Nested child maps.
* @return {?object} A set of child instances.
* @internal
*/
instantiateChildren: function (nestedChildNodes, transaction, context) {
if (nestedChildNodes == null) {
return null;
}
var childInstances = {};
traverseAllChildren(nestedChildNodes, instantiateChild, childInstances);
return childInstances;
},
/**
* Updates the rendered children and returns a new set of children.
*
* @param {?object} prevChildren Previously initialized set of children.
* @param {?object} nextChildren Flat child element maps.
* @param {ReactReconcileTransaction} transaction
* @param {object} context
* @return {?object} A new set of child instances.
* @internal
*/
updateChildren: function (prevChildren, nextChildren, transaction, context) {
// We currently don't have a way to track moves here but if we use iterators
// instead of for..in we can zip the iterators and check if an item has
// moved.
// TODO: If nothing has changed, return the prevChildren object so that we
// can quickly bailout if nothing has changed.
if (!nextChildren && !prevChildren) {
return null;
}
var name;
for (name in nextChildren) {
if (!nextChildren.hasOwnProperty(name)) {
continue;
}
var prevChild = prevChildren && prevChildren[name];
var prevElement = prevChild && prevChild._currentElement;
var nextElement = nextChildren[name];
if (prevChild != null && shouldUpdateReactComponent(prevElement, nextElement)) {
ReactReconciler.receiveComponent(prevChild, nextElement, transaction, context);
nextChildren[name] = prevChild;
} else {
if (prevChild) {
ReactReconciler.unmountComponent(prevChild, name);
}
// The child must be instantiated before it's mounted.
var nextChildInstance = instantiateReactComponent(nextElement, null);
nextChildren[name] = nextChildInstance;
}
}
// Unmount children that are no longer present.
for (name in prevChildren) {
if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) {
ReactReconciler.unmountComponent(prevChildren[name]);
}
}
return nextChildren;
},
/**
* Unmounts all rendered children. This should be used to clean up children
* when this component is unmounted.
*
* @param {?object} renderedChildren Previously initialized set of children.
* @internal
*/
unmountChildren: function (renderedChildren) {
for (var name in renderedChildren) {
if (renderedChildren.hasOwnProperty(name)) {
var renderedChild = renderedChildren[name];
ReactReconciler.unmountComponent(renderedChild);
}
}
}
};
module.exports = ReactChildReconciler;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 116 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule flattenChildren
*/
'use strict';
var traverseAllChildren = __webpack_require__(111);
var warning = __webpack_require__(25);
/**
* @param {function} traverseContext Context passed through traversal.
* @param {?ReactComponent} child React child component.
* @param {!string} name String name of key path to child.
*/
function flattenSingleChildIntoContext(traverseContext, child, name) {
// We found a component instance.
var result = traverseContext;
var keyUnique = result[name] === undefined;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name) : undefined;
}
if (keyUnique && child != null) {
result[name] = child;
}
}
/**
* Flattens children that are typically specified as `props.children`. Any null
* children will not be included in the resulting object.
* @return {!object} flattened children keyed by name.
*/
function flattenChildren(children) {
if (children == null) {
return children;
}
var result = {};
traverseAllChildren(children, flattenSingleChildIntoContext, result);
return result;
}
module.exports = flattenChildren;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 117 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule shallowEqual
* @typechecks
*
*/
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* Performs equality by iterating through keys on an object and returning false
* when any key has values which are not strictly equal between the arguments.
* Returns true when the values of all keys are strictly equal.
*/
function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
return false;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
// Test for A's keys different from B.
var bHasOwnProperty = hasOwnProperty.bind(objB);
for (var i = 0; i < keysA.length; i++) {
if (!bHasOwnProperty(keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) {
return false;
}
}
return true;
}
module.exports = shallowEqual;
/***/ },
/* 118 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactEventListener
* @typechecks static-only
*/
'use strict';
var EventListener = __webpack_require__(119);
var ExecutionEnvironment = __webpack_require__(9);
var PooledClass = __webpack_require__(56);
var ReactInstanceHandles = __webpack_require__(45);
var ReactMount = __webpack_require__(28);
var ReactUpdates = __webpack_require__(54);
var assign = __webpack_require__(39);
var getEventTarget = __webpack_require__(81);
var getUnboundedScrollPosition = __webpack_require__(120);
var DOCUMENT_FRAGMENT_NODE_TYPE = 11;
/**
* Finds the parent React component of `node`.
*
* @param {*} node
* @return {?DOMEventTarget} Parent container, or `null` if the specified node
* is not nested.
*/
function findParent(node) {
// TODO: It may be a good idea to cache this to prevent unnecessary DOM
// traversal, but caching is difficult to do correctly without using a
// mutation observer to listen for all DOM changes.
var nodeID = ReactMount.getID(node);
var rootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID);
var container = ReactMount.findReactContainerForID(rootID);
var parent = ReactMount.getFirstReactDOM(container);
return parent;
}
// Used to store ancestor hierarchy in top level callback
function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) {
this.topLevelType = topLevelType;
this.nativeEvent = nativeEvent;
this.ancestors = [];
}
assign(TopLevelCallbackBookKeeping.prototype, {
destructor: function () {
this.topLevelType = null;
this.nativeEvent = null;
this.ancestors.length = 0;
}
});
PooledClass.addPoolingTo(TopLevelCallbackBookKeeping, PooledClass.twoArgumentPooler);
function handleTopLevelImpl(bookKeeping) {
// TODO: Re-enable event.path handling
//
// if (bookKeeping.nativeEvent.path && bookKeeping.nativeEvent.path.length > 1) {
// // New browsers have a path attribute on native events
// handleTopLevelWithPath(bookKeeping);
// } else {
// // Legacy browsers don't have a path attribute on native events
// handleTopLevelWithoutPath(bookKeeping);
// }
void handleTopLevelWithPath; // temporarily unused
handleTopLevelWithoutPath(bookKeeping);
}
// Legacy browsers don't have a path attribute on native events
function handleTopLevelWithoutPath(bookKeeping) {
var topLevelTarget = ReactMount.getFirstReactDOM(getEventTarget(bookKeeping.nativeEvent)) || window;
// Loop through the hierarchy, in case there's any nested components.
// It's important that we build the array of ancestors before calling any
// event handlers, because event handlers can modify the DOM, leading to
// inconsistencies with ReactMount's node cache. See #1105.
var ancestor = topLevelTarget;
while (ancestor) {
bookKeeping.ancestors.push(ancestor);
ancestor = findParent(ancestor);
}
for (var i = 0; i < bookKeeping.ancestors.length; i++) {
topLevelTarget = bookKeeping.ancestors[i];
var topLevelTargetID = ReactMount.getID(topLevelTarget) || '';
ReactEventListener._handleTopLevel(bookKeeping.topLevelType, topLevelTarget, topLevelTargetID, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent));
}
}
// New browsers have a path attribute on native events
function handleTopLevelWithPath(bookKeeping) {
var path = bookKeeping.nativeEvent.path;
var currentNativeTarget = path[0];
var eventsFired = 0;
for (var i = 0; i < path.length; i++) {
var currentPathElement = path[i];
if (currentPathElement.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE) {
currentNativeTarget = path[i + 1];
}
// TODO: slow
var reactParent = ReactMount.getFirstReactDOM(currentPathElement);
if (reactParent === currentPathElement) {
var currentPathElementID = ReactMount.getID(currentPathElement);
var newRootID = ReactInstanceHandles.getReactRootIDFromNodeID(currentPathElementID);
bookKeeping.ancestors.push(currentPathElement);
var topLevelTargetID = ReactMount.getID(currentPathElement) || '';
eventsFired++;
ReactEventListener._handleTopLevel(bookKeeping.topLevelType, currentPathElement, topLevelTargetID, bookKeeping.nativeEvent, currentNativeTarget);
// Jump to the root of this React render tree
while (currentPathElementID !== newRootID) {
i++;
currentPathElement = path[i];
currentPathElementID = ReactMount.getID(currentPathElement);
}
}
}
if (eventsFired === 0) {
ReactEventListener._handleTopLevel(bookKeeping.topLevelType, window, '', bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent));
}
}
function scrollValueMonitor(cb) {
var scrollPosition = getUnboundedScrollPosition(window);
cb(scrollPosition);
}
var ReactEventListener = {
_enabled: true,
_handleTopLevel: null,
WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null,
setHandleTopLevel: function (handleTopLevel) {
ReactEventListener._handleTopLevel = handleTopLevel;
},
setEnabled: function (enabled) {
ReactEventListener._enabled = !!enabled;
},
isEnabled: function () {
return ReactEventListener._enabled;
},
/**
* Traps top-level events by using event bubbling.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {string} handlerBaseName Event name (e.g. "click").
* @param {object} handle Element on which to attach listener.
* @return {?object} An object with a remove function which will forcefully
* remove the listener.
* @internal
*/
trapBubbledEvent: function (topLevelType, handlerBaseName, handle) {
var element = handle;
if (!element) {
return null;
}
return EventListener.listen(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType));
},
/**
* Traps a top-level event by using event capturing.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {string} handlerBaseName Event name (e.g. "click").
* @param {object} handle Element on which to attach listener.
* @return {?object} An object with a remove function which will forcefully
* remove the listener.
* @internal
*/
trapCapturedEvent: function (topLevelType, handlerBaseName, handle) {
var element = handle;
if (!element) {
return null;
}
return EventListener.capture(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType));
},
monitorScrollValue: function (refresh) {
var callback = scrollValueMonitor.bind(null, refresh);
EventListener.listen(window, 'scroll', callback);
},
dispatchEvent: function (topLevelType, nativeEvent) {
if (!ReactEventListener._enabled) {
return;
}
var bookKeeping = TopLevelCallbackBookKeeping.getPooled(topLevelType, nativeEvent);
try {
// Event queue being processed in the same cycle allows
// `preventDefault`.
ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping);
} finally {
TopLevelCallbackBookKeeping.release(bookKeeping);
}
}
};
module.exports = ReactEventListener;
/***/ },
/* 119 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, 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.
*
* @providesModule EventListener
* @typechecks
*/
'use strict';
var emptyFunction = __webpack_require__(15);
/**
* Upstream version of event listener. Does not take into account specific
* nature of platform.
*/
var EventListener = {
/**
* Listen to DOM events during the bubble phase.
*
* @param {DOMEventTarget} target DOM element to register listener on.
* @param {string} eventType Event type, e.g. 'click' or 'mouseover'.
* @param {function} callback Callback function.
* @return {object} Object with a `remove` method.
*/
listen: function (target, eventType, callback) {
if (target.addEventListener) {
target.addEventListener(eventType, callback, false);
return {
remove: function () {
target.removeEventListener(eventType, callback, false);
}
};
} else if (target.attachEvent) {
target.attachEvent('on' + eventType, callback);
return {
remove: function () {
target.detachEvent('on' + eventType, callback);
}
};
}
},
/**
* Listen to DOM events during the capture phase.
*
* @param {DOMEventTarget} target DOM element to register listener on.
* @param {string} eventType Event type, e.g. 'click' or 'mouseover'.
* @param {function} callback Callback function.
* @return {object} Object with a `remove` method.
*/
capture: function (target, eventType, callback) {
if (target.addEventListener) {
target.addEventListener(eventType, callback, true);
return {
remove: function () {
target.removeEventListener(eventType, callback, true);
}
};
} else {
if (process.env.NODE_ENV !== 'production') {
console.error('Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.');
}
return {
remove: emptyFunction
};
}
},
registerDefault: function () {}
};
module.exports = EventListener;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 120 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getUnboundedScrollPosition
* @typechecks
*/
'use strict';
/**
* Gets the scroll position of the supplied element or window.
*
* The return values are unbounded, unlike `getScrollPosition`. This means they
* may be negative or exceed the element boundaries (which is possible using
* inertial scrolling).
*
* @param {DOMWindow|DOMElement} scrollable
* @return {object} Map with `x` and `y` keys.
*/
function getUnboundedScrollPosition(scrollable) {
if (scrollable === window) {
return {
x: window.pageXOffset || document.documentElement.scrollLeft,
y: window.pageYOffset || document.documentElement.scrollTop
};
}
return {
x: scrollable.scrollLeft,
y: scrollable.scrollTop
};
}
module.exports = getUnboundedScrollPosition;
/***/ },
/* 121 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactInjection
*/
'use strict';
var DOMProperty = __webpack_require__(23);
var EventPluginHub = __webpack_require__(31);
var ReactComponentEnvironment = __webpack_require__(64);
var ReactClass = __webpack_require__(122);
var ReactEmptyComponent = __webpack_require__(68);
var ReactBrowserEventEmitter = __webpack_require__(29);
var ReactNativeComponent = __webpack_require__(69);
var ReactPerf = __webpack_require__(18);
var ReactRootIndex = __webpack_require__(46);
var ReactUpdates = __webpack_require__(54);
var ReactInjection = {
Component: ReactComponentEnvironment.injection,
Class: ReactClass.injection,
DOMProperty: DOMProperty.injection,
EmptyComponent: ReactEmptyComponent.injection,
EventPluginHub: EventPluginHub.injection,
EventEmitter: ReactBrowserEventEmitter.injection,
NativeComponent: ReactNativeComponent.injection,
Perf: ReactPerf.injection,
RootIndex: ReactRootIndex.injection,
Updates: ReactUpdates.injection
};
module.exports = ReactInjection;
/***/ },
/* 122 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactClass
*/
'use strict';
var ReactComponent = __webpack_require__(123);
var ReactElement = __webpack_require__(42);
var ReactPropTypeLocations = __webpack_require__(65);
var ReactPropTypeLocationNames = __webpack_require__(66);
var ReactNoopUpdateQueue = __webpack_require__(124);
var assign = __webpack_require__(39);
var emptyObject = __webpack_require__(58);
var invariant = __webpack_require__(13);
var keyMirror = __webpack_require__(17);
var keyOf = __webpack_require__(79);
var warning = __webpack_require__(25);
var MIXINS_KEY = keyOf({ mixins: null });
/**
* Policies that describe methods in `ReactClassInterface`.
*/
var SpecPolicy = keyMirror({
/**
* These methods may be defined only once by the class specification or mixin.
*/
DEFINE_ONCE: null,
/**
* These methods may be defined by both the class specification and mixins.
* Subsequent definitions will be chained. These methods must return void.
*/
DEFINE_MANY: null,
/**
* These methods are overriding the base class.
*/
OVERRIDE_BASE: null,
/**
* These methods are similar to DEFINE_MANY, except we assume they return
* objects. We try to merge the keys of the return values of all the mixed in
* functions. If there is a key conflict we throw.
*/
DEFINE_MANY_MERGED: null
});
var injectedMixins = [];
var warnedSetProps = false;
function warnSetProps() {
if (!warnedSetProps) {
warnedSetProps = true;
process.env.NODE_ENV !== 'production' ? warning(false, 'setProps(...) and replaceProps(...) are deprecated. ' + 'Instead, call render again at the top level.') : undefined;
}
}
/**
* Composite components are higher-level components that compose other composite
* or native components.
*
* To create a new type of `ReactClass`, pass a specification of
* your new class to `React.createClass`. The only requirement of your class
* specification is that you implement a `render` method.
*
* var MyComponent = React.createClass({
* render: function() {
* return <div>Hello World</div>;
* }
* });
*
* The class specification supports a specific protocol of methods that have
* special meaning (e.g. `render`). See `ReactClassInterface` for
* more the comprehensive protocol. Any other properties and methods in the
* class specification will be available on the prototype.
*
* @interface ReactClassInterface
* @internal
*/
var ReactClassInterface = {
/**
* An array of Mixin objects to include when defining your component.
*
* @type {array}
* @optional
*/
mixins: SpecPolicy.DEFINE_MANY,
/**
* An object containing properties and methods that should be defined on
* the component's constructor instead of its prototype (static methods).
*
* @type {object}
* @optional
*/
statics: SpecPolicy.DEFINE_MANY,
/**
* Definition of prop types for this component.
*
* @type {object}
* @optional
*/
propTypes: SpecPolicy.DEFINE_MANY,
/**
* Definition of context types for this component.
*
* @type {object}
* @optional
*/
contextTypes: SpecPolicy.DEFINE_MANY,
/**
* Definition of context types this component sets for its children.
*
* @type {object}
* @optional
*/
childContextTypes: SpecPolicy.DEFINE_MANY,
// ==== Definition methods ====
/**
* Invoked when the component is mounted. Values in the mapping will be set on
* `this.props` if that prop is not specified (i.e. using an `in` check).
*
* This method is invoked before `getInitialState` and therefore cannot rely
* on `this.state` or use `this.setState`.
*
* @return {object}
* @optional
*/
getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED,
/**
* Invoked once before the component is mounted. The return value will be used
* as the initial value of `this.state`.
*
* getInitialState: function() {
* return {
* isOn: false,
* fooBaz: new BazFoo()
* }
* }
*
* @return {object}
* @optional
*/
getInitialState: SpecPolicy.DEFINE_MANY_MERGED,
/**
* @return {object}
* @optional
*/
getChildContext: SpecPolicy.DEFINE_MANY_MERGED,
/**
* Uses props from `this.props` and state from `this.state` to render the
* structure of the component.
*
* No guarantees are made about when or how often this method is invoked, so
* it must not have side effects.
*
* render: function() {
* var name = this.props.name;
* return <div>Hello, {name}!</div>;
* }
*
* @return {ReactComponent}
* @nosideeffects
* @required
*/
render: SpecPolicy.DEFINE_ONCE,
// ==== Delegate methods ====
/**
* Invoked when the component is initially created and about to be mounted.
* This may have side effects, but any external subscriptions or data created
* by this method must be cleaned up in `componentWillUnmount`.
*
* @optional
*/
componentWillMount: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component has been mounted and has a DOM representation.
* However, there is no guarantee that the DOM node is in the document.
*
* Use this as an opportunity to operate on the DOM when the component has
* been mounted (initialized and rendered) for the first time.
*
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidMount: SpecPolicy.DEFINE_MANY,
/**
* Invoked before the component receives new props.
*
* Use this as an opportunity to react to a prop transition by updating the
* state using `this.setState`. Current props are accessed via `this.props`.
*
* componentWillReceiveProps: function(nextProps, nextContext) {
* this.setState({
* likesIncreasing: nextProps.likeCount > this.props.likeCount
* });
* }
*
* NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop
* transition may cause a state change, but the opposite is not true. If you
* need it, you are probably looking for `componentWillUpdate`.
*
* @param {object} nextProps
* @optional
*/
componentWillReceiveProps: SpecPolicy.DEFINE_MANY,
/**
* Invoked while deciding if the component should be updated as a result of
* receiving new props, state and/or context.
*
* Use this as an opportunity to `return false` when you're certain that the
* transition to the new props/state/context will not require a component
* update.
*
* shouldComponentUpdate: function(nextProps, nextState, nextContext) {
* return !equal(nextProps, this.props) ||
* !equal(nextState, this.state) ||
* !equal(nextContext, this.context);
* }
*
* @param {object} nextProps
* @param {?object} nextState
* @param {?object} nextContext
* @return {boolean} True if the component should update.
* @optional
*/
shouldComponentUpdate: SpecPolicy.DEFINE_ONCE,
/**
* Invoked when the component is about to update due to a transition from
* `this.props`, `this.state` and `this.context` to `nextProps`, `nextState`
* and `nextContext`.
*
* Use this as an opportunity to perform preparation before an update occurs.
*
* NOTE: You **cannot** use `this.setState()` in this method.
*
* @param {object} nextProps
* @param {?object} nextState
* @param {?object} nextContext
* @param {ReactReconcileTransaction} transaction
* @optional
*/
componentWillUpdate: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component's DOM representation has been updated.
*
* Use this as an opportunity to operate on the DOM when the component has
* been updated.
*
* @param {object} prevProps
* @param {?object} prevState
* @param {?object} prevContext
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidUpdate: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component is about to be removed from its parent and have
* its DOM representation destroyed.
*
* Use this as an opportunity to deallocate any external resources.
*
* NOTE: There is no `componentDidUnmount` since your component will have been
* destroyed by that point.
*
* @optional
*/
componentWillUnmount: SpecPolicy.DEFINE_MANY,
// ==== Advanced methods ====
/**
* Updates the component's currently mounted DOM representation.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @internal
* @overridable
*/
updateComponent: SpecPolicy.OVERRIDE_BASE
};
/**
* Mapping from class specification keys to special processing functions.
*
* Although these are declared like instance properties in the specification
* when defining classes using `React.createClass`, they are actually static
* and are accessible on the constructor instead of the prototype. Despite
* being static, they must be defined outside of the "statics" key under
* which all other static methods are defined.
*/
var RESERVED_SPEC_KEYS = {
displayName: function (Constructor, displayName) {
Constructor.displayName = displayName;
},
mixins: function (Constructor, mixins) {
if (mixins) {
for (var i = 0; i < mixins.length; i++) {
mixSpecIntoComponent(Constructor, mixins[i]);
}
}
},
childContextTypes: function (Constructor, childContextTypes) {
if (process.env.NODE_ENV !== 'production') {
validateTypeDef(Constructor, childContextTypes, ReactPropTypeLocations.childContext);
}
Constructor.childContextTypes = assign({}, Constructor.childContextTypes, childContextTypes);
},
contextTypes: function (Constructor, contextTypes) {
if (process.env.NODE_ENV !== 'production') {
validateTypeDef(Constructor, contextTypes, ReactPropTypeLocations.context);
}
Constructor.contextTypes = assign({}, Constructor.contextTypes, contextTypes);
},
/**
* Special case getDefaultProps which should move into statics but requires
* automatic merging.
*/
getDefaultProps: function (Constructor, getDefaultProps) {
if (Constructor.getDefaultProps) {
Constructor.getDefaultProps = createMergedResultFunction(Constructor.getDefaultProps, getDefaultProps);
} else {
Constructor.getDefaultProps = getDefaultProps;
}
},
propTypes: function (Constructor, propTypes) {
if (process.env.NODE_ENV !== 'production') {
validateTypeDef(Constructor, propTypes, ReactPropTypeLocations.prop);
}
Constructor.propTypes = assign({}, Constructor.propTypes, propTypes);
},
statics: function (Constructor, statics) {
mixStaticSpecIntoComponent(Constructor, statics);
},
autobind: function () {} };
// noop
function validateTypeDef(Constructor, typeDef, location) {
for (var propName in typeDef) {
if (typeDef.hasOwnProperty(propName)) {
// use a warning instead of an invariant so components
// don't show up in prod but not in __DEV__
process.env.NODE_ENV !== 'production' ? warning(typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName) : undefined;
}
}
}
function validateMethodOverride(proto, name) {
var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null;
// Disallow overriding of base class methods unless explicitly allowed.
if (ReactClassMixin.hasOwnProperty(name)) {
!(specPolicy === SpecPolicy.OVERRIDE_BASE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to override ' + '`%s` from your class specification. Ensure that your method names ' + 'do not overlap with React methods.', name) : invariant(false) : undefined;
}
// Disallow defining methods more than once unless explicitly allowed.
if (proto.hasOwnProperty(name)) {
!(specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name) : invariant(false) : undefined;
}
}
/**
* Mixin helper which handles policy validation and reserved
* specification keys when building React classses.
*/
function mixSpecIntoComponent(Constructor, spec) {
if (!spec) {
return;
}
!(typeof spec !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to ' + 'use a component class as a mixin. Instead, just use a regular object.') : invariant(false) : undefined;
!!ReactElement.isValidElement(spec) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to ' + 'use a component as a mixin. Instead, just use a regular object.') : invariant(false) : undefined;
var proto = Constructor.prototype;
// By handling mixins before any other properties, we ensure the same
// chaining order is applied to methods with DEFINE_MANY policy, whether
// mixins are listed before or after these methods in the spec.
if (spec.hasOwnProperty(MIXINS_KEY)) {
RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins);
}
for (var name in spec) {
if (!spec.hasOwnProperty(name)) {
continue;
}
if (name === MIXINS_KEY) {
// We have already handled mixins in a special case above.
continue;
}
var property = spec[name];
validateMethodOverride(proto, name);
if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) {
RESERVED_SPEC_KEYS[name](Constructor, property);
} else {
// Setup methods on prototype:
// The following member methods should not be automatically bound:
// 1. Expected ReactClass methods (in the "interface").
// 2. Overridden methods (that were mixed in).
var isReactClassMethod = ReactClassInterface.hasOwnProperty(name);
var isAlreadyDefined = proto.hasOwnProperty(name);
var isFunction = typeof property === 'function';
var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false;
if (shouldAutoBind) {
if (!proto.__reactAutoBindMap) {
proto.__reactAutoBindMap = {};
}
proto.__reactAutoBindMap[name] = property;
proto[name] = property;
} else {
if (isAlreadyDefined) {
var specPolicy = ReactClassInterface[name];
// These cases should already be caught by validateMethodOverride.
!(isReactClassMethod && (specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name) : invariant(false) : undefined;
// For methods which are defined more than once, call the existing
// methods before calling the new property, merging if appropriate.
if (specPolicy === SpecPolicy.DEFINE_MANY_MERGED) {
proto[name] = createMergedResultFunction(proto[name], property);
} else if (specPolicy === SpecPolicy.DEFINE_MANY) {
proto[name] = createChainedFunction(proto[name], property);
}
} else {
proto[name] = property;
if (process.env.NODE_ENV !== 'production') {
// Add verbose displayName to the function, which helps when looking
// at profiling tools.
if (typeof property === 'function' && spec.displayName) {
proto[name].displayName = spec.displayName + '_' + name;
}
}
}
}
}
}
}
function mixStaticSpecIntoComponent(Constructor, statics) {
if (!statics) {
return;
}
for (var name in statics) {
var property = statics[name];
if (!statics.hasOwnProperty(name)) {
continue;
}
var isReserved = (name in RESERVED_SPEC_KEYS);
!!isReserved ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You are attempting to define a reserved ' + 'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' + 'as an instance property instead; it will still be accessible on the ' + 'constructor.', name) : invariant(false) : undefined;
var isInherited = (name in Constructor);
!!isInherited ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You are attempting to define ' + '`%s` on your component more than once. This conflict may be ' + 'due to a mixin.', name) : invariant(false) : undefined;
Constructor[name] = property;
}
}
/**
* Merge two objects, but throw if both contain the same key.
*
* @param {object} one The first object, which is mutated.
* @param {object} two The second object
* @return {object} one after it has been mutated to contain everything in two.
*/
function mergeIntoWithNoDuplicateKeys(one, two) {
!(one && two && typeof one === 'object' && typeof two === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.') : invariant(false) : undefined;
for (var key in two) {
if (two.hasOwnProperty(key)) {
!(one[key] === undefined) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: `%s`. This conflict ' + 'may be due to a mixin; in particular, this may be caused by two ' + 'getInitialState() or getDefaultProps() methods returning objects ' + 'with clashing keys.', key) : invariant(false) : undefined;
one[key] = two[key];
}
}
return one;
}
/**
* Creates a function that invokes two functions and merges their return values.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createMergedResultFunction(one, two) {
return function mergedResult() {
var a = one.apply(this, arguments);
var b = two.apply(this, arguments);
if (a == null) {
return b;
} else if (b == null) {
return a;
}
var c = {};
mergeIntoWithNoDuplicateKeys(c, a);
mergeIntoWithNoDuplicateKeys(c, b);
return c;
};
}
/**
* Creates a function that invokes two functions and ignores their return vales.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createChainedFunction(one, two) {
return function chainedFunction() {
one.apply(this, arguments);
two.apply(this, arguments);
};
}
/**
* Binds a method to the component.
*
* @param {object} component Component whose method is going to be bound.
* @param {function} method Method to be bound.
* @return {function} The bound method.
*/
function bindAutoBindMethod(component, method) {
var boundMethod = method.bind(component);
if (process.env.NODE_ENV !== 'production') {
boundMethod.__reactBoundContext = component;
boundMethod.__reactBoundMethod = method;
boundMethod.__reactBoundArguments = null;
var componentName = component.constructor.displayName;
var _bind = boundMethod.bind;
/* eslint-disable block-scoped-var, no-undef */
boundMethod.bind = function (newThis) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
// User is trying to bind() an autobound method; we effectively will
// ignore the value of "this" that the user is trying to use, so
// let's warn.
if (newThis !== component && newThis !== null) {
process.env.NODE_ENV !== 'production' ? warning(false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName) : undefined;
} else if (!args.length) {
process.env.NODE_ENV !== 'production' ? warning(false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName) : undefined;
return boundMethod;
}
var reboundMethod = _bind.apply(boundMethod, arguments);
reboundMethod.__reactBoundContext = component;
reboundMethod.__reactBoundMethod = method;
reboundMethod.__reactBoundArguments = args;
return reboundMethod;
/* eslint-enable */
};
}
return boundMethod;
}
/**
* Binds all auto-bound methods in a component.
*
* @param {object} component Component whose method is going to be bound.
*/
function bindAutoBindMethods(component) {
for (var autoBindKey in component.__reactAutoBindMap) {
if (component.__reactAutoBindMap.hasOwnProperty(autoBindKey)) {
var method = component.__reactAutoBindMap[autoBindKey];
component[autoBindKey] = bindAutoBindMethod(component, method);
}
}
}
/**
* Add more to the ReactClass base class. These are all legacy features and
* therefore not already part of the modern ReactComponent.
*/
var ReactClassMixin = {
/**
* TODO: This will be deprecated because state should always keep a consistent
* type signature and the only use case for this, is to avoid that.
*/
replaceState: function (newState, callback) {
this.updater.enqueueReplaceState(this, newState);
if (callback) {
this.updater.enqueueCallback(this, callback);
}
},
/**
* Checks whether or not this composite component is mounted.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function () {
return this.updater.isMounted(this);
},
/**
* Sets a subset of the props.
*
* @param {object} partialProps Subset of the next props.
* @param {?function} callback Called after props are updated.
* @final
* @public
* @deprecated
*/
setProps: function (partialProps, callback) {
if (process.env.NODE_ENV !== 'production') {
warnSetProps();
}
this.updater.enqueueSetProps(this, partialProps);
if (callback) {
this.updater.enqueueCallback(this, callback);
}
},
/**
* Replace all the props.
*
* @param {object} newProps Subset of the next props.
* @param {?function} callback Called after props are updated.
* @final
* @public
* @deprecated
*/
replaceProps: function (newProps, callback) {
if (process.env.NODE_ENV !== 'production') {
warnSetProps();
}
this.updater.enqueueReplaceProps(this, newProps);
if (callback) {
this.updater.enqueueCallback(this, callback);
}
}
};
var ReactClassComponent = function () {};
assign(ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin);
/**
* Module for creating composite components.
*
* @class ReactClass
*/
var ReactClass = {
/**
* Creates a composite component class given a class specification.
*
* @param {object} spec Class specification (which must define `render`).
* @return {function} Component constructor function.
* @public
*/
createClass: function (spec) {
var Constructor = function (props, context, updater) {
// This constructor is overridden by mocks. The argument is used
// by mocks to assert on what gets mounted.
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory') : undefined;
}
// Wire up auto-binding
if (this.__reactAutoBindMap) {
bindAutoBindMethods(this);
}
this.props = props;
this.context = context;
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
this.state = null;
// ReactClasses doesn't have constructors. Instead, they use the
// getInitialState and componentWillMount methods for initialization.
var initialState = this.getInitialState ? this.getInitialState() : null;
if (process.env.NODE_ENV !== 'production') {
// We allow auto-mocks to proceed as if they're returning null.
if (typeof initialState === 'undefined' && this.getInitialState._isMockFunction) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
initialState = null;
}
}
!(typeof initialState === 'object' && !Array.isArray(initialState)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent') : invariant(false) : undefined;
this.state = initialState;
};
Constructor.prototype = new ReactClassComponent();
Constructor.prototype.constructor = Constructor;
injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor));
mixSpecIntoComponent(Constructor, spec);
// Initialize the defaultProps property after all mixins have been merged.
if (Constructor.getDefaultProps) {
Constructor.defaultProps = Constructor.getDefaultProps();
}
if (process.env.NODE_ENV !== 'production') {
// This is a tag to indicate that the use of these method names is ok,
// since it's used with createClass. If it's not, then it's likely a
// mistake so we'll warn you to use the static property, property
// initializer or constructor respectively.
if (Constructor.getDefaultProps) {
Constructor.getDefaultProps.isReactClassApproved = {};
}
if (Constructor.prototype.getInitialState) {
Constructor.prototype.getInitialState.isReactClassApproved = {};
}
}
!Constructor.prototype.render ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createClass(...): Class specification must implement a `render` method.') : invariant(false) : undefined;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(!Constructor.prototype.componentShouldUpdate, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', spec.displayName || 'A component') : undefined;
process.env.NODE_ENV !== 'production' ? warning(!Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component') : undefined;
}
// Reduce time spent doing lookups by setting these on the prototype.
for (var methodName in ReactClassInterface) {
if (!Constructor.prototype[methodName]) {
Constructor.prototype[methodName] = null;
}
}
return Constructor;
},
injection: {
injectMixin: function (mixin) {
injectedMixins.push(mixin);
}
}
};
module.exports = ReactClass;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 123 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactComponent
*/
'use strict';
var ReactNoopUpdateQueue = __webpack_require__(124);
var canDefineProperty = __webpack_require__(43);
var emptyObject = __webpack_require__(58);
var invariant = __webpack_require__(13);
var warning = __webpack_require__(25);
/**
* Base class helpers for the updating state of a component.
*/
function ReactComponent(props, context, updater) {
this.props = props;
this.context = context;
this.refs = emptyObject;
// We initialize the default updater but the real one gets injected by the
// renderer.
this.updater = updater || ReactNoopUpdateQueue;
}
ReactComponent.prototype.isReactComponent = {};
/**
* Sets a subset of the state. Always use this to mutate
* state. You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* There is no guarantee that calls to `setState` will run synchronously,
* as they may eventually be batched together. You can provide an optional
* callback that will be executed when the call to setState is actually
* completed.
*
* When a function is provided to setState, it will be called at some point in
* the future (not synchronously). It will be called with the up to date
* component arguments (state, props, context). These values can be different
* from this.* because your function may be called after receiveProps but before
* shouldComponentUpdate, and this new state, props, and context will not yet be
* assigned to this.
*
* @param {object|function} partialState Next partial state or function to
* produce next partial state to be merged with current state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
ReactComponent.prototype.setState = function (partialState, callback) {
!(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.') : invariant(false) : undefined;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().') : undefined;
}
this.updater.enqueueSetState(this, partialState);
if (callback) {
this.updater.enqueueCallback(this, callback);
}
};
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {?function} callback Called after update is complete.
* @final
* @protected
*/
ReactComponent.prototype.forceUpdate = function (callback) {
this.updater.enqueueForceUpdate(this);
if (callback) {
this.updater.enqueueCallback(this, callback);
}
};
/**
* Deprecated APIs. These APIs used to exist on classic React classes but since
* we would like to deprecate them, we're not going to move them over to this
* modern base class. Instead, we define a getter that warns if it's accessed.
*/
if (process.env.NODE_ENV !== 'production') {
var deprecatedAPIs = {
getDOMNode: ['getDOMNode', 'Use ReactDOM.findDOMNode(component) instead.'],
isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],
replaceProps: ['replaceProps', 'Instead, call render again at the top level.'],
replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'],
setProps: ['setProps', 'Instead, call render again at the top level.']
};
var defineDeprecationWarning = function (methodName, info) {
if (canDefineProperty) {
Object.defineProperty(ReactComponent.prototype, methodName, {
get: function () {
process.env.NODE_ENV !== 'production' ? warning(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]) : undefined;
return undefined;
}
});
}
};
for (var fnName in deprecatedAPIs) {
if (deprecatedAPIs.hasOwnProperty(fnName)) {
defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
}
}
}
module.exports = ReactComponent;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 124 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactNoopUpdateQueue
*/
'use strict';
var warning = __webpack_require__(25);
function warnTDZ(publicInstance, callerName) {
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, publicInstance.constructor && publicInstance.constructor.displayName || '') : undefined;
}
}
/**
* This is the abstract API for an update queue.
*/
var ReactNoopUpdateQueue = {
/**
* Checks whether or not this composite component is mounted.
* @param {ReactClass} publicInstance The instance we want to test.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function (publicInstance) {
return false;
},
/**
* Enqueue a callback that will be executed after all the pending updates
* have processed.
*
* @param {ReactClass} publicInstance The instance to use as `this` context.
* @param {?function} callback Called after state is updated.
* @internal
*/
enqueueCallback: function (publicInstance, callback) {},
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @internal
*/
enqueueForceUpdate: function (publicInstance) {
warnTDZ(publicInstance, 'forceUpdate');
},
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} completeState Next state.
* @internal
*/
enqueueReplaceState: function (publicInstance, completeState) {
warnTDZ(publicInstance, 'replaceState');
},
/**
* Sets a subset of the state. This only exists because _pendingState is
* internal. This provides a merging strategy that is not available to deep
* properties which is confusing. TODO: Expose pendingState or don't use it
* during the merge.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialState Next partial state to be merged with state.
* @internal
*/
enqueueSetState: function (publicInstance, partialState) {
warnTDZ(publicInstance, 'setState');
},
/**
* Sets a subset of the props.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialProps Subset of the next props.
* @internal
*/
enqueueSetProps: function (publicInstance, partialProps) {
warnTDZ(publicInstance, 'setProps');
},
/**
* Replaces all of the props.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} props New props.
* @internal
*/
enqueueReplaceProps: function (publicInstance, props) {
warnTDZ(publicInstance, 'replaceProps');
}
};
module.exports = ReactNoopUpdateQueue;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 125 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactReconcileTransaction
* @typechecks static-only
*/
'use strict';
var CallbackQueue = __webpack_require__(55);
var PooledClass = __webpack_require__(56);
var ReactBrowserEventEmitter = __webpack_require__(29);
var ReactDOMFeatureFlags = __webpack_require__(41);
var ReactInputSelection = __webpack_require__(126);
var Transaction = __webpack_require__(57);
var assign = __webpack_require__(39);
/**
* Ensures that, when possible, the selection range (currently selected text
* input) is not disturbed by performing the transaction.
*/
var SELECTION_RESTORATION = {
/**
* @return {Selection} Selection information.
*/
initialize: ReactInputSelection.getSelectionInformation,
/**
* @param {Selection} sel Selection information returned from `initialize`.
*/
close: ReactInputSelection.restoreSelection
};
/**
* Suppresses events (blur/focus) that could be inadvertently dispatched due to
* high level DOM manipulations (like temporarily removing a text input from the
* DOM).
*/
var EVENT_SUPPRESSION = {
/**
* @return {boolean} The enabled status of `ReactBrowserEventEmitter` before
* the reconciliation.
*/
initialize: function () {
var currentlyEnabled = ReactBrowserEventEmitter.isEnabled();
ReactBrowserEventEmitter.setEnabled(false);
return currentlyEnabled;
},
/**
* @param {boolean} previouslyEnabled Enabled status of
* `ReactBrowserEventEmitter` before the reconciliation occurred. `close`
* restores the previous value.
*/
close: function (previouslyEnabled) {
ReactBrowserEventEmitter.setEnabled(previouslyEnabled);
}
};
/**
* Provides a queue for collecting `componentDidMount` and
* `componentDidUpdate` callbacks during the the transaction.
*/
var ON_DOM_READY_QUEUEING = {
/**
* Initializes the internal `onDOMReady` queue.
*/
initialize: function () {
this.reactMountReady.reset();
},
/**
* After DOM is flushed, invoke all registered `onDOMReady` callbacks.
*/
close: function () {
this.reactMountReady.notifyAll();
}
};
/**
* Executed within the scope of the `Transaction` instance. Consider these as
* being member methods, but with an implied ordering while being isolated from
* each other.
*/
var TRANSACTION_WRAPPERS = [SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING];
/**
* Currently:
* - The order that these are listed in the transaction is critical:
* - Suppresses events.
* - Restores selection range.
*
* Future:
* - Restore document/overflow scroll positions that were unintentionally
* modified via DOM insertions above the top viewport boundary.
* - Implement/integrate with customized constraint based layout system and keep
* track of which dimensions must be remeasured.
*
* @class ReactReconcileTransaction
*/
function ReactReconcileTransaction(forceHTML) {
this.reinitializeTransaction();
// Only server-side rendering really needs this option (see
// `ReactServerRendering`), but server-side uses
// `ReactServerRenderingTransaction` instead. This option is here so that it's
// accessible and defaults to false when `ReactDOMComponent` and
// `ReactTextComponent` checks it in `mountComponent`.`
this.renderToStaticMarkup = false;
this.reactMountReady = CallbackQueue.getPooled(null);
this.useCreateElement = !forceHTML && ReactDOMFeatureFlags.useCreateElement;
}
var Mixin = {
/**
* @see Transaction
* @abstract
* @final
* @return {array<object>} List of operation wrap procedures.
* TODO: convert to array<TransactionWrapper>
*/
getTransactionWrappers: function () {
return TRANSACTION_WRAPPERS;
},
/**
* @return {object} The queue to collect `onDOMReady` callbacks with.
*/
getReactMountReady: function () {
return this.reactMountReady;
},
/**
* `PooledClass` looks for this, and will invoke this before allowing this
* instance to be reused.
*/
destructor: function () {
CallbackQueue.release(this.reactMountReady);
this.reactMountReady = null;
}
};
assign(ReactReconcileTransaction.prototype, Transaction.Mixin, Mixin);
PooledClass.addPoolingTo(ReactReconcileTransaction);
module.exports = ReactReconcileTransaction;
/***/ },
/* 126 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactInputSelection
*/
'use strict';
var ReactDOMSelection = __webpack_require__(127);
var containsNode = __webpack_require__(59);
var focusNode = __webpack_require__(95);
var getActiveElement = __webpack_require__(129);
function isInDocument(node) {
return containsNode(document.documentElement, node);
}
/**
* @ReactInputSelection: React input selection module. Based on Selection.js,
* but modified to be suitable for react and has a couple of bug fixes (doesn't
* assume buttons have range selections allowed).
* Input selection module for React.
*/
var ReactInputSelection = {
hasSelectionCapabilities: function (elem) {
var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
return nodeName && (nodeName === 'input' && elem.type === 'text' || nodeName === 'textarea' || elem.contentEditable === 'true');
},
getSelectionInformation: function () {
var focusedElem = getActiveElement();
return {
focusedElem: focusedElem,
selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null
};
},
/**
* @restoreSelection: If any selection information was potentially lost,
* restore it. This is useful when performing operations that could remove dom
* nodes and place them back in, resulting in focus being lost.
*/
restoreSelection: function (priorSelectionInformation) {
var curFocusedElem = getActiveElement();
var priorFocusedElem = priorSelectionInformation.focusedElem;
var priorSelectionRange = priorSelectionInformation.selectionRange;
if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) {
ReactInputSelection.setSelection(priorFocusedElem, priorSelectionRange);
}
focusNode(priorFocusedElem);
}
},
/**
* @getSelection: Gets the selection bounds of a focused textarea, input or
* contentEditable node.
* -@input: Look up selection bounds of this input
* -@return {start: selectionStart, end: selectionEnd}
*/
getSelection: function (input) {
var selection;
if ('selectionStart' in input) {
// Modern browser with input or textarea.
selection = {
start: input.selectionStart,
end: input.selectionEnd
};
} else if (document.selection && (input.nodeName && input.nodeName.toLowerCase() === 'input')) {
// IE8 input.
var range = document.selection.createRange();
// There can only be one selection per document in IE, so it must
// be in our element.
if (range.parentElement() === input) {
selection = {
start: -range.moveStart('character', -input.value.length),
end: -range.moveEnd('character', -input.value.length)
};
}
} else {
// Content editable or old IE textarea.
selection = ReactDOMSelection.getOffsets(input);
}
return selection || { start: 0, end: 0 };
},
/**
* @setSelection: Sets the selection bounds of a textarea or input and focuses
* the input.
* -@input Set selection bounds of this input or textarea
* -@offsets Object of same form that is returned from get*
*/
setSelection: function (input, offsets) {
var start = offsets.start;
var end = offsets.end;
if (typeof end === 'undefined') {
end = start;
}
if ('selectionStart' in input) {
input.selectionStart = start;
input.selectionEnd = Math.min(end, input.value.length);
} else if (document.selection && (input.nodeName && input.nodeName.toLowerCase() === 'input')) {
var range = input.createTextRange();
range.collapse(true);
range.moveStart('character', start);
range.moveEnd('character', end - start);
range.select();
} else {
ReactDOMSelection.setOffsets(input, offsets);
}
}
};
module.exports = ReactInputSelection;
/***/ },
/* 127 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMSelection
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(9);
var getNodeForCharacterOffset = __webpack_require__(128);
var getTextContentAccessor = __webpack_require__(75);
/**
* While `isCollapsed` is available on the Selection object and `collapsed`
* is available on the Range object, IE11 sometimes gets them wrong.
* If the anchor/focus nodes and offsets are the same, the range is collapsed.
*/
function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) {
return anchorNode === focusNode && anchorOffset === focusOffset;
}
/**
* Get the appropriate anchor and focus node/offset pairs for IE.
*
* The catch here is that IE's selection API doesn't provide information
* about whether the selection is forward or backward, so we have to
* behave as though it's always forward.
*
* IE text differs from modern selection in that it behaves as though
* block elements end with a new line. This means character offsets will
* differ between the two APIs.
*
* @param {DOMElement} node
* @return {object}
*/
function getIEOffsets(node) {
var selection = document.selection;
var selectedRange = selection.createRange();
var selectedLength = selectedRange.text.length;
// Duplicate selection so we can move range without breaking user selection.
var fromStart = selectedRange.duplicate();
fromStart.moveToElementText(node);
fromStart.setEndPoint('EndToStart', selectedRange);
var startOffset = fromStart.text.length;
var endOffset = startOffset + selectedLength;
return {
start: startOffset,
end: endOffset
};
}
/**
* @param {DOMElement} node
* @return {?object}
*/
function getModernOffsets(node) {
var selection = window.getSelection && window.getSelection();
if (!selection || selection.rangeCount === 0) {
return null;
}
var anchorNode = selection.anchorNode;
var anchorOffset = selection.anchorOffset;
var focusNode = selection.focusNode;
var focusOffset = selection.focusOffset;
var currentRange = selection.getRangeAt(0);
// In Firefox, range.startContainer and range.endContainer can be "anonymous
// divs", e.g. the up/down buttons on an <input type="number">. Anonymous
// divs do not seem to expose properties, triggering a "Permission denied
// error" if any of its properties are accessed. The only seemingly possible
// way to avoid erroring is to access a property that typically works for
// non-anonymous divs and catch any error that may otherwise arise. See
// https://bugzilla.mozilla.org/show_bug.cgi?id=208427
try {
/* eslint-disable no-unused-expressions */
currentRange.startContainer.nodeType;
currentRange.endContainer.nodeType;
/* eslint-enable no-unused-expressions */
} catch (e) {
return null;
}
// If the node and offset values are the same, the selection is collapsed.
// `Selection.isCollapsed` is available natively, but IE sometimes gets
// this value wrong.
var isSelectionCollapsed = isCollapsed(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset);
var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length;
var tempRange = currentRange.cloneRange();
tempRange.selectNodeContents(node);
tempRange.setEnd(currentRange.startContainer, currentRange.startOffset);
var isTempRangeCollapsed = isCollapsed(tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset);
var start = isTempRangeCollapsed ? 0 : tempRange.toString().length;
var end = start + rangeLength;
// Detect whether the selection is backward.
var detectionRange = document.createRange();
detectionRange.setStart(anchorNode, anchorOffset);
detectionRange.setEnd(focusNode, focusOffset);
var isBackward = detectionRange.collapsed;
return {
start: isBackward ? end : start,
end: isBackward ? start : end
};
}
/**
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
function setIEOffsets(node, offsets) {
var range = document.selection.createRange().duplicate();
var start, end;
if (typeof offsets.end === 'undefined') {
start = offsets.start;
end = start;
} else if (offsets.start > offsets.end) {
start = offsets.end;
end = offsets.start;
} else {
start = offsets.start;
end = offsets.end;
}
range.moveToElementText(node);
range.moveStart('character', start);
range.setEndPoint('EndToStart', range);
range.moveEnd('character', end - start);
range.select();
}
/**
* In modern non-IE browsers, we can support both forward and backward
* selections.
*
* Note: IE10+ supports the Selection object, but it does not support
* the `extend` method, which means that even in modern IE, it's not possible
* to programatically create a backward selection. Thus, for all IE
* versions, we use the old IE API to create our selections.
*
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
function setModernOffsets(node, offsets) {
if (!window.getSelection) {
return;
}
var selection = window.getSelection();
var length = node[getTextContentAccessor()].length;
var start = Math.min(offsets.start, length);
var end = typeof offsets.end === 'undefined' ? start : Math.min(offsets.end, length);
// IE 11 uses modern selection, but doesn't support the extend method.
// Flip backward selections, so we can set with a single range.
if (!selection.extend && start > end) {
var temp = end;
end = start;
start = temp;
}
var startMarker = getNodeForCharacterOffset(node, start);
var endMarker = getNodeForCharacterOffset(node, end);
if (startMarker && endMarker) {
var range = document.createRange();
range.setStart(startMarker.node, startMarker.offset);
selection.removeAllRanges();
if (start > end) {
selection.addRange(range);
selection.extend(endMarker.node, endMarker.offset);
} else {
range.setEnd(endMarker.node, endMarker.offset);
selection.addRange(range);
}
}
}
var useIEOffsets = ExecutionEnvironment.canUseDOM && 'selection' in document && !('getSelection' in window);
var ReactDOMSelection = {
/**
* @param {DOMElement} node
*/
getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets,
/**
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets
};
module.exports = ReactDOMSelection;
/***/ },
/* 128 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getNodeForCharacterOffset
*/
'use strict';
/**
* Given any node return the first leaf node without children.
*
* @param {DOMElement|DOMTextNode} node
* @return {DOMElement|DOMTextNode}
*/
function getLeafNode(node) {
while (node && node.firstChild) {
node = node.firstChild;
}
return node;
}
/**
* Get the next sibling within a container. This will walk up the
* DOM if a node's siblings have been exhausted.
*
* @param {DOMElement|DOMTextNode} node
* @return {?DOMElement|DOMTextNode}
*/
function getSiblingNode(node) {
while (node) {
if (node.nextSibling) {
return node.nextSibling;
}
node = node.parentNode;
}
}
/**
* Get object describing the nodes which contain characters at offset.
*
* @param {DOMElement|DOMTextNode} root
* @param {number} offset
* @return {?object}
*/
function getNodeForCharacterOffset(root, offset) {
var node = getLeafNode(root);
var nodeStart = 0;
var nodeEnd = 0;
while (node) {
if (node.nodeType === 3) {
nodeEnd = nodeStart + node.textContent.length;
if (nodeStart <= offset && nodeEnd >= offset) {
return {
node: node,
offset: offset - nodeStart
};
}
nodeStart = nodeEnd;
}
node = getLeafNode(getSiblingNode(node));
}
}
module.exports = getNodeForCharacterOffset;
/***/ },
/* 129 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getActiveElement
* @typechecks
*/
/**
* Same as document.activeElement but wraps in a try-catch block. In IE it is
* not safe to call document.activeElement if there is nothing focused.
*
* The activeElement will be null only if the document body is not yet defined.
*/
"use strict";
function getActiveElement() /*?DOMElement*/{
try {
return document.activeElement || document.body;
} catch (e) {
return document.body;
}
}
module.exports = getActiveElement;
/***/ },
/* 130 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SelectEventPlugin
*/
'use strict';
var EventConstants = __webpack_require__(30);
var EventPropagators = __webpack_require__(73);
var ExecutionEnvironment = __webpack_require__(9);
var ReactInputSelection = __webpack_require__(126);
var SyntheticEvent = __webpack_require__(77);
var getActiveElement = __webpack_require__(129);
var isTextInputElement = __webpack_require__(82);
var keyOf = __webpack_require__(79);
var shallowEqual = __webpack_require__(117);
var topLevelTypes = EventConstants.topLevelTypes;
var skipSelectionChangeEvent = ExecutionEnvironment.canUseDOM && 'documentMode' in document && document.documentMode <= 11;
var eventTypes = {
select: {
phasedRegistrationNames: {
bubbled: keyOf({ onSelect: null }),
captured: keyOf({ onSelectCapture: null })
},
dependencies: [topLevelTypes.topBlur, topLevelTypes.topContextMenu, topLevelTypes.topFocus, topLevelTypes.topKeyDown, topLevelTypes.topMouseDown, topLevelTypes.topMouseUp, topLevelTypes.topSelectionChange]
}
};
var activeElement = null;
var activeElementID = null;
var lastSelection = null;
var mouseDown = false;
// Track whether a listener exists for this plugin. If none exist, we do
// not extract events.
var hasListener = false;
var ON_SELECT_KEY = keyOf({ onSelect: null });
/**
* Get an object which is a unique representation of the current selection.
*
* The return value will not be consistent across nodes or browsers, but
* two identical selections on the same node will return identical objects.
*
* @param {DOMElement} node
* @return {object}
*/
function getSelection(node) {
if ('selectionStart' in node && ReactInputSelection.hasSelectionCapabilities(node)) {
return {
start: node.selectionStart,
end: node.selectionEnd
};
} else if (window.getSelection) {
var selection = window.getSelection();
return {
anchorNode: selection.anchorNode,
anchorOffset: selection.anchorOffset,
focusNode: selection.focusNode,
focusOffset: selection.focusOffset
};
} else if (document.selection) {
var range = document.selection.createRange();
return {
parentElement: range.parentElement(),
text: range.text,
top: range.boundingTop,
left: range.boundingLeft
};
}
}
/**
* Poll selection to see whether it's changed.
*
* @param {object} nativeEvent
* @return {?SyntheticEvent}
*/
function constructSelectEvent(nativeEvent, nativeEventTarget) {
// Ensure we have the right element, and that the user is not dragging a
// selection (this matches native `select` event behavior). In HTML5, select
// fires only on input and textarea thus if there's no focused element we
// won't dispatch.
if (mouseDown || activeElement == null || activeElement !== getActiveElement()) {
return null;
}
// Only fire when selection has actually changed.
var currentSelection = getSelection(activeElement);
if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
lastSelection = currentSelection;
var syntheticEvent = SyntheticEvent.getPooled(eventTypes.select, activeElementID, nativeEvent, nativeEventTarget);
syntheticEvent.type = 'select';
syntheticEvent.target = activeElement;
EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent);
return syntheticEvent;
}
return null;
}
/**
* This plugin creates an `onSelect` event that normalizes select events
* across form elements.
*
* Supported elements are:
* - input (see `isTextInputElement`)
* - textarea
* - contentEditable
*
* This differs from native browser implementations in the following ways:
* - Fires on contentEditable fields as well as inputs.
* - Fires for collapsed selection.
* - Fires after user input.
*/
var SelectEventPlugin = {
eventTypes: eventTypes,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
if (!hasListener) {
return null;
}
switch (topLevelType) {
// Track the input node that has focus.
case topLevelTypes.topFocus:
if (isTextInputElement(topLevelTarget) || topLevelTarget.contentEditable === 'true') {
activeElement = topLevelTarget;
activeElementID = topLevelTargetID;
lastSelection = null;
}
break;
case topLevelTypes.topBlur:
activeElement = null;
activeElementID = null;
lastSelection = null;
break;
// Don't fire the event while the user is dragging. This matches the
// semantics of the native select event.
case topLevelTypes.topMouseDown:
mouseDown = true;
break;
case topLevelTypes.topContextMenu:
case topLevelTypes.topMouseUp:
mouseDown = false;
return constructSelectEvent(nativeEvent, nativeEventTarget);
// Chrome and IE fire non-standard event when selection is changed (and
// sometimes when it hasn't). IE's event fires out of order with respect
// to key and input events on deletion, so we discard it.
//
// Firefox doesn't support selectionchange, so check selection status
// after each key entry. The selection changes after keydown and before
// keyup, but we check on keydown as well in the case of holding down a
// key, when multiple keydown events are fired but only one keyup is.
// This is also our approach for IE handling, for the reason above.
case topLevelTypes.topSelectionChange:
if (skipSelectionChangeEvent) {
break;
}
// falls through
case topLevelTypes.topKeyDown:
case topLevelTypes.topKeyUp:
return constructSelectEvent(nativeEvent, nativeEventTarget);
}
return null;
},
didPutListener: function (id, registrationName, listener) {
if (registrationName === ON_SELECT_KEY) {
hasListener = true;
}
}
};
module.exports = SelectEventPlugin;
/***/ },
/* 131 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ServerReactRootIndex
* @typechecks
*/
'use strict';
/**
* Size of the reactRoot ID space. We generate random numbers for React root
* IDs and if there's a collision the events and DOM update system will
* get confused. In the future we need a way to generate GUIDs but for
* now this will work on a smaller scale.
*/
var GLOBAL_MOUNT_POINT_MAX = Math.pow(2, 53);
var ServerReactRootIndex = {
createReactRootIndex: function () {
return Math.ceil(Math.random() * GLOBAL_MOUNT_POINT_MAX);
}
};
module.exports = ServerReactRootIndex;
/***/ },
/* 132 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SimpleEventPlugin
*/
'use strict';
var EventConstants = __webpack_require__(30);
var EventListener = __webpack_require__(119);
var EventPropagators = __webpack_require__(73);
var ReactMount = __webpack_require__(28);
var SyntheticClipboardEvent = __webpack_require__(133);
var SyntheticEvent = __webpack_require__(77);
var SyntheticFocusEvent = __webpack_require__(134);
var SyntheticKeyboardEvent = __webpack_require__(135);
var SyntheticMouseEvent = __webpack_require__(86);
var SyntheticDragEvent = __webpack_require__(138);
var SyntheticTouchEvent = __webpack_require__(139);
var SyntheticUIEvent = __webpack_require__(87);
var SyntheticWheelEvent = __webpack_require__(140);
var emptyFunction = __webpack_require__(15);
var getEventCharCode = __webpack_require__(136);
var invariant = __webpack_require__(13);
var keyOf = __webpack_require__(79);
var topLevelTypes = EventConstants.topLevelTypes;
var eventTypes = {
abort: {
phasedRegistrationNames: {
bubbled: keyOf({ onAbort: true }),
captured: keyOf({ onAbortCapture: true })
}
},
blur: {
phasedRegistrationNames: {
bubbled: keyOf({ onBlur: true }),
captured: keyOf({ onBlurCapture: true })
}
},
canPlay: {
phasedRegistrationNames: {
bubbled: keyOf({ onCanPlay: true }),
captured: keyOf({ onCanPlayCapture: true })
}
},
canPlayThrough: {
phasedRegistrationNames: {
bubbled: keyOf({ onCanPlayThrough: true }),
captured: keyOf({ onCanPlayThroughCapture: true })
}
},
click: {
phasedRegistrationNames: {
bubbled: keyOf({ onClick: true }),
captured: keyOf({ onClickCapture: true })
}
},
contextMenu: {
phasedRegistrationNames: {
bubbled: keyOf({ onContextMenu: true }),
captured: keyOf({ onContextMenuCapture: true })
}
},
copy: {
phasedRegistrationNames: {
bubbled: keyOf({ onCopy: true }),
captured: keyOf({ onCopyCapture: true })
}
},
cut: {
phasedRegistrationNames: {
bubbled: keyOf({ onCut: true }),
captured: keyOf({ onCutCapture: true })
}
},
doubleClick: {
phasedRegistrationNames: {
bubbled: keyOf({ onDoubleClick: true }),
captured: keyOf({ onDoubleClickCapture: true })
}
},
drag: {
phasedRegistrationNames: {
bubbled: keyOf({ onDrag: true }),
captured: keyOf({ onDragCapture: true })
}
},
dragEnd: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragEnd: true }),
captured: keyOf({ onDragEndCapture: true })
}
},
dragEnter: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragEnter: true }),
captured: keyOf({ onDragEnterCapture: true })
}
},
dragExit: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragExit: true }),
captured: keyOf({ onDragExitCapture: true })
}
},
dragLeave: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragLeave: true }),
captured: keyOf({ onDragLeaveCapture: true })
}
},
dragOver: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragOver: true }),
captured: keyOf({ onDragOverCapture: true })
}
},
dragStart: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragStart: true }),
captured: keyOf({ onDragStartCapture: true })
}
},
drop: {
phasedRegistrationNames: {
bubbled: keyOf({ onDrop: true }),
captured: keyOf({ onDropCapture: true })
}
},
durationChange: {
phasedRegistrationNames: {
bubbled: keyOf({ onDurationChange: true }),
captured: keyOf({ onDurationChangeCapture: true })
}
},
emptied: {
phasedRegistrationNames: {
bubbled: keyOf({ onEmptied: true }),
captured: keyOf({ onEmptiedCapture: true })
}
},
encrypted: {
phasedRegistrationNames: {
bubbled: keyOf({ onEncrypted: true }),
captured: keyOf({ onEncryptedCapture: true })
}
},
ended: {
phasedRegistrationNames: {
bubbled: keyOf({ onEnded: true }),
captured: keyOf({ onEndedCapture: true })
}
},
error: {
phasedRegistrationNames: {
bubbled: keyOf({ onError: true }),
captured: keyOf({ onErrorCapture: true })
}
},
focus: {
phasedRegistrationNames: {
bubbled: keyOf({ onFocus: true }),
captured: keyOf({ onFocusCapture: true })
}
},
input: {
phasedRegistrationNames: {
bubbled: keyOf({ onInput: true }),
captured: keyOf({ onInputCapture: true })
}
},
keyDown: {
phasedRegistrationNames: {
bubbled: keyOf({ onKeyDown: true }),
captured: keyOf({ onKeyDownCapture: true })
}
},
keyPress: {
phasedRegistrationNames: {
bubbled: keyOf({ onKeyPress: true }),
captured: keyOf({ onKeyPressCapture: true })
}
},
keyUp: {
phasedRegistrationNames: {
bubbled: keyOf({ onKeyUp: true }),
captured: keyOf({ onKeyUpCapture: true })
}
},
load: {
phasedRegistrationNames: {
bubbled: keyOf({ onLoad: true }),
captured: keyOf({ onLoadCapture: true })
}
},
loadedData: {
phasedRegistrationNames: {
bubbled: keyOf({ onLoadedData: true }),
captured: keyOf({ onLoadedDataCapture: true })
}
},
loadedMetadata: {
phasedRegistrationNames: {
bubbled: keyOf({ onLoadedMetadata: true }),
captured: keyOf({ onLoadedMetadataCapture: true })
}
},
loadStart: {
phasedRegistrationNames: {
bubbled: keyOf({ onLoadStart: true }),
captured: keyOf({ onLoadStartCapture: true })
}
},
// Note: We do not allow listening to mouseOver events. Instead, use the
// onMouseEnter/onMouseLeave created by `EnterLeaveEventPlugin`.
mouseDown: {
phasedRegistrationNames: {
bubbled: keyOf({ onMouseDown: true }),
captured: keyOf({ onMouseDownCapture: true })
}
},
mouseMove: {
phasedRegistrationNames: {
bubbled: keyOf({ onMouseMove: true }),
captured: keyOf({ onMouseMoveCapture: true })
}
},
mouseOut: {
phasedRegistrationNames: {
bubbled: keyOf({ onMouseOut: true }),
captured: keyOf({ onMouseOutCapture: true })
}
},
mouseOver: {
phasedRegistrationNames: {
bubbled: keyOf({ onMouseOver: true }),
captured: keyOf({ onMouseOverCapture: true })
}
},
mouseUp: {
phasedRegistrationNames: {
bubbled: keyOf({ onMouseUp: true }),
captured: keyOf({ onMouseUpCapture: true })
}
},
paste: {
phasedRegistrationNames: {
bubbled: keyOf({ onPaste: true }),
captured: keyOf({ onPasteCapture: true })
}
},
pause: {
phasedRegistrationNames: {
bubbled: keyOf({ onPause: true }),
captured: keyOf({ onPauseCapture: true })
}
},
play: {
phasedRegistrationNames: {
bubbled: keyOf({ onPlay: true }),
captured: keyOf({ onPlayCapture: true })
}
},
playing: {
phasedRegistrationNames: {
bubbled: keyOf({ onPlaying: true }),
captured: keyOf({ onPlayingCapture: true })
}
},
progress: {
phasedRegistrationNames: {
bubbled: keyOf({ onProgress: true }),
captured: keyOf({ onProgressCapture: true })
}
},
rateChange: {
phasedRegistrationNames: {
bubbled: keyOf({ onRateChange: true }),
captured: keyOf({ onRateChangeCapture: true })
}
},
reset: {
phasedRegistrationNames: {
bubbled: keyOf({ onReset: true }),
captured: keyOf({ onResetCapture: true })
}
},
scroll: {
phasedRegistrationNames: {
bubbled: keyOf({ onScroll: true }),
captured: keyOf({ onScrollCapture: true })
}
},
seeked: {
phasedRegistrationNames: {
bubbled: keyOf({ onSeeked: true }),
captured: keyOf({ onSeekedCapture: true })
}
},
seeking: {
phasedRegistrationNames: {
bubbled: keyOf({ onSeeking: true }),
captured: keyOf({ onSeekingCapture: true })
}
},
stalled: {
phasedRegistrationNames: {
bubbled: keyOf({ onStalled: true }),
captured: keyOf({ onStalledCapture: true })
}
},
submit: {
phasedRegistrationNames: {
bubbled: keyOf({ onSubmit: true }),
captured: keyOf({ onSubmitCapture: true })
}
},
suspend: {
phasedRegistrationNames: {
bubbled: keyOf({ onSuspend: true }),
captured: keyOf({ onSuspendCapture: true })
}
},
timeUpdate: {
phasedRegistrationNames: {<|fim▁hole|> captured: keyOf({ onTimeUpdateCapture: true })
}
},
touchCancel: {
phasedRegistrationNames: {
bubbled: keyOf({ onTouchCancel: true }),
captured: keyOf({ onTouchCancelCapture: true })
}
},
touchEnd: {
phasedRegistrationNames: {
bubbled: keyOf({ onTouchEnd: true }),
captured: keyOf({ onTouchEndCapture: true })
}
},
touchMove: {
phasedRegistrationNames: {
bubbled: keyOf({ onTouchMove: true }),
captured: keyOf({ onTouchMoveCapture: true })
}
},
touchStart: {
phasedRegistrationNames: {
bubbled: keyOf({ onTouchStart: true }),
captured: keyOf({ onTouchStartCapture: true })
}
},
volumeChange: {
phasedRegistrationNames: {
bubbled: keyOf({ onVolumeChange: true }),
captured: keyOf({ onVolumeChangeCapture: true })
}
},
waiting: {
phasedRegistrationNames: {
bubbled: keyOf({ onWaiting: true }),
captured: keyOf({ onWaitingCapture: true })
}
},
wheel: {
phasedRegistrationNames: {
bubbled: keyOf({ onWheel: true }),
captured: keyOf({ onWheelCapture: true })
}
}
};
var topLevelEventsToDispatchConfig = {
topAbort: eventTypes.abort,
topBlur: eventTypes.blur,
topCanPlay: eventTypes.canPlay,
topCanPlayThrough: eventTypes.canPlayThrough,
topClick: eventTypes.click,
topContextMenu: eventTypes.contextMenu,
topCopy: eventTypes.copy,
topCut: eventTypes.cut,
topDoubleClick: eventTypes.doubleClick,
topDrag: eventTypes.drag,
topDragEnd: eventTypes.dragEnd,
topDragEnter: eventTypes.dragEnter,
topDragExit: eventTypes.dragExit,
topDragLeave: eventTypes.dragLeave,
topDragOver: eventTypes.dragOver,
topDragStart: eventTypes.dragStart,
topDrop: eventTypes.drop,
topDurationChange: eventTypes.durationChange,
topEmptied: eventTypes.emptied,
topEncrypted: eventTypes.encrypted,
topEnded: eventTypes.ended,
topError: eventTypes.error,
topFocus: eventTypes.focus,
topInput: eventTypes.input,
topKeyDown: eventTypes.keyDown,
topKeyPress: eventTypes.keyPress,
topKeyUp: eventTypes.keyUp,
topLoad: eventTypes.load,
topLoadedData: eventTypes.loadedData,
topLoadedMetadata: eventTypes.loadedMetadata,
topLoadStart: eventTypes.loadStart,
topMouseDown: eventTypes.mouseDown,
topMouseMove: eventTypes.mouseMove,
topMouseOut: eventTypes.mouseOut,
topMouseOver: eventTypes.mouseOver,
topMouseUp: eventTypes.mouseUp,
topPaste: eventTypes.paste,
topPause: eventTypes.pause,
topPlay: eventTypes.play,
topPlaying: eventTypes.playing,
topProgress: eventTypes.progress,
topRateChange: eventTypes.rateChange,
topReset: eventTypes.reset,
topScroll: eventTypes.scroll,
topSeeked: eventTypes.seeked,
topSeeking: eventTypes.seeking,
topStalled: eventTypes.stalled,
topSubmit: eventTypes.submit,
topSuspend: eventTypes.suspend,
topTimeUpdate: eventTypes.timeUpdate,
topTouchCancel: eventTypes.touchCancel,
topTouchEnd: eventTypes.touchEnd,
topTouchMove: eventTypes.touchMove,
topTouchStart: eventTypes.touchStart,
topVolumeChange: eventTypes.volumeChange,
topWaiting: eventTypes.waiting,
topWheel: eventTypes.wheel
};
for (var type in topLevelEventsToDispatchConfig) {
topLevelEventsToDispatchConfig[type].dependencies = [type];
}
var ON_CLICK_KEY = keyOf({ onClick: null });
var onClickListeners = {};
var SimpleEventPlugin = {
eventTypes: eventTypes,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType];
if (!dispatchConfig) {
return null;
}
var EventConstructor;
switch (topLevelType) {
case topLevelTypes.topAbort:
case topLevelTypes.topCanPlay:
case topLevelTypes.topCanPlayThrough:
case topLevelTypes.topDurationChange:
case topLevelTypes.topEmptied:
case topLevelTypes.topEncrypted:
case topLevelTypes.topEnded:
case topLevelTypes.topError:
case topLevelTypes.topInput:
case topLevelTypes.topLoad:
case topLevelTypes.topLoadedData:
case topLevelTypes.topLoadedMetadata:
case topLevelTypes.topLoadStart:
case topLevelTypes.topPause:
case topLevelTypes.topPlay:
case topLevelTypes.topPlaying:
case topLevelTypes.topProgress:
case topLevelTypes.topRateChange:
case topLevelTypes.topReset:
case topLevelTypes.topSeeked:
case topLevelTypes.topSeeking:
case topLevelTypes.topStalled:
case topLevelTypes.topSubmit:
case topLevelTypes.topSuspend:
case topLevelTypes.topTimeUpdate:
case topLevelTypes.topVolumeChange:
case topLevelTypes.topWaiting:
// HTML Events
// @see http://www.w3.org/TR/html5/index.html#events-0
EventConstructor = SyntheticEvent;
break;
case topLevelTypes.topKeyPress:
// FireFox creates a keypress event for function keys too. This removes
// the unwanted keypress events. Enter is however both printable and
// non-printable. One would expect Tab to be as well (but it isn't).
if (getEventCharCode(nativeEvent) === 0) {
return null;
}
/* falls through */
case topLevelTypes.topKeyDown:
case topLevelTypes.topKeyUp:
EventConstructor = SyntheticKeyboardEvent;
break;
case topLevelTypes.topBlur:
case topLevelTypes.topFocus:
EventConstructor = SyntheticFocusEvent;
break;
case topLevelTypes.topClick:
// Firefox creates a click event on right mouse clicks. This removes the
// unwanted click events.
if (nativeEvent.button === 2) {
return null;
}
/* falls through */
case topLevelTypes.topContextMenu:
case topLevelTypes.topDoubleClick:
case topLevelTypes.topMouseDown:
case topLevelTypes.topMouseMove:
case topLevelTypes.topMouseOut:
case topLevelTypes.topMouseOver:
case topLevelTypes.topMouseUp:
EventConstructor = SyntheticMouseEvent;
break;
case topLevelTypes.topDrag:
case topLevelTypes.topDragEnd:
case topLevelTypes.topDragEnter:
case topLevelTypes.topDragExit:
case topLevelTypes.topDragLeave:
case topLevelTypes.topDragOver:
case topLevelTypes.topDragStart:
case topLevelTypes.topDrop:
EventConstructor = SyntheticDragEvent;
break;
case topLevelTypes.topTouchCancel:
case topLevelTypes.topTouchEnd:
case topLevelTypes.topTouchMove:
case topLevelTypes.topTouchStart:
EventConstructor = SyntheticTouchEvent;
break;
case topLevelTypes.topScroll:
EventConstructor = SyntheticUIEvent;
break;
case topLevelTypes.topWheel:
EventConstructor = SyntheticWheelEvent;
break;
case topLevelTypes.topCopy:
case topLevelTypes.topCut:
case topLevelTypes.topPaste:
EventConstructor = SyntheticClipboardEvent;
break;
}
!EventConstructor ? process.env.NODE_ENV !== 'production' ? invariant(false, 'SimpleEventPlugin: Unhandled event type, `%s`.', topLevelType) : invariant(false) : undefined;
var event = EventConstructor.getPooled(dispatchConfig, topLevelTargetID, nativeEvent, nativeEventTarget);
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
},
didPutListener: function (id, registrationName, listener) {
// Mobile Safari does not fire properly bubble click events on
// non-interactive elements, which means delegated click listeners do not
// fire. The workaround for this bug involves attaching an empty click
// listener on the target node.
if (registrationName === ON_CLICK_KEY) {
var node = ReactMount.getNode(id);
if (!onClickListeners[id]) {
onClickListeners[id] = EventListener.listen(node, 'click', emptyFunction);
}
}
},
willDeleteListener: function (id, registrationName) {
if (registrationName === ON_CLICK_KEY) {
onClickListeners[id].remove();
delete onClickListeners[id];
}
}
};
module.exports = SimpleEventPlugin;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 133 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticClipboardEvent
* @typechecks static-only
*/
'use strict';
var SyntheticEvent = __webpack_require__(77);
/**
* @interface Event
* @see http://www.w3.org/TR/clipboard-apis/
*/
var ClipboardEventInterface = {
clipboardData: function (event) {
return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface);
module.exports = SyntheticClipboardEvent;
/***/ },
/* 134 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticFocusEvent
* @typechecks static-only
*/
'use strict';
var SyntheticUIEvent = __webpack_require__(87);
/**
* @interface FocusEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var FocusEventInterface = {
relatedTarget: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface);
module.exports = SyntheticFocusEvent;
/***/ },
/* 135 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticKeyboardEvent
* @typechecks static-only
*/
'use strict';
var SyntheticUIEvent = __webpack_require__(87);
var getEventCharCode = __webpack_require__(136);
var getEventKey = __webpack_require__(137);
var getEventModifierState = __webpack_require__(88);
/**
* @interface KeyboardEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var KeyboardEventInterface = {
key: getEventKey,
location: null,
ctrlKey: null,
shiftKey: null,
altKey: null,
metaKey: null,
repeat: null,
locale: null,
getModifierState: getEventModifierState,
// Legacy Interface
charCode: function (event) {
// `charCode` is the result of a KeyPress event and represents the value of
// the actual printable character.
// KeyPress is deprecated, but its replacement is not yet final and not
// implemented in any major browser. Only KeyPress has charCode.
if (event.type === 'keypress') {
return getEventCharCode(event);
}
return 0;
},
keyCode: function (event) {
// `keyCode` is the result of a KeyDown/Up event and represents the value of
// physical keyboard key.
// The actual meaning of the value depends on the users' keyboard layout
// which cannot be detected. Assuming that it is a US keyboard layout
// provides a surprisingly accurate mapping for US and European users.
// Due to this, it is left to the user to implement at this time.
if (event.type === 'keydown' || event.type === 'keyup') {
return event.keyCode;
}
return 0;
},
which: function (event) {
// `which` is an alias for either `keyCode` or `charCode` depending on the
// type of the event.
if (event.type === 'keypress') {
return getEventCharCode(event);
}
if (event.type === 'keydown' || event.type === 'keyup') {
return event.keyCode;
}
return 0;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface);
module.exports = SyntheticKeyboardEvent;
/***/ },
/* 136 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getEventCharCode
* @typechecks static-only
*/
'use strict';
/**
* `charCode` represents the actual "character code" and is safe to use with
* `String.fromCharCode`. As such, only keys that correspond to printable
* characters produce a valid `charCode`, the only exception to this is Enter.
* The Tab-key is considered non-printable and does not have a `charCode`,
* presumably because it does not produce a tab-character in browsers.
*
* @param {object} nativeEvent Native browser event.
* @return {number} Normalized `charCode` property.
*/
function getEventCharCode(nativeEvent) {
var charCode;
var keyCode = nativeEvent.keyCode;
if ('charCode' in nativeEvent) {
charCode = nativeEvent.charCode;
// FF does not set `charCode` for the Enter-key, check against `keyCode`.
if (charCode === 0 && keyCode === 13) {
charCode = 13;
}
} else {
// IE8 does not implement `charCode`, but `keyCode` has the correct value.
charCode = keyCode;
}
// Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
// Must not discard the (non-)printable Enter-key.
if (charCode >= 32 || charCode === 13) {
return charCode;
}
return 0;
}
module.exports = getEventCharCode;
/***/ },
/* 137 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getEventKey
* @typechecks static-only
*/
'use strict';
var getEventCharCode = __webpack_require__(136);
/**
* Normalization of deprecated HTML5 `key` values
* @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
*/
var normalizeKey = {
'Esc': 'Escape',
'Spacebar': ' ',
'Left': 'ArrowLeft',
'Up': 'ArrowUp',
'Right': 'ArrowRight',
'Down': 'ArrowDown',
'Del': 'Delete',
'Win': 'OS',
'Menu': 'ContextMenu',
'Apps': 'ContextMenu',
'Scroll': 'ScrollLock',
'MozPrintableKey': 'Unidentified'
};
/**
* Translation from legacy `keyCode` to HTML5 `key`
* Only special keys supported, all others depend on keyboard layout or browser
* @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
*/
var translateToKey = {
8: 'Backspace',
9: 'Tab',
12: 'Clear',
13: 'Enter',
16: 'Shift',
17: 'Control',
18: 'Alt',
19: 'Pause',
20: 'CapsLock',
27: 'Escape',
32: ' ',
33: 'PageUp',
34: 'PageDown',
35: 'End',
36: 'Home',
37: 'ArrowLeft',
38: 'ArrowUp',
39: 'ArrowRight',
40: 'ArrowDown',
45: 'Insert',
46: 'Delete',
112: 'F1', 113: 'F2', 114: 'F3', 115: 'F4', 116: 'F5', 117: 'F6',
118: 'F7', 119: 'F8', 120: 'F9', 121: 'F10', 122: 'F11', 123: 'F12',
144: 'NumLock',
145: 'ScrollLock',
224: 'Meta'
};
/**
* @param {object} nativeEvent Native browser event.
* @return {string} Normalized `key` property.
*/
function getEventKey(nativeEvent) {
if (nativeEvent.key) {
// Normalize inconsistent values reported by browsers due to
// implementations of a working draft specification.
// FireFox implements `key` but returns `MozPrintableKey` for all
// printable characters (normalized to `Unidentified`), ignore it.
var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
if (key !== 'Unidentified') {
return key;
}
}
// Browser does not implement `key`, polyfill as much of it as we can.
if (nativeEvent.type === 'keypress') {
var charCode = getEventCharCode(nativeEvent);
// The enter-key is technically both printable and non-printable and can
// thus be captured by `keypress`, no other non-printable key should.
return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
}
if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
// While user keyboard layout determines the actual meaning of each
// `keyCode` value, almost all function keys have a universal value.
return translateToKey[nativeEvent.keyCode] || 'Unidentified';
}
return '';
}
module.exports = getEventKey;
/***/ },
/* 138 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticDragEvent
* @typechecks static-only
*/
'use strict';
var SyntheticMouseEvent = __webpack_require__(86);
/**
* @interface DragEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var DragEventInterface = {
dataTransfer: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface);
module.exports = SyntheticDragEvent;
/***/ },
/* 139 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticTouchEvent
* @typechecks static-only
*/
'use strict';
var SyntheticUIEvent = __webpack_require__(87);
var getEventModifierState = __webpack_require__(88);
/**
* @interface TouchEvent
* @see http://www.w3.org/TR/touch-events/
*/
var TouchEventInterface = {
touches: null,
targetTouches: null,
changedTouches: null,
altKey: null,
metaKey: null,
ctrlKey: null,
shiftKey: null,
getModifierState: getEventModifierState
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface);
module.exports = SyntheticTouchEvent;
/***/ },
/* 140 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticWheelEvent
* @typechecks static-only
*/
'use strict';
var SyntheticMouseEvent = __webpack_require__(86);
/**
* @interface WheelEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var WheelEventInterface = {
deltaX: function (event) {
return 'deltaX' in event ? event.deltaX :
// Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
},
deltaY: function (event) {
return 'deltaY' in event ? event.deltaY :
// Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
'wheelDeltaY' in event ? -event.wheelDeltaY :
// Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
'wheelDelta' in event ? -event.wheelDelta : 0;
},
deltaZ: null,
// Browsers without "deltaMode" is reporting in raw wheel delta where one
// notch on the scroll is always +/- 120, roughly equivalent to pixels.
// A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
// ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
deltaMode: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticMouseEvent}
*/
function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface);
module.exports = SyntheticWheelEvent;
/***/ },
/* 141 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SVGDOMPropertyConfig
*/
'use strict';
var DOMProperty = __webpack_require__(23);
var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE;
var NS = {
xlink: 'http://www.w3.org/1999/xlink',
xml: 'http://www.w3.org/XML/1998/namespace'
};
var SVGDOMPropertyConfig = {
Properties: {
clipPath: MUST_USE_ATTRIBUTE,
cx: MUST_USE_ATTRIBUTE,
cy: MUST_USE_ATTRIBUTE,
d: MUST_USE_ATTRIBUTE,
dx: MUST_USE_ATTRIBUTE,
dy: MUST_USE_ATTRIBUTE,
fill: MUST_USE_ATTRIBUTE,
fillOpacity: MUST_USE_ATTRIBUTE,
fontFamily: MUST_USE_ATTRIBUTE,
fontSize: MUST_USE_ATTRIBUTE,
fx: MUST_USE_ATTRIBUTE,
fy: MUST_USE_ATTRIBUTE,
gradientTransform: MUST_USE_ATTRIBUTE,
gradientUnits: MUST_USE_ATTRIBUTE,
markerEnd: MUST_USE_ATTRIBUTE,
markerMid: MUST_USE_ATTRIBUTE,
markerStart: MUST_USE_ATTRIBUTE,
offset: MUST_USE_ATTRIBUTE,
opacity: MUST_USE_ATTRIBUTE,
patternContentUnits: MUST_USE_ATTRIBUTE,
patternUnits: MUST_USE_ATTRIBUTE,
points: MUST_USE_ATTRIBUTE,
preserveAspectRatio: MUST_USE_ATTRIBUTE,
r: MUST_USE_ATTRIBUTE,
rx: MUST_USE_ATTRIBUTE,
ry: MUST_USE_ATTRIBUTE,
spreadMethod: MUST_USE_ATTRIBUTE,
stopColor: MUST_USE_ATTRIBUTE,
stopOpacity: MUST_USE_ATTRIBUTE,
stroke: MUST_USE_ATTRIBUTE,
strokeDasharray: MUST_USE_ATTRIBUTE,
strokeLinecap: MUST_USE_ATTRIBUTE,
strokeOpacity: MUST_USE_ATTRIBUTE,
strokeWidth: MUST_USE_ATTRIBUTE,
textAnchor: MUST_USE_ATTRIBUTE,
transform: MUST_USE_ATTRIBUTE,
version: MUST_USE_ATTRIBUTE,
viewBox: MUST_USE_ATTRIBUTE,
x1: MUST_USE_ATTRIBUTE,
x2: MUST_USE_ATTRIBUTE,
x: MUST_USE_ATTRIBUTE,
xlinkActuate: MUST_USE_ATTRIBUTE,
xlinkArcrole: MUST_USE_ATTRIBUTE,
xlinkHref: MUST_USE_ATTRIBUTE,
xlinkRole: MUST_USE_ATTRIBUTE,
xlinkShow: MUST_USE_ATTRIBUTE,
xlinkTitle: MUST_USE_ATTRIBUTE,
xlinkType: MUST_USE_ATTRIBUTE,
xmlBase: MUST_USE_ATTRIBUTE,
xmlLang: MUST_USE_ATTRIBUTE,
xmlSpace: MUST_USE_ATTRIBUTE,
y1: MUST_USE_ATTRIBUTE,
y2: MUST_USE_ATTRIBUTE,
y: MUST_USE_ATTRIBUTE
},
DOMAttributeNamespaces: {
xlinkActuate: NS.xlink,
xlinkArcrole: NS.xlink,
xlinkHref: NS.xlink,
xlinkRole: NS.xlink,
xlinkShow: NS.xlink,
xlinkTitle: NS.xlink,
xlinkType: NS.xlink,
xmlBase: NS.xml,
xmlLang: NS.xml,
xmlSpace: NS.xml
},
DOMAttributeNames: {
clipPath: 'clip-path',
fillOpacity: 'fill-opacity',
fontFamily: 'font-family',
fontSize: 'font-size',
gradientTransform: 'gradientTransform',
gradientUnits: 'gradientUnits',
markerEnd: 'marker-end',
markerMid: 'marker-mid',
markerStart: 'marker-start',
patternContentUnits: 'patternContentUnits',
patternUnits: 'patternUnits',
preserveAspectRatio: 'preserveAspectRatio',
spreadMethod: 'spreadMethod',
stopColor: 'stop-color',
stopOpacity: 'stop-opacity',
strokeDasharray: 'stroke-dasharray',
strokeLinecap: 'stroke-linecap',
strokeOpacity: 'stroke-opacity',
strokeWidth: 'stroke-width',
textAnchor: 'text-anchor',
viewBox: 'viewBox',
xlinkActuate: 'xlink:actuate',
xlinkArcrole: 'xlink:arcrole',
xlinkHref: 'xlink:href',
xlinkRole: 'xlink:role',
xlinkShow: 'xlink:show',
xlinkTitle: 'xlink:title',
xlinkType: 'xlink:type',
xmlBase: 'xml:base',
xmlLang: 'xml:lang',
xmlSpace: 'xml:space'
}
};
module.exports = SVGDOMPropertyConfig;
/***/ },
/* 142 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDefaultPerf
* @typechecks static-only
*/
'use strict';
var DOMProperty = __webpack_require__(23);
var ReactDefaultPerfAnalysis = __webpack_require__(143);
var ReactMount = __webpack_require__(28);
var ReactPerf = __webpack_require__(18);
var performanceNow = __webpack_require__(144);
function roundFloat(val) {
return Math.floor(val * 100) / 100;
}
function addValue(obj, key, val) {
obj[key] = (obj[key] || 0) + val;
}
var ReactDefaultPerf = {
_allMeasurements: [], // last item in the list is the current one
_mountStack: [0],
_injected: false,
start: function () {
if (!ReactDefaultPerf._injected) {
ReactPerf.injection.injectMeasure(ReactDefaultPerf.measure);
}
ReactDefaultPerf._allMeasurements.length = 0;
ReactPerf.enableMeasure = true;
},
stop: function () {
ReactPerf.enableMeasure = false;
},
getLastMeasurements: function () {
return ReactDefaultPerf._allMeasurements;
},
printExclusive: function (measurements) {
measurements = measurements || ReactDefaultPerf._allMeasurements;
var summary = ReactDefaultPerfAnalysis.getExclusiveSummary(measurements);
console.table(summary.map(function (item) {
return {
'Component class name': item.componentName,
'Total inclusive time (ms)': roundFloat(item.inclusive),
'Exclusive mount time (ms)': roundFloat(item.exclusive),
'Exclusive render time (ms)': roundFloat(item.render),
'Mount time per instance (ms)': roundFloat(item.exclusive / item.count),
'Render time per instance (ms)': roundFloat(item.render / item.count),
'Instances': item.count
};
}));
// TODO: ReactDefaultPerfAnalysis.getTotalTime() does not return the correct
// number.
},
printInclusive: function (measurements) {
measurements = measurements || ReactDefaultPerf._allMeasurements;
var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements);
console.table(summary.map(function (item) {
return {
'Owner > component': item.componentName,
'Inclusive time (ms)': roundFloat(item.time),
'Instances': item.count
};
}));
console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms');
},
getMeasurementsSummaryMap: function (measurements) {
var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements, true);
return summary.map(function (item) {
return {
'Owner > component': item.componentName,
'Wasted time (ms)': item.time,
'Instances': item.count
};
});
},
printWasted: function (measurements) {
measurements = measurements || ReactDefaultPerf._allMeasurements;
console.table(ReactDefaultPerf.getMeasurementsSummaryMap(measurements));
console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms');
},
printDOM: function (measurements) {
measurements = measurements || ReactDefaultPerf._allMeasurements;
var summary = ReactDefaultPerfAnalysis.getDOMSummary(measurements);
console.table(summary.map(function (item) {
var result = {};
result[DOMProperty.ID_ATTRIBUTE_NAME] = item.id;
result.type = item.type;
result.args = JSON.stringify(item.args);
return result;
}));
console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms');
},
_recordWrite: function (id, fnName, totalTime, args) {
// TODO: totalTime isn't that useful since it doesn't count paints/reflows
var writes = ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1].writes;
writes[id] = writes[id] || [];
writes[id].push({
type: fnName,
time: totalTime,
args: args
});
},
measure: function (moduleName, fnName, func) {
return function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var totalTime;
var rv;
var start;
if (fnName === '_renderNewRootComponent' || fnName === 'flushBatchedUpdates') {
// A "measurement" is a set of metrics recorded for each flush. We want
// to group the metrics for a given flush together so we can look at the
// components that rendered and the DOM operations that actually
// happened to determine the amount of "wasted work" performed.
ReactDefaultPerf._allMeasurements.push({
exclusive: {},
inclusive: {},
render: {},
counts: {},
writes: {},
displayNames: {},
totalTime: 0,
created: {}
});
start = performanceNow();
rv = func.apply(this, args);
ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1].totalTime = performanceNow() - start;
return rv;
} else if (fnName === '_mountImageIntoNode' || moduleName === 'ReactBrowserEventEmitter' || moduleName === 'ReactDOMIDOperations' || moduleName === 'CSSPropertyOperations' || moduleName === 'DOMChildrenOperations' || moduleName === 'DOMPropertyOperations') {
start = performanceNow();
rv = func.apply(this, args);
totalTime = performanceNow() - start;
if (fnName === '_mountImageIntoNode') {
var mountID = ReactMount.getID(args[1]);
ReactDefaultPerf._recordWrite(mountID, fnName, totalTime, args[0]);
} else if (fnName === 'dangerouslyProcessChildrenUpdates') {
// special format
args[0].forEach(function (update) {
var writeArgs = {};
if (update.fromIndex !== null) {
writeArgs.fromIndex = update.fromIndex;
}
if (update.toIndex !== null) {
writeArgs.toIndex = update.toIndex;
}
if (update.textContent !== null) {
writeArgs.textContent = update.textContent;
}
if (update.markupIndex !== null) {
writeArgs.markup = args[1][update.markupIndex];
}
ReactDefaultPerf._recordWrite(update.parentID, update.type, totalTime, writeArgs);
});
} else {
// basic format
var id = args[0];
if (typeof id === 'object') {
id = ReactMount.getID(args[0]);
}
ReactDefaultPerf._recordWrite(id, fnName, totalTime, Array.prototype.slice.call(args, 1));
}
return rv;
} else if (moduleName === 'ReactCompositeComponent' && (fnName === 'mountComponent' || fnName === 'updateComponent' || // TODO: receiveComponent()?
fnName === '_renderValidatedComponent')) {
if (this._currentElement.type === ReactMount.TopLevelWrapper) {
return func.apply(this, args);
}
var rootNodeID = fnName === 'mountComponent' ? args[0] : this._rootNodeID;
var isRender = fnName === '_renderValidatedComponent';
var isMount = fnName === 'mountComponent';
var mountStack = ReactDefaultPerf._mountStack;
var entry = ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1];
if (isRender) {
addValue(entry.counts, rootNodeID, 1);
} else if (isMount) {
entry.created[rootNodeID] = true;
mountStack.push(0);
}
start = performanceNow();
rv = func.apply(this, args);
totalTime = performanceNow() - start;
if (isRender) {
addValue(entry.render, rootNodeID, totalTime);
} else if (isMount) {
var subMountTime = mountStack.pop();
mountStack[mountStack.length - 1] += totalTime;
addValue(entry.exclusive, rootNodeID, totalTime - subMountTime);
addValue(entry.inclusive, rootNodeID, totalTime);
} else {
addValue(entry.inclusive, rootNodeID, totalTime);
}
entry.displayNames[rootNodeID] = {
current: this.getName(),
owner: this._currentElement._owner ? this._currentElement._owner.getName() : '<root>'
};
return rv;
} else {
return func.apply(this, args);
}
};
}
};
module.exports = ReactDefaultPerf;
/***/ },
/* 143 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDefaultPerfAnalysis
*/
'use strict';
var assign = __webpack_require__(39);
// Don't try to save users less than 1.2ms (a number I made up)
var DONT_CARE_THRESHOLD = 1.2;
var DOM_OPERATION_TYPES = {
'_mountImageIntoNode': 'set innerHTML',
INSERT_MARKUP: 'set innerHTML',
MOVE_EXISTING: 'move',
REMOVE_NODE: 'remove',
SET_MARKUP: 'set innerHTML',
TEXT_CONTENT: 'set textContent',
'setValueForProperty': 'update attribute',
'setValueForAttribute': 'update attribute',
'deleteValueForProperty': 'remove attribute',
'setValueForStyles': 'update styles',
'replaceNodeWithMarkup': 'replace',
'updateTextContent': 'set textContent'
};
function getTotalTime(measurements) {
// TODO: return number of DOM ops? could be misleading.
// TODO: measure dropped frames after reconcile?
// TODO: log total time of each reconcile and the top-level component
// class that triggered it.
var totalTime = 0;
for (var i = 0; i < measurements.length; i++) {
var measurement = measurements[i];
totalTime += measurement.totalTime;
}
return totalTime;
}
function getDOMSummary(measurements) {
var items = [];
measurements.forEach(function (measurement) {
Object.keys(measurement.writes).forEach(function (id) {
measurement.writes[id].forEach(function (write) {
items.push({
id: id,
type: DOM_OPERATION_TYPES[write.type] || write.type,
args: write.args
});
});
});
});
return items;
}
function getExclusiveSummary(measurements) {
var candidates = {};
var displayName;
for (var i = 0; i < measurements.length; i++) {
var measurement = measurements[i];
var allIDs = assign({}, measurement.exclusive, measurement.inclusive);
for (var id in allIDs) {
displayName = measurement.displayNames[id].current;
candidates[displayName] = candidates[displayName] || {
componentName: displayName,
inclusive: 0,
exclusive: 0,
render: 0,
count: 0
};
if (measurement.render[id]) {
candidates[displayName].render += measurement.render[id];
}
if (measurement.exclusive[id]) {
candidates[displayName].exclusive += measurement.exclusive[id];
}
if (measurement.inclusive[id]) {
candidates[displayName].inclusive += measurement.inclusive[id];
}
if (measurement.counts[id]) {
candidates[displayName].count += measurement.counts[id];
}
}
}
// Now make a sorted array with the results.
var arr = [];
for (displayName in candidates) {
if (candidates[displayName].exclusive >= DONT_CARE_THRESHOLD) {
arr.push(candidates[displayName]);
}
}
arr.sort(function (a, b) {
return b.exclusive - a.exclusive;
});
return arr;
}
function getInclusiveSummary(measurements, onlyClean) {
var candidates = {};
var inclusiveKey;
for (var i = 0; i < measurements.length; i++) {
var measurement = measurements[i];
var allIDs = assign({}, measurement.exclusive, measurement.inclusive);
var cleanComponents;
if (onlyClean) {
cleanComponents = getUnchangedComponents(measurement);
}
for (var id in allIDs) {
if (onlyClean && !cleanComponents[id]) {
continue;
}
var displayName = measurement.displayNames[id];
// Inclusive time is not useful for many components without knowing where
// they are instantiated. So we aggregate inclusive time with both the
// owner and current displayName as the key.
inclusiveKey = displayName.owner + ' > ' + displayName.current;
candidates[inclusiveKey] = candidates[inclusiveKey] || {
componentName: inclusiveKey,
time: 0,
count: 0
};
if (measurement.inclusive[id]) {
candidates[inclusiveKey].time += measurement.inclusive[id];
}
if (measurement.counts[id]) {
candidates[inclusiveKey].count += measurement.counts[id];
}
}
}
// Now make a sorted array with the results.
var arr = [];
for (inclusiveKey in candidates) {
if (candidates[inclusiveKey].time >= DONT_CARE_THRESHOLD) {
arr.push(candidates[inclusiveKey]);
}
}
arr.sort(function (a, b) {
return b.time - a.time;
});
return arr;
}
function getUnchangedComponents(measurement) {
// For a given reconcile, look at which components did not actually
// render anything to the DOM and return a mapping of their ID to
// the amount of time it took to render the entire subtree.
var cleanComponents = {};
var dirtyLeafIDs = Object.keys(measurement.writes);
var allIDs = assign({}, measurement.exclusive, measurement.inclusive);
for (var id in allIDs) {
var isDirty = false;
// For each component that rendered, see if a component that triggered
// a DOM op is in its subtree.
for (var i = 0; i < dirtyLeafIDs.length; i++) {
if (dirtyLeafIDs[i].indexOf(id) === 0) {
isDirty = true;
break;
}
}
// check if component newly created
if (measurement.created[id]) {
isDirty = true;
}
if (!isDirty && measurement.counts[id] > 0) {
cleanComponents[id] = true;
}
}
return cleanComponents;
}
var ReactDefaultPerfAnalysis = {
getExclusiveSummary: getExclusiveSummary,
getInclusiveSummary: getInclusiveSummary,
getDOMSummary: getDOMSummary,
getTotalTime: getTotalTime
};
module.exports = ReactDefaultPerfAnalysis;
/***/ },
/* 144 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule performanceNow
* @typechecks
*/
'use strict';
var performance = __webpack_require__(145);
var performanceNow;
/**
* Detect if we can use `window.performance.now()` and gracefully fallback to
* `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now
* because of Facebook's testing infrastructure.
*/
if (performance.now) {
performanceNow = function () {
return performance.now();
};
} else {
performanceNow = function () {
return Date.now();
};
}
module.exports = performanceNow;
/***/ },
/* 145 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule performance
* @typechecks
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(9);
var performance;
if (ExecutionEnvironment.canUseDOM) {
performance = window.performance || window.msPerformance || window.webkitPerformance;
}
module.exports = performance || {};
/***/ },
/* 146 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactVersion
*/
'use strict';
module.exports = '0.14.5';
/***/ },
/* 147 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule renderSubtreeIntoContainer
*/
'use strict';
var ReactMount = __webpack_require__(28);
module.exports = ReactMount.renderSubtreeIntoContainer;
/***/ },
/* 148 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMServer
*/
'use strict';
var ReactDefaultInjection = __webpack_require__(71);
var ReactServerRendering = __webpack_require__(149);
var ReactVersion = __webpack_require__(146);
ReactDefaultInjection.inject();
var ReactDOMServer = {
renderToString: ReactServerRendering.renderToString,
renderToStaticMarkup: ReactServerRendering.renderToStaticMarkup,
version: ReactVersion
};
module.exports = ReactDOMServer;
/***/ },
/* 149 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks static-only
* @providesModule ReactServerRendering
*/
'use strict';
var ReactDefaultBatchingStrategy = __webpack_require__(92);
var ReactElement = __webpack_require__(42);
var ReactInstanceHandles = __webpack_require__(45);
var ReactMarkupChecksum = __webpack_require__(48);
var ReactServerBatchingStrategy = __webpack_require__(150);
var ReactServerRenderingTransaction = __webpack_require__(151);
var ReactUpdates = __webpack_require__(54);
var emptyObject = __webpack_require__(58);
var instantiateReactComponent = __webpack_require__(62);
var invariant = __webpack_require__(13);
/**
* @param {ReactElement} element
* @return {string} the HTML markup
*/
function renderToString(element) {
!ReactElement.isValidElement(element) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'renderToString(): You must pass a valid ReactElement.') : invariant(false) : undefined;
var transaction;
try {
ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy);
var id = ReactInstanceHandles.createReactRootID();
transaction = ReactServerRenderingTransaction.getPooled(false);
return transaction.perform(function () {
var componentInstance = instantiateReactComponent(element, null);
var markup = componentInstance.mountComponent(id, transaction, emptyObject);
return ReactMarkupChecksum.addChecksumToMarkup(markup);
}, null);
} finally {
ReactServerRenderingTransaction.release(transaction);
// Revert to the DOM batching strategy since these two renderers
// currently share these stateful modules.
ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy);
}
}
/**
* @param {ReactElement} element
* @return {string} the HTML markup, without the extra React ID and checksum
* (for generating static pages)
*/
function renderToStaticMarkup(element) {
!ReactElement.isValidElement(element) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'renderToStaticMarkup(): You must pass a valid ReactElement.') : invariant(false) : undefined;
var transaction;
try {
ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy);
var id = ReactInstanceHandles.createReactRootID();
transaction = ReactServerRenderingTransaction.getPooled(true);
return transaction.perform(function () {
var componentInstance = instantiateReactComponent(element, null);
return componentInstance.mountComponent(id, transaction, emptyObject);
}, null);
} finally {
ReactServerRenderingTransaction.release(transaction);
// Revert to the DOM batching strategy since these two renderers
// currently share these stateful modules.
ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy);
}
}
module.exports = {
renderToString: renderToString,
renderToStaticMarkup: renderToStaticMarkup
};
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 150 */
/***/ function(module, exports) {
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactServerBatchingStrategy
* @typechecks
*/
'use strict';
var ReactServerBatchingStrategy = {
isBatchingUpdates: false,
batchedUpdates: function (callback) {
// Don't do anything here. During the server rendering we don't want to
// schedule any updates. We will simply ignore them.
}
};
module.exports = ReactServerBatchingStrategy;
/***/ },
/* 151 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactServerRenderingTransaction
* @typechecks
*/
'use strict';
var PooledClass = __webpack_require__(56);
var CallbackQueue = __webpack_require__(55);
var Transaction = __webpack_require__(57);
var assign = __webpack_require__(39);
var emptyFunction = __webpack_require__(15);
/**
* Provides a `CallbackQueue` queue for collecting `onDOMReady` callbacks
* during the performing of the transaction.
*/
var ON_DOM_READY_QUEUEING = {
/**
* Initializes the internal `onDOMReady` queue.
*/
initialize: function () {
this.reactMountReady.reset();
},
close: emptyFunction
};
/**
* Executed within the scope of the `Transaction` instance. Consider these as
* being member methods, but with an implied ordering while being isolated from
* each other.
*/
var TRANSACTION_WRAPPERS = [ON_DOM_READY_QUEUEING];
/**
* @class ReactServerRenderingTransaction
* @param {boolean} renderToStaticMarkup
*/
function ReactServerRenderingTransaction(renderToStaticMarkup) {
this.reinitializeTransaction();
this.renderToStaticMarkup = renderToStaticMarkup;
this.reactMountReady = CallbackQueue.getPooled(null);
this.useCreateElement = false;
}
var Mixin = {
/**
* @see Transaction
* @abstract
* @final
* @return {array} Empty list of operation wrap procedures.
*/
getTransactionWrappers: function () {
return TRANSACTION_WRAPPERS;
},
/**
* @return {object} The queue to collect `onDOMReady` callbacks with.
*/
getReactMountReady: function () {
return this.reactMountReady;
},
/**
* `PooledClass` looks for this, and will invoke this before allowing this
* instance to be reused.
*/
destructor: function () {
CallbackQueue.release(this.reactMountReady);
this.reactMountReady = null;
}
};
assign(ReactServerRenderingTransaction.prototype, Transaction.Mixin, Mixin);
PooledClass.addPoolingTo(ReactServerRenderingTransaction);
module.exports = ReactServerRenderingTransaction;
/***/ },
/* 152 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactIsomorphic
*/
'use strict';
var ReactChildren = __webpack_require__(110);
var ReactComponent = __webpack_require__(123);
var ReactClass = __webpack_require__(122);
var ReactDOMFactories = __webpack_require__(153);
var ReactElement = __webpack_require__(42);
var ReactElementValidator = __webpack_require__(154);
var ReactPropTypes = __webpack_require__(107);
var ReactVersion = __webpack_require__(146);
var assign = __webpack_require__(39);
var onlyChild = __webpack_require__(156);
var createElement = ReactElement.createElement;
var createFactory = ReactElement.createFactory;
var cloneElement = ReactElement.cloneElement;
if (process.env.NODE_ENV !== 'production') {
createElement = ReactElementValidator.createElement;
createFactory = ReactElementValidator.createFactory;
cloneElement = ReactElementValidator.cloneElement;
}
var React = {
// Modern
Children: {
map: ReactChildren.map,
forEach: ReactChildren.forEach,
count: ReactChildren.count,
toArray: ReactChildren.toArray,
only: onlyChild
},
Component: ReactComponent,
createElement: createElement,
cloneElement: cloneElement,
isValidElement: ReactElement.isValidElement,
// Classic
PropTypes: ReactPropTypes,
createClass: ReactClass.createClass,
createFactory: createFactory,
createMixin: function (mixin) {
// Currently a noop. Will be used to validate and trace mixins.
return mixin;
},
// This looks DOM specific but these are actually isomorphic helpers
// since they are just generating DOM strings.
DOM: ReactDOMFactories,
version: ReactVersion,
// Hook for JSX spread, don't use this for anything else.
__spread: assign
};
module.exports = React;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 153 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMFactories
* @typechecks static-only
*/
'use strict';
var ReactElement = __webpack_require__(42);
var ReactElementValidator = __webpack_require__(154);
var mapObject = __webpack_require__(155);
/**
* Create a factory that creates HTML tag elements.
*
* @param {string} tag Tag name (e.g. `div`).
* @private
*/
function createDOMFactory(tag) {
if (process.env.NODE_ENV !== 'production') {
return ReactElementValidator.createFactory(tag);
}
return ReactElement.createFactory(tag);
}
/**
* Creates a mapping from supported HTML tags to `ReactDOMComponent` classes.
* This is also accessible via `React.DOM`.
*
* @public
*/
var ReactDOMFactories = mapObject({
a: 'a',
abbr: 'abbr',
address: 'address',
area: 'area',
article: 'article',
aside: 'aside',
audio: 'audio',
b: 'b',
base: 'base',
bdi: 'bdi',
bdo: 'bdo',
big: 'big',
blockquote: 'blockquote',
body: 'body',
br: 'br',
button: 'button',
canvas: 'canvas',
caption: 'caption',
cite: 'cite',
code: 'code',
col: 'col',
colgroup: 'colgroup',
data: 'data',
datalist: 'datalist',
dd: 'dd',
del: 'del',
details: 'details',
dfn: 'dfn',
dialog: 'dialog',
div: 'div',
dl: 'dl',
dt: 'dt',
em: 'em',
embed: 'embed',
fieldset: 'fieldset',
figcaption: 'figcaption',
figure: 'figure',
footer: 'footer',
form: 'form',
h1: 'h1',
h2: 'h2',
h3: 'h3',
h4: 'h4',
h5: 'h5',
h6: 'h6',
head: 'head',
header: 'header',
hgroup: 'hgroup',
hr: 'hr',
html: 'html',
i: 'i',
iframe: 'iframe',
img: 'img',
input: 'input',
ins: 'ins',
kbd: 'kbd',
keygen: 'keygen',
label: 'label',
legend: 'legend',
li: 'li',
link: 'link',
main: 'main',
map: 'map',
mark: 'mark',
menu: 'menu',
menuitem: 'menuitem',
meta: 'meta',
meter: 'meter',
nav: 'nav',
noscript: 'noscript',
object: 'object',
ol: 'ol',
optgroup: 'optgroup',
option: 'option',
output: 'output',
p: 'p',
param: 'param',
picture: 'picture',
pre: 'pre',
progress: 'progress',
q: 'q',
rp: 'rp',
rt: 'rt',
ruby: 'ruby',
s: 's',
samp: 'samp',
script: 'script',
section: 'section',
select: 'select',
small: 'small',
source: 'source',
span: 'span',
strong: 'strong',
style: 'style',
sub: 'sub',
summary: 'summary',
sup: 'sup',
table: 'table',
tbody: 'tbody',
td: 'td',
textarea: 'textarea',
tfoot: 'tfoot',
th: 'th',
thead: 'thead',
time: 'time',
title: 'title',
tr: 'tr',
track: 'track',
u: 'u',
ul: 'ul',
'var': 'var',
video: 'video',
wbr: 'wbr',
// SVG
circle: 'circle',
clipPath: 'clipPath',
defs: 'defs',
ellipse: 'ellipse',
g: 'g',
image: 'image',
line: 'line',
linearGradient: 'linearGradient',
mask: 'mask',
path: 'path',
pattern: 'pattern',
polygon: 'polygon',
polyline: 'polyline',
radialGradient: 'radialGradient',
rect: 'rect',
stop: 'stop',
svg: 'svg',
text: 'text',
tspan: 'tspan'
}, createDOMFactory);
module.exports = ReactDOMFactories;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 154 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactElementValidator
*/
/**
* ReactElementValidator provides a wrapper around a element factory
* which validates the props passed to the element. This is intended to be
* used only in DEV and could be replaced by a static type checker for languages
* that support it.
*/
'use strict';
var ReactElement = __webpack_require__(42);
var ReactPropTypeLocations = __webpack_require__(65);
var ReactPropTypeLocationNames = __webpack_require__(66);
var ReactCurrentOwner = __webpack_require__(5);
var canDefineProperty = __webpack_require__(43);
var getIteratorFn = __webpack_require__(108);
var invariant = __webpack_require__(13);
var warning = __webpack_require__(25);
function getDeclarationErrorAddendum() {
if (ReactCurrentOwner.current) {
var name = ReactCurrentOwner.current.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
/**
* Warn if there's no key explicitly set on dynamic arrays of children or
* object keys are not valid. This allows us to keep track of children between
* updates.
*/
var ownerHasKeyUseWarning = {};
var loggedTypeFailures = {};
/**
* Warn if the element doesn't have an explicit key assigned to it.
* This element is in an array. The array could grow and shrink or be
* reordered. All children that haven't already been validated are required to
* have a "key" property assigned to it.
*
* @internal
* @param {ReactElement} element Element that requires a key.
* @param {*} parentType element's parent's type.
*/
function validateExplicitKey(element, parentType) {
if (!element._store || element._store.validated || element.key != null) {
return;
}
element._store.validated = true;
var addenda = getAddendaForKeyUse('uniqueKey', element, parentType);
if (addenda === null) {
// we already showed the warning
return;
}
process.env.NODE_ENV !== 'production' ? warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s%s', addenda.parentOrOwner || '', addenda.childOwner || '', addenda.url || '') : undefined;
}
/**
* Shared warning and monitoring code for the key warnings.
*
* @internal
* @param {string} messageType A key used for de-duping warnings.
* @param {ReactElement} element Component that requires a key.
* @param {*} parentType element's parent's type.
* @returns {?object} A set of addenda to use in the warning message, or null
* if the warning has already been shown before (and shouldn't be shown again).
*/
function getAddendaForKeyUse(messageType, element, parentType) {
var addendum = getDeclarationErrorAddendum();
if (!addendum) {
var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
if (parentName) {
addendum = ' Check the top-level render call using <' + parentName + '>.';
}
}
var memoizer = ownerHasKeyUseWarning[messageType] || (ownerHasKeyUseWarning[messageType] = {});
if (memoizer[addendum]) {
return null;
}
memoizer[addendum] = true;
var addenda = {
parentOrOwner: addendum,
url: ' See https://fb.me/react-warning-keys for more information.',
childOwner: null
};
// Usually the current owner is the offender, but if it accepts children as a
// property, it may be the creator of the child that's responsible for
// assigning it a key.
if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
// Give the component that originally created this child.
addenda.childOwner = ' It was passed a child from ' + element._owner.getName() + '.';
}
return addenda;
}
/**
* Ensure that every element either is passed in a static location, in an
* array with an explicit keys property defined, or in an object literal
* with valid key property.
*
* @internal
* @param {ReactNode} node Statically passed child of any type.
* @param {*} parentType node's parent's type.
*/
function validateChildKeys(node, parentType) {
if (typeof node !== 'object') {
return;
}
if (Array.isArray(node)) {
for (var i = 0; i < node.length; i++) {
var child = node[i];
if (ReactElement.isValidElement(child)) {
validateExplicitKey(child, parentType);
}
}
} else if (ReactElement.isValidElement(node)) {
// This element was passed in a valid location.
if (node._store) {
node._store.validated = true;
}
} else if (node) {
var iteratorFn = getIteratorFn(node);
// Entry iterators provide implicit keys.
if (iteratorFn) {
if (iteratorFn !== node.entries) {
var iterator = iteratorFn.call(node);
var step;
while (!(step = iterator.next()).done) {
if (ReactElement.isValidElement(step.value)) {
validateExplicitKey(step.value, parentType);
}
}
}
}
}
}
/**
* Assert that the props are valid
*
* @param {string} componentName Name of the component for error messages.
* @param {object} propTypes Map of prop name to a ReactPropType
* @param {object} props
* @param {string} location e.g. "prop", "context", "child context"
* @private
*/
function checkPropTypes(componentName, propTypes, props, location) {
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
!(typeof propTypes[propName] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName) : invariant(false) : undefined;
error = propTypes[propName](props, propName, componentName, location);
} catch (ex) {
error = ex;
}
process.env.NODE_ENV !== 'production' ? warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', ReactPropTypeLocationNames[location], propName, typeof error) : undefined;
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var addendum = getDeclarationErrorAddendum();
process.env.NODE_ENV !== 'production' ? warning(false, 'Failed propType: %s%s', error.message, addendum) : undefined;
}
}
}
}
/**
* Given an element, validate that its props follow the propTypes definition,
* provided by the type.
*
* @param {ReactElement} element
*/
function validatePropTypes(element) {
var componentClass = element.type;
if (typeof componentClass !== 'function') {
return;
}
var name = componentClass.displayName || componentClass.name;
if (componentClass.propTypes) {
checkPropTypes(name, componentClass.propTypes, element.props, ReactPropTypeLocations.prop);
}
if (typeof componentClass.getDefaultProps === 'function') {
process.env.NODE_ENV !== 'production' ? warning(componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : undefined;
}
}
var ReactElementValidator = {
createElement: function (type, props, children) {
var validType = typeof type === 'string' || typeof type === 'function';
// We warn in this case but don't throw. We expect the element creation to
// succeed and there will likely be errors in render.
process.env.NODE_ENV !== 'production' ? warning(validType, 'React.createElement: type should not be null, undefined, boolean, or ' + 'number. It should be a string (for DOM elements) or a ReactClass ' + '(for composite components).%s', getDeclarationErrorAddendum()) : undefined;
var element = ReactElement.createElement.apply(this, arguments);
// The result can be nullish if a mock or a custom function is used.
// TODO: Drop this when these are no longer allowed as the type argument.
if (element == null) {
return element;
}
// Skip key warning if the type isn't valid since our key validation logic
// doesn't expect a non-string/function type and can throw confusing errors.
// We don't want exception behavior to differ between dev and prod.
// (Rendering will throw with a helpful message and as soon as the type is
// fixed, the key warnings will appear.)
if (validType) {
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], type);
}
}
validatePropTypes(element);
return element;
},
createFactory: function (type) {
var validatedFactory = ReactElementValidator.createElement.bind(null, type);
// Legacy hook TODO: Warn if this is accessed
validatedFactory.type = type;
if (process.env.NODE_ENV !== 'production') {
if (canDefineProperty) {
Object.defineProperty(validatedFactory, 'type', {
enumerable: false,
get: function () {
process.env.NODE_ENV !== 'production' ? warning(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.') : undefined;
Object.defineProperty(this, 'type', {
value: type
});
return type;
}
});
}
}
return validatedFactory;
},
cloneElement: function (element, props, children) {
var newElement = ReactElement.cloneElement.apply(this, arguments);
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], newElement.type);
}
validatePropTypes(newElement);
return newElement;
}
};
module.exports = ReactElementValidator;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 155 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule mapObject
*/
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* Executes the provided `callback` once for each enumerable own property in the
* object and constructs a new object from the results. The `callback` is
* invoked with three arguments:
*
* - the property value
* - the property name
* - the object being traversed
*
* Properties that are added after the call to `mapObject` will not be visited
* by `callback`. If the values of existing properties are changed, the value
* passed to `callback` will be the value at the time `mapObject` visits them.
* Properties that are deleted before being visited are not visited.
*
* @grep function objectMap()
* @grep function objMap()
*
* @param {?object} object
* @param {function} callback
* @param {*} context
* @return {?object}
*/
function mapObject(object, callback, context) {
if (!object) {
return null;
}
var result = {};
for (var name in object) {
if (hasOwnProperty.call(object, name)) {
result[name] = callback.call(context, object[name], name, object);
}
}
return result;
}
module.exports = mapObject;
/***/ },
/* 156 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule onlyChild
*/
'use strict';
var ReactElement = __webpack_require__(42);
var invariant = __webpack_require__(13);
/**
* Returns the first child in a collection of children and verifies that there
* is only one child in the collection. The current implementation of this
* function assumes that a single child gets passed without a wrapper, but the
* purpose of this helper function is to abstract away the particular structure
* of children.
*
* @param {?object} children Child collection structure.
* @return {ReactComponent} The first and only `ReactComponent` contained in the
* structure.
*/
function onlyChild(children) {
!ReactElement.isValidElement(children) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'onlyChild must be passed a children with exactly one child.') : invariant(false) : undefined;
return children;
}
module.exports = onlyChild;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 157 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule deprecated
*/
'use strict';
var assign = __webpack_require__(39);
var warning = __webpack_require__(25);
/**
* This will log a single deprecation notice per function and forward the call
* on to the new API.
*
* @param {string} fnName The name of the function
* @param {string} newModule The module that fn will exist in
* @param {string} newPackage The module that fn will exist in
* @param {*} ctx The context this forwarded call should run in
* @param {function} fn The function to forward on to
* @return {function} The function that will warn once and then call fn
*/
function deprecated(fnName, newModule, newPackage, ctx, fn) {
var warned = false;
if (process.env.NODE_ENV !== 'production') {
var newFn = function () {
process.env.NODE_ENV !== 'production' ? warning(warned,
// Require examples in this string must be split to prevent React's
// build tools from mistaking them for real requires.
// Otherwise the build tools will attempt to build a '%s' module.
'React.%s is deprecated. Please use %s.%s from require' + '(\'%s\') ' + 'instead.', fnName, newModule, fnName, newPackage) : undefined;
warned = true;
return fn.apply(ctx, arguments);
};
// We need to make sure all properties of the original fn are copied over.
// In particular, this is needed to support PropTypes
return assign(newFn, fn);
}
return fn;
}
module.exports = deprecated;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ },
/* 158 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
module.exports = __webpack_require__(3);
/***/ }
/******/ ]);<|fim▁end|>
|
bubbled: keyOf({ onTimeUpdate: true }),
|
<|file_name|>structfile.py<|end_file_name|><|fim▁begin|>"""A way to read and write structs to a binary file, with fast access
Licensed under the 3-clause BSD License:
Copyright (c) 2011-2014, Neeraj Kumar (neerajkumar.org)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL NEERAJ KUMAR BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import os, sys, time
import struct
class StructFile(object):
"""A file which contains structs"""
def __init__(self, structfmt, fname):
"""Initializes a structfile using the given structfmt and fname.
The file is opened in the given mode ('rb' as default)."""
self.struct = struct.Struct(structfmt)
self.size = self.struct.size
self.fname = fname
if not os.path.exists(fname):
open(fname, 'wb').close()
self.readptr = open(fname, 'rb')
try:
self.writeptr = open(fname, 'r+b')
except IOError:
self.writeptr = None
def __len__(self):
"""Returns the number of structs in this file"""
f = self.readptr
f.seek(0, os.SEEK_END)
n = f.tell()
return n/self.size
def __iter__(self):
"""Iterates over structs in this file, from the beginning"""
f = open(self.fname, 'rb')
while 1:
try:
yield self.struct.unpack(f.read(self.size))
except EOFError:
break
def __getitem__(self, i):
"""Returns the i'th struct.
Negative indices work as well.
Raised IndexError on invalid index.
"""
l = len(self)
if i < 0:
i += l
if i >= l: raise IndexError
f = self.readptr
f.seek(self.size*i)
return self.struct.unpack(f.read(self.size))
def __setitem__(self, i, val):
"""Sets the i'th struct. The file must already have this many structs.<|fim▁hole|> """
l = len(self)
if i < 0:
i += l
if i >= l: raise IndexError
f = self.writeptr
if not f: raise IOError
f.seek(self.size*i)
f.write(self.struct.pack(*val))
def flush(self):
"""Flushes the file if any changes have been made.
Raises IOError if the file doesn't have write permissions.
"""
if not self.writeptr: raise IOError
self.writeptr.flush()
def append(self, val):
"""Adds the given value to the end of the file.
Raises IOError if the file doesn't have write permissions.
"""
f = self.writeptr
if not f: raise IOError
f.seek(0, os.SEEK_END)
f.write(self.struct.pack(*val))<|fim▁end|>
|
Negative indices work as well.
Raised IndexError on invalid index.
Raises IOError if the file doesn't have write permissions.
|
<|file_name|>ICalendar.java<|end_file_name|><|fim▁begin|>package cgeo.calendar;
<|fim▁hole|>
static final String URI_SCHEME = "add";
static final String URI_HOST = "cgeo.org";
static final String PARAM_SHORT_DESC = "shortDesc"; // cache short description
static final String PARAM_HIDDEN_DATE = "hiddenDate"; // cache hidden date in milliseconds
static final String PARAM_URL = "url"; // cache URL
static final String PARAM_NOTE = "note"; // personal note
static final String PARAM_NAME = "name"; // cache name
static final String PARAM_LOCATION = "location"; // cache location, or empty string
static final String PARAM_COORDS = "coords"; // cache coordinates, or empty string
static final String PARAM_START_TIME_MINUTES = "time"; // time of start
}<|fim▁end|>
|
public interface ICalendar {
static final String CALENDAR_ADDON_URI = "market://details?id=cgeo.calendar";
static final String INTENT = "cgeo.calendar.RESERVE";
|
<|file_name|>types.spec.ts<|end_file_name|><|fim▁begin|>/*!
* Copyright(c) 2018-2021 Vasu Vanka
* MIT Licensed
*/
import {
GET,
PUT,
POST,
PATCH,
DELETE,
HttpMethod,
CREATED,
OK,
BADREQUEST,
INTERNALSERVERERROR,
IAppConfig,
} from "../src/types";
describe("Types", () => {
it("Get", () => {
expect(GET).toEqual("get");<|fim▁hole|> expect(GET).not.toEqual("any");
});
it("PUT", () => {
expect(PUT).toEqual("put");
});
it("PUT not equal to any", () => {
expect(PUT).not.toEqual("any");
});
it("POST", () => {
expect(POST).toEqual("post");
});
it("POST not equal to any", () => {
expect(POST).not.toEqual("any");
});
it("PATCH", () => {
expect(PATCH).toEqual("patch");
});
it("PATCH not equal to any", () => {
expect(PATCH).not.toEqual("any");
});
it("DELETE", () => {
expect(DELETE).toEqual("delete");
});
it("DELETE not equal to any", () => {
expect(DELETE).not.toEqual("any");
});
});
describe("Type HttpMethod", () => {
it("type HttpMethod equal to get", () => {
var value: HttpMethod = "get";
expect(value).toEqual("get");
});
it("type HttpMethod equal to post", () => {
var value: HttpMethod = "post";
expect(value).toEqual("post");
});
it("type HttpMethod equal to put", () => {
var value: HttpMethod = "put";
expect(value).toEqual("put");
});
it("type HttpMethod equal to delete", () => {
var value: HttpMethod = "delete";
expect(value).toEqual("delete");
});
it("type HttpMethod equal to patch", () => {
var value: HttpMethod = "patch";
expect(value).toEqual("patch");
});
it("type HttpMethod equal to copy", () => {
var value: HttpMethod = "copy";
expect(value).toEqual("copy");
});
it("type HttpMethod equal to head", () => {
var value: HttpMethod = "head";
expect(value).toEqual("head");
});
it("type HttpMethod equal to options", () => {
var value: HttpMethod = "options";
expect(value).toEqual("options");
});
it("type HttpMethod not equal to any", () => {
var value: HttpMethod = "post";
expect(value).not.toEqual("any");
});
});
describe("Http status codes", () => {
it("created 201 ok", () => {
expect(CREATED).toEqual(201);
});
it("created not any otherthan 200", () => {
expect(CREATED).not.toEqual(400);
});
it("badrequest 400 ok", () => {
expect(BADREQUEST).toEqual(400);
});
it("badrequest not any otherthan 400", () => {
expect(BADREQUEST).not.toEqual(401);
});
it("success 200 ok", () => {
expect(OK).toEqual(200);
});
it("success not any otherthan 200", () => {
expect(BADREQUEST).not.toEqual(401);
});
it("internal server error 500 ok", () => {
expect(INTERNALSERVERERROR).toEqual(500);
});
it("internal server error not any otherthan 200", () => {
expect(INTERNALSERVERERROR).not.toEqual(401);
});
});
describe("IAppConfig", () => {
var appConfig: IAppConfig = {
appBaseUrl: "/hello",
port: 3000,
version: "v01",
hostname: "testdomain",
db: {
url: "mongodb://localhost:27017/test",
},
cors: {},
bodyParser: {},
clusterMode: false,
};
it("test property types of IAppConfig", () => {
expect(typeof appConfig.appBaseUrl).toBe("string");
expect(typeof appConfig.port).toBe("number");
expect(typeof appConfig.version).toBe("string");
expect(typeof appConfig.hostname).toBe("string");
expect(typeof appConfig.bodyParser).toBe("object");
expect(typeof appConfig.db).toBe("object");
expect(typeof appConfig.clusterMode).toBe("boolean");
});
});<|fim▁end|>
|
});
it("Get not equal to any", () => {
|
<|file_name|>ManifestDataNode.java<|end_file_name|><|fim▁begin|>package org.netbeans.modules.manifestsupport.dataobject;
import org.openide.loaders.DataNode;
import org.openide.nodes.Children;
public class ManifestDataNode extends DataNode {
private static final String IMAGE_ICON_BASE = "SET/PATH/TO/ICON/HERE";
public ManifestDataNode(ManifestDataObject obj) {
super(obj, Children.LEAF);
// setIconBaseWithExtension(IMAGE_ICON_BASE);
}
// /** Creates a property sheet. */
<|fim▁hole|>// protected Sheet createSheet() {
// Sheet s = super.createSheet();
// Sheet.Set ss = s.get(Sheet.PROPERTIES);
// if (ss == null) {
// ss = Sheet.createPropertiesSet();
// s.put(ss);
// }
// // TODO add some relevant properties: ss.put(...)
// return s;
// }
}<|fim▁end|>
| |
<|file_name|>error.go<|end_file_name|><|fim▁begin|>package render
import (
"github.com/gin-gonic/gin"
)
/* ================================================================================
* Render 工具模块<|fim▁hole|> * ================================================================================ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* 输出错误消息
* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
func Error(c *gin.Context, msg string) {
String(c, msg, 400)
}<|fim▁end|>
|
* qq group: 582452342
* email : [email protected]
* author : 美丽的地球啊 - mliu
|
<|file_name|>reconciler_controller_stub.go<|end_file_name|><|fim▁begin|>/*
Copyright 2020 The Knative Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package generators
import (
"io"
<|fim▁hole|>)
// reconcilerControllerStubGenerator produces a file of the stub of the
// controller for a custom impl with injection.
type reconcilerControllerStubGenerator struct {
generator.DefaultGen
outputPackage string
imports namer.ImportTracker
typeToGenerate *types.Type
reconcilerPkg string
informerPackagePath string
reconcilerClass string
hasReconcilerClass bool
}
var _ generator.Generator = (*reconcilerControllerStubGenerator)(nil)
func (g *reconcilerControllerStubGenerator) Filter(c *generator.Context, t *types.Type) bool {
// Only process the type for this generator.
return t == g.typeToGenerate
}
func (g *reconcilerControllerStubGenerator) Namers(c *generator.Context) namer.NameSystems {
return namer.NameSystems{
"raw": namer.NewRawNamer(g.outputPackage, g.imports),
}
}
func (g *reconcilerControllerStubGenerator) Imports(c *generator.Context) (imports []string) {
imports = append(imports, g.imports.ImportLines()...)
return
}
func (g *reconcilerControllerStubGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {
sw := generator.NewSnippetWriter(w, c, "{{", "}}")
klog.V(5).Info("processing type ", t)
m := map[string]interface{}{
"type": t,
"class": g.reconcilerClass,
"hasClass": g.hasReconcilerClass,
"informerGet": c.Universe.Function(types.Name{
Package: g.informerPackagePath,
Name: "Get",
}),
"controllerImpl": c.Universe.Type(types.Name{Package: "knative.dev/pkg/controller", Name: "Impl"}),
"reconcilerNewImpl": c.Universe.Type(types.Name{
Package: g.reconcilerPkg,
Name: "NewImpl",
}),
"loggingFromContext": c.Universe.Function(types.Name{
Package: "knative.dev/pkg/logging",
Name: "FromContext",
}),
"contextContext": c.Universe.Type(types.Name{
Package: "context",
Name: "Context",
}),
"configmapWatcher": c.Universe.Type(types.Name{
Package: "knative.dev/pkg/configmap",
Name: "Watcher",
}),
"classAnnotationKey": c.Universe.Variable(types.Name{
Package: g.reconcilerPkg,
Name: "ClassAnnotationKey",
}),
"annotationFilterFunc": c.Universe.Function(types.Name{
Package: "knative.dev/pkg/reconciler",
Name: "AnnotationFilterFunc",
}),
"filterHandler": c.Universe.Type(types.Name{
Package: "k8s.io/client-go/tools/cache",
Name: "FilteringResourceEventHandler",
}),
}
sw.Do(reconcilerControllerStub, m)
return sw.Error()
}
var reconcilerControllerStub = `
// TODO: PLEASE COPY AND MODIFY THIS FILE AS A STARTING POINT
// NewController creates a Reconciler for {{.type|public}} and returns the result of NewImpl.
func NewController(
ctx {{.contextContext|raw}},
cmw {{.configmapWatcher|raw}},
) *{{.controllerImpl|raw}} {
logger := {{.loggingFromContext|raw}}(ctx)
{{.type|lowercaseSingular}}Informer := {{.informerGet|raw}}(ctx)
{{if .hasClass}}
classValue := "default" // TODO: update this to the appropriate value.
classFilter := {{.annotationFilterFunc|raw}}({{.classAnnotationKey|raw}}, classValue, false /*allowUnset*/)
{{end}}
// TODO: setup additional informers here.
{{if .hasClass}}// TODO: remember to use the classFilter from above to filter appropriately.{{end}}
r := &Reconciler{}
impl := {{.reconcilerNewImpl|raw}}(ctx, r{{if .hasClass}}, classValue{{end}})
logger.Info("Setting up event handlers.")
{{if .hasClass}}
{{.type|lowercaseSingular}}Informer.Informer().AddEventHandler({{.filterHandler|raw}}{
FilterFunc: classFilter,
Handler: controller.HandleAll(impl.Enqueue),
})
{{else}}
{{.type|lowercaseSingular}}Informer.Informer().AddEventHandler(controller.HandleAll(impl.Enqueue))
{{end}}
// TODO: add additional informer event handlers here.
return impl
}
`<|fim▁end|>
|
"k8s.io/gengo/generator"
"k8s.io/gengo/namer"
"k8s.io/gengo/types"
"k8s.io/klog"
|
<|file_name|>configurationResolver.ts<|end_file_name|><|fim▁begin|>/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IStringDictionary } from 'vs/base/common/collections';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
export const IConfigurationResolverService = createDecorator<IConfigurationResolverService>('configurationResolverService');
export interface IConfigurationResolverService {
_serviceBrand: any;
<|fim▁hole|> resolve(folder: IWorkspaceFolder | undefined, value: IStringDictionary<string>): IStringDictionary<string>;
/**
* Recursively resolves all variables in the given config and returns a copy of it with substituted values.
* Command variables are only substituted if a "commandValueMapping" dictionary is given and if it contains an entry for the command.
*/
resolveAny(folder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): any;
/**
* Recursively resolves all variables (including commands and user input) in the given config and returns a copy of it with substituted values.
* If a "variables" dictionary (with names -> command ids) is given, command variables are first mapped through it before being resolved.
*
* @param section For example, 'tasks' or 'debug'. Used for resolving inputs.
* @param variables Aliases for commands.
*/
resolveWithInteractionReplace(folder: IWorkspaceFolder | undefined, config: any, section?: string, variables?: IStringDictionary<string>): Promise<any>;
/**
* Similar to resolveWithInteractionReplace, except without the replace. Returns a map of variables and their resolution.
* Keys in the map will be of the format input:variableName or command:variableName.
*/
resolveWithInteraction(folder: IWorkspaceFolder | undefined, config: any, section?: string, variables?: IStringDictionary<string>): Promise<Map<string, string> | undefined>;
}
export interface PromptStringInputInfo {
id: string;
type: 'promptString';
description: string;
default?: string;
}
export interface PickStringInputInfo {
id: string;
type: 'pickString';
description: string;
options: string[];
default?: string;
}
export interface CommandInputInfo {
id: string;
type: 'command';
command: string;
args?: any;
}
export type ConfiguredInput = PromptStringInputInfo | PickStringInputInfo | CommandInputInfo;<|fim▁end|>
|
resolve(folder: IWorkspaceFolder | undefined, value: string): string;
resolve(folder: IWorkspaceFolder | undefined, value: string[]): string[];
|
<|file_name|>fib.py<|end_file_name|><|fim▁begin|>"""
The Fibonacci Sequence is the series of numbers:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
The next number is found by adding up the two numbers before it.
The 2 is found by adding the two numbers before it (1+1)
Similarly, the 3 is found by adding the two numbers before it (1+2),
And the 5 is (2+3),
and so on!
"""
"""
Using lists to return a list of fib numbers
"""
def fib1(limit=10):
"""
Returns a list of fib numbers
"""
nth_number = limit
if limit <= 1:
answer = [0]
elif limit == 2:
answer = [0,1]
else:
fib_num = [0,1]
while len(fib_num) < nth_number:
fib1 = fib_num[len(fib_num)-2]
fib2 = fib_num[len(fib_num)-1]
fib3 = fib2 + fib1
fib_num.append(fib3)
answer = fib_num
return answer
"""
How to return a specific fib number.
"""
def fib2(nth_num=10):
"""
Returns the nth fib number
"""
# Base cases
fib1 = 0
fib2 = 1
if nth_num <= 1:
answer = fib1
elif nth_num == 2:
answer = fib2
else:
current_fib = 2
while nth_num - current_fib > 0:
fib1, fib2 = fib2, fib1 + fib2
current_fib = current_fib + 1
answer = fib2
return answer
"""
Solve with generators
"""
def fib3(nth_num=10):
"""
A generator that yields fib numbers
"""
# Base case
fib1 = 0
fib2 = 1<|fim▁hole|> if nth_num <= 1:
yield fib1
elif nth_num == 2:
yield fib1
yield fib2
else:
yield fib1
yield fib2
current_fib = 2
while nth_num - current_fib > 0:
fib1, fib2 = fib2, fib1 + fib2
yield fib2
current_fib = current_fib + 1
def fib_list(limit=10):
answer = []
for fib_num in fib3(limit):
answer.append(fib_num)
return answer
def nth_fib_num(nth_num=10):
answer = 0
for fib_num in fib3(nth_num):
answer = fib_num
return answer
if __name__ == "__main__":
print(fib1(10))
print(fib2(10))
print(fib_list(10))
print(nth_fib_num(10))<|fim▁end|>
| |
<|file_name|>homepage.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe.model.document import Document
from frappe.website.utils import delete_page_cache
class Homepage(Document):
def validate(self):
if not self.description:
self.description = frappe._("This is an example website auto-generated from ERPNext")
delete_page_cache('home')
def setup_items(self):
for d in frappe.get_all('Item', fields=['name', 'item_name', 'description', 'image'],
filters={'show_in_website': 1}, limit=3):<|fim▁hole|> if not doc.route:
# set missing route
doc.save()
self.append('products', dict(item_code=d.name,
item_name=d.item_name, description=d.description, image=d.image))<|fim▁end|>
|
doc = frappe.get_doc('Item', d.name)
|
<|file_name|>util.rs<|end_file_name|><|fim▁begin|>use std::collections::HashMap;
use std::sync::mpsc::{self, Receiver};
use std::thread;
use failure::format_err;
use octobot_lib::errors::*;
fn escape_for_slack(str: &str) -> String {
str.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
}
pub fn make_link(url: &str, text: &str) -> String {
format!("<{}|{}>", escape_for_slack(url), escape_for_slack(text))
}
fn find_github_username(name: &str) -> Option<&str> {
if name.is_empty() {
return None;
}
for (pos, character) in name.char_indices() {
//All characters in usernames must be alphanumeric,
//with the exception of '-'
if !character.is_alphanumeric() && character != '-' {
return Some(name.split_at(pos).0);
}
}
Some(name)
}
pub fn get_mentioned_usernames(body: &str) -> Vec<&str> {
let mut mentions = Vec::new();
for token in body.split_whitespace() {
if token.starts_with('@') && token.len() > 1 {
if let Some(username) = find_github_username(token.split_at(1).1) {
mentions.push(username);
}
}
}
mentions
}
pub fn format_duration(dur: std::time::Duration) -> String {
let seconds = dur.as_secs();
let ms = (dur.subsec_micros() as f64) / 1000_f64;
if seconds > 0 {
format!("{} s, {:.4} ms", seconds, ms)
} else {
format!("{:.4} ms", ms)
}
}
pub fn check_unique_event<T>(event: T, events: &mut Vec<T>, trim_at: usize, trim_to: usize) -> bool
where
T: PartialEq,
{
let unique = !events.contains(&event);
if unique {
events.push(event);
if events.len() > trim_at {
// reverse so that that we keep recent events
events.reverse();
events.truncate(trim_to);
events.reverse();
}
}
unique
}
pub fn parse_query(query_params: Option<&str>) -> HashMap<String, String> {
if query_params.is_none() {
return HashMap::new();
}
query_params
.unwrap()
.split('&')
.filter_map(|v| {
let parts = v.splitn(2, '=').collect::<Vec<_>>();
if parts.len() != 2 {
None
} else {
Some((parts[0].to_string(), parts[1].to_string()))
}
})
.collect::<HashMap<_, _>>()
}
// cf. https://github.com/rust-lang/rust/issues/39364
pub fn recv_timeout<T>(rx: &Receiver<T>, timeout: std::time::Duration) -> Result<T> {
let sleep_time = std::time::Duration::from_millis(50);
let mut time_left = timeout;
loop {
match rx.try_recv() {
Ok(r) => {
return Ok(r);
}
Err(mpsc::TryRecvError::Empty) => match time_left.checked_sub(sleep_time) {
Some(sub) => {
time_left = sub;
thread::sleep(sleep_time);
}
None => {
return Err(format_err!("Timed out waiting"));
}
},<|fim▁hole|> Err(mpsc::TryRecvError::Disconnected) => {
return Err(format_err!("Channel disconnected!"));
}
};
}
}
#[cfg(test)]
mod tests {
use super::*;
use maplit::hashmap;
#[test]
fn test_make_link() {
assert_eq!(
"<http://the-url|the text>",
make_link("http://the-url", "the text")
);
}
#[test]
fn test_make_link_escapes() {
assert_eq!(
"<http://the-url&hello=<>|the text & <> stuff>",
make_link("http://the-url&hello=<>", "the text & <> stuff")
);
}
#[test]
fn test_find_github_username() {
assert_eq!(Some("user"), find_github_username("user"));
assert_eq!(Some("user"), find_github_username("user,"));
assert_eq!(Some("user"), find_github_username("user,junk"));
assert_eq!(Some("user-tanium"), find_github_username("user-tanium"));
assert_eq!(Some("a"), find_github_username("a"));
assert_eq!(Some("a"), find_github_username("a,"));
assert_eq!(None, find_github_username(""));
}
#[test]
fn test_mentioned_users() {
assert_eq!(
vec!["mentioned-user", "other-mentioned-user"],
get_mentioned_usernames(
"Hey @mentioned-user, let me know what @other-mentioned-user thinks"
)
);
assert_eq!(
Vec::<&str>::new(),
get_mentioned_usernames("This won't count as a mention@notamention")
);
}
#[test]
fn test_check_unique_event() {
let trim_at = 5;
let trim_to = 2;
let mut events: Vec<String> = vec![];
assert!(check_unique_event(
"A".into(),
&mut events,
trim_at,
trim_to
));
assert_eq!(vec!["A"], events);
assert!(check_unique_event(
"B".into(),
&mut events,
trim_at,
trim_to
));
assert_eq!(vec!["A", "B"], events);
assert!(!check_unique_event(
"B".into(),
&mut events,
trim_at,
trim_to
));
assert_eq!(vec!["A", "B"], events);
assert!(check_unique_event(
"C".into(),
&mut events,
trim_at,
trim_to
));
assert!(check_unique_event(
"D".into(),
&mut events,
trim_at,
trim_to
));
assert!(check_unique_event(
"E".into(),
&mut events,
trim_at,
trim_to
));
assert_eq!(vec!["A", "B", "C", "D", "E"], events);
// next one should trigger a trim!
assert!(check_unique_event(
"F".into(),
&mut events,
trim_at,
trim_to
));
assert_eq!(vec!["E", "F"], events);
}
#[test]
fn test_parse_query() {
let map = hashmap! {
"A".to_string() => "1".to_string(),
"B".to_string() => "Hello%20There".to_string(),
};
assert_eq!(map, parse_query(Some("A=1&B=Hello%20There")));
}
#[test]
fn test_parse_query_none() {
assert_eq!(HashMap::new(), parse_query(None));
}
}<|fim▁end|>
| |
<|file_name|>attempted-access-non-fatal.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that bogus field access is non-fatal
fn main() {
let x = 0;
let _ = x.foo; //~ ERROR attempted access of field<|fim▁hole|><|fim▁end|>
|
let _ = x.bar; //~ ERROR attempted access of field
}
|
<|file_name|>int.rs<|end_file_name|><|fim▁begin|>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information<|fim▁hole|> * "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.
*/
#![allow(unused_imports)]
extern crate tvm_frontend as tvm;
use std::convert::TryInto;
use tvm::{errors::Error, *};
fn main() {
fn sum(args: &[TVMArgValue]) -> Result<TVMRetValue, Error> {
let mut ret = 0i64;
for arg in args.iter() {
let val: i64 = arg.try_into()?;
ret += val;
}
Ok(TVMRetValue::from(ret))
}
tvm::function::register(sum, "mysum".to_owned(), false).unwrap();
let mut registered = function::Builder::default();
registered.get_function("mysum");
assert!(registered.func.is_some());
let ret: i64 = registered
.args(&[10, 20, 30])
.invoke()
.unwrap()
.try_into()
.unwrap();
assert_eq!(ret, 60);
}<|fim▁end|>
|
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
|
<|file_name|>script_utils.py<|end_file_name|><|fim▁begin|>import logging
import os
import subprocess
import traceback
from zipfile import ZipFile
from os import listdir
from os.path import isfile, join
'''
A utility python module containing a set of methods necessary for this kbase
module.
'''
LEVELS = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL}
def create_logger(log_dir, name):
"""Create a logger
args: name (str): name of logger
returns: logger (obj): logging.Logger instance
"""
logger = logging.getLogger(name)
fmt = logging.Formatter('%(asctime)s - %(process)d - %(name)s - '
' %(levelname)s -%(message)s')
hdl = logging.FileHandler(os.path.join(log_dir, name + '.log'))
hdl.setFormatter(fmt)
logger.addHandler(hdl)
return logger
def if_obj_exists(logger, ws_client, ws_id, o_type, obj_l):
obj_list = ws_client.list_objects({"workspaces": [ws_id], "type": o_type, 'showHidden': 1})
obj_names = [i[1] for i in obj_list]
existing_names = [i for i in obj_l if i in obj_names]
obj_ids = None
if len(existing_names) != 0:
e_queries = [{'name': j, 'workspace': ws_id} for j in existing_names]
e_infos = ws_client.get_object_info_new({"objects": e_queries})
obj_ids = [(str(k[1]), (str(k[6]) + '/' + str(k[0]) + '/' + str(k[4]))) for k in e_infos]
return obj_ids
def log(message, level=logging.INFO, logger=None):
if logger is None:
if level == logging.DEBUG:
print('\nDEBUG: ' + message + '\n')
elif level == logging.INFO:
print('\nINFO: ' + message + '\n')
elif level == logging.WARNING:
print('\nWARNING: ' + message + '\n')
elif level == logging.ERROR:
print('\nERROR: ' + message + '\n')
elif level == logging.CRITICAL:
print('\nCRITICAL: ' + message + '\n')
else:
logger.log(level, '\n' + message + '\n')
def zip_files(logger, src_path, output_fn):
"""
Compress all index files (not directory) into an output zip file on disk.
"""
files = [f for f in listdir(src_path) if isfile(join(src_path, f))]
with ZipFile(output_fn, 'w', allowZip64=True) as izip:
for f in files:
izip.write(join(src_path, f), f)
def unzip_files(logger, src_fn, dst_path):
"""
Extract all index files into an output zip file on disk.
"""
with ZipFile(src_fn, 'r') as ozip:
ozip.extractall(dst_path)
def whereis(program):
"""
returns path of program if it exists in your ``$PATH`` variable or `
`None`` otherwise
"""
for path in os.environ.get('PATH', '').split(':'):
if os.path.exists(os.path.join(path, program)) and not os.path.isdir(
os.path.join(path, program)):
return os.path.join(path, program)
return None
def runProgram(logger=None,
progName=None,
argStr=None,
script_dir=None,
working_dir=None):
"""
Convenience func to handle calling and monitoring output of external programs.
:param progName: name of system program command
:param argStr: string containing command line options for ``progName``
:returns: subprocess.communicate object
"""
# Ensure program is callable.
if script_dir is not None:
progPath = os.path.join(script_dir, progName)
else:
progPath = progName
progPath = whereis(progName)
if not progPath:
raise RuntimeError(
None,
'{0} command not found in your PATH environmental variable. {1}'.format(
progName,
os.environ.get(
'PATH',
'')))
# Construct shell command
cmdStr = "%s %s" % (progPath, argStr)
print "Executing : " + cmdStr
if logger is not None:
logger.info("Executing : " + cmdStr)
# if working_dir is None:
logger.info("Executing: " + cmdStr + " on cwd")
else:
logger.info("Executing: " + cmdStr + " on " + working_dir)
# Set up process obj
process = subprocess.Popen(cmdStr,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=working_dir)
# Get results
result, stderr = process.communicate()
# print result
# print stderr
# keep this until your code is stable for easier debugging
if logger is not None and result is not None and len(result) > 0:
logger.info(result)
else:
print result
if logger is not None and stderr is not None and len(stderr) > 0:
logger.info(stderr)
else:
print stderr
# Check returncode for success/failure
if process.returncode != 0:
raise Exception("Command execution failed {0}".format(
"".join(traceback.format_exc())))
raise RuntimeError(
'Return Code : {0} , result {1} , progName {2}'.format(
process.returncode, result, progName))
# Return result
return {"result": result, "stderr": stderr}
def check_sys_stat(logger):
check_disk_space(logger)
check_memory_usage(logger)
check_cpu_usage(logger)
def check_disk_space(logger):
runProgram(logger=logger, progName="df", argStr="-h")<|fim▁hole|>
def check_memory_usage(logger):
runProgram(logger=logger, progName="vmstat", argStr="-s")
def check_cpu_usage(logger):
runProgram(logger=logger, progName="mpstat", argStr="-P ALL")<|fim▁end|>
| |
<|file_name|>ad_group_ad_error.pb.go<|end_file_name|><|fim▁begin|>// Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/ads/googleads/v1/errors/ad_group_ad_error.proto
package errors
import (
fmt "fmt"
math "math"
proto "github.com/golang/protobuf/proto"
_ "google.golang.org/genproto/googleapis/api/annotations"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
// Enum describing possible ad group ad errors.
type AdGroupAdErrorEnum_AdGroupAdError int32
const (
// Enum unspecified.
AdGroupAdErrorEnum_UNSPECIFIED AdGroupAdErrorEnum_AdGroupAdError = 0
// The received error code is not known in this version.
AdGroupAdErrorEnum_UNKNOWN AdGroupAdErrorEnum_AdGroupAdError = 1
// No link found between the adgroup ad and the label.
AdGroupAdErrorEnum_AD_GROUP_AD_LABEL_DOES_NOT_EXIST AdGroupAdErrorEnum_AdGroupAdError = 2
// The label has already been attached to the adgroup ad.
AdGroupAdErrorEnum_AD_GROUP_AD_LABEL_ALREADY_EXISTS AdGroupAdErrorEnum_AdGroupAdError = 3
// The specified ad was not found in the adgroup
AdGroupAdErrorEnum_AD_NOT_UNDER_ADGROUP AdGroupAdErrorEnum_AdGroupAdError = 4
// Removed ads may not be modified
AdGroupAdErrorEnum_CANNOT_OPERATE_ON_REMOVED_ADGROUPAD AdGroupAdErrorEnum_AdGroupAdError = 5
// An ad of this type is deprecated and cannot be created. Only deletions
// are permitted.
AdGroupAdErrorEnum_CANNOT_CREATE_DEPRECATED_ADS AdGroupAdErrorEnum_AdGroupAdError = 6
// Text ads are deprecated and cannot be created. Use expanded text ads
// instead.
AdGroupAdErrorEnum_CANNOT_CREATE_TEXT_ADS AdGroupAdErrorEnum_AdGroupAdError = 7
// A required field was not specified or is an empty string.
AdGroupAdErrorEnum_EMPTY_FIELD AdGroupAdErrorEnum_AdGroupAdError = 8
// An ad may only be modified once per call
AdGroupAdErrorEnum_RESOURCE_REFERENCED_IN_MULTIPLE_OPS AdGroupAdErrorEnum_AdGroupAdError = 9
)
var AdGroupAdErrorEnum_AdGroupAdError_name = map[int32]string{
0: "UNSPECIFIED",
1: "UNKNOWN",
2: "AD_GROUP_AD_LABEL_DOES_NOT_EXIST",
3: "AD_GROUP_AD_LABEL_ALREADY_EXISTS",
4: "AD_NOT_UNDER_ADGROUP",
5: "CANNOT_OPERATE_ON_REMOVED_ADGROUPAD",
6: "CANNOT_CREATE_DEPRECATED_ADS",
7: "CANNOT_CREATE_TEXT_ADS",
8: "EMPTY_FIELD",
9: "RESOURCE_REFERENCED_IN_MULTIPLE_OPS",
}
var AdGroupAdErrorEnum_AdGroupAdError_value = map[string]int32{
"UNSPECIFIED": 0,
"UNKNOWN": 1,
"AD_GROUP_AD_LABEL_DOES_NOT_EXIST": 2,
"AD_GROUP_AD_LABEL_ALREADY_EXISTS": 3,
"AD_NOT_UNDER_ADGROUP": 4,
"CANNOT_OPERATE_ON_REMOVED_ADGROUPAD": 5,
"CANNOT_CREATE_DEPRECATED_ADS": 6,
"CANNOT_CREATE_TEXT_ADS": 7,
"EMPTY_FIELD": 8,
"RESOURCE_REFERENCED_IN_MULTIPLE_OPS": 9,
}
func (x AdGroupAdErrorEnum_AdGroupAdError) String() string {
return proto.EnumName(AdGroupAdErrorEnum_AdGroupAdError_name, int32(x))
}
func (AdGroupAdErrorEnum_AdGroupAdError) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_0a1e540bf367b66f, []int{0, 0}
}
// Container for enum describing possible ad group ad errors.
type AdGroupAdErrorEnum struct {
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`<|fim▁hole|>func (m *AdGroupAdErrorEnum) String() string { return proto.CompactTextString(m) }
func (*AdGroupAdErrorEnum) ProtoMessage() {}
func (*AdGroupAdErrorEnum) Descriptor() ([]byte, []int) {
return fileDescriptor_0a1e540bf367b66f, []int{0}
}
func (m *AdGroupAdErrorEnum) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_AdGroupAdErrorEnum.Unmarshal(m, b)
}
func (m *AdGroupAdErrorEnum) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_AdGroupAdErrorEnum.Marshal(b, m, deterministic)
}
func (m *AdGroupAdErrorEnum) XXX_Merge(src proto.Message) {
xxx_messageInfo_AdGroupAdErrorEnum.Merge(m, src)
}
func (m *AdGroupAdErrorEnum) XXX_Size() int {
return xxx_messageInfo_AdGroupAdErrorEnum.Size(m)
}
func (m *AdGroupAdErrorEnum) XXX_DiscardUnknown() {
xxx_messageInfo_AdGroupAdErrorEnum.DiscardUnknown(m)
}
var xxx_messageInfo_AdGroupAdErrorEnum proto.InternalMessageInfo
func init() {
proto.RegisterEnum("google.ads.googleads.v1.errors.AdGroupAdErrorEnum_AdGroupAdError", AdGroupAdErrorEnum_AdGroupAdError_name, AdGroupAdErrorEnum_AdGroupAdError_value)
proto.RegisterType((*AdGroupAdErrorEnum)(nil), "google.ads.googleads.v1.errors.AdGroupAdErrorEnum")
}
func init() {
proto.RegisterFile("google/ads/googleads/v1/errors/ad_group_ad_error.proto", fileDescriptor_0a1e540bf367b66f)
}
var fileDescriptor_0a1e540bf367b66f = []byte{
// 448 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x92, 0x51, 0x6b, 0xd4, 0x40,
0x10, 0xc7, 0xbd, 0x54, 0x5b, 0xdd, 0x82, 0x86, 0x28, 0x22, 0xa5, 0x94, 0x72, 0x0a, 0xbe, 0x25,
0x1c, 0x82, 0x0f, 0xf1, 0x69, 0x2e, 0x3b, 0x77, 0x04, 0x73, 0x9b, 0x65, 0x93, 0x9c, 0xad, 0x1c,
0x2c, 0xd1, 0x3d, 0xc2, 0x41, 0x9b, 0x3d, 0xb2, 0xd7, 0x7e, 0x20, 0x1f, 0x7d, 0xf7, 0x4b, 0x88,
0x9f, 0xc4, 0x07, 0x3f, 0x83, 0x6c, 0xb6, 0x77, 0x70, 0xa0, 0x7d, 0xda, 0x3f, 0x33, 0xbf, 0xff,
0xcc, 0xee, 0xce, 0x90, 0xf7, 0x8d, 0xd6, 0xcd, 0xd5, 0x32, 0xaa, 0x95, 0x89, 0x9c, 0xb4, 0xea,
0x76, 0x14, 0x2d, 0xbb, 0x4e, 0x77, 0x26, 0xaa, 0x95, 0x6c, 0x3a, 0x7d, 0xb3, 0x96, 0xb5, 0x92,
0x7d, 0x28, 0x5c, 0x77, 0x7a, 0xa3, 0x83, 0x33, 0x07, 0x87, 0xb5, 0x32, 0xe1, 0xce, 0x17, 0xde,
0x8e, 0x42, 0xe7, 0x3b, 0x39, 0xdd, 0xd6, 0x5d, 0xaf, 0xa2, 0xba, 0x6d, 0xf5, 0xa6, 0xde, 0xac,
0x74, 0x6b, 0x9c, 0x7b, 0xf8, 0xcb, 0x23, 0x01, 0xa8, 0xa9, 0x2d, 0x0c, 0x0a, 0xad, 0x03, 0xdb,
0x9b, 0xeb, 0xe1, 0x0f, 0x8f, 0x3c, 0xdd, 0x0f, 0x07, 0xcf, 0xc8, 0x71, 0xc5, 0x0a, 0x8e, 0x49,
0x3a, 0x49, 0x91, 0xfa, 0x0f, 0x82, 0x63, 0x72, 0x54, 0xb1, 0x8f, 0x2c, 0xff, 0xc4, 0xfc, 0x41,
0xf0, 0x86, 0x9c, 0x03, 0x95, 0x53, 0x91, 0x57, 0x5c, 0x02, 0x95, 0x19, 0x8c, 0x31, 0x93, 0x34,
0xc7, 0x42, 0xb2, 0xbc, 0x94, 0x78, 0x91, 0x16, 0xa5, 0xef, 0xfd, 0x9b, 0x82, 0x4c, 0x20, 0xd0,
0x4b, 0x07, 0x15, 0xfe, 0x41, 0xf0, 0x8a, 0xbc, 0x00, 0xda, 0xfb, 0x2a, 0x46, 0x51, 0x48, 0xa0,
0xbd, 0xc3, 0x7f, 0x18, 0xbc, 0x25, 0xaf, 0x13, 0x60, 0x36, 0x93, 0x73, 0x14, 0x50, 0xa2, 0xcc,
0x99, 0x14, 0x38, 0xcb, 0xe7, 0x48, 0xb7, 0x18, 0x50, 0xff, 0x51, 0x70, 0x4e, 0x4e, 0xef, 0xc0,
0x44, 0xa0, 0xe5, 0x28, 0x72, 0x81, 0x09, 0x94, 0x3d, 0x57, 0xf8, 0x87, 0xc1, 0x09, 0x79, 0xb9,
0x4f, 0x94, 0x78, 0x51, 0xf6, 0xb9, 0x23, 0xfb, 0x54, 0x9c, 0xf1, 0xf2, 0x52, 0x4e, 0x52, 0xcc,
0xa8, 0xff, 0xd8, 0xf6, 0x15, 0x58, 0xe4, 0x95, 0x48, 0x50, 0x0a, 0x9c, 0xa0, 0x40, 0x96, 0x20,
0x95, 0x29, 0x93, 0xb3, 0x2a, 0x2b, 0x53, 0x9e, 0xa1, 0xcc, 0x79, 0xe1, 0x3f, 0x19, 0xff, 0x19,
0x90, 0xe1, 0x57, 0x7d, 0x1d, 0xde, 0x3f, 0x93, 0xf1, 0xf3, 0xfd, 0xbf, 0xe5, 0x76, 0x14, 0x7c,
0xf0, 0x99, 0xde, 0xd9, 0x1a, 0x7d, 0x55, 0xb7, 0x4d, 0xa8, 0xbb, 0x26, 0x6a, 0x96, 0x6d, 0x3f,
0xa8, 0xed, 0x4a, 0xac, 0x57, 0xe6, 0x7f, 0x1b, 0xf2, 0xc1, 0x1d, 0xdf, 0xbc, 0x83, 0x29, 0xc0,
0x77, 0xef, 0x6c, 0xea, 0x8a, 0x81, 0x32, 0xa1, 0x93, 0x56, 0xcd, 0x47, 0x61, 0xdf, 0xd2, 0xfc,
0xdc, 0x02, 0x0b, 0x50, 0x66, 0xb1, 0x03, 0x16, 0xf3, 0xd1, 0xc2, 0x01, 0xbf, 0xbd, 0xa1, 0x8b,
0xc6, 0x31, 0x28, 0x13, 0xc7, 0x3b, 0x24, 0x8e, 0xe7, 0xa3, 0x38, 0x76, 0xd0, 0x97, 0xc3, 0xfe,
0x76, 0xef, 0xfe, 0x06, 0x00, 0x00, 0xff, 0xff, 0x5f, 0xb4, 0xd4, 0xe6, 0xbe, 0x02, 0x00, 0x00,
}<|fim▁end|>
|
}
func (m *AdGroupAdErrorEnum) Reset() { *m = AdGroupAdErrorEnum{} }
|
<|file_name|>message.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
"""
用户消息相关的视图
"""
from rest_framework import generics
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import SearchFilter
from account.serializers.message import MessageSerializer
from account.models import Message
class MessageCreateView(generics.CreateAPIView):
"""创建用户消息api"""
queryset = Message.objects.all()
serializer_class = MessageSerializer
# 权限控制
permission_classes = (IsAuthenticated,)
class MessageListView(generics.ListAPIView):
"""
用户消息列表api View
> 用户只能看到自己的消息列表
"""
# queryset = Message.objects.filter(deleted=False)
serializer_class = MessageSerializer
# 权限控制
permission_classes = (IsAuthenticated,)
# 搜索和过滤
filter_backends = (DjangoFilterBackend, SearchFilter)
filter_fields = ('category', 'unread')
search_fields = ('title', 'content')
ordering_fields = ('id', 'time_added')
ordering = ('-time_added',)
def get_queryset(self):
# 第1步:获取到请求的用户
# 用户只可以看到自己的消息列表
user = self.request.user
# 第2步:获取到是否已读:unread=0/1(已读/未读)
queryset = Message.objects.filter(user=user, is_deleted=False).order_by('-id')
# 第3步:返回结果集
return queryset
<|fim▁hole|> 用户消息详情View
> 只能获取到用户自己的消息,即使是超级用户,也只能查看到自己的消息,不可以去看别人的
"""
queryset = Message.objects.filter(is_deleted=False)
serializer_class = MessageSerializer
# 权限控制
permission_classes = (IsAuthenticated,)
def get_object(self):
# 1. 先获取到用户
user = self.request.user
# 2. 调用父类的方法获取到这个对象
instance = super().get_object()
# 3. 如果这个对象user是请求的用户,那么返回对象,不是的话返回None
if instance and user == instance.user:
return instance
else:
return None
def retrieve(self, request, *args, **kwargs):
# 1. 获取到对象
instance = self.get_object()
# 2. 修改unread
if instance.unread:
instance.unread = False
instance.save(update_fields=('unread',))
return super().retrieve(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
# 1. 获取到user和对象
user = self.request.user
instance = self.get_object()
# 2. 如果是自己的消息或者是超级管理员,那么就可以删除本条消息
if instance.is_deleted:
response = Response(status=204)
else:
if instance.user == user or user.is_superuser:
instance.is_deleted = True
instance.save()
response = Response(status=204)
else:
response = Response("没权限删除", status=403)
# 3. 返回响应
return response<|fim▁end|>
|
class MessageDetailView(generics.RetrieveDestroyAPIView):
"""
|
<|file_name|>questdisplay.cpp<|end_file_name|><|fim▁begin|>#include "questdisplay.h"
#include "../core/global.h"
//QuestLister stuff
QuestLister::QuestLister(int xp, int yp, int wp, int hp) : BasicGUI(xp, yp, wp, hp) {
headerSize = 35;
//-1 due to the header
displayableQuestCount = h / headerSize - 1;
padding = 5;
selectedElementPos = 0;
defaultBGTexture = Global::resourceHandler->getATexture(TT::GUI, "questlistdefaultbg");
headBGTexture = Global::resourceHandler->getATexture(TT::GUI, "questlistheadbg");
selectedBGTexture = Global::resourceHandler->getATexture(TT::GUI, "questlistselectedbg");
questDisplay = NULL;
}
void QuestLister::render() {
//Setting rectangle
SDL_Rect destinationRect = {x, y, w, headerSize};
headBGTexture->render(destinationRect);
ATexture* headerText = Global::resourceHandler->getTextTexture("Active quests", Global::resourceHandler->getColor("iteminfo-desc"), headerSize * 3 / 4);
Dimension d = headerText->getDimensions();
SDL_Rect textDestRect = destinationRect;
textDestRect.x += padding;
textDestRect.y += padding;
textDestRect.w = d.W();
textDestRect.h = d.H();
headerText->render(textDestRect);
for (int i = 0; i < displayableQuestCount; i++) {
destinationRect.y += headerSize;
if (selectedElementPos == i) {
selectedBGTexture->render(destinationRect);
} else {
defaultBGTexture->render(destinationRect);
}
Quest* currentQuest = getQuest(i);
if (currentQuest != NULL) {
ATexture* headerText = Global::resourceHandler->getTextTexture(currentQuest->getName(), Global::resourceHandler->getColor("iteminfo-desc"), headerSize * 2 / 3);
Dimension d = headerText->getDimensions();
textDestRect = destinationRect;
textDestRect.x += padding;
textDestRect.y += padding;
textDestRect.w = d.W();
textDestRect.h = d.H();
headerText->render(textDestRect);
}
}
}
Quest* QuestLister::getQuest(unsigned int index) {
//NULL checking
if (index >= questsToDisplay.size()) {
return NULL;
}
return questsToDisplay[index];
}
int QuestLister::getHeaderSize() {
return headerSize;
}
int QuestLister::getPadding() {
return padding;
}
QuestDisplay* QuestLister::getQuestDisplay() {
return questDisplay;
}
void QuestLister::addQuest(Quest* questToAdd) {<|fim▁hole|>}
void QuestLister::setPadding(int newPadding) {
padding = newPadding;
}
void QuestLister::setQuestDisplay(QuestDisplay* newQuestDisplay) {
questDisplay = newQuestDisplay;
}
void QuestLister::handleLeftClickEvent(int xp, int yp) {
selectedElementPos = (yp - y) / headerSize - 1;
Quest* currentQuest = getQuest(selectedElementPos);
questDisplay->setQuest(currentQuest);
}
void QuestLister::handleMouseWheelEvent(bool up) {
//TODO implementation
}
//QuestDisplay stuff
QuestDisplay::QuestDisplay(int xp, int yp, int wp, int hp) : BasicGUI(xp, yp, wp, hp) {
currentQuest = NULL;
bgTexture = Global::resourceHandler->getATexture(TT::GUI, "questlistselectedbg");
titleSize = 36;
descSize = 22;
padding = 12;
}
void QuestDisplay::render() {
//Setting rectangle
SDL_Rect destinationRect = {x, y, w, h};
bgTexture->render(destinationRect);
if (currentQuest != NULL) {
SDL_Rect textDestRect;
ATexture* titleText = Global::resourceHandler->getTextTexture(currentQuest->getName(), Global::resourceHandler->getColor("iteminfo-desc"), titleSize);
Dimension d = titleText->getDimensions();
textDestRect = destinationRect;
textDestRect.x += (textDestRect.w - d.W()) / 2;
textDestRect.w = d.W();
textDestRect.h = d.H();
titleText->render(textDestRect);
ATexture* descText = Global::resourceHandler->getTextTexture(currentQuest->getDescription(), Global::resourceHandler->getColor("iteminfo-desc"), descSize);
d = descText->getDimensions();
textDestRect = destinationRect;
textDestRect.x += padding;
textDestRect.y += textDestRect.h / 6;
textDestRect.w = d.W();
textDestRect.h = d.H();
descText->render(textDestRect);
int size = 100;
ATexture* objText = NULL;
ATexture* oText = NULL;
switch(currentQuest->getQuestObjective()) {
case QuestObjective::TALK_WITH_NPC:
objText = Global::resourceHandler->getTextTexture("Talk to:", Global::resourceHandler->getColor("iteminfo-desc"), descSize);
oText = currentQuest->getQOTalkTarget()->texture;
break;
case QuestObjective::KILL_NPC:
objText = Global::resourceHandler->getTextTexture("Kill:", Global::resourceHandler->getColor("iteminfo-desc"), descSize);
oText = currentQuest->getQOKillTarget()->texture;
break;
case QuestObjective::VISIT_STRUCTURE:
objText = Global::resourceHandler->getTextTexture("Visit:", Global::resourceHandler->getColor("iteminfo-desc"), descSize);
oText = currentQuest->getQOStructTarget()->texture;
break;
}
d = objText->getDimensions();
textDestRect = destinationRect;
textDestRect.x += padding;
textDestRect.y += textDestRect.h * 2 / 6;
textDestRect.w = d.W();
textDestRect.h = d.H();
objText->render(textDestRect);
oText->render({x + textDestRect.w + padding * 4, textDestRect.y, size, size});
ATexture* rewardText = Global::resourceHandler->getTextTexture("Reward:", Global::resourceHandler->getColor("iteminfo-desc"), descSize);
d = rewardText->getDimensions();
textDestRect = destinationRect;
textDestRect.x += padding;
textDestRect.y += textDestRect.h * 3 / 6;
textDestRect.w = d.W();
textDestRect.h = d.H();
rewardText->render(textDestRect);
Global::resourceHandler->getATexture(TT::GUI, "gold")->render({x + textDestRect.w + padding * 4, textDestRect.y, size, size});
ATexture* goldText = Global::resourceHandler->getTextTexture(std::to_string(currentQuest->getRewardGold()), Global::resourceHandler->getColor("gold"), descSize * 3);
d = goldText->getDimensions();
textDestRect.x += textDestRect.w + size + padding * 6;
textDestRect.w = d.W();
textDestRect.h = d.H();
goldText->render(textDestRect);
int rowLength = w / size;
//int rows = (int)std::ceil((double)currentQuest->getRewardItemsSize() / rowLength);
for (unsigned int i = 0; i < currentQuest->getRewardItemsSize(); i++) {
destinationRect.x = x + (i % rowLength) * size;
destinationRect.y = y + h * 4 / 6 + ((i / rowLength) * size);
destinationRect.w = size;
destinationRect.h = size;
currentQuest->getRewardItem(i)->render(destinationRect, false);
}
}
}
Quest* QuestDisplay::getQuest() {
return currentQuest;
}
void QuestDisplay::setQuest(Quest* newQuest) {
currentQuest = newQuest;
}<|fim▁end|>
|
questsToDisplay.push_back(questToAdd);
|
<|file_name|>index.ts<|end_file_name|><|fim▁begin|><|fim▁hole|>export * from './AuthenticationService';
export * from './AuthenticationInitializer';
export * from './userMenu/UserMenu';<|fim▁end|>
| |
<|file_name|>BsVendor$Dollar.java<|end_file_name|><|fim▁begin|>package org.docksidestage.oracle.dbflute.bsentity;
import java.util.List;
import java.util.ArrayList;
import org.dbflute.dbmeta.DBMeta;
import org.dbflute.dbmeta.AbstractEntity;
import org.dbflute.dbmeta.accessory.DomainEntity;
import org.docksidestage.oracle.dbflute.allcommon.DBMetaInstanceHandler;
import org.docksidestage.oracle.dbflute.exentity.*;
/**
* The entity of VENDOR_$_DOLLAR as TABLE. <br>
* <pre>
* [primary-key]
* VENDOR_$_DOLLAR_ID
*
* [column]
* VENDOR_$_DOLLAR_ID, VENDOR_$_DOLLAR_NAME
*
* [sequence]
*
*
* [identity]
*
*
* [version-no]
*
*
* [foreign table]
*
*
* [referrer table]
*
*
* [foreign property]
*
*
* [referrer property]
*
*
* [get/set template]
* /= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
* Long vendor$DollarId = entity.getVendor$DollarId();
* String vendor$DollarName = entity.getVendor$DollarName();
* entity.setVendor$DollarId(vendor$DollarId);
* entity.setVendor$DollarName(vendor$DollarName);
* = = = = = = = = = =/
* </pre>
* @author oracleman
*/
public abstract class BsVendor$Dollar extends AbstractEntity implements DomainEntity {
// ===================================================================================
// Definition
// ==========
/** The serial version UID for object serialization. (Default) */
private static final long serialVersionUID = 1L;
// ===================================================================================
// Attribute
// =========
/** VENDOR_$_DOLLAR_ID: {PK, NotNull, NUMBER(16)} */
protected Long _vendor$DollarId;
/** VENDOR_$_DOLLAR_NAME: {NotNull, VARCHAR2(32)} */
protected String _vendor$DollarName;
// ===================================================================================
// DB Meta
// =======
/** {@inheritDoc} */
public DBMeta asDBMeta() {
return DBMetaInstanceHandler.findDBMeta(asTableDbName());
}
/** {@inheritDoc} */
public String asTableDbName() {
return "VENDOR_$_DOLLAR";
}
// ===================================================================================
// Key Handling
// ============
/** {@inheritDoc} */
public boolean hasPrimaryKeyValue() {
if (_vendor$DollarId == null) { return false; }
return true;
}
// ===================================================================================
// Foreign Property
// ================
// ===================================================================================
// Referrer Property
// =================
protected <ELEMENT> List<ELEMENT> newReferrerList() { // overriding to import
return new ArrayList<ELEMENT>();
}
// ===================================================================================
// Basic Override
// ==============
@Override
protected boolean doEquals(Object obj) {
if (obj instanceof BsVendor$Dollar) {
BsVendor$Dollar other = (BsVendor$Dollar)obj;
if (!xSV(_vendor$DollarId, other._vendor$DollarId)) { return false; }
return true;
} else {
return false;
}
}
@Override
protected int doHashCode(int initial) {
int hs = initial;
hs = xCH(hs, asTableDbName());
hs = xCH(hs, _vendor$DollarId);
return hs;
}
@Override
protected String doBuildStringWithRelation(String li) {
return "";
}
@Override
protected String doBuildColumnString(String dm) {
StringBuilder sb = new StringBuilder();
sb.append(dm).append(xfND(_vendor$DollarId));
sb.append(dm).append(xfND(_vendor$DollarName));
if (sb.length() > dm.length()) {
sb.delete(0, dm.length());
}
sb.insert(0, "{").append("}");
return sb.toString();
}
@Override
protected String doBuildRelationString(String dm) {
return "";
}
@Override
public Vendor$Dollar clone() {
return (Vendor$Dollar)super.clone();
}
// ===================================================================================
// Accessor
// ========
/**
* [get] VENDOR_$_DOLLAR_ID: {PK, NotNull, NUMBER(16)} <br>
* @return The value of the column 'VENDOR_$_DOLLAR_ID'. (basically NotNull if selected: for the constraint)
*/
public Long getVendor$DollarId() {
checkSpecifiedProperty("vendor$DollarId");
return _vendor$DollarId;
}
/**
* [set] VENDOR_$_DOLLAR_ID: {PK, NotNull, NUMBER(16)} <br>
* @param vendor$DollarId The value of the column 'VENDOR_$_DOLLAR_ID'. (basically NotNull if update: for the constraint)
*/
public void setVendor$DollarId(Long vendor$DollarId) {
registerModifiedProperty("vendor$DollarId");
_vendor$DollarId = vendor$DollarId;
}<|fim▁hole|> * @return The value of the column 'VENDOR_$_DOLLAR_NAME'. (basically NotNull if selected: for the constraint)
*/
public String getVendor$DollarName() {
checkSpecifiedProperty("vendor$DollarName");
return _vendor$DollarName;
}
/**
* [set] VENDOR_$_DOLLAR_NAME: {NotNull, VARCHAR2(32)} <br>
* @param vendor$DollarName The value of the column 'VENDOR_$_DOLLAR_NAME'. (basically NotNull if update: for the constraint)
*/
public void setVendor$DollarName(String vendor$DollarName) {
registerModifiedProperty("vendor$DollarName");
_vendor$DollarName = vendor$DollarName;
}
}<|fim▁end|>
|
/**
* [get] VENDOR_$_DOLLAR_NAME: {NotNull, VARCHAR2(32)} <br>
|
<|file_name|>format.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub use self::Invocation::*;
use self::ArgumentType::*;
use self::Position::*;
use ast;
use codemap::{Span, respan};
use ext::base::*;
use ext::base;
use ext::build::AstBuilder;
use fmt_macros as parse;
use parse::token::{InternedString, special_idents};
use parse::token;
use ptr::P;
use std::collections::HashMap;
use std::string;
#[deriving(PartialEq)]
enum ArgumentType {
Known(string::String),
Unsigned
}
enum Position {
Exact(uint),
Named(string::String),
}
struct Context<'a, 'b:'a> {
ecx: &'a mut ExtCtxt<'b>,
fmtsp: Span,
/// Parsed argument expressions and the types that we've found so far for
/// them.
args: Vec<P<ast::Expr>>,
arg_types: Vec<Option<ArgumentType>>,
/// Parsed named expressions and the types that we've found for them so far.
/// Note that we keep a side-array of the ordering of the named arguments
/// found to be sure that we can translate them in the same order that they
/// were declared in.
names: HashMap<string::String, P<ast::Expr>>,
name_types: HashMap<string::String, ArgumentType>,
name_ordering: Vec<string::String>,
/// The latest consecutive literal strings, or empty if there weren't any.
literal: string::String,
/// Collection of the compiled `rt::Argument` structures
pieces: Vec<P<ast::Expr>>,
/// Collection of string literals
str_pieces: Vec<P<ast::Expr>>,
/// Stays `true` if all formatting parameters are default (as in "{}{}").
all_pieces_simple: bool,
name_positions: HashMap<string::String, uint>,
method_statics: Vec<P<ast::Item>>,
/// Updated as arguments are consumed or methods are entered
nest_level: uint,
next_arg: uint,
}
pub enum Invocation {
Call(P<ast::Expr>),
MethodCall(P<ast::Expr>, ast::Ident),
}
/// Parses the arguments from the given list of tokens, returning None
/// if there's a parse error so we can continue parsing other format!
/// expressions.
///
/// If parsing succeeds, the second return value is:
///
/// Some((fmtstr, unnamed arguments, ordering of named arguments,
/// named arguments))
fn parse_args(ecx: &mut ExtCtxt, sp: Span, allow_method: bool,
tts: &[ast::TokenTree])
-> (Invocation, Option<(P<ast::Expr>, Vec<P<ast::Expr>>, Vec<string::String>,
HashMap<string::String, P<ast::Expr>>)>) {
let mut args = Vec::new();
let mut names = HashMap::<string::String, P<ast::Expr>>::new();
let mut order = Vec::new();
let mut p = ecx.new_parser_from_tts(tts);
// Parse the leading function expression (maybe a block, maybe a path)
let invocation = if allow_method {
let e = p.parse_expr();
if !p.eat(&token::Comma) {
ecx.span_err(sp, "expected token: `,`");
return (Call(e), None);
}
MethodCall(e, p.parse_ident())
} else {
Call(p.parse_expr())
};
if !p.eat(&token::Comma) {
ecx.span_err(sp, "expected token: `,`");
return (invocation, None);
}
if p.token == token::Eof {
ecx.span_err(sp, "requires at least a format string argument");
return (invocation, None);
}
let fmtstr = p.parse_expr();
let mut named = false;
while p.token != token::Eof {
if !p.eat(&token::Comma) {
ecx.span_err(sp, "expected token: `,`");
return (invocation, None);
}
if p.token == token::Eof { break } // accept trailing commas
if named || (p.token.is_ident() && p.look_ahead(1, |t| *t == token::Eq)) {
named = true;
let ident = match p.token {
token::Ident(i, _) => {
p.bump();
i
}
_ if named => {
ecx.span_err(p.span,
"expected ident, positional arguments \
cannot follow named arguments");
return (invocation, None);
}
_ => {
ecx.span_err(p.span,
format!("expected ident for named argument, found `{}`",
p.this_token_to_string()).as_slice());
return (invocation, None);
}
};
let interned_name = token::get_ident(ident);
let name = interned_name.get();
p.expect(&token::Eq);
let e = p.parse_expr();
match names.get(name) {
None => {}
Some(prev) => {
ecx.span_err(e.span,
format!("duplicate argument named `{}`",
name).as_slice());
ecx.parse_sess.span_diagnostic.span_note(prev.span, "previously here");
continue
}
}
order.push(name.to_string());
names.insert(name.to_string(), e);
} else {
args.push(p.parse_expr());
}
}
return (invocation, Some((fmtstr, args, order, names)));
}
impl<'a, 'b> Context<'a, 'b> {
/// Verifies one piece of a parse string. All errors are not emitted as
/// fatal so we can continue giving errors about this and possibly other
/// format strings.
fn verify_piece(&mut self, p: &parse::Piece) {
match *p {
parse::String(..) => {}
parse::NextArgument(ref arg) => {
// width/precision first, if they have implicit positional
// parameters it makes more sense to consume them first.
self.verify_count(arg.format.width);
self.verify_count(arg.format.precision);
// argument second, if it's an implicit positional parameter
// it's written second, so it should come after width/precision.
let pos = match arg.position {
parse::ArgumentNext => {
let i = self.next_arg;
if self.check_positional_ok() {
self.next_arg += 1;
}
Exact(i)
}
parse::ArgumentIs(i) => Exact(i),
parse::ArgumentNamed(s) => Named(s.to_string()),
};
let ty = Known(arg.format.ty.to_string());
self.verify_arg_type(pos, ty);
}
}
}
fn verify_count(&mut self, c: parse::Count) {
match c {
parse::CountImplied | parse::CountIs(..) => {}
parse::CountIsParam(i) => {
self.verify_arg_type(Exact(i), Unsigned);
}
parse::CountIsName(s) => {
self.verify_arg_type(Named(s.to_string()), Unsigned);
}
parse::CountIsNextParam => {
if self.check_positional_ok() {
let next_arg = self.next_arg;
self.verify_arg_type(Exact(next_arg), Unsigned);
self.next_arg += 1;
}
}
}
}
fn check_positional_ok(&mut self) -> bool {
if self.nest_level != 0 {
self.ecx.span_err(self.fmtsp, "cannot use implicit positional \
arguments nested inside methods");
false
} else {
true
}
}
fn describe_num_args(&self) -> string::String {
match self.args.len() {
0 => "no arguments given".to_string(),
1 => "there is 1 argument".to_string(),
x => format!("there are {} arguments", x),
}
}
fn verify_arg_type(&mut self, arg: Position, ty: ArgumentType) {
match arg {
Exact(arg) => {
if self.args.len() <= arg {
let msg = format!("invalid reference to argument `{}` ({})",
arg, self.describe_num_args());
self.ecx.span_err(self.fmtsp, msg.as_slice());
return;
}
{
let arg_type = match self.arg_types[arg] {
None => None,
Some(ref x) => Some(x)
};
self.verify_same(self.args[arg].span, &ty, arg_type);
}
if self.arg_types[arg].is_none() {
self.arg_types[arg] = Some(ty);
}
}
Named(name) => {
let span = match self.names.get(&name) {
Some(e) => e.span,
None => {
let msg = format!("there is no argument named `{}`", name);
self.ecx.span_err(self.fmtsp, msg.as_slice());
return;
}
};
self.verify_same(span, &ty, self.name_types.get(&name));
if !self.name_types.contains_key(&name) {
self.name_types.insert(name.clone(), ty);
}
// Assign this named argument a slot in the arguments array if
// it hasn't already been assigned a slot.
if !self.name_positions.contains_key(&name) {
let slot = self.name_positions.len();
self.name_positions.insert(name, slot);
}
}
}
}
/// When we're keeping track of the types that are declared for certain
/// arguments, we assume that `None` means we haven't seen this argument
/// yet, `Some(None)` means that we've seen the argument, but no format was
/// specified, and `Some(Some(x))` means that the argument was declared to
/// have type `x`.
///
/// Obviously `Some(Some(x)) != Some(Some(y))`, but we consider it true
/// that: `Some(None) == Some(Some(x))`
fn verify_same(&self,
sp: Span,
ty: &ArgumentType,
before: Option<&ArgumentType>) {
let cur = match before {
None => return,
Some(t) => t,
};
if *ty == *cur {
return
}
match (cur, ty) {
(&Known(ref cur), &Known(ref ty)) => {
self.ecx.span_err(sp,
format!("argument redeclared with type `{}` when \
it was previously `{}`",
*ty,
*cur).as_slice());
}
(&Known(ref cur), _) => {
self.ecx.span_err(sp,
format!("argument used to format with `{}` was \
attempted to not be used for formatting",
*cur).as_slice());
}
(_, &Known(ref ty)) => {
self.ecx.span_err(sp,
format!("argument previously used as a format \
argument attempted to be used as `{}`",
*ty).as_slice());
}
(_, _) => {
self.ecx.span_err(sp, "argument declared with multiple formats");
}
}
}
/// These attributes are applied to all statics that this syntax extension
/// will generate.
fn static_attrs(ecx: &ExtCtxt, fmtsp: Span) -> Vec<ast::Attribute> {
// Flag statics as `inline` so LLVM can merge duplicate globals as much
// as possible (which we're generating a whole lot of).
let unnamed = ecx.meta_word(fmtsp, InternedString::new("inline"));
let unnamed = ecx.attribute(fmtsp, unnamed);
// Do not warn format string as dead code
let dead_code = ecx.meta_word(fmtsp, InternedString::new("dead_code"));
let allow_dead_code = ecx.meta_list(fmtsp,
InternedString::new("allow"),
vec![dead_code]);
let allow_dead_code = ecx.attribute(fmtsp, allow_dead_code);
vec![unnamed, allow_dead_code]
}
fn rtpath(ecx: &ExtCtxt, s: &str) -> Vec<ast::Ident> {
vec![ecx.ident_of("std"), ecx.ident_of("fmt"), ecx.ident_of("rt"), ecx.ident_of(s)]
}
fn trans_count(&self, c: parse::Count) -> P<ast::Expr> {
let sp = self.fmtsp;
match c {
parse::CountIs(i) => {
self.ecx.expr_call_global(sp, Context::rtpath(self.ecx, "CountIs"),
vec!(self.ecx.expr_uint(sp, i)))
}
parse::CountIsParam(i) => {
self.ecx.expr_call_global(sp, Context::rtpath(self.ecx, "CountIsParam"),
vec!(self.ecx.expr_uint(sp, i)))
}
parse::CountImplied => {
let path = self.ecx.path_global(sp, Context::rtpath(self.ecx,
"CountImplied"));
self.ecx.expr_path(path)
}
parse::CountIsNextParam => {
let path = self.ecx.path_global(sp, Context::rtpath(self.ecx,
"CountIsNextParam"));
self.ecx.expr_path(path)
}
parse::CountIsName(n) => {
let i = match self.name_positions.get(n) {
Some(&i) => i,
None => 0, // error already emitted elsewhere
};
let i = i + self.args.len();
self.ecx.expr_call_global(sp, Context::rtpath(self.ecx, "CountIsParam"),
vec!(self.ecx.expr_uint(sp, i)))
}
}
}
/// Translate the accumulated string literals to a literal expression
fn trans_literal_string(&mut self) -> P<ast::Expr> {
let sp = self.fmtsp;
let s = token::intern_and_get_ident(self.literal.as_slice());
self.literal.clear();
self.ecx.expr_str(sp, s)
}
/// Translate a `parse::Piece` to a static `rt::Argument` or append
/// to the `literal` string.
fn trans_piece(&mut self, piece: &parse::Piece) -> Option<P<ast::Expr>> {
let sp = self.fmtsp;
match *piece {
parse::String(s) => {
self.literal.push_str(s);
None
}
parse::NextArgument(ref arg) => {
// Translate the position
let pos = match arg.position {
// These two have a direct mapping
parse::ArgumentNext => {
let path = self.ecx.path_global(sp, Context::rtpath(self.ecx,
"ArgumentNext"));
self.ecx.expr_path(path)
}
parse::ArgumentIs(i) => {
self.ecx.expr_call_global(sp, Context::rtpath(self.ecx, "ArgumentIs"),
vec!(self.ecx.expr_uint(sp, i)))
}
// Named arguments are converted to positional arguments at
// the end of the list of arguments
parse::ArgumentNamed(n) => {
let i = match self.name_positions.get(n) {
Some(&i) => i,
None => 0, // error already emitted elsewhere
};
let i = i + self.args.len();
self.ecx.expr_call_global(sp, Context::rtpath(self.ecx, "ArgumentIs"),
vec!(self.ecx.expr_uint(sp, i)))
}
};
let simple_arg = parse::Argument {
position: parse::ArgumentNext,
format: parse::FormatSpec {
fill: arg.format.fill,
align: parse::AlignUnknown,
flags: 0,
precision: parse::CountImplied,
width: parse::CountImplied,
ty: arg.format.ty
}
};
let fill = match arg.format.fill { Some(c) => c, None => ' ' };
if *arg != simple_arg || fill != ' ' {
self.all_pieces_simple = false;
}
// Translate the format
let fill = self.ecx.expr_lit(sp, ast::LitChar(fill));
let align = match arg.format.align {
parse::AlignLeft => {
self.ecx.path_global(sp, Context::rtpath(self.ecx, "AlignLeft"))
}
parse::AlignRight => {
self.ecx.path_global(sp, Context::rtpath(self.ecx, "AlignRight"))
}
parse::AlignCenter => {
self.ecx.path_global(sp, Context::rtpath(self.ecx, "AlignCenter"))
}
parse::AlignUnknown => {
self.ecx.path_global(sp, Context::rtpath(self.ecx, "AlignUnknown"))
}
};
let align = self.ecx.expr_path(align);
let flags = self.ecx.expr_uint(sp, arg.format.flags);
let prec = self.trans_count(arg.format.precision);
let width = self.trans_count(arg.format.width);
let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, "FormatSpec"));
let fmt = self.ecx.expr_struct(sp, path, vec!(
self.ecx.field_imm(sp, self.ecx.ident_of("fill"), fill),
self.ecx.field_imm(sp, self.ecx.ident_of("align"), align),
self.ecx.field_imm(sp, self.ecx.ident_of("flags"), flags),
self.ecx.field_imm(sp, self.ecx.ident_of("precision"), prec),
self.ecx.field_imm(sp, self.ecx.ident_of("width"), width)));
let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, "Argument"));
Some(self.ecx.expr_struct(sp, path, vec!(
self.ecx.field_imm(sp, self.ecx.ident_of("position"), pos),
self.ecx.field_imm(sp, self.ecx.ident_of("format"), fmt))))
}
}
}
fn item_static_array(ecx: &mut ExtCtxt,
name: ast::Ident,
piece_ty: P<ast::Ty>,
pieces: Vec<P<ast::Expr>>)
-> P<ast::Stmt> {
let fmtsp = piece_ty.span;
let fmt = ecx.expr_vec(fmtsp, pieces);
let fmt = ecx.expr_addr_of(fmtsp, fmt);
let ty = ast::TyVec(piece_ty);
let ty = ast::TyRptr(Some(ecx.lifetime(fmtsp, special_idents::static_lifetime.name)),
ast::MutTy{ mutbl: ast::MutImmutable, ty: ecx.ty(fmtsp, ty) });
let ty = ecx.ty(fmtsp, ty);
let st = ast::ItemStatic(ty, ast::MutImmutable, fmt);
let item = ecx.item(fmtsp, name, Context::static_attrs(ecx, fmtsp), st);
let decl = respan(fmtsp, ast::DeclItem(item));
P(respan(fmtsp, ast::StmtDecl(P(decl), ast::DUMMY_NODE_ID)))
}
/// Actually builds the expression which the iformat! block will be expanded
/// to
fn to_expr(mut self, invocation: Invocation) -> P<ast::Expr> {
let mut lets = Vec::new();
let mut locals = Vec::new();
let mut names = Vec::from_fn(self.name_positions.len(), |_| None);
let mut pats = Vec::new();
let mut heads = Vec::new();
// First, declare all of our methods that are statics
for method in self.method_statics.into_iter() {
let decl = respan(self.fmtsp, ast::DeclItem(method));
lets.push(P(respan(self.fmtsp,
ast::StmtDecl(P(decl), ast::DUMMY_NODE_ID))));
}
// Next, build up the static array which will become our precompiled
// format "string"
let static_str_name = self.ecx.ident_of("__STATIC_FMTSTR");
let static_lifetime = self.ecx.lifetime(self.fmtsp, self.ecx.ident_of("'static").name);
let piece_ty = self.ecx.ty_rptr(
self.fmtsp,
self.ecx.ty_ident(self.fmtsp, self.ecx.ident_of("str")),<|fim▁hole|> Some(static_lifetime),
ast::MutImmutable);
lets.push(Context::item_static_array(self.ecx,
static_str_name,
piece_ty,
self.str_pieces));
// Then, build up the static array which will store our precompiled
// nonstandard placeholders, if there are any.
let static_args_name = self.ecx.ident_of("__STATIC_FMTARGS");
if !self.all_pieces_simple {
let piece_ty = self.ecx.ty_path(self.ecx.path_all(
self.fmtsp,
true, Context::rtpath(self.ecx, "Argument"),
vec![static_lifetime],
vec![]
));
lets.push(Context::item_static_array(self.ecx,
static_args_name,
piece_ty,
self.pieces));
}
// Right now there is a bug such that for the expression:
// foo(bar(&1))
// the lifetime of `1` doesn't outlast the call to `bar`, so it's not
// valid for the call to `foo`. To work around this all arguments to the
// format! string are shoved into locals. Furthermore, we shove the address
// of each variable because we don't want to move out of the arguments
// passed to this function.
for (i, e) in self.args.into_iter().enumerate() {
let arg_ty = match self.arg_types[i].as_ref() {
Some(ty) => ty,
None => continue // error already generated
};
let name = self.ecx.ident_of(format!("__arg{}", i).as_slice());
pats.push(self.ecx.pat_ident(e.span, name));
locals.push(Context::format_arg(self.ecx, e.span, arg_ty,
self.ecx.expr_ident(e.span, name)));
heads.push(self.ecx.expr_addr_of(e.span, e));
}
for name in self.name_ordering.iter() {
let e = match self.names.remove(name) {
Some(e) => e,
None => continue
};
let arg_ty = match self.name_types.get(name) {
Some(ty) => ty,
None => continue
};
let lname = self.ecx.ident_of(format!("__arg{}",
*name).as_slice());
pats.push(self.ecx.pat_ident(e.span, lname));
names[self.name_positions[*name]] =
Some(Context::format_arg(self.ecx, e.span, arg_ty,
self.ecx.expr_ident(e.span, lname)));
heads.push(self.ecx.expr_addr_of(e.span, e));
}
// Now create a vector containing all the arguments
let slicename = self.ecx.ident_of("__args_vec");
{
let args = names.into_iter().map(|a| a.unwrap());
let args = locals.into_iter().chain(args);
let args = self.ecx.expr_vec_slice(self.fmtsp, args.collect());
lets.push(self.ecx.stmt_let(self.fmtsp, false, slicename, args));
}
// Now create the fmt::Arguments struct with all our locals we created.
let pieces = self.ecx.expr_ident(self.fmtsp, static_str_name);
let args_slice = self.ecx.expr_ident(self.fmtsp, slicename);
let (fn_name, fn_args) = if self.all_pieces_simple {
("new", vec![pieces, args_slice])
} else {
let fmt = self.ecx.expr_ident(self.fmtsp, static_args_name);
("with_placeholders", vec![pieces, fmt, args_slice])
};
let result = self.ecx.expr_call_global(self.fmtsp, vec!(
self.ecx.ident_of("std"),
self.ecx.ident_of("fmt"),
self.ecx.ident_of("Arguments"),
self.ecx.ident_of(fn_name)), fn_args);
// We did all the work of making sure that the arguments
// structure is safe, so we can safely have an unsafe block.
let result = self.ecx.expr_block(P(ast::Block {
view_items: Vec::new(),
stmts: Vec::new(),
expr: Some(result),
id: ast::DUMMY_NODE_ID,
rules: ast::UnsafeBlock(ast::CompilerGenerated),
span: self.fmtsp,
}));
let resname = self.ecx.ident_of("__args");
lets.push(self.ecx.stmt_let(self.fmtsp, false, resname, result));
let res = self.ecx.expr_ident(self.fmtsp, resname);
let result = match invocation {
Call(e) => {
let span = e.span;
self.ecx.expr_call(span, e,
vec!(self.ecx.expr_addr_of(span, res)))
}
MethodCall(e, m) => {
let span = e.span;
self.ecx.expr_method_call(span, e, m,
vec!(self.ecx.expr_addr_of(span, res)))
}
};
let body = self.ecx.expr_block(self.ecx.block(self.fmtsp, lets,
Some(result)));
// Constructs an AST equivalent to:
//
// match (&arg0, &arg1) {
// (tmp0, tmp1) => body
// }
//
// It was:
//
// let tmp0 = &arg0;
// let tmp1 = &arg1;
// body
//
// Because of #11585 the new temporary lifetime rule, the enclosing
// statements for these temporaries become the let's themselves.
// If one or more of them are RefCell's, RefCell borrow() will also
// end there; they don't last long enough for body to use them. The
// match expression solves the scope problem.
//
// Note, it may also very well be transformed to:
//
// match arg0 {
// ref tmp0 => {
// match arg1 => {
// ref tmp1 => body } } }
//
// But the nested match expression is proved to perform not as well
// as series of let's; the first approach does.
let pat = self.ecx.pat_tuple(self.fmtsp, pats);
let arm = self.ecx.arm(self.fmtsp, vec!(pat), body);
let head = self.ecx.expr(self.fmtsp, ast::ExprTup(heads));
self.ecx.expr_match(self.fmtsp, head, vec!(arm))
}
fn format_arg(ecx: &ExtCtxt, sp: Span,
ty: &ArgumentType, arg: P<ast::Expr>)
-> P<ast::Expr> {
let trait_ = match *ty {
Known(ref tyname) => {
match tyname.as_slice() {
"" => "Show",
"e" => "LowerExp",
"E" => "UpperExp",
"o" => "Octal",
"p" => "Pointer",
"b" => "Binary",
"x" => "LowerHex",
"X" => "UpperHex",
_ => {
ecx.span_err(sp,
format!("unknown format trait `{}`",
*tyname).as_slice());
"Dummy"
}
}
}
Unsigned => {
return ecx.expr_call_global(sp, vec![
ecx.ident_of("std"),
ecx.ident_of("fmt"),
ecx.ident_of("argumentuint")], vec![arg])
}
};
let format_fn = ecx.path_global(sp, vec![
ecx.ident_of("std"),
ecx.ident_of("fmt"),
ecx.ident_of(trait_),
ecx.ident_of("fmt")]);
ecx.expr_call_global(sp, vec![
ecx.ident_of("std"),
ecx.ident_of("fmt"),
ecx.ident_of("argument")], vec![ecx.expr_path(format_fn), arg])
}
}
pub fn expand_format_args<'cx>(ecx: &'cx mut ExtCtxt, sp: Span,
tts: &[ast::TokenTree])
-> Box<base::MacResult+'cx> {
match parse_args(ecx, sp, false, tts) {
(invocation, Some((efmt, args, order, names))) => {
MacExpr::new(expand_preparsed_format_args(ecx, sp, invocation, efmt,
args, order, names))
}
(_, None) => MacExpr::new(ecx.expr_uint(sp, 2))
}
}
/// Take the various parts of `format_args!(extra, efmt, args...,
/// name=names...)` and construct the appropriate formatting
/// expression.
pub fn expand_preparsed_format_args(ecx: &mut ExtCtxt, sp: Span,
invocation: Invocation,
efmt: P<ast::Expr>,
args: Vec<P<ast::Expr>>,
name_ordering: Vec<string::String>,
names: HashMap<string::String, P<ast::Expr>>)
-> P<ast::Expr> {
let arg_types = Vec::from_fn(args.len(), |_| None);
let mut cx = Context {
ecx: ecx,
args: args,
arg_types: arg_types,
names: names,
name_positions: HashMap::new(),
name_types: HashMap::new(),
name_ordering: name_ordering,
nest_level: 0,
next_arg: 0,
literal: string::String::new(),
pieces: Vec::new(),
str_pieces: Vec::new(),
all_pieces_simple: true,
method_statics: Vec::new(),
fmtsp: sp,
};
cx.fmtsp = efmt.span;
let fmt = match expr_to_string(cx.ecx,
efmt,
"format argument must be a string literal.") {
Some((fmt, _)) => fmt,
None => return DummyResult::raw_expr(sp)
};
let mut parser = parse::Parser::new(fmt.get());
loop {
match parser.next() {
Some(piece) => {
if parser.errors.len() > 0 { break }
cx.verify_piece(&piece);
match cx.trans_piece(&piece) {
Some(piece) => {
let s = cx.trans_literal_string();
cx.str_pieces.push(s);
cx.pieces.push(piece);
}
None => {}
}
}
None => break
}
}
match parser.errors.remove(0) {
Some(error) => {
cx.ecx.span_err(cx.fmtsp,
format!("invalid format string: {}",
error).as_slice());
return DummyResult::raw_expr(sp);
}
None => {}
}
if !cx.literal.is_empty() {
let s = cx.trans_literal_string();
cx.str_pieces.push(s);
}
// Make sure that all arguments were used and all arguments have types.
for (i, ty) in cx.arg_types.iter().enumerate() {
if ty.is_none() {
cx.ecx.span_err(cx.args[i].span, "argument never used");
}
}
for (name, e) in cx.names.iter() {
if !cx.name_types.contains_key(name) {
cx.ecx.span_err(e.span, "named argument never used");
}
}
cx.to_expr(invocation)
}<|fim▁end|>
| |
<|file_name|>lib_output.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv, sys, subprocess
from lib_time import *
<|fim▁hole|># normalize the dictionary with the word count to generate the wordcloud
def normalize_dict(dic):
max_elem = max(dic.values())
for key, value in dic.items():
normalized_val = int((100 * value)/max_elem)
if normalized_val == 0:
normalized_val = 1
dic[key]= normalized_val
return dic
# writes the normalized dict in a txt to be pasted manually in wordle.net
def dict_to_txt_for_wordle(dict_in, filename, sort_key=lambda t:t, value_key=lambda t:t):
if not dict_in:
dict_in = {'No hashtags found':1}
ordered_list = []
dict_in = normalize_dict(dict_in)
for key, value in dict_in.items():
ordered_list.append([key, value_key(value)])
ordered_list = sorted(ordered_list, key=sort_key, reverse=True)
out = open(filename, 'w', encoding= 'utf-8')
for item in ordered_list[:120]:
i = 0
while i < item[1]:
out.write(item[0] + ' ')
i+=1
out.close()
# creates a CSV file of the dictionary data received
def top_something_to_csv(dict_in, filename, column_titles, reverse, sort_key, value_format=lambda t: t):
ordered_list = []
for key, value in dict_in.items():
ordered_list.append([key, value_format(value)])
ordered_list = sorted(ordered_list, key=sort_key, reverse=reverse)
with open(filename, 'w', newline='', encoding="utf8") as csvfile:
file_writer = csv.writer(csvfile, delimiter='|', quotechar='"', quoting=csv.QUOTE_MINIMAL)
file_writer.writerow(column_titles)
for item in ordered_list:
file_writer.writerow([item[0], item[1]])
csvfile.close()
# writes a CSV file in the following format:
# post_type | interactions_# | %_of_total
# where interactions can be shares, likes or comments
def int_dictionary_to_csv(int_dict_in, filename, column_titles):
total = sum(int_dict_in.values())
float_dict_post_percent = {}
for key, value in int_dict_in.items():
float_dict_post_percent[key] = (value * 100)/total
with open(filename, 'w', newline='', encoding="utf8") as csvfile:
file_writer = csv.writer(csvfile, delimiter='|', quotechar='"', quoting=csv.QUOTE_MINIMAL)
file_writer.writerow(column_titles)
for key, value in float_dict_post_percent.items():
file_writer.writerow([key, int_dict_in[key], float_to_percentage(value)])
# writes a CSV file in the following format:
# date(dd/mm/yyyy) | post_type | post_text| interactions_#
# where interactions can be shares, likes or comments and post_type can be status, photo, video or share
def int_dictionary_interactions_summary_to_csv(int_dict_comments_in, int_dict_shares_in, int_dict_likes_in, filename):
column_titles = ['post_type', 'comments_#', 'comments_%', '', 'likes_#', 'likes_%','', 'shares_#', 'shares_%',]
total_comments = sum(int_dict_comments_in.values())
total_shares = sum(int_dict_shares_in.values())
total_likes = sum(int_dict_likes_in.values())
with open(filename, 'w', newline='', encoding="utf8") as csvfile:
file_writer = csv.writer(csvfile, delimiter='|', quotechar='"', quoting=csv.QUOTE_MINIMAL)
file_writer.writerow(column_titles)
for key in int_dict_comments_in.keys():
pct_comments = (int_dict_comments_in[key]*100)/total_comments
pct_likes = (int_dict_likes_in[key]*100)/total_likes
pct_shares = (int_dict_shares_in[key]*100)/total_shares
file_writer.writerow([key, int_dict_comments_in[key], float_to_percentage(pct_comments),' ', int_dict_likes_in[key], float_to_percentage(pct_likes), ' ', int_dict_shares_in[key], float_to_percentage(pct_shares)])
# writes a CSV file in the following format:
# dd/mm/YYYY | post_type | post_text | interactions_#
# where interactions can be shares, likes or comments
def interactions_summary_to_csv(list_summary, filename, column_titles):
list_summary = sorted(list_summary, key = lambda x: x[0])
with open(filename, 'w', newline='', encoding="utf8") as csvfile:
file_writer = csv.writer(csvfile, delimiter='|', quotechar='"', quoting=csv.QUOTE_MINIMAL)
file_writer.writerow(column_titles)
for item in list_summary:
line = [timestamp_to_str_date(item[0])] + item[1:]
file_writer.writerow(line)
# creates a CSV file of the dictionary data received
def top_something_to_csv(dict_in, filename, column_titles, reverse, sort_key, value_format=lambda t: t):
ordered_list = []
for key, value in dict_in.items():
ordered_list.append([key, value_format(value)])
ordered_list = sorted(ordered_list, key=sort_key, reverse=reverse)
with open(filename, 'w', newline='', encoding="utf8") as csvfile:
file_writer = csv.writer(csvfile, delimiter='|', quotechar='"', quoting=csv.QUOTE_MINIMAL)
file_writer.writerow(column_titles)
for item in ordered_list:
file_writer.writerow([item[0], item[1]])
csvfile.close()
def comments_timeline():
list_datetime_commments = []
with open('comments.tab', 'rt', encoding="utf8") as csvfile:
csv_in = csv.reader(csvfile, delimiter='\t')
next(csv_in)
for line in csv_in:
str_raw_time = line[3]
temp_datetime = datetime.datetime.strptime(str_raw_time, "%Y-%m-%dT%H:%M:%S+0000")
list_datetime_commments.append(temp_datetime)
dict_int_str_date = comments_per_day(list_datetime_commments)
dict_int_str_date_hour = comments_per_hour(list_datetime_commments)
top_something_to_csv(dict_int_str_date, 'comments_per_day.csv', ['date', 'number_of_comments'], reverse=False, sort_key=lambda t: datetime.date(int(t[0][6:]), int(t[0][3:5]), int(t[0][:2])))
top_something_to_csv(dict_int_str_date_hour, 'comments_per_hour.csv', ['date', 'number_of_comments'], reverse=False, sort_key=lambda t: datetime.datetime.strptime(t[0], "%d/%m/%Y %H"))
def write_top_comment_replies(top_comments_list):
with open('top_comments_replies.csv', 'w', newline='', encoding="utf8") as csvfile:
file_writer = csv.writer(csvfile, delimiter='|', quotechar='"', quoting=csv.QUOTE_MINIMAL)
file_writer.writerow(['post_text', 'comment_text', 'likes_#'])
for item in top_comments_list:
if item[3] == '1':
file_writer.writerow([item[0], item[1], item[2]])
def write_top_comments(top_comments_list):
with open('top_comments.csv', 'w', newline='', encoding="utf8") as csvfile:
file_writer = csv.writer(csvfile, delimiter='|', quotechar='"', quoting=csv.QUOTE_MINIMAL)
file_writer.writerow(['post_text', 'comment_text', 'likes_#', 'is_reply'])
for item in top_comments_list:
file_writer.writerow(item)
def cleanup_posts():
subprocess.call(["sh", "cleanup_posts.sh"])
def cleanup_comments():
subprocess.call(["sh", "cleanup_comments.sh"])<|fim▁end|>
|
# returns the given float number with only 2 decimals and a % appended
def float_to_percentage(float_number):
return("%0.2f" % float_number +"%")
|
<|file_name|>push_reducer.ts<|end_file_name|><|fim▁begin|>import {JSONAPIDataObject, JSONAPIListResponse} from "../json-api";
import * as actions from "./push_actions";
import {Certificate} from "./types";
export interface PushState {
items?: JSONAPIListResponse<JSONAPIDataObject<Certificate>>;
loading: boolean;
error: boolean;
errorDetail?: any
lastReceived?: Date;
}
const initialState: PushState = {
loading: false,
error: false,
errorDetail: null,
lastReceived: null,
};
export type PushAction = actions.FetchPushCertificatesActionResponse;
export function push(state: PushState = initialState, action: PushAction): PushState {
switch (action.type) {
case actions.PUSHCERT_REQUEST:
return {<|fim▁hole|> case actions.PUSHCERT_FAILURE:
return {
...state,
loading: false,
error: true,
errorDetail: action.payload,
};
case actions.PUSHCERT_SUCCESS:
return {
...state,
items: action.payload,
lastReceived: new Date(),
error: false,
errorDetail: null,
};
default:
return state;
}
}<|fim▁end|>
|
...state,
loading: true,
};
|
<|file_name|>test_IndependentDiscretization.py<|end_file_name|><|fim▁begin|>from rlpy.Representations import IndependentDiscretization<|fim▁hole|>
def test_number_of_cells():
""" Ensure create appropriate # of cells (despite ``discretization``) """
mapDir = os.path.join(__rlpy_location__, "Domains", "GridWorldMaps")
mapname=os.path.join(mapDir, "4x5.txt") # expect 4*5 = 20 states
domain = GridWorld(mapname=mapname)
rep = IndependentDiscretization(domain, discretization=100)
assert rep.features_num == 9
rep = IndependentDiscretization(domain, discretization=5)
assert rep.features_num == 9
def test_phi_cells():
""" Ensure correct features are activated for corresponding state """
mapDir = os.path.join(__rlpy_location__, "Domains", "GridWorldMaps")
mapname=os.path.join(mapDir, "4x5.txt") # expect 4*5 = 20 states
domain = GridWorld(mapname=mapname)
rep = IndependentDiscretization(domain)
for r in np.arange(4):
for c in np.arange(5):
phiVec = rep.phi(np.array([r,c]), terminal=False)
assert sum(phiVec) == 2 # 1 for each dimension
assert phiVec[r] == 1 # correct row activated
assert phiVec[4+c] == 1 # correct col activated
def test_continuous_discr():
""" Ensure correct discretization in continuous state spaces """
# NOTE - if possible, test a domain with mixed discr/continuous
domain = InfiniteTrackCartPole.InfTrackCartPole() #2 continuous dims
rep = IndependentDiscretization(domain, discretization=20)
assert rep.features_num == 40
rep = IndependentDiscretization(domain, discretization=50)
assert rep.features_num == 100<|fim▁end|>
|
from rlpy.Domains import GridWorld, InfiniteTrackCartPole
import numpy as np
from rlpy.Tools import __rlpy_location__
import os
|
<|file_name|>export.rs<|end_file_name|><|fim▁begin|>pub mod cf;
pub mod container;
mod export_common;
pub mod mesos;<|fim▁hole|><|fim▁end|>
|
pub mod tar;
|
<|file_name|>platform-examples.component.ts<|end_file_name|><|fim▁begin|>import { Component, ChangeDetectionStrategy } from "@angular/core";
import { Link } from "./../../link";
let menuLinks = [
new Link("Usage", "/platform/usage")
];
@Component({
moduleId: module.id,
templateUrl: "./../../examples-list.component.html",
changeDetection: ChangeDetectionStrategy.OnPush
})
export class PlatformExamplesComponent {
public links: Array<Link>;
constructor() {
this.links = [];<|fim▁hole|> this.links.push(menuLinks[i]);
}
}
}<|fim▁end|>
|
for (let i = 0; i < menuLinks.length; i++) {
|
<|file_name|>test_sphere.py<|end_file_name|><|fim▁begin|>from impedance_map.sphere import correlation_coefficient, form_factor, \
pair_distribution_function_PY, structure_factor_function_PY, \
cross_section_dimension, fit_correlation_coefficient_nls, \
fit_form_factor_nls
import numpy as np
import math
import unittest
class TestCode(unittest.TestCase):
def test1_sphere_cross_section_dimension(self):
a = 1
q = 0
A = cross_section_dimension(a, q)
A_real = 1
self.assertTrue(A == A_real)
def test2_sphere_cross_section_dimension(self):
a = 1
q = 1
A = cross_section_dimension(a, q)
A_real = 0
self.assertTrue(A == A_real)
def test3_sphere_cross_section_dimension(self):
a = 1
q = 0.5
A = cross_section_dimension(a, q)
A_real = np.sqrt(1 - 0.5 ** 2)
self.assertTrue(A == A_real)
def test1_sphere_form_factor(self):
ndim = 1
a = 1
k = np.linspace(0, 6, 7)
H = form_factor(k=k, a=a, ndim=ndim)
Hr = np.array([1., 0.70807342, 0.20670545, 0.00221276, 0.03579688,
0.03678143, 0.0021687])
self.assertTrue(np.allclose(H, Hr))
def test2_sphere_form_factor(self):
ndim = 2
a = 1
k = np.linspace(0, 6, 7)
H = form_factor(k=k, a=a, ndim=ndim)
Hr = np.array([1., 0.77457807, 0.3326115, 0.05109377, 0.00109043,
0.01716929, 0.008506])
self.assertTrue(np.allclose(H, Hr))
def test3_sphere_form_factor(self):
ndim = 3
a = 1
k = np.linspace(0, 6, 7)
H = form_factor(k=k, a=a, ndim=ndim)
Hr = np.array([1., 0.81632316, 0.42653525, 0.11949293, 0.00758346,
0.00325512, 0.00703836])
self.assertTrue(np.allclose(H, Hr))
def test1_sphere_corr_coeff(self):
ndim = 1
a = 1.
r = np.linspace(0., 2., 11)
b = correlation_coefficient(ndim=ndim, a=a, r=r)
b_real = np.linspace(1., 0., 11)
self.assertTrue(np.allclose(b, b_real))
def test2_sphere_corr_coeff(self):
ndim = 1
a = 1.
r = np.linspace(0., 3., 16)
b = correlation_coefficient(ndim=ndim, a=a, r=r)
b_real = np.zeros(len(r))
b_real[0:11] = np.linspace(1., 0., 11)
self.assertTrue(np.allclose(b, b_real))
def test3_sphere_corr_coeff(self):
ndim = 1
a = 3.
r = np.linspace(0., 6., 11)
b = correlation_coefficient(ndim=ndim, a=a, r=r)
b_real = np.linspace(1., 0., 11)
self.assertTrue(np.allclose(b, b_real))
def test4_sphere_corr_coeff(self):
ndim = 1
a = 0.0
r = np.linspace(0., 6., 11)
b = correlation_coefficient(ndim=ndim, a=a, r=r)
b_real = np.zeros(11)
self.assertTrue(np.allclose(b, b_real))
def test5_sphere_corr_coeff(self):
ndim = 2
a = 1.
r = np.linspace(0., 2., 6)
b = correlation_coefficient(ndim=ndim, a=a, r=r)
b_real = np.array([1., 0.74706008, 0.50463158, 0.28475698, 0.10408804,
0.])
self.assertTrue(np.allclose(b, b_real))
def test6_sphere_corr_coeff(self):
ndim = 2
a = 1.
r = np.linspace(0., 3.2, 9)
b = correlation_coefficient(ndim=ndim, a=a, r=r)
b_real = np.array([1., 0.74706008, 0.50463158, 0.28475698, 0.10408804,
0., 0., 0., 0.])
self.assertTrue(np.allclose(b, b_real))
def test7_sphere_corr_coeff(self):
ndim = 2
a = 3.
r = np.linspace(0., 6., 6)
b = correlation_coefficient(ndim=ndim, a=a, r=r)
b_real = np.array([1., 0.74706008, 0.50463158, 0.28475698, 0.10408804,
0.])
self.assertTrue(np.allclose(b, b_real))
def test8_sphere_corr_coeff(self):
ndim = 2
a = 0.0
r = np.linspace(0., 6., 6)
b = correlation_coefficient(ndim=ndim, a=a, r=r)
b_real = np.zeros(6)
self.assertTrue(np.allclose(b, b_real))
def test9_sphere_corr_coeff(self):
ndim = 3
a = 1.
r = np.linspace(0., 2., 6)
b = correlation_coefficient(ndim=ndim, a=a, r=r)
b_real = np.array([1., 0.704, 0.432, 0.208, 0.056, 0.])
self.assertTrue(np.allclose(b, b_real))
def test10_sphere_corr_coeff(self):
ndim = 3
a = 1.
r = np.linspace(0., 3.2, 9)
b = correlation_coefficient(ndim=ndim, a=a, r=r)
b_real = np.array([1., 0.704, 0.432, 0.208, 0.056, 0., 0., 0., 0.])
self.assertTrue(np.allclose(b, b_real))
def test11_sphere_corr_coeff(self):
ndim = 3
a = 3.
r = np.linspace(0., 6., 6)
b = correlation_coefficient(ndim=ndim, a=a, r=r)
b_real = np.array([1., 0.704, 0.432, 0.208, 0.056, 0.])
self.assertTrue(np.allclose(b, b_real))
def test13_sphere_corr_coeff(self):
ndim = 3
a = 0.0
r = np.linspace(0., 6., 6)
b = correlation_coefficient(ndim=ndim, a=a, r=r)
b_real = np.zeros(6)
self.assertTrue(np.allclose(b, b_real))
def test1_pair_distribution_function_PY(self):
f = 0.4
a = 0.01
rb = np.linspace(1, 5, 5)
r = rb * 2 * a
g = pair_distribution_function_PY(r, a, f)
g_real = np.asarray([ 1.665534 , 1.14167826, 1.04312259, 1.01389934, 1.00453527])
self.assertTrue(np.allclose(g, g_real))
def test1_structure_factor_function_PY(self):
k = np.linspace(0, 10, 5)
f = 0.15
a = 0.01
S = structure_factor_function_PY(k/a, a=0.01, f=0.15)
S_real = np.asarray([ 0.30887944, 1.03988757, 0.95564256, 0.98177134, 1.00532684])
self.assertTrue(np.allclose(S, S_real))
def test1_fit_correlation_coefficient_nls(self):
a = 0.75
r = np.linspace(0, 3., 10)
y = correlation_coefficient(a=a, r=r)
a_guess = fit_correlation_coefficient_nls(r, y)
self.assertTrue(np.allclose(a, a_guess))
def test1_fit_form_factor_nls(self):
a = 0.75
k = np.linspace(0.01, 3, 10)
y = form_factor(a=a, k=k)
a_guess = fit_form_factor_nls(k, y)<|fim▁hole|>if __name__ == '__main__':
print 'Running unit tests for impedance_map.sphere'
unittest.main()<|fim▁end|>
|
self.assertTrue(np.allclose(a, a_guess))
|
<|file_name|>win_delay_load_hook.rs<|end_file_name|><|fim▁begin|>//! Rust port of [win_delay_load_hook.cc][].
//!
//! When the addon tries to load the "node.exe" DLL module, this module gives it the pointer to the
//! .exe we are running in instead. Typically, that will be the same value. But if the node executable
//! was renamed, you would not otherwise get the correct DLL.
//!
//! [win_delay_load_hook.cc]: https://github.com/nodejs/node-gyp/blob/e18a61afc1669d4897e6c5c8a6694f4995a0f4d6/src/win_delay_load_hook.cc
<|fim▁hole|>use winapi::um::libloaderapi::GetModuleHandleA;
use std::ffi::CStr;
use std::ptr::null_mut;
// Structures hand-copied from
// https://docs.microsoft.com/en-us/cpp/build/reference/structure-and-constant-definitions
#[repr(C)]
#[allow(non_snake_case)]
struct DelayLoadProc {
fImportByName: BOOL,
// Technically this is `union{LPCSTR; DWORD;}` but we don't access it anyways.
szProcName: LPCSTR,
}
#[repr(C)]
#[allow(non_snake_case)]
struct DelayLoadInfo {
/// size of structure
cb: DWORD,
/// raw form of data (everything is there)
/// Officially a pointer to ImgDelayDescr but we don't access it.
pidd: LPVOID,
/// points to address of function to load
ppfn: *mut FARPROC,
/// name of dll
szDll: LPCSTR,
/// name or ordinal of procedure
dlp: DelayLoadProc,
/// the hInstance of the library we have loaded
hmodCur: HMODULE,
/// the actual function that will be called
pfnCur: FARPROC,
/// error received (if an error notification)
dwLastError: DWORD,
}
#[allow(non_snake_case)]
type PfnDliHook = unsafe extern "C" fn(dliNotify: usize, pdli: *const DelayLoadInfo) -> FARPROC;
const HOST_BINARIES: &[&[u8]] = &[b"node.exe", b"electron.exe"];
unsafe extern "C" fn load_exe_hook(event: usize, info: *const DelayLoadInfo) -> FARPROC {
if event != 0x01 /* dliNotePreLoadLibrary */ {
return null_mut();
}
let dll_name = CStr::from_ptr((*info).szDll);
if !HOST_BINARIES.iter().any(|&host_name| host_name == dll_name.to_bytes()) {
return null_mut();
}
let exe_handle = GetModuleHandleA(null_mut());
// PfnDliHook sometimes has to return a FARPROC, sometimes an HMODULE, but only one
// of them could be specified in the header, so we have to cast our HMODULE to that.
exe_handle as FARPROC
}
#[no_mangle]
static mut __pfnDliNotifyHook2: *mut PfnDliHook = load_exe_hook as *mut PfnDliHook;<|fim▁end|>
|
use winapi::shared::minwindef::{BOOL, DWORD, FARPROC, HMODULE, LPVOID};
use winapi::shared::ntdef::LPCSTR;
|
<|file_name|>wizard.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2015 thomasv@gitorious, kyuupichan@gmail
#
# 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.
from electrum import WalletStorage
from electrum.plugins import run_hook
from util import PrintError
from wallet import Wallet
from i18n import _
MSG_GENERATING_WAIT = _("Electrum is generating your addresses, please wait...")
MSG_ENTER_ANYTHING = _("Please enter a seed phrase, a master key, a list of "
"Unobtanium addresses, or a list of private keys")
MSG_ENTER_SEED_OR_MPK = _("Please enter a seed phrase or a master key (xpub or xprv):")
MSG_VERIFY_SEED = _("Your seed is important!\nTo make sure that you have properly saved your seed, please retype it here.")
MSG_COSIGNER = _("Please enter the master public key of cosigner #%d:")
MSG_SHOW_MPK = _("Here is your master public key:")
MSG_ENTER_PASSWORD = _("Choose a password to encrypt your wallet keys. "
"Enter nothing if you want to disable encryption.")
MSG_RESTORE_PASSPHRASE = \
_("Please enter the passphrase you used when creating your %s wallet. "
"Note this is NOT a password. Enter nothing if you did not use "
"one or are unsure.")
class WizardBase(PrintError):
'''Base class for gui-specific install wizards.'''
user_actions = ('create', 'restore')
wallet_kinds = [
('standard', _("Standard wallet")),
('multisig', _("Multi-signature wallet")),
]
# Derived classes must set:
# self.language_for_seed
# self.plugins
def show_error(self, msg):
raise NotImplementedError
def show_warning(self, msg):
raise NotImplementedError
<|fim▁hole|> def remove_from_recently_open(self, filename):
"""Remove filename from the recently used list."""
raise NotImplementedError
def query_create_or_restore(self, wallet_kinds):
"""Ask the user what they want to do, and which wallet kind.
wallet_kinds is an array of translated wallet descriptions.
Return a a tuple (action, kind_index). Action is 'create' or
'restore', and kind the index of the wallet kind chosen."""
raise NotImplementedError
def query_multisig(self, action):
"""Asks the user what kind of multisig wallet they want. Returns a
string like "2of3". Action is 'create' or 'restore'."""
raise NotImplementedError
def query_choice(self, msg, choices):
"""Asks the user which of several choices they would like.
Return the index of the choice."""
raise NotImplementedError
def query_hw_wallet_choice(self, msg, action, choices):
"""Asks the user which hardware wallet kind they are using. Action is
'create' or 'restore' from the initial screen. As this is
confusing for hardware wallets ask a new question with the
three possibilities Initialize ('create'), Use ('create') or
Restore a software-only wallet ('restore'). Return a pair
(action, choice)."""
raise NotImplementedError
def show_and_verify_seed(self, seed):
"""Show the user their seed. Ask them to re-enter it. Return
True on success."""
raise NotImplementedError
def request_passphrase(self, device_text, restore=True):
"""Request a passphrase for a wallet from the given device and
confirm it. restore is True if restoring a wallet. Should return
a unicode string."""
raise NotImplementedError
def request_password(self, msg=None):
"""Request the user enter a new password and confirm it. Return
the password or None for no password."""
raise NotImplementedError
def request_seed(self, msg, is_valid=None):
"""Request the user enter a seed. Returns the seed the user entered.
is_valid is a function that returns True if a seed is valid, for
dynamic feedback. If not provided, Wallet.is_any is used."""
raise NotImplementedError
def request_many(self, n, xpub_hot=None):
"""If xpub_hot is provided, a new wallet is being created. Request N
master public keys for cosigners; xpub_hot is the master xpub
key for the wallet.
If xpub_hot is None, request N cosigning master xpub keys,
xprv keys, or seeds in order to perform wallet restore."""
raise NotImplementedError
def choose_server(self, network):
"""Choose a server if one is not set in the config anyway."""
raise NotImplementedError
def show_restore(self, wallet, network):
"""Show restore result"""
pass
def finished(self):
"""Called when the wizard is done."""
pass
def run(self, network, storage):
'''The main entry point of the wizard. Open a wallet from the given
filename. If the file doesn't exist launch the GUI-specific
install wizard proper, created by calling create_wizard().'''
need_sync = False
is_restore = False
if storage.file_exists:
wallet = Wallet(storage)
if wallet.imported_keys:
self.update_wallet_format(wallet)
else:
cr, wallet = self.create_or_restore(storage)
if not wallet:
return
need_sync = True
is_restore = (cr == 'restore')
while True:
action = wallet.get_action()
if not action:
break
need_sync = True
self.run_wallet_action(wallet, action)
# Save the wallet after each action
wallet.storage.write()
if network:
# Show network dialog if config does not exist
if self.config.get('auto_connect') is None:
self.choose_server(network)
else:
self.show_warning(_('You are offline'))
if need_sync:
self.create_addresses(wallet)
# start wallet threads
if network:
wallet.start_threads(network)
if is_restore:
self.show_restore(wallet, network)
self.finished()
return wallet
def run_wallet_action(self, wallet, action):
self.print_error("action %s on %s" % (action, wallet.basename()))
# Run the action on the wallet plugin, if any, then the
# wallet and finally ourselves
calls = []
if hasattr(wallet, 'plugin'):
calls.append((wallet.plugin, (wallet, self)))
calls.extend([(wallet, ()), (self, (wallet, ))])
calls = [(getattr(actor, action), args) for (actor, args) in calls
if hasattr(actor, action)]
if not calls:
raise RuntimeError("No handler found for %s action" % action)
for method, args in calls:
method(*args)
def create_or_restore(self, storage):
'''After querying the user what they wish to do, create or restore
a wallet and return it.'''
self.remove_from_recently_open(storage.path)
# Filter out any unregistered wallet kinds
registered_kinds = Wallet.categories()
kinds, descriptions = zip(*[pair for pair in WizardBase.wallet_kinds
if pair[0] in registered_kinds])
action, kind_index = self.query_create_or_restore(descriptions)
assert action in WizardBase.user_actions
kind = kinds[kind_index]
if kind == 'multisig':
wallet_type = self.query_multisig(action)
elif kind == 'hardware':
# The create/restore distinction is not obvious for hardware
# wallets; so we ask for the action again and default based
# on the prior choice :)
hw_wallet_types, choices = self.plugins.hardware_wallets(action)
msg = _('Select the type of hardware wallet: ')
action, choice = self.query_hw_wallet_choice(msg, action, choices)
wallet_type = hw_wallet_types[choice]
elif kind == 'twofactor':
wallet_type = '2fa'
else:
wallet_type = 'standard'
if action == 'create':
wallet = self.create_wallet(storage, wallet_type, kind)
else:
wallet = self.restore_wallet(storage, wallet_type, kind)
return action, wallet
def construct_wallet(self, storage, wallet_type):
storage.put('wallet_type', wallet_type)
return Wallet(storage)
def create_wallet(self, storage, wallet_type, kind):
wallet = self.construct_wallet(storage, wallet_type)
if kind == 'hardware':
wallet.plugin.on_create_wallet(wallet, self)
return wallet
def restore_wallet(self, storage, wallet_type, kind):
if wallet_type == 'standard':
return self.restore_standard_wallet(storage)
if kind == 'multisig':
return self.restore_multisig_wallet(storage, wallet_type)
# Plugin (two-factor or hardware)
wallet = self.construct_wallet(storage, wallet_type)
return wallet.plugin.on_restore_wallet(wallet, self)
def restore_standard_wallet(self, storage):
text = self.request_seed(MSG_ENTER_ANYTHING)
need_password = Wallet.should_encrypt(text)
password = self.request_password() if need_password else None
return Wallet.from_text(text, password, storage)
def restore_multisig_wallet(self, storage, wallet_type):
# FIXME: better handling of duplicate keys
m, n = Wallet.multisig_type(wallet_type)
key_list = self.request_many(n - 1)
need_password = any(Wallet.should_encrypt(text) for text in key_list)
password = self.request_password() if need_password else None
return Wallet.from_multisig(key_list, password, storage, wallet_type)
def create_seed(self, wallet):
'''The create_seed action creates a seed and generates
master keys.'''
seed = wallet.make_seed(self.language_for_seed)
self.show_and_verify_seed(seed)
password = self.request_password()
wallet.add_seed(seed, password)
wallet.create_master_keys(password)
def create_main_account(self, wallet):
# FIXME: BIP44 restore requires password
wallet.create_main_account()
def create_addresses(self, wallet):
wallet.synchronize()
def add_cosigners(self, wallet):
# FIXME: better handling of duplicate keys
m, n = Wallet.multisig_type(wallet.wallet_type)
xpub1 = wallet.master_public_keys.get("x1/")
xpubs = self.request_many(n - 1, xpub1)
for i, xpub in enumerate(xpubs):
wallet.add_master_public_key("x%d/" % (i + 2), xpub)
def update_wallet_format(self, wallet):
# Backwards compatibility: convert old-format imported keys
msg = _("Please enter your password in order to update "
"imported keys")
if wallet.use_encryption:
password = self.request_password(msg)
else:
password = None
try:
wallet.convert_imported_keys(password)
except Exception as e:
self.show_error(str(e))
# Call synchronize to regenerate addresses in case we're offline
if wallet.get_master_public_keys() and not wallet.addresses():
wallet.synchronize()<|fim▁end|>
| |
<|file_name|>1000.cpp<|end_file_name|><|fim▁begin|>// 1000. 连通性问题
#include <iostream>
using namespace std;
int unionFind[100001];
int find(int val) {
if (val == unionFind[val]) return val;
unionFind[val] = find(unionFind[val]);
return unionFind[val];
}<|fim▁hole|>int main() {
int a, b;
for (int i = 0; i < 100001; i++) {
unionFind[i] = i;
}
while (cin >> a >> b) {
if (find(a) != find(b)) {
cout << a << ' ' << b << endl;
unionFind[find(a)] = unionFind[find(b)];
}
}
}<|fim▁end|>
| |
<|file_name|>list.rs<|end_file_name|><|fim▁begin|>use clap::ArgMatches;
use doapi::{DoManager, DoRequest};
use config::Config;
use message::CliMessage;
pub fn run(m: &ArgMatches, cfg: &mut Config) {
if m.is_present("verbose") {
cfg.verbose = true;
}
if m.is_present("nosend") {
cfg.no_send = true;
}
let domgr = DoManager::with_token(&cfg.auth[..]);
match m.subcommand() {
("regions", Some(m)) => {
if cfg.verbose || m.is_present("verbose") {
CliMessage::Request(
&domgr.regions()
.to_string()
.replace("\n", "\n\t")[..]).display();
}
if cfg.no_send || m.is_present("nosend") {
return;
}
if cfg.verbose || m.is_present("verbose") {
CliMessage::JsonResponse.display();
match domgr.regions().retrieve_json() {
Ok(s) => {
CliMessage::Success.display();
println!("\n\t{}\n", s);
}
Err(e) => {
CliMessage::Failure.display();
println!("\n\t{}\n", e);
}
}
}
CliMessage::Regions.display();
match domgr.regions().retrieve() {
Ok(v) => {
CliMessage::Success.display();
for reg in v.iter() {
CliMessage::Region.display();
println!("\t{}\n", ®.to_string()[..].replace("\n", "\n\t"));
}
if v.is_empty() {
println!("\tNo regions to dipslay");
}
}
Err(e) => {
CliMessage::Failure.display();
println!("{}\n", e);
}
}
}
("sizes", Some(m)) => {
if cfg.verbose || m.is_present("verbose") {
CliMessage::Request(
&domgr.sizes()
.to_string()
.replace("\n", "\n\t")[..]).display();
}
if cfg.no_send || m.is_present("nosend") {
return;
}
if cfg.verbose || m.is_present("verbose") {
CliMessage::JsonResponse.display();
match domgr.sizes().retrieve_json() {
Ok(s) => {
CliMessage::Success.display();
println!("\n\t{}\n", s);
}
Err(e) => {
CliMessage::Failure.display();
println!("\n\t{}\n", e);
}
}
}
CliMessage::Sizes.display();
match domgr.sizes().retrieve() {
Ok(v) => {
CliMessage::Success.display();
for siz in v.iter() {
CliMessage::Size.display();
println!("\t{}\n", &siz.to_string()[..].replace("\n", "\n\t"));
}
if v.is_empty() {
println!("\tNo sizes to dipslay");
}
}
Err(e) => {
CliMessage::Failure.display();
println!("{}\n", e);
}
}
}
("images", Some(m)) => {
let request = if m.is_present("applications") {
domgr.images().applications()
} else if m.is_present("distributions") {
domgr.images().distributions()
} else if m.is_present("private") {
domgr.images().private()
} else if m.is_present("available") {
domgr.images().available()
} else {
domgr.images()
};
if cfg.verbose || m.is_present("verbose") {
CliMessage::Request(
&request.to_string()
.replace("\n", "\n\t")[..]
).display();
}
if cfg.no_send || m.is_present("nosend") {
return;
}
if cfg.verbose || m.is_present("verbose") {
CliMessage::JsonResponse.display();
match request.retrieve_json() {
Ok(s) => {
CliMessage::Success.display();
println!("\n\t{}\n", s);
}
Err(e) => {
CliMessage::Failure.display();
println!("\n\t{}\n", e);
}
}
}
CliMessage::Images.display();
match request.retrieve() {
Ok(v) => {
CliMessage::Success.display();
for img in v.iter() {
CliMessage::ImageList.display();
println!("\t{}\n", &img.to_string()[..].replace("\n", "\n\t"));
}
if v.is_empty() {
println!("\tNo images to dipslay");
}
}
Err(e) => {
CliMessage::Failure.display();
println!("{}\n", e);
}
}
}
("ssh-keys", Some(m)) => {
if cfg.verbose || m.is_present("verbose") {
CliMessage::Request(
&domgr.ssh_keys()
.to_string()
.replace("\n", "\n\t")[..]).display();
}
if cfg.no_send || m.is_present("nosend") {
return;
}
if cfg.verbose || m.is_present("verbose") {
CliMessage::JsonResponse.display();
match domgr.ssh_keys().retrieve_json() {
Ok(s) => {
CliMessage::Success.display();
println!("\n\t{}\n", s);
}
Err(e) => {
CliMessage::Failure.display();
println!("\n\t{}\n", e);
}
}
}
CliMessage::SshKeys.display();
match domgr.ssh_keys().retrieve() {
Ok(v) => {
CliMessage::Success.display();
for k in v.iter() {
CliMessage::AnonSshKey.display();
println!("\t{}\n", &k.to_string()[..].replace("\n", "\n\t"));
}
if v.is_empty() {
println!("\tNo SSH keys to dipslay");
}
}
Err(e) => {
CliMessage::Failure.display();
println!("{}\n", e);
}
}
}
("droplets", Some(m)) => {
if cfg.verbose || m.is_present("verbose") {
CliMessage::Request(
&domgr.droplets()
.to_string()
.replace("\n", "\n\t")[..]).display();
}
if cfg.no_send || m.is_present("nosend") {
return;
}
if cfg.verbose || m.is_present("verbose") {
CliMessage::JsonResponse.display();
match domgr.droplets().retrieve_json() {
Ok(s) => {
CliMessage::Success.display();
println!("\n\t{}\n", s);
}
Err(e) => {
CliMessage::Failure.display();
println!("\n\t{}\n", e);
}
}
}
CliMessage::Droplets.display();
match domgr.droplets().retrieve() {
Ok(v) => {
CliMessage::Success.display();
for d in v.iter() {
CliMessage::AnonDroplet.display();
println!("\t{}", &d.to_string()[..].replace("\n", "\n\t"));
}
if v.is_empty() {
println!("\tNo droplets to dipslay");
}
}
Err(e) => {
CliMessage::Failure.display();
println!("{}\n", e);
}
}
}<|fim▁hole|> .to_string()
.replace("\n", "\n\t")[..]).display();
}
if cfg.no_send || m.is_present("nosend") {
return;
}
if cfg.verbose || m.is_present("verbose") {
CliMessage::JsonResponse.display();
match domgr.domains().retrieve_json() {
Ok(s) => {
CliMessage::Success.display();
println!("\n\t{}\n", s);
}
Err(e) => {
CliMessage::Failure.display();
println!("\n\t{}\n", e);
}
}
}
CliMessage::Domains.display();
match domgr.domains().retrieve() {
Ok(v) => {
CliMessage::Success.display();
for d in v.iter() {
CliMessage::Domains.display();
println!("\t{}\n", &d.to_string()[..].replace("\n", "\n\t"));
}
if v.is_empty() {
println!("\tNo domains to dipslay");
}
}
Err(e) => {
CliMessage::Failure.display();
println!("{}\n", e);
}
}
}
("account-actions", Some(m)) => {
if cfg.verbose || m.is_present("verbose") {
CliMessage::Request(
&domgr.account()
.actions()
.to_string()
.replace("\n", "\n\t")[..]).display();
}
if cfg.no_send || m.is_present("nosend") {
return;
}
if cfg.verbose || m.is_present("verbose") {
CliMessage::JsonResponse.display();
match domgr.account().actions().retrieve_json() {
Ok(s) => {
CliMessage::Success.display();
println!("\n\t{}\n", s);
}
Err(e) => {
CliMessage::Failure.display();
println!("\n\t{}\n", e);
}
}
}
CliMessage::Actions.display();
match domgr.account().actions().retrieve() {
Ok(v) => {
CliMessage::Success.display();
for act in v.iter() {
CliMessage::Action.display();
println!("\t{}\n", &act.to_string()[..].replace("\n", "\n\t"));
}
if v.is_empty() {
println!("\tNo account actions to dipslay");
}
}
Err(e) => {
CliMessage::Failure.display();
println!("{}\n", e);
}
}
}
_ => unreachable!(),
}
}<|fim▁end|>
|
("domains", Some(m)) => {
if cfg.verbose || m.is_present("verbose") {
CliMessage::Request(
&domgr.domains()
|
<|file_name|>review_gui_helper.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (C) 2009 Canonical
#
# Authors:
# Michael Vogt
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; version 3.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
from gi.repository import GObject, Gtk, Gdk
import datetime
import gettext
import logging
import os
import json
import sys
import tempfile
import time
import threading
# py3
try:
from urllib.request import urlopen
urlopen # pyflakes
from queue import Queue
Queue # pyflakes
except ImportError:
# py2 fallbacks
from urllib import urlopen
from Queue import Queue
from gettext import gettext as _
from softwarecenter.backend.ubuntusso import get_ubuntu_sso_backend
import piston_mini_client
from softwarecenter.paths import SOFTWARE_CENTER_CONFIG_DIR
from softwarecenter.enums import Icons, SOFTWARE_CENTER_NAME_KEYRING
from softwarecenter.config import get_config
from softwarecenter.distro import get_distro, get_current_arch
from softwarecenter.backend.login_sso import get_sso_backend
from softwarecenter.backend.reviews import Review
from softwarecenter.db.database import Application
from softwarecenter.gwibber_helper import GwibberHelper, GwibberHelperMock
from softwarecenter.i18n import get_language
from softwarecenter.ui.gtk3.SimpleGtkbuilderApp import SimpleGtkbuilderApp
from softwarecenter.ui.gtk3.dialogs import SimpleGtkbuilderDialog
from softwarecenter.ui.gtk3.widgets.stars import ReactiveStar
from softwarecenter.utils import make_string_from_list, utf8
from softwarecenter.backend.piston.rnrclient import RatingsAndReviewsAPI
from softwarecenter.backend.piston.rnrclient_pristine import ReviewRequest
# get current distro and set default server root
distro = get_distro()
SERVER_ROOT = distro.REVIEWS_SERVER
# server status URL
SERVER_STATUS_URL = SERVER_ROOT + "/server-status/"
class UserCancelException(Exception):
""" user pressed cancel """
pass
TRANSMIT_STATE_NONE = "transmit-state-none"
TRANSMIT_STATE_INPROGRESS = "transmit-state-inprogress"
TRANSMIT_STATE_DONE = "transmit-state-done"
TRANSMIT_STATE_ERROR = "transmit-state-error"
class GRatingsAndReviews(GObject.GObject):
""" Access ratings&reviews API as a gobject """
__gsignals__ = {
# send when a transmit is started
"transmit-start": (GObject.SIGNAL_RUN_LAST,
GObject.TYPE_NONE,
(GObject.TYPE_PYOBJECT, ),
),
# send when a transmit was successful
"transmit-success": (GObject.SIGNAL_RUN_LAST,
GObject.TYPE_NONE,
(GObject.TYPE_PYOBJECT, ),
),
# send when a transmit failed
"transmit-failure": (GObject.SIGNAL_RUN_LAST,
GObject.TYPE_NONE,
(GObject.TYPE_PYOBJECT, str),
),
}
def __init__(self, token):
super(GRatingsAndReviews, self).__init__()
# piston worker thread
self.worker_thread = Worker(token)
self.worker_thread.start()
GObject.timeout_add(500,
self._check_thread_status,
None)
def submit_review(self, review):
self.emit("transmit-start", review)
self.worker_thread.pending_reviews.put(review)
def report_abuse(self, review_id, summary, text):
self.emit("transmit-start", review_id)
self.worker_thread.pending_reports.put((int(review_id), summary, text))
def submit_usefulness(self, review_id, is_useful):
self.emit("transmit-start", review_id)
self.worker_thread.pending_usefulness.put((int(review_id), is_useful))
def modify_review(self, review_id, review):
self.emit("transmit-start", review_id)
self.worker_thread.pending_modify.put((int(review_id), review))
def delete_review(self, review_id):
self.emit("transmit-start", review_id)
self.worker_thread.pending_delete.put(int(review_id))
def server_status(self):
self.worker_thread.pending_server_status()
def shutdown(self):
self.worker_thread.shutdown()
# internal
def _check_thread_status(self, data):
if self.worker_thread._transmit_state == TRANSMIT_STATE_DONE:
self.emit("transmit-success", "")
self.worker_thread._transmit_state = TRANSMIT_STATE_NONE
elif self.worker_thread._transmit_state == TRANSMIT_STATE_ERROR:
self.emit("transmit-failure", "",
self.worker_thread._transmit_error_str)
self.worker_thread._transmit_state = TRANSMIT_STATE_NONE
return True
class Worker(threading.Thread):
def __init__(self, token):
# init parent
threading.Thread.__init__(self)
self.pending_reviews = Queue()
self.pending_reports = Queue()
self.pending_usefulness = Queue()
self.pending_modify = Queue()
self.pending_delete = Queue()
self.pending_server_status = Queue()
self._shutdown = False
# FIXME: instead of a binary value we need the state associated
# with each request from the queue
self._transmit_state = TRANSMIT_STATE_NONE
self._transmit_error_str = ""
self.display_name = "No display name"
auth = piston_mini_client.auth.OAuthAuthorizer(token["token"],
token["token_secret"], token["consumer_key"],
token["consumer_secret"])
# change default server to the SSL one
distro = get_distro()
service_root = distro.REVIEWS_SERVER
self.rnrclient = RatingsAndReviewsAPI(service_root=service_root,
auth=auth)
def run(self):
"""Main thread run interface, logs into launchpad and waits
for commands
"""
logging.debug("worker thread run")
# loop
self._wait_for_commands()
def shutdown(self):
"""Request shutdown"""
self._shutdown = True
def _wait_for_commands(self):
"""internal helper that waits for commands"""
while True:
#logging.debug("worker: _wait_for_commands")
self._submit_reviews_if_pending()
self._submit_reports_if_pending()
self._submit_usefulness_if_pending()
self._submit_modify_if_pending()
self._submit_delete_if_pending()
time.sleep(0.2)
if (self._shutdown and
self.pending_reviews.empty() and
self.pending_usefulness.empty() and
self.pending_reports.empty() and
self.pending_modify.empty() and
self.pending_delete.empty()):
return
def _submit_usefulness_if_pending(self):
""" the actual usefulness function """
while not self.pending_usefulness.empty():
logging.debug("POST usefulness")
self._transmit_state = TRANSMIT_STATE_INPROGRESS
(review_id, is_useful) = self.pending_usefulness.get()
try:
res = self.rnrclient.submit_usefulness(
review_id=review_id, useful=str(is_useful))
self._transmit_state = TRANSMIT_STATE_DONE
sys.stdout.write(json.dumps(res))
except Exception as e:
logging.exception("submit_usefulness failed")
err_str = self._get_error_messages(e)
self._transmit_error_str = err_str
self._write_exception_html_log_if_needed(e)
self._transmit_state = TRANSMIT_STATE_ERROR
self.pending_usefulness.task_done()
def _submit_modify_if_pending(self):
""" the actual modify function """
while not self.pending_modify.empty():
logging.debug("_modify_review")
self._transmit_state = TRANSMIT_STATE_INPROGRESS
(review_id, review) = self.pending_modify.get()
summary = review['summary']
review_text = review['review_text']
rating = review['rating']
try:
res = self.rnrclient.modify_review(review_id=review_id,
summary=summary,
review_text=review_text,
rating=rating)
self._transmit_state = TRANSMIT_STATE_DONE
sys.stdout.write(json.dumps(vars(res)))
except Exception as e:
logging.exception("modify_review")
err_str = self._get_error_messages(e)
self._write_exception_html_log_if_needed(e)
self._transmit_state = TRANSMIT_STATE_ERROR
self._transmit_error_str = err_str
self.pending_modify.task_done()
def _submit_delete_if_pending(self):
""" the actual deletion """
while not self.pending_delete.empty():
logging.debug("POST delete")
self._transmit_state = TRANSMIT_STATE_INPROGRESS
review_id = self.pending_delete.get()
try:
res = self.rnrclient.delete_review(review_id=review_id)
self._transmit_state = TRANSMIT_STATE_DONE
sys.stdout.write(json.dumps(res))
except Exception as e:
logging.exception("delete_review failed")
self._write_exception_html_log_if_needed(e)
self._transmit_error_str = _("Failed to delete review")
self._transmit_state = TRANSMIT_STATE_ERROR
self.pending_delete.task_done()
def _submit_reports_if_pending(self):
""" the actual report function """
while not self.pending_reports.empty():
logging.debug("POST report")
self._transmit_state = TRANSMIT_STATE_INPROGRESS
(review_id, summary, text) = self.pending_reports.get()
try:
res = self.rnrclient.flag_review(review_id=review_id,
reason=summary,
text=text)
self._transmit_state = TRANSMIT_STATE_DONE
sys.stdout.write(json.dumps(res))
except Exception as e:
logging.exception("flag_review failed")
err_str = self._get_error_messages(e)
self._transmit_error_str = err_str
self._write_exception_html_log_if_needed(e)
self._transmit_state = TRANSMIT_STATE_ERROR
self.pending_reports.task_done()
def _write_exception_html_log_if_needed(self, e):
# write out a "oops.html"
if type(e) is piston_mini_client.APIError:
f = tempfile.NamedTemporaryFile(
prefix="sc_submit_oops_", suffix=".html", delete=False)
# new piston-mini-client has only the body of the returned data
# older just pushes it into a big string
if hasattr(e, "body") and e.body:
f.write(e.body)
else:
f.write(str(e))
# reviews
def queue_review(self, review):
""" queue a new review for sending to LP """
logging.debug("queue_review %s" % review)
self.pending_reviews.put(review)
def _submit_reviews_if_pending(self):
""" the actual submit function """
while not self.pending_reviews.empty():
logging.debug("_submit_review")
self._transmit_state = TRANSMIT_STATE_INPROGRESS
review = self.pending_reviews.get()
piston_review = ReviewRequest()
piston_review.package_name = review.app.pkgname
piston_review.app_name = review.app.appname
piston_review.summary = review.summary
piston_review.version = review.package_version
piston_review.review_text = review.text
piston_review.date = str(review.date)
piston_review.rating = review.rating
piston_review.language = review.language
piston_review.arch_tag = get_current_arch()
piston_review.origin = review.origin
piston_review.distroseries = distro.get_codename()
try:
res = self.rnrclient.submit_review(review=piston_review)
self._transmit_state = TRANSMIT_STATE_DONE
# output the resulting ReviewDetails object as json so
# that the parent can read it
sys.stdout.write(json.dumps(vars(res)))
except Exception as e:
logging.exception("submit_review")
err_str = self._get_error_messages(e)
self._write_exception_html_log_if_needed(e)
self._transmit_state = TRANSMIT_STATE_ERROR
self._transmit_error_str = err_str
self.pending_reviews.task_done()
def _get_error_messages(self, e):
if type(e) is piston_mini_client.APIError:
try:
logging.warning(e.body)
error_msg = json.loads(e.body)['errors']
errs = error_msg["__all__"]
err_str = _("Server's response was:")
for err in errs:
err_str = _("%s\n%s") % (err_str, err)
except:
err_str = _("Unknown error communicating with server. "
"Check your log and consider raising a bug report "
"if this problem persists")
logging.warning(e)
else:
err_str = _("Unknown error communicating with server. Check "
"your log and consider raising a bug report if this "
"problem persists")
logging.warning(e)
return err_str
def verify_server_status(self):
""" verify that the server we want to talk to can be reached
this method should be overriden if clients talk to a different
server than rnr
"""
try:
resp = urlopen(SERVER_STATUS_URL).read()
if resp != "ok":
return False
except Exception as e:
logging.error("exception from '%s': '%s'" % (SERVER_STATUS_URL, e))
return False
return True
class BaseApp(SimpleGtkbuilderApp):
def __init__(self, datadir, uifile):
SimpleGtkbuilderApp.__init__(
self, os.path.join(datadir, "ui/gtk3", uifile), "software-center")
# generic data
self.token = None
self.display_name = None
self._login_successful = False
self._whoami_token_reset_nr = 0
#persistent config
configfile = os.path.join(
SOFTWARE_CENTER_CONFIG_DIR, "submit_reviews.cfg")
self.config = get_config(configfile)
# status spinner
self.status_spinner = Gtk.Spinner()
self.status_spinner.set_size_request(32, 32)
self.login_spinner_vbox.pack_start(self.status_spinner, False, False,
0)
self.login_spinner_vbox.reorder_child(self.status_spinner, 0)
self.status_spinner.show()
#submit status spinner
self.submit_spinner = Gtk.Spinner()
self.submit_spinner.set_size_request(*Gtk.icon_size_lookup(
Gtk.IconSize.SMALL_TOOLBAR)[:2])
#submit error image
self.submit_error_img = Gtk.Image()
self.submit_error_img.set_from_stock(Gtk.STOCK_DIALOG_ERROR,
Gtk.IconSize.SMALL_TOOLBAR)
#submit success image
self.submit_success_img = Gtk.Image()
self.submit_success_img.set_from_stock(Gtk.STOCK_APPLY,
Gtk.IconSize.SMALL_TOOLBAR)
#submit warn image
self.submit_warn_img = Gtk.Image()
self.submit_warn_img.set_from_stock(Gtk.STOCK_DIALOG_INFO,
Gtk.IconSize.SMALL_TOOLBAR)
#label size to prevent image or spinner from resizing
self.label_transmit_status.set_size_request(-1,
Gtk.icon_size_lookup(Gtk.IconSize.SMALL_TOOLBAR)[1])
def _get_parent_xid_for_login_window(self):
# no get_xid() yet in gir world
#return self.submit_window.get_window().get_xid()
return ""
def run(self):
# initially display a 'Connecting...' page
self.main_notebook.set_current_page(0)
self.login_status_label.set_markup(_(u"Signing in\u2026"))
self.status_spinner.start()
self.submit_window.show()
# now run the loop
self.login()
def quit(self, exitcode=0):
sys.exit(exitcode)
def _add_spellcheck_to_textview(self, textview):
""" adds a spellchecker (if available) to the given Gtk.textview """
pass
#~ try:
#~ import gtkspell
#~ # mvo: gtkspell.get_from_text_view() is broken, so we use this
#~ # method instead, the second argument is the language to
#~ # use (that is directly passed to pspell)
#~ spell = gtkspell.Spell(textview, None)
#~ except:
#~ return
#~ return spell
def login(self, show_register=True):
logging.debug("login()")
login_window_xid = self._get_parent_xid_for_login_window()
help_text = _("To review software or to report abuse you need to "
"sign in to a Ubuntu Single Sign-On account.")
self.sso = get_sso_backend(login_window_xid,
SOFTWARE_CENTER_NAME_KEYRING, help_text)
self.sso.connect("login-successful", self._maybe_login_successful)
self.sso.connect("login-canceled", self._login_canceled)
if show_register:
self.sso.login_or_register()
else:
self.sso.login()
def _login_canceled(self, sso):
self.status_spinner.hide()
self.login_status_label.set_markup(
'<b><big>%s</big></b>' % _("Login was canceled"))
def _maybe_login_successful(self, sso, oauth_result):
"""called after we have the token, then we go and figure out our
name
"""
logging.debug("_maybe_login_successful")
self.token = oauth_result
self.ssoapi = get_ubuntu_sso_backend()
self.ssoapi.connect("whoami", self._whoami_done)
self.ssoapi.connect("error", self._whoami_error)
# this will automatically verify the token and retrigger login
# if its expired
self.ssoapi.whoami()
def _whoami_done(self, ssologin, result):
logging.debug("_whoami_done")
self.display_name = result["displayname"]
self._create_gratings_api()
self.login_successful(self.display_name)
def _whoami_error(self, ssologin, e):
logging.error("whoami error '%s'" % e)
# show error
self.status_spinner.hide()
self.login_status_label.set_markup(
'<b><big>%s</big></b>' % _("Failed to log in"))
def login_successful(self, display_name):
""" callback when the login was successful """
pass
def on_button_cancel_clicked(self, button=None):
# bring it down gracefully
if hasattr(self, "api"):
self.api.shutdown()
while Gtk.events_pending():
Gtk.main_iteration()
self.quit(1)
def _create_gratings_api(self):
self.api = GRatingsAndReviews(self.token)
self.api.connect("transmit-start", self.on_transmit_start)
self.api.connect("transmit-success", self.on_transmit_success)
self.api.connect("transmit-failure", self.on_transmit_failure)
def on_transmit_start(self, api, trans):
self.button_post.set_sensitive(False)
self.button_cancel.set_sensitive(False)
self._change_status("progress", _(self.SUBMIT_MESSAGE))
def on_transmit_success(self, api, trans):
self.api.shutdown()
self.quit()
def on_transmit_failure(self, api, trans, error):
self._change_status("fail", error)
self.button_post.set_sensitive(True)
self.button_cancel.set_sensitive(True)
def _change_status(self, type, message):
"""method to separate the updating of status icon/spinner and
message in the submit review window, takes a type (progress,
fail, success, clear, warning) as a string and a message
string then updates status area accordingly
"""
self._clear_status_imagery()
self.label_transmit_status.set_text("")
if type == "progress":
self.status_hbox.pack_start(self.submit_spinner, False, False, 0)
self.status_hbox.reorder_child(self.submit_spinner, 0)
self.submit_spinner.show()
self.submit_spinner.start()
self.label_transmit_status.set_text(message)
elif type == "fail":
self.status_hbox.pack_start(self.submit_error_img, False, False, 0)
self.status_hbox.reorder_child(self.submit_error_img, 0)
self.submit_error_img.show()
self.label_transmit_status.set_text(_(self.FAILURE_MESSAGE))
self.error_textview.get_buffer().set_text(_(message))
self.detail_expander.show()
elif type == "success":
self.status_hbox.pack_start(self.submit_success_img, False, False,
0)
self.status_hbox.reorder_child(self.submit_success_img, 0)
self.submit_success_img.show()
self.label_transmit_status.set_text(message)
elif type == "warning":
self.status_hbox.pack_start(self.submit_warn_img, False, False, 0)
self.status_hbox.reorder_child(self.submit_warn_img, 0)
self.submit_warn_img.show()
self.label_transmit_status.set_text(message)
def _clear_status_imagery(self):
self.detail_expander.hide()
self.detail_expander.set_expanded(False)
#clears spinner or error image from dialog submission label
# before trying to display one or the other
if self.submit_spinner.get_parent():
self.status_hbox.remove(self.submit_spinner)
if self.submit_error_img.get_window():
self.status_hbox.remove(self.submit_error_img)
if self.submit_success_img.get_window():
self.status_hbox.remove(self.submit_success_img)
if self.submit_warn_img.get_window():
self.status_hbox.remove(self.submit_warn_img)
class SubmitReviewsApp(BaseApp):
""" review a given application or package """
STAR_SIZE = (32, 32)
APP_ICON_SIZE = 48
#character limits for text boxes and hurdles for indicator changes
# (overall field maximum, limit to display warning, limit to change
# colour)
SUMMARY_CHAR_LIMITS = (80, 60, 70)
REVIEW_CHAR_LIMITS = (5000, 4900, 4950)
#alert colours for character warning labels
NORMAL_COLOUR = "000000"
ERROR_COLOUR = "FF0000"
SUBMIT_MESSAGE = _("Submitting Review")
FAILURE_MESSAGE = _("Failed to submit review")
SUCCESS_MESSAGE = _("Review submitted")
def __init__(self, app, version, iconname, origin, parent_xid, datadir,
action="submit", review_id=0):
BaseApp.__init__(self, datadir, "submit_review.ui")
self.datadir = datadir
# legal fineprint, do not change without consulting a lawyer
msg = _("By submitting this review, you agree not to include "
"anything defamatory, infringing, or illegal. Canonical "
"may, at its discretion, publish your name and review in "
"Ubuntu Software Center and elsewhere, and allow the "
"software or content author to publish it too.")
self.label_legal_fineprint.set_markup(
'<span size="x-small">%s</span>' % msg)
# additional icons come from app-install-data
self.icons = Gtk.IconTheme.get_default()
self.icons.append_search_path("/usr/share/app-install/icons/")
self.submit_window.connect("destroy", self.on_button_cancel_clicked)
self._add_spellcheck_to_textview(self.textview_review)
self.star_rating = ReactiveStar()
alignment = Gtk.Alignment.new(0.0, 0.5, 1.0, 1.0)
alignment.set_padding(3, 3, 3, 3)
alignment.add(self.star_rating)
self.star_rating.set_size_as_pixel_value(36)
self.star_caption = Gtk.Label()
alignment.show_all()
self.rating_hbox.pack_start(alignment, True, True, 0)
self.rating_hbox.reorder_child(alignment, 0)
self.rating_hbox.pack_start(self.star_caption, False, False, 0)
self.rating_hbox.reorder_child(self.star_caption, 1)
self.review_buffer = self.textview_review.get_buffer()
self.detail_expander.hide()
self.retrieve_api = RatingsAndReviewsAPI()
# data
self.app = app
self.version = version
self.origin = origin
self.iconname = iconname
self.action = action
self.review_id = int(review_id)
# parent xid
#~ if parent_xid:
#~ win = Gdk.Window.foreign_new(int(parent_xid))
#~ wnck_get_xid_from_pid(os.getpid())
#~ win = ''
#~ self.review_buffer.set_text(str(win))
#~ if win:
#~ self.submit_window.realize()
#~ self.submit_window.get_window().set_transient_for(win)
self.submit_window.set_position(Gtk.WindowPosition.MOUSE)
self._confirm_cancel_yes_handler = 0
self._confirm_cancel_no_handler = 0
self._displaying_cancel_confirmation = False
self.submit_window.connect("key-press-event", self._on_key_press_event)
self.review_summary_entry.connect('changed',
self._on_mandatory_text_entry_changed)
self.star_rating.connect('changed', self._on_mandatory_fields_changed)
self.review_buffer.connect('changed', self._on_text_entry_changed)
# gwibber stuff
self.gwibber_combo = Gtk.ComboBoxText.new()
#cells = self.gwibber_combo.get_cells()
#cells[0].set_property("ellipsize", pango.ELLIPSIZE_END)
self.gwibber_hbox.pack_start(self.gwibber_combo, True, True, 0)
if "SOFTWARE_CENTER_GWIBBER_MOCK_USERS" in os.environ:
self.gwibber_helper = GwibberHelperMock()
else:
self.gwibber_helper = GwibberHelper()
# get a dict with a saved gwibber_send (boolean) and gwibber
# account_id for persistent state
self.gwibber_prefs = self._get_gwibber_prefs()
# gwibber stuff
self._setup_gwibber_gui()
#now setup rest of app based on whether submit or modify
if self.action == "submit":
self._init_submit()
elif self.action == "modify":
self._init_modify()
def _init_submit(self):
self.submit_window.set_title(_("Review %s") %
gettext.dgettext("app-install-data", self.app.name))
def _init_modify(self):
self._populate_review()
self.submit_window.set_title(_("Modify Your %(appname)s Review") % {
'appname': gettext.dgettext("app-install-data", self.app.name)})
self.button_post.set_label(_("Modify"))
self.SUBMIT_MESSAGE = _("Updating your review")
self.FAILURE_MESSAGE = _("Failed to edit review")
self.SUCCESS_MESSAGE = _("Review updated")
self._enable_or_disable_post_button()
def _populate_review(self):
try:
review_data = self.retrieve_api.get_review(
review_id=self.review_id)
app = Application(appname=review_data.app_name,
pkgname=review_data.package_name)
self.app = app
self.review_summary_entry.set_text(review_data.summary)
self.star_rating.set_rating(review_data.rating)
self.review_buffer.set_text(review_data.review_text)
# save original review field data, for comparison purposes when
# user makes changes to fields
self.orig_summary_text = review_data.summary
self.orig_star_rating = review_data.rating
self.orig_review_text = review_data.review_text
self.version = review_data.version
self.origin = review_data.origin
except piston_mini_client.APIError:
logging.warn(
'Unable to retrieve review id %s for editing. Exiting' %
self.review_id)
self.quit(2)
def _setup_details(self, widget, app, iconname, version, display_name):
# icon shazam
try:
icon = self.icons.load_icon(iconname, self.APP_ICON_SIZE, 0)
except:
icon = self.icons.load_icon(Icons.MISSING_APP, self.APP_ICON_SIZE,
0)
self.review_appicon.set_from_pixbuf(icon)
# title
app = utf8(gettext.dgettext("app-install-data", app.name))
version = utf8(version)
self.review_title.set_markup(
'<b><span size="x-large">%s</span></b>\n%s' % (app, version))
# review label
self.review_label.set_markup(_('Review by: %s') %
display_name.encode('utf8'))
# review summary label
self.review_summary_label.set_markup(_('Summary:'))
#rating label
self.rating_label.set_markup(_('Rating:'))
#error detail link label
self.label_expander.set_markup('<small><u>%s</u></small>' %
(_('Error Details')))
def _has_user_started_reviewing(self):
summary_chars = self.review_summary_entry.get_text_length()
review_chars = self.review_buffer.get_char_count()
return summary_chars > 0 or review_chars > 0
def _on_mandatory_fields_changed(self, *args):
self._enable_or_disable_post_button()
def _on_mandatory_text_entry_changed(self, widget):
self._check_summary_character_count()
self._on_mandatory_fields_changed(widget)
def _on_text_entry_changed(self, widget):
self._check_review_character_count()
self._on_mandatory_fields_changed(widget)
def _enable_or_disable_post_button(self):
summary_chars = self.review_summary_entry.get_text_length()
review_chars = self.review_buffer.get_char_count()
if (summary_chars and summary_chars <= self.SUMMARY_CHAR_LIMITS[0] and
review_chars and review_chars <= self.REVIEW_CHAR_LIMITS[0] and
int(self.star_rating.get_rating()) > 0):
self.button_post.set_sensitive(True)
self._change_status("clear", "")
else:
self.button_post.set_sensitive(False)
self._change_status("clear", "")
# set post button insensitive, if review being modified is the same
# as what is currently in the UI fields checks if 'original' review
# attributes exist to avoid exceptions when this method has been
# called prior to review being retrieved
if self.action == 'modify' and hasattr(self, "orig_star_rating"):
if self._modify_review_is_the_same():
self.button_post.set_sensitive(False)
self._change_status("warning", _("Can't submit unmodified"))
else:
self._change_status("clear", "")
def _modify_review_is_the_same(self):
"""checks if review fields are the same as the review being modified
and returns True if so
"""
# perform an initial check on character counts to return False if any
# don't match, avoids doing unnecessary string comparisons
if (self.review_summary_entry.get_text_length() !=
len(self.orig_summary_text) or
self.review_buffer.get_char_count() != len(self.orig_review_text)):
return False
#compare rating
if self.star_rating.get_rating() != self.orig_star_rating:
return False
#compare summary text
if (self.review_summary_entry.get_text().decode('utf-8') !=
self.orig_summary_text):
return False
#compare review text
if (self.review_buffer.get_text(
self.review_buffer.get_start_iter(),
self.review_buffer.get_end_iter(),
include_hidden_chars=False).decode('utf-8') !=
self.orig_review_text):
return False
return True
def _check_summary_character_count(self):
summary_chars = self.review_summary_entry.get_text_length()
if summary_chars > self.SUMMARY_CHAR_LIMITS[1] - 1:
markup = self._get_fade_colour_markup(
self.NORMAL_COLOUR, self.ERROR_COLOUR,
self.SUMMARY_CHAR_LIMITS[2], self.SUMMARY_CHAR_LIMITS[0],
summary_chars)
self.summary_char_label.set_markup(markup)
else:
self.summary_char_label.set_text('')
def _check_review_character_count(self):
review_chars = self.review_buffer.get_char_count()
if review_chars > self.REVIEW_CHAR_LIMITS[1] - 1:
markup = self._get_fade_colour_markup(
self.NORMAL_COLOUR, self.ERROR_COLOUR,
self.REVIEW_CHAR_LIMITS[2], self.REVIEW_CHAR_LIMITS[0],
review_chars)
self.review_char_label.set_markup(markup)
else:
self.review_char_label.set_text('')
def _get_fade_colour_markup(self, full_col, empty_col, cmin, cmax, curr):
"""takes two colours as well as a minimum and maximum value then
fades one colour into the other based on the proportion of the
current value between the min and max
returns a pango color string
"""
markup = '<span fgcolor="#%s">%s</span>'
if curr > cmax:
return markup % (empty_col, str(cmax - curr))
elif curr <= cmin: # saves division by 0 later if cmin == cmax
return markup % (full_col, str(cmax - curr))
else:
#distance between min and max values to fade colours
scale = cmax - cmin
#percentage to fade colour by, based on current number of chars
percentage = (curr - cmin) / float(scale)
full_rgb = self._convert_html_to_rgb(full_col)
empty_rgb = self._convert_html_to_rgb(empty_col)
#calc changes to each of the r g b values to get the faded colour
red_change = full_rgb[0] - empty_rgb[0]
green_change = full_rgb[1] - empty_rgb[1]
blue_change = full_rgb[2] - empty_rgb[2]
new_red = int(full_rgb[0] - (percentage * red_change))
new_green = int(full_rgb[1] - (percentage * green_change))
new_blue = int(full_rgb[2] - (percentage * blue_change))
return_color = self._convert_rgb_to_html(new_red, new_green,
new_blue)
return markup % (return_color, str(cmax - curr))
def _convert_html_to_rgb(self, html):
r = html[0:2]
g = html[2:4]
b = html[4:6]
return (int(r, 16), int(g, 16), int(b, 16))
def _convert_rgb_to_html(self, r, g, b):
return "%s%s%s" % ("%02X" % r,
"%02X" % g,
"%02X" % b)
def on_button_post_clicked(self, button):
logging.debug("enter_review ok button")
review = Review(self.app)
text_buffer = self.textview_review.get_buffer()
review.text = text_buffer.get_text(text_buffer.get_start_iter(),
text_buffer.get_end_iter(),
False) # include_hidden_chars
review.summary = self.review_summary_entry.get_text()
review.date = datetime.datetime.now()
review.language = get_language()
review.rating = int(self.star_rating.get_rating())
review.package_version = self.version
review.origin = self.origin
if self.action == "submit":
self.api.submit_review(review)
elif self.action == "modify":
changes = {'review_text': review.text,
'summary': review.summary,
'rating': review.rating}
self.api.modify_review(self.review_id, changes)
def login_successful(self, display_name):
self.main_notebook.set_current_page(1)
self._setup_details(self.submit_window, self.app,
self.iconname, self.version, display_name)
self.textview_review.grab_focus()
def _setup_gwibber_gui(self):
self.gwibber_accounts = self.gwibber_helper.accounts()
list_length = len(self.gwibber_accounts)
if list_length == 0:
self._on_no_gwibber_accounts()
elif list_length == 1:
self._on_one_gwibber_account()
else:
self._on_multiple_gwibber_accounts()
def _get_gwibber_prefs(self):
if self.config.has_option("reviews", "gwibber_send"):
send = self.config.getboolean("reviews", "gwibber_send")
else:
send = False
if self.config.has_option("reviews", "account_id"):
account_id = self.config.get("reviews", "account_id")
else:
account_id = False
return {
"gwibber_send": send,
"account_id": account_id
}
def _on_no_gwibber_accounts(self):
self.gwibber_hbox.hide()
self.gwibber_checkbutton.set_active(False)
def _on_one_gwibber_account(self):
account = self.gwibber_accounts[0]
self.gwibber_hbox.show()
self.gwibber_combo.hide()
from softwarecenter.utils import utf8
acct_text = utf8(_("Also post this review to %s (@%s)")) % (
utf8(account['service'].capitalize()), utf8(account['username']))
self.gwibber_checkbutton.set_label(acct_text)
# simplifies on_transmit_successful later
self.gwibber_combo.append_text(acct_text)
self.gwibber_combo.set_active(0)
# auto select submit via gwibber checkbutton if saved prefs say True
self.gwibber_checkbutton.set_active(self.gwibber_prefs['gwibber_send'])
def _on_multiple_gwibber_accounts(self):
self.gwibber_hbox.show()
self.gwibber_combo.show()
# setup accounts combo
self.gwibber_checkbutton.set_label(_("Also post this review to: "))
for account in self.gwibber_accounts:
acct_text = "%s (@%s)" % (
account['service'].capitalize(), account['username'])
self.gwibber_combo.append_text(acct_text)
# add "all" to both combo and accounts (the later is only pseudo)
self.gwibber_combo.append_text(_("All my Gwibber services"))
self.gwibber_accounts.append({"id": "pseudo-sc-all"})
# reapply preferences
self.gwibber_checkbutton.set_active(self.gwibber_prefs['gwibber_send'])
gwibber_active_account = 0
for account in self.gwibber_accounts:
if account['id'] == self.gwibber_prefs['account_id']:
gwibber_active_account = self.gwibber_accounts.index(account)
self.gwibber_combo.set_active(gwibber_active_account)
def _post_to_one_gwibber_account(self, msg, account):
""" little helper to facilitate posting message to twitter account
passed in
"""
status_text = _("Posting to %s") % utf8(
account['service'].capitalize())
self._change_status("progress", status_text)
return self.gwibber_helper.send_message(msg, account['id'])
def on_transmit_success(self, api, trans):
"""on successful submission of a review, try to send to gwibber as
well
"""
self._run_gwibber_submits(api, trans)
def _on_key_press_event(self, widget, event):
if event.keyval == Gdk.KEY_Escape:
self._confirm_cancellation()
def _confirm_cancellation(self):
if (self._has_user_started_reviewing() and not
self._displaying_cancel_confirmation):
def do_cancel(widget):
self.submit_window.destroy()
self.quit()
def undo_cancel(widget):
self._displaying_cancel_confirmation = False
self.response_hbuttonbox.set_visible(True)
self.main_notebook.set_current_page(1)
self.response_hbuttonbox.set_visible(False)
self.confirm_cancel_yes.grab_focus()
self.main_notebook.set_current_page(2)
self._displaying_cancel_confirmation = True
if not self._confirm_cancel_yes_handler:
tag = self.confirm_cancel_yes.connect("clicked", do_cancel)
self._confirm_cancel_yes_handler = tag
if not self._confirm_cancel_no_handler:
tag = self.confirm_cancel_no.connect("clicked", undo_cancel)
self._confirm_cancel_no_handler = tag
else:
self.submit_window.destroy()
self.quit()
def _get_send_accounts(self, sel_index):
"""return the account referenced by the passed in index, or all
accounts if the index of the combo points to the pseudo-sc-all
string
"""
if self.gwibber_accounts[sel_index]["id"] == "pseudo-sc-all":
return self.gwibber_accounts
else:
return [self.gwibber_accounts[sel_index]]
def _submit_to_gwibber(self, msg, send_accounts):
"""for each send_account passed in, try to submit to gwibber
then return a list of accounts that failed to submit (empty list
if all succeeded)
"""<|fim▁hole|> #list of gwibber accounts that failed to submit, used later to allow
# selective re-send if user desires
failed_accounts = []
for account in send_accounts:
if account["id"] != "pseudo-sc-all":
if not self._post_to_one_gwibber_account(msg, account):
failed_accounts.append(account)
return failed_accounts
def _run_gwibber_submits(self, api, trans):
"""check if gwibber send should occur and send via gwibber if so"""
gwibber_success = True
using_gwibber = self.gwibber_checkbutton.get_active()
if using_gwibber:
i = self.gwibber_combo.get_active()
msg = (self._gwibber_message())
send_accounts = self._get_send_accounts(i)
self._save_gwibber_state(True, self.gwibber_accounts[i]['id'])
#tries to send to gwibber, and gets back any failed accounts
failed_accounts = self._submit_to_gwibber(msg, send_accounts)
if len(failed_accounts) > 0:
gwibber_success = False
#FIXME: send an error string to this method instead of empty
# string
self._on_gwibber_fail(api, trans, failed_accounts, "")
else:
# prevent _save_gwibber_state from overwriting the account id
# in config if the checkbutton was not selected
self._save_gwibber_state(False, None)
# run parent handler on gwibber success, otherwise this will be dealt
# with in _on_gwibber_fail
if gwibber_success:
self._success_status()
BaseApp.on_transmit_success(self, api, trans)
def _gwibber_retry_some(self, api, trans, accounts):
""" perform selective retrying of gwibber posting, using only
accounts passed in
"""
gwibber_success = True
failed_accounts = []
msg = (self._gwibber_message())
for account in accounts:
if not self._post_to_one_gwibber_account(msg, account):
failed_accounts.append(account)
gwibber_success = False
if not gwibber_success:
#FIXME: send an error string to this method instead of empty string
self._on_gwibber_fail(api, trans, failed_accounts, "")
else:
self._success_status()
BaseApp.on_transmit_success(self, api, trans)
def _success_status(self):
"""Updates status area to show success for 2 seconds then allows
window to proceed
"""
self._change_status("success", _(self.SUCCESS_MESSAGE))
while Gtk.events_pending():
Gtk.main_iteration()
time.sleep(2)
def _on_gwibber_fail(self, api, trans, failed_accounts, error):
self._change_status("fail", _("Problems posting to Gwibber"))
#list to hold service strings in the format: "Service (@username)"
failed_services = []
for account in failed_accounts:
failed_services.append("%s (@%s)" % (
account['service'].capitalize(), account['username']))
glade_dialog = SimpleGtkbuilderDialog(self.datadir,
domain="software-center")
dialog = glade_dialog.dialog_gwibber_error
dialog.set_transient_for(self.submit_window)
# build the failure string
# TRANSLATORS: the part in %s can either be a single entry
# like "facebook" or a string like
# "factbook and twister"
error_str = gettext.ngettext(
"There was a problem posting this review to %s.",
"There was a problem posting this review to %s.",
len(failed_services))
error_str = make_string_from_list(error_str, failed_services)
dialog.set_markup(error_str)
dialog.format_secondary_text(error)
result = dialog.run()
dialog.destroy()
if result == Gtk.RESPONSE_ACCEPT:
self._gwibber_retry_some(api, trans, failed_accounts)
else:
BaseApp.on_transmit_success(self, api, trans)
def _save_gwibber_state(self, gwibber_send, account_id):
if not self.config.has_section("reviews"):
self.config.add_section("reviews")
self.config.set("reviews", "gwibber_send", str(gwibber_send))
if account_id:
self.config.set("reviews", "account_id", account_id)
self.config.write()
def _gwibber_message(self, max_len=140):
""" build a gwibber message of max_len"""
def _gwibber_message_string_from_data(appname, rating, summary, link):
""" helper so that we do not duplicate the "reviewed..." string """
return _("reviewed %(appname)s in Ubuntu: %(rating)s "
"%(summary)s %(link)s") % {
'appname': appname,
'rating': rating,
'summary': summary,
'link': link}
rating = self.star_rating.get_rating()
rating_string = ''
#fill star ratings for string
for i in range(1, 6):
if i <= rating:
rating_string = rating_string + u"\u2605"
else:
rating_string = rating_string + u"\u2606"
review_summary_text = self.review_summary_entry.get_text()
# FIXME: currently the link is not useful (at all) for most
# people not runnig ubuntu
#app_link = "http://apt.ubuntu.com/p/%s" % self.app.pkgname
app_link = ""
gwib_msg = _gwibber_message_string_from_data(
self.app.name, rating_string, review_summary_text, app_link)
#check char count and ellipsize review summary if larger than 140 chars
if len(gwib_msg) > max_len:
chars_to_reduce = len(gwib_msg) - (max_len - 1)
new_char_count = len(review_summary_text) - chars_to_reduce
review_summary_text = (review_summary_text[:new_char_count] +
u"\u2026")
gwib_msg = _gwibber_message_string_from_data(
self.app.name, rating_string, review_summary_text, app_link)
return gwib_msg
class ReportReviewApp(BaseApp):
""" report a given application or package """
APP_ICON_SIZE = 48
SUBMIT_MESSAGE = _(u"Sending report\u2026")
FAILURE_MESSAGE = _("Failed to submit report")
def __init__(self, review_id, parent_xid, datadir):
BaseApp.__init__(self, datadir, "report_abuse.ui")
# status
self._add_spellcheck_to_textview(self.textview_report)
## make button sensitive when textview has content
self.textview_report.get_buffer().connect(
"changed", self._enable_or_disable_report_button)
# data
self.review_id = review_id
# title
self.submit_window.set_title(_("Flag as Inappropriate"))
# parent xid
#if parent_xid:
# #win = Gtk.gdk.window_foreign_new(int(parent_xid))
# if win:
# self.submit_window.realize()
# self.submit_window.window.set_transient_for(win)
# mousepos
self.submit_window.set_position(Gtk.WindowPosition.MOUSE)
# simple APIs ftw!
self.combobox_report_summary = Gtk.ComboBoxText.new()
self.report_body_vbox.pack_start(self.combobox_report_summary, False,
False, 0)
self.report_body_vbox.reorder_child(self.combobox_report_summary, 2)
self.combobox_report_summary.show()
for term in [_(u"Please make a selection\u2026"),
# TRANSLATORS: The following is one entry in a combobox that is
# located directly beneath a label asking 'Why is this review
# inappropriate?'.
# This text refers to a possible reason for why the corresponding
# review is being flagged as inappropriate.
_("Offensive language"),
# TRANSLATORS: The following is one entry in a combobox that is
# located directly beneath a label asking 'Why is this review
# inappropriate?'.
# This text refers to a possible reason for why the corresponding
# review is being flagged as inappropriate.
_("Infringes copyright"),
# TRANSLATORS: The following is one entry in a combobox that is
# located directly beneath a label asking 'Why is this review
# inappropriate?'.
# This text refers to a possible reason for why the corresponding
# review is being flagged as inappropriate.
_("Contains inaccuracies"),
# TRANSLATORS: The following is one entry in a combobox that is
# located directly beneath a label asking 'Why is this review
# inappropriate?'.
# This text refers to a possible reason for why the corresponding
# review is being flagged as inappropriate.
_("Other")]:
self.combobox_report_summary.append_text(term)
self.combobox_report_summary.set_active(0)
self.combobox_report_summary.connect(
"changed", self._enable_or_disable_report_button)
def _enable_or_disable_report_button(self, widget):
if (self.textview_report.get_buffer().get_char_count() > 0 and
self.combobox_report_summary.get_active() != 0):
self.button_post.set_sensitive(True)
else:
self.button_post.set_sensitive(False)
def _setup_details(self, widget, display_name):
# report label
self.report_label.set_markup(_('Please give details:'))
# review summary label
self.report_summary_label.set_markup(
_('Why is this review inappropriate?'))
#error detail link label
self.label_expander.set_markup('<small><u>%s</u></small>'
% (_('Error Details')))
def on_button_post_clicked(self, button):
logging.debug("report_abuse ok button")
report_summary = self.combobox_report_summary.get_active_text()
text_buffer = self.textview_report.get_buffer()
report_text = text_buffer.get_text(text_buffer.get_start_iter(),
text_buffer.get_end_iter(),
include_hidden_chars=False)
self.api.report_abuse(self.review_id, report_summary, report_text)
def login_successful(self, display_name):
logging.debug("login_successful")
self.main_notebook.set_current_page(1)
#self.label_reporter.set_text(display_name)
self._setup_details(self.submit_window, display_name)
class SubmitUsefulnessApp(BaseApp):
SUBMIT_MESSAGE = _(u"Sending usefulness\u2026")
def __init__(self, review_id, parent_xid, is_useful, datadir):
BaseApp.__init__(self, datadir, "submit_usefulness.ui")
# data
self.review_id = review_id
self.is_useful = bool(is_useful)
# no UI except for error conditions
self.parent_xid = parent_xid
# override behavior of baseapp here as we don't actually
# have a UI by default
def _get_parent_xid_for_login_window(self):
return self.parent_xid
def login_successful(self, display_name):
logging.debug("submit usefulness")
self.main_notebook.set_current_page(1)
self.api.submit_usefulness(self.review_id, self.is_useful)
def on_transmit_failure(self, api, trans, error):
logging.warn("exiting - error: %s" % error)
self.api.shutdown()
self.quit(2)
# override parents run to only trigger login (and subsequent
# events) but no UI, if this is commented out, there is some
# stub ui that can be useful for testing
def run(self):
self.login()
# override UI update methods from BaseApp to prevent them
# causing errors if called when UI is hidden
def _clear_status_imagery(self):
pass
def _change_status(self, type, message):
pass
class DeleteReviewApp(BaseApp):
SUBMIT_MESSAGE = _(u"Deleting review\u2026")
FAILURE_MESSAGE = _("Failed to delete review")
def __init__(self, review_id, parent_xid, datadir):
# uses same UI as submit usefulness because
# (a) it isn't shown and (b) it's similar in usage
BaseApp.__init__(self, datadir, "submit_usefulness.ui")
# data
self.review_id = review_id
# no UI except for error conditions
self.parent_xid = parent_xid
# override behavior of baseapp here as we don't actually
# have a UI by default
def _get_parent_xid_for_login_window(self):
return self.parent_xid
def login_successful(self, display_name):
logging.debug("delete review")
self.main_notebook.set_current_page(1)
self.api.delete_review(self.review_id)
def on_transmit_failure(self, api, trans, error):
logging.warn("exiting - error: %s" % error)
self.api.shutdown()
self.quit(2)
# override parents run to only trigger login (and subsequent
# events) but no UI, if this is commented out, there is some
# stub ui that can be useful for testing
def run(self):
self.login()
# override UI update methods from BaseApp to prevent them
# causing errors if called when UI is hidden
def _clear_status_imagery(self):
pass
def _change_status(self, type, message):
pass<|fim▁end|>
| |
<|file_name|>eventhandler.go<|end_file_name|><|fim▁begin|>package events
import (
"errors"
"github.com/miketheprogrammer/go-thrust/lib/commands"
"github.com/miketheprogrammer/go-thrust/lib/dispatcher"
)
/*
Create a new EventHandler for a give event.
*/
func NewHandler(event string, fn interface{}) (ThrustEventHandler, error) {
h := ThrustEventHandler{}
h.Event = event
h.Type = "event"
err := h.SetHandleFunc(fn)
dispatcher.RegisterHandler(h)
return h, err
}
/**<|fim▁hole|>**/
type Handler interface {
Handle(cr commands.CommandResponse)
Register()
SetHandleFunc(fn interface{})
}
type ThrustEventHandler struct {
Type string
Event string
Handler interface{}
}
func (teh ThrustEventHandler) Handle(cr commands.CommandResponse) {
if cr.Action != "event" {
return
}
if cr.Type != teh.Event && teh.Event != "*" {
return
}
cr.Event.Type = cr.Type
if fn, ok := teh.Handler.(func(commands.CommandResponse)); ok == true {
fn(cr)
return
}
if fn, ok := teh.Handler.(func(commands.EventResult)); ok == true {
fn(cr.Event)
return
}
}
func (teh *ThrustEventHandler) SetHandleFunc(fn interface{}) error {
if fn, ok := fn.(func(commands.CommandResponse)); ok == true {
teh.Handler = fn
return nil
}
if fn, ok := fn.(func(commands.EventResult)); ok == true {
teh.Handler = fn
return nil
}
return errors.New("Invalid Handler Definition")
}<|fim▁end|>
|
Begin Thrust Handler Code.
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2013 - Red Hat, 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.
from solum import objects
from solum.objects import extension as abstract_extension
from solum.objects import operation as abstract_operation
from solum.objects import plan as abstract_plan
from solum.objects import sensor as abstract_sensor
from solum.objects import service as abstract_srvc
from solum.objects.sqlalchemy import extension
from solum.objects.sqlalchemy import operation
from solum.objects.sqlalchemy import plan<|fim▁hole|>
def load():
"""Activate the sqlalchemy backend."""
objects.registry.add(abstract_plan.Plan, plan.Plan)
objects.registry.add(abstract_plan.PlanList, plan.PlanList)
objects.registry.add(abstract_srvc.Service, service.Service)
objects.registry.add(abstract_srvc.ServiceList, service.ServiceList)
objects.registry.add(abstract_operation.Operation, operation.Operation)
objects.registry.add(abstract_operation.OperationList,
operation.OperationList)
objects.registry.add(abstract_sensor.Sensor, sensor.Sensor)
objects.registry.add(abstract_sensor.SensorList, sensor.SensorList)
objects.registry.add(abstract_extension.Extension, extension.Extension)
objects.registry.add(abstract_extension.ExtensionList,
extension.ExtensionList)<|fim▁end|>
|
from solum.objects.sqlalchemy import sensor
from solum.objects.sqlalchemy import service
|
<|file_name|>UrlHistory.java<|end_file_name|><|fim▁begin|>/*
* The University of Wales, Cardiff Triana Project Software License (Based
* on the Apache Software License Version 1.1)
*
* Copyright (c) 2007 University of Wales, Cardiff. All rights reserved.
*
* Redistribution and use of the software in source and binary forms, with
* or without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The end-user documentation included with the redistribution, if any,
* must include the following acknowledgment: "This product includes
* software developed by the University of Wales, Cardiff for the Triana
* Project (http://www.trianacode.org)." Alternately, this
* acknowledgment may appear in the software itself, if and wherever
* such third-party acknowledgments normally appear.
*
* 4. The names "Triana" and "University of Wales, Cardiff" must not be
* used to endorse or promote products derived from this software
* without prior written permission. For written permission, please
* contact [email protected].
*
* 5. Products derived from this software may not be called "Triana," nor
* may Triana appear in their name, without prior written permission of
* the University of Wales, Cardiff.
*
* 6. This software may not be sold, used or incorporated into any product
* for sale to third parties.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL UNIVERSITY OF WALES, CARDIFF OR ITS CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*
* ------------------------------------------------------------------------
*<|fim▁hole|> * This software consists of voluntary contributions made by many
* individuals on behalf of the Triana Project. For more information on the
* Triana Project, please see. http://www.trianacode.org.
*
* This license is based on the BSD license as adopted by the Apache
* Foundation and is governed by the laws of England and Wales.
*
*/
package org.trianacode.gui.help;
import java.net.URL;
import java.util.Enumeration;
import java.util.Vector;
/**
* @version $Revision: 4048 $
*/
public class UrlHistory extends Vector {
private int urlIndex;
private int urlCount;
// A vector which contains the UrlEventListeners
protected Vector urlEventVector;
public UrlHistory() {
super();
urlEventVector = new Vector();
urlIndex = -1;
urlCount = 0;
// System.out.println("*** Creating UrlHistory ***");
}
public void addUrl(URL url) {
urlIndex++;
urlCount = urlIndex + 1;
if (urlCount > elementCount) {
setSize(urlCount + 10);
}
setElementAt(url, urlIndex);
// System.out.println("*** Adding URL ***");
processUrlEvent(new UrlEvent(this));
}
public URL getPreviousUrl() {
if (urlIndex <= 0) {
return null;
}
urlIndex--;
processUrlEvent(new UrlEvent(this));
return (URL) elementAt(urlIndex);
}
public URL getNextUrl() {
if (urlIndex >= (urlCount - 1)) {
return null;
}
urlIndex++;
processUrlEvent(new UrlEvent(this));
return (URL) elementAt(urlIndex);
}
public int getIndex() {
return urlIndex;
}
public int countUrls() {
return urlCount;
}
public void addUrlEventListener(UrlEventListener urlListener) {
urlEventVector.addElement(urlListener);
}
public void removeUrlEventListener(UrlEventListener urlListener) {
urlEventVector.removeElement(urlListener);
}
private void processUrlEvent(UrlEvent event) {
UrlEventListener listener;
Enumeration e = urlEventVector.elements();
while (e.hasMoreElements()) {
// System.out.println("*** Throwing UrlEvent ***");
listener = (UrlEventListener) e.nextElement();
listener.indexChanged(event);
}
}
}<|fim▁end|>
| |
<|file_name|>cppu.py<|end_file_name|><|fim▁begin|># -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*-
#
# This file is part of the LibreOffice project.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
import six
<|fim▁hole|>
class UnoAnyPrinter(object):
'''Prints UNO any'''
def __init__(self, typename, value):
self.value = value
self.typename = typename.replace('com::sun::star::', '')
def to_string(self):
type_desc = self.value['pType']
assert type_desc
type = make_uno_type(type_desc.dereference())
assert type
if type_desc.dereference()['eTypeClass'] == TypeClass.VOID:
return ('%s(%s)' % (self.typename, type.tag))
else:
ptr = self.value['pData']
assert ptr
return ('%s(%s: %s)' % (self.typename, type.tag, str(uno_cast(type, ptr).dereference())))
class UnoReferencePrinter(object):
'''Prints reference to a UNO interface'''
def __init__(self, typename, value):
self.value = value
self.typename = typename.replace('com::sun::star::', '')
def to_string(self):
iface = self.value['_pInterface']
if iface:
try:
return '%s to (%s) %s' % (self.typename, str(iface.dynamic_type), str(iface))
except:
# fallback for potential problem:
# base class 'com::sun::star::uno::XInterface' is ambiguous
return '%s to (XInterface) %s' % (self.typename, str(iface))
else:
return "empty %s" % self.typename
class UnoSequencePrinter(object):
'''Prints UNO Sequence'''
class iterator(six.Iterator):
'''Sequence iterator'''
def __init__(self, first, size):
self.item = first
self.size = size
self.count = 0
def __iter__(self):
return self
def __next__(self):
if self.count == self.size:
raise StopIteration
count = self.count
self.count = self.count + 1
elem = self.item.dereference()
self.item = self.item + 1
return ('[%d]' % count, elem)
def __init__(self, typename, value):
self.value = value
self.typename = typename.replace('com::sun::star::', '')
def to_string(self):
pimpl = self.value['_pSequence']
if pimpl:
impl = pimpl.dereference()
elems = impl['nElements']
if elems == 0:
return "empty %s" % self.typename
else:
return "%s of length %d" % (self.typename, elems)
else:
return "uninitialized %s" % self.typename
def children(self):
pimpl = self.value['_pSequence']
if pimpl:
impl = pimpl.dereference()
elemtype = self.value.type.template_argument(0)
elements = impl['elements'].cast(elemtype.pointer())
return self.iterator(elements, int(impl['nElements']))
else:
# TODO is that the best thing to do here?
return None
def display_hint(self):
if self.value['_pSequence']:
return 'array'
else:
return None
class UnoTypePrinter(object):
'''Prints UNO Type'''
def __init__(self, typename, value):
self.value = value
self.typename = typename.replace('com::sun::star::', '')
def to_string(self):
uno = make_uno_type(self.value)
if uno:
return "%s %s" % (self.typename, uno.tag)
# return "%s %s" % (self.typename, uno.typename)
else:
return "invalid %s" % self.typename
class CppuThreadpoolThreadPoolPrinter(object):
'''Prints cppu_threadpool::ThreadPool objects (a hack to avoid infinite recursion through sal.RtlReferencePrinter when printing an rtl::Reference<cppu_threadpool::ThreadPool> whose std::list<cppu_threadpool::WaitingThread*> m_lstThreads member, via rtl::Reference<cppu_threadpool::ORequestThread> thread member, via rtl::Reference<cppu_threadpool::ThreadPool> m_aThreadPool member, has a circular reference back)'''
def __init__(self, typename, value):
self.typename = typename
self.value = value
def to_string(self):
return '%s@%s' % (self.typename, self.value.address)
printer = None
def build_pretty_printers():
global printer
printer = printing.Printer("libreoffice/cppu")
# basic UNO stuff
printer.add('_uno_Any', UnoAnyPrinter)
printer.add('com::sun::star::uno::Any', UnoAnyPrinter)
printer.add('com::sun::star::uno::Reference', UnoReferencePrinter)
printer.add('com::sun::star::uno::Sequence', UnoSequencePrinter)
printer.add('com::sun::star::uno::Type', UnoTypePrinter)
printer.add('cppu_threadpool::ThreadPool', CppuThreadpoolThreadPoolPrinter)
def register_pretty_printers(obj):
printing.register_pretty_printer(printer, obj)
build_pretty_printers()
# vim:set shiftwidth=4 softtabstop=4 expandtab:<|fim▁end|>
|
from libreoffice.util import printing
from libreoffice.util.uno import TypeClass, make_uno_type, uno_cast
|
<|file_name|>testTwoLayerQG.py<|end_file_name|><|fim▁begin|>import time, sys
import numpy as np
import matplotlib.pyplot as plt
sys.path.append('../../')
from py2Periodic.physics import twoLayerQG
from numpy import pi
params = {
'f0' : 1.0e-4,
'Lx' : 1.0e6,
'beta' : 1.5e-11,
'defRadius' : 1.5e4, <|fim▁hole|> 'U2' : 0.0,
'bottomDrag' : 1.0e-7,
'nx' : 128,
'dt' : 1.0e3,
'visc' : 2.0e8,
'viscOrder' : 4.0,
'timeStepper': 'AB3',
'nThreads' : 4,
'useFilter' : False,
}
# Create the two-layer model
qg = twoLayerQG.model(**params)
qg.describe_model()
# Initial condition:
Ro = 1.0e-3
f0 = 1.0e-4
q1 = Ro*f0*np.random.standard_normal(qg.physVarShape)
q2 = Ro*f0*np.random.standard_normal(qg.physVarShape)
qg.set_q1_and_q2(q1, q2)
# Run a loop
nt = 1e3
for ii in np.arange(0, 1e3):
qg.step_nSteps(nSteps=nt, dnLog=nt)
qg.update_state_variables()
fig = plt.figure('Perturbation vorticity', figsize=(8, 8)); plt.clf()
plt.subplot(221); plt.imshow(qg.q1)
plt.subplot(222); plt.imshow(qg.q2)
plt.subplot(223); plt.imshow(np.abs(qg.soln[0:qg.ny//2, :, 0]))
plt.subplot(224); plt.imshow(np.abs(qg.soln[0:qg.ny//2, :, 1]))
plt.pause(0.01), plt.draw()
print("Close the plot to end the program")
plt.show()<|fim▁end|>
|
'H1' : 500.0,
'H2' : 2000.0,
'U1' : 2.5e-2,
|
<|file_name|>temca_graph.py<|end_file_name|><|fim▁begin|>"""
Python wrapper for functionality exposed in the TemcaGraph dll.
@author: jayb
"""
from ctypes import *
import logging
import threading
import time
import os
import sys
import numpy as np
from pytemca.image.imageproc import fit_sin
from numpy.ctypeslib import ndpointer
if sys.flags.debug:
rel = "../x64/Debug/TemcaGraphDLL.dll"
else:
rel = "../x64/Release/TemcaGraphDLL.dll"
dll_path = os.path.join(os.path.dirname(__file__), rel)
class StatusCallbackInfo(Structure):
_fields_ = [
("status", c_int),
# -1 : fatal error
# 0: finishied init (startup),
# 1: starting new frame,
# 2: finished frame capture (ie. time to move the stage),
# 3: Sync step completed
# 4: Async step completed
# 5: Processing finished (except Async graphs)
# 6: Shutdown finished
("info_code", c_int),
# value indicates which sync or async step completed
("error_string", c_char * 256)
]
STATUSCALLBACKFUNC = CFUNCTYPE(c_int, POINTER(StatusCallbackInfo)) # returns c_int
class CameraInfo(Structure):
'''
Information about the current camera in use.
'''
_fields_ = [
("width", c_int),
("height", c_int),
("format", c_int),
("pixel_depth", c_int),
("camera_bpp", c_int),
("camera_model", c_char * 256),
("camera_id", c_char * 256)
]
class FocusInfo(Structure):
'''
Information about focus quality.
'''
_fields_ = [
("focus_score", c_float),
("astig_score", c_float),
("astig_angle", c_float),
("astig_profile", c_float * 360)
]
class QCInfo(Structure):
'''
Information about image quality.
'''
_fields_ = [
("min_value", c_int),
("max_value", c_int),
("mean_value", c_int),
("histogram", c_int * 256),
]
class ROIInfo(Structure):
'''
Information about the selected ROI used for stitching.
'''
_fields_ = [
("gridX", c_int),
("gridY", c_int),
]
class MatcherInfo(Structure):
'''
Match parameters from the Matcher.
'''
_fields_ = [
("dX", c_float),
("dY", c_float),
("distance", c_float),
("rotation", c_float),
("good_matches", c_int),
]
class TemcaGraphDLL(object):
"""
Hooks onto the C++ DLL. These are all the foreign functions we are going to be using
from the dll, along with their arguments types and return values.
"""
_TemcaGraphDLL = WinDLL(dll_path)
open = _TemcaGraphDLL.temca_open
open.argtypes = [c_int, c_char_p, STATUSCALLBACKFUNC]
open.restype = c_uint32
close = _TemcaGraphDLL.temca_close
close.argtype = [None]
close.restype = c_uint32
set_mode = _TemcaGraphDLL.setMode
set_mode.argtypes = [c_char_p]
set_mode.restype = c_uint32
get_camera_info = _TemcaGraphDLL.getCameraInfo
get_camera_info.restype = CameraInfo
get_focus_info = _TemcaGraphDLL.getFocusInfo
get_focus_info.restype = FocusInfo
set_fft_size = _TemcaGraphDLL.setFFTSize
set_fft_size.argtypes = [c_int, c_int, c_int]
set_fft_size.restype = None
get_qc_info = _TemcaGraphDLL.getQCInfo
get_qc_info.restype = QCInfo
grab_frame = _TemcaGraphDLL.grabFrame
grab_frame.argtypes = [c_char_p, c_int, c_int]
grab_frame.restype = None
get_last_frame = _TemcaGraphDLL.getLastFrame
get_last_frame.argtypes = [ndpointer(c_uint16, flags="C_CONTIGUOUS")]
get_last_frame.restype = None
get_preview_frame = _TemcaGraphDLL.getPreviewFrame
get_preview_frame.argtypes = [ndpointer(c_uint8, flags="C_CONTIGUOUS")]
get_preview_frame.restype = None
set_parameter = _TemcaGraphDLL.setParameter
set_parameter.argtypes = [c_char_p, c_int]
set_parameter.restype = None
get_parameter = _TemcaGraphDLL.getParameter
get_parameter.argtypes = [c_char_p]
get_parameter.restype = c_uint32
get_status = _TemcaGraphDLL.getStatus
get_status.restype = StatusCallbackInfo
setRoiInfo = _TemcaGraphDLL.setROI
setRoiInfo.restype = None
setRoiInfo.argtypes = [ POINTER( ROIInfo) ]
grab_matcher_template = _TemcaGraphDLL.grabMatcherTemplate
grab_matcher_template.restype = None
grab_matcher_template.argtypes = [c_int, c_int, c_int, c_int]
get_matcher_info = _TemcaGraphDLL.getMatcherInfo
get_matcher_info.restype = MatcherInfo
get_matcher_info.argtypes = None
class TemcaGraph(object):
'''
Python class which wraps the C++ TemcaGraphDLL and provides the linkage between Python and the C++ OpenCVGraph world.
The Python events which are triggered by C++ callbacks are::
eventInitCompleted - all graphs have finished building
eventStartNewFrame - ready for client to issue a frame grab request
eventCaptureCompleted - exposure completed
eventCapturePostProcessingCompleted - xfer to CUDA, upshift, Bright/Dark correction finished
eventSyncProcessingCompleted - Synchronous processing has finished
eventAsyncProcessingCompleted - Asynchronous processing has finished (may overlap next exposure)
eventFiniCompleted - graph has finished shutting down
'''
def __init__(self,):
'''
Many additional class variables are defined in the open() function
'''
self.aborting = False
self.eventInitCompleted = threading.Event() # Event signalling that initialization is complete.
self.eventStartNewFrame = threading.Event()
self.eventCaptureCompleted = threading.Event()
self.eventCapturePostProcessingCompleted = threading.Event()
self.eventSyncProcessingCompleted = threading.Event()
self.eventAsyncProcessingCompleted = threading.Event()
self.eventFiniCompleted = threading.Event()
# all events after eventStartNewFrame, and before eventFiniCompleted
self.eventsAllCaptureLoop = [self.eventCaptureCompleted,
self.eventCapturePostProcessingCompleted,
self.eventSyncProcessingCompleted,
self.eventAsyncProcessingCompleted]
self.threadLock = threading.Lock()
self.preview_decimation_factor = 4
self.wait_time = 10 # in seconds. If we reach this limit, its an error
def wait_graph_event (self, event):
'''
Waits for the specified event to signal indicating a change in the graph state,
and then clears the event.
'''
self.threadLock.acquire()
event.wait(self.wait_time)
event.clear()
self.threadLock.release()
def wait_all_capture_events(self):
for e in self.eventsAllCaptureLoop:
self.wait_graph_event(e)
def wait_start_of_frame(self):
'''
Wait for the event which indicates the graph is ready to start a new frame.
'''
self.wait_graph_event(self.eventStartNewFrame)
def open(self, dummyCamera = False, dummyPath = None, callback=None):
'''
Open up the Temca C++ DLL.
If dummyCamera is True, create a dummy TEMCA image source using...
either a real camera, image, directory, or movie according to dummyPath which MUST be specified
as no default path is provided. If dummyPath is an integer string, then an OpenCV camera will be used
corresponding to that index.
'''
if callback == None:
callback = self.statusCallback
# prevent the callback from being garbage collected !!!
self.callback = STATUSCALLBACKFUNC(callback)
self.dummyPath = dummyPath
t = time.clock()
if not TemcaGraphDLL.open(dummyCamera, self.dummyPath, self.callback):
raise EnvironmentError('Cannot open TemcaGraphDLL. Possiblities: camera, is offline, not installed, or already in use')
logging.info("TemcaGraph DLL initialized in %s seconds" % (time.clock() - t))
self.eventInitCompleted.wait()
# get info about frame dimensions
fi = self.get_camera_info()
self.image_width = fi['width']
self.image_height = fi['height']
self.pixel_depth = fi['pixel_depth'] # 16 ALWAYS
self.camera_bpp = fi['camera_bpp'] # 12 for Ximea (upshift to full 16 bpp)
self.camera_model = fi['camera_model']
self.camera_id = fi['camera_id']
# if this is changed dynamically, reallocate preview frames
self.set_parameter('preview_decimation_factor', self.preview_decimation_factor)
def close(self):
'''
Close down all graphs.
'''
TemcaGraphDLL.close()
def set_mode(self, graphType):
'''
Sets the overall mode of operation for the Temca graph.
Each mode activates a subset of the overall graph.::
graphType SYNC ASYNC
-----------------------------------------------------
temca : ximea, postCap, QC Stitch
Focus
FileWriter
raw : ximea, postCap, FileWriter
preview : ximea, postCap, QC
Focus
'''
return TemcaGraphDLL.set_mode(graphType)
def set_parameter(self, parameter, value):
'''
General purpose way to set random parameters on the graph.
'value' must be an int. Valid parameters are::
'exposure' for Ximea, this is in microseconds
'gain' for Ximea, this is in dB * 1000
'preview_decimation_factor' (2, 4, 8, ...)
'''
TemcaGraphDLL.set_parameter(parameter, value)
def get_parameter(self, parameter):
'''
General purpose way to get random parameters on the graph.
Return value is an int. Valid parameters are given under set_parameter.
'''
return TemcaGraphDLL.get_parameter(parameter)
def get_camera_info(self):
'''
Returns a dictionary with details of the capture format including width, height, bytes per pixel, and the camera model and serial number.
'''
info = TemcaGraphDLL.get_camera_info()
return {'width' : info.width, 'height' : info.height,
'pixel_depth' : info.pixel_depth, 'camera_bpp' : info.camera_bpp,
'camera_model' : info.camera_model, 'camera_id' : info.camera_id}
def get_focus_info(self):
''' returns focus and astigmatism values, some calculated in CUDA, some in python '''
info = TemcaGraphDLL.get_focus_info()
astig_amp, astig_angle, offset, wave = fit_sin(info.astig_profile)
astig_score = astig_amp/np.ptp(info.astig_profile)
array_type = c_float*len(info.astig_profile)
astig_profile_pointer = cast(info.astig_profile, POINTER(array_type))
astig_numpy = np.frombuffer(astig_profile_pointer.contents, dtype=np.float32)
# return the profile?
return {'focus_score': info.focus_score, 'astig_score': astig_score, 'astig_angle' : astig_angle,
'astig_profile' : astig_numpy,}
def set_fft_size(self, dimension, start_freq, end_freq):
''' Set the dimension of the FFT (which must be a power of 2) and the start and end frequency for focus/astig measurement.
Both start and end frequencies must be less than dimension.
'''
TemcaGraphDLL.set_fft_size(dimension, start_freq, end_freq);
def get_qc_info(self):
''' Get the min, max, mean, and histogram from the last image acquired. '''
info = TemcaGraphDLL.get_qc_info()
array_type = c_int*len(info.histogram)
hist_profile_pointer = cast(info.histogram, POINTER(array_type))
hist_numpy = np.frombuffer(hist_profile_pointer.contents, dtype=np.int32)
return {'min':info.min_value, 'max': info.max_value, 'mean':info.mean_value, 'histogram':hist_numpy}
def grab_matcher_template(self, x, y, width, height):
''' Set the ROI to use as the template on the next image acquired. '''
TemcaGraphDLL.grab_matcher_template(x, y, width, height)
def get_matcher_info(self):
''' Return Match status from the matcher. If "good_matches" is 0, then the match operation failed'''
info = TemcaGraphDLL.get_matcher_info()
return {'dX': info.dX, 'dY': info.dY, 'distance': info.distance, 'rotation': info.rotation, 'good_matches': info.good_matches}
def get_status(self):
return TemcaGraphDLL.get_status()
def grab_frame(self, filename = "none", roiX = 0, roiY = 0):
'''
Trigger capture of a frame. This function does not wait for completion of anything.
'''
TemcaGraphDLL.grab_frame(filename, roiX, roiY)
def grab_frame_wait_completion(self, filename = "none", roiX = 0, roiY = 0):
'''
Trigger capture of a frame. This function waits for completion of all graphs.
'''
self.wait_start_of_frame()
self.grab_frame(filename, roiX, roiY) # filename doesn't matter in preview, nor does roi
self.wait_all_capture_events()
def allocate_frame(self):
'''
Allocate memory as a numpy array to hold a complete frame (16bpp grayscale).
'''
return np.zeros(shape=(self.image_width,self.image_height), dtype= np.uint16)
def allocate_preview_frame(self):
'''
Allocate memory as a numpy array to hold a preview frame (8bpp grayscale).
'''
return np.zeros(shape=(self.image_width/self.preview_decimation_factor,self.image_height/self.preview_decimation_factor), dtype= np.uint8)
def get_last_frame(self, img):
'''
Get a copy of the last frame captured as an ndarray (16bpp grayscale).
This must be called only after eventCapturePostProcessingCompleted has signaled and before the next frame is acquired.
'''
assert (img.shape == (self.image_width, self.image_height) and (img.dtype.type == np.uint16))
TemcaGraphDLL.get_last_frame(img)
def get_preview_frame(self, img):
'''
Get a copy of the preview image as an ndarray (8bpp grayscale).
This must be called only after eventCapturePostProcessingCompleted has signaled and before the next frame is acquired.
'''
assert (img.shape == (self.image_width/self.preview_decimation_factor, self.image_height/self.preview_decimation_factor) and (img.dtype.type == np.uint8))
TemcaGraphDLL.get_preview_frame(img)
def optimize_exposure(self):
'''
Search for optimal exposure value using binary search.
'''
min_high_value = 61000
max_high_value = 63000
exposure_step = 100000 #uS
self.set_mode('preview')
exp = self.get_parameter('exposure')
def _searchDirection():
''' return 0 = just right, 1 go up, -1 go down '''
self.grab_frame_wait_completion()
info = self.get_qc_info()
m = info['max']
if m > min_high_value and m < max_high_value:
return 0 # just right
elif m >= max_high_value:
return +1 # too high
else:
return -1 # too low
#overshoot top end
dir = _searchDirection()
while dir < 0:
exp = exp + exposure_step
self.set_parameter('exposure', exp)
dir = _searchDirection()
if dir == 0:
return;
exp_top = exp
#overshoot bottom end
while dir > 0:
exp = exp - exposure_step
self.set_parameter('exposure', exp)
dir = _searchDirection()
if dir == 0:
return;
exp_bottom = exp
# binary search, starting from bottom
exposure_step = exp_top - exp_bottom
while dir != 0 and exposure_step >= 2:
exposure_step = exposure_step / 2
if dir < 0:
exp += exposure_step
else:
exp -= exposure_step
self.set_parameter('exposure', exp)
dir = _searchDirection()
def set_roi_info (self, roiInfo):
'''
Set the dimensions of the ROI. This information is used for stitching.
'''
TemcaGraphDLL.setRoiInfo (roiInfo)
def statusCallback (self, statusInfo):
'''
Called by the C++ Temca graph runner whenever status changes.
These values correspond to the Python events activated. ::
-1 : fatal error
0: finished init (startup)
1: starting new frame
2: finished frame capture (ie. time to move the stage)
3: capture post processing finished (preview ready)
4: Sync step completed
5: Async step completed
6: Shutdown finished
'''
retValue = True
status = statusInfo.contents.status
info = statusInfo.contents.info_code
#logging.info ('callback status: ' + str(status) + ', info: ' + str(info))
tid = threading.currentThread()
if (status == -1):
self.aborting = True
error_string = statusInfo.contents.error_string<|fim▁hole|> retValue = False
elif status == 0:
# finished initialization of all graphs
self.eventInitCompleted.set()
elif status == 1:
# ready to start the next frame (start of the loop)
self.eventStartNewFrame.set()
elif status == 2:
# capture completed
# (move the stage now)
self.eventCaptureCompleted.set()
elif status == 3:
# post processing finished (*16, bright dark, spatial correction, preview ready)
self.eventCapturePostProcessingCompleted.set()
elif status == 4:
# all synchronous processing for the frame is complete
self.eventSyncProcessingCompleted.set()
elif status == 5:
# all asynchronous processing for the frame is complete
self.eventAsyncProcessingCompleted.set()
elif status == 6:
# graph is finished all processing. Close app.
self.eventFiniCompleted.set()
return retValue
if __name__ == '__main__':
import cv2
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# Open the DLL which runs all TEMCA graphs
#os.environ["PATH"] += os.pathsep
temcaGraph = TemcaGraph()
temcaGraph.open(dummyCamera = True)
showRawImage = True
showPreviewImage = True
if showRawImage or showPreviewImage:
import numpy as np
if showRawImage:
imgRaw = temcaGraph.allocate_frame()
if showPreviewImage:
imgPreview = temcaGraph.allocate_preview_frame() # 8bpp and decimated
# wait for graph to complete initialization
temcaGraph.eventInitCompleted.wait(temcaGraph.wait_time)
#temcaGraph.optimize_exposure()
temcaGraph.set_mode('preview')
#for j in range(10):
# temcaGraph.grab_frame_wait_completion()
# sys.stdout.write('.')
# info = temcaGraph.get_qc_info()
#for mode in ['temca', 'preview', 'raw']:
#for mode in ['temca']:
for mode in ['preview']:
print
print mode
temcaGraph.set_mode(mode)
frameCounter = 0
# set ROI grid size (for stitching only)
roiInfo = ROIInfo()
roiInfo.gridX = 5
roiInfo.gridY = 5
temcaGraph.set_roi_info (roiInfo)
for y in range(roiInfo.gridY):
for x in range (roiInfo.gridX):
if temcaGraph.aborting:
break
temcaGraph.wait_start_of_frame()
temcaGraph.grab_frame('j:/junk/pyframe' + str(frameCounter) + '.tif', x, y) # filename doesn't matter in preview
sys.stdout.write('.')
temcaGraph.wait_graph_event(temcaGraph.eventCaptureCompleted)
# move the stage here
# wait for Async ready event (stitching complete for previous frame)
if frameCounter > 0:
temcaGraph.wait_graph_event(temcaGraph.eventAsyncProcessingCompleted)
# wait for preview ready event
temcaGraph.wait_graph_event(temcaGraph.eventCapturePostProcessingCompleted)
# get a copy of the frame and display it?
if showRawImage:
temcaGraph.get_last_frame(imgRaw)
cv2.imshow('imgRaw', imgRaw)
cv2.waitKey(1);
# get a copy of the preview and display it?
if showPreviewImage:
temcaGraph.get_preview_frame(imgPreview)
cv2.imshow('imgPreview', imgPreview)
cv2.waitKey(1);
# wait for Sync ready event (QC and Focus complete)
temcaGraph.wait_graph_event(temcaGraph.eventSyncProcessingCompleted)
qcInfo = temcaGraph.get_qc_info()
#histogram = qcInfo['histogram']
focusInfo = temcaGraph.get_focus_info()
#print qcInfo
frameCounter += 1
temcaGraph.close()
temcaGraph.wait_graph_event(temcaGraph.eventFiniCompleted)<|fim▁end|>
|
logging.info ('callback error is' + error_string)
|
<|file_name|>tables.py<|end_file_name|><|fim▁begin|># Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
from django.conf import settings
from django.core.urlresolvers import reverse
from django.utils.http import urlencode
from django.utils.translation import ugettext_lazy as _
from keystoneclient import exceptions
from horizon import messages
from horizon import tables
from openstack_dashboard import api
from openstack_dashboard.dashboards.admin.domains import constants
LOG = logging.getLogger(__name__)
class ViewGroupsLink(tables.LinkAction):
name = "groups"
verbose_name = _("Modify Groups")
url = "horizon:admin:domains:update"
classes = ("ajax-modal",)
icon = "pencil"
def get_link_url(self, domain):
step = 'update_group_members'
base_url = reverse(self.url, args=[domain.id])
param = urlencode({"step": step})
return "?".join([base_url, param])
class CreateDomainLink(tables.LinkAction):
name = "create"
verbose_name = _("Create Domain")
url = constants.DOMAINS_CREATE_URL
classes = ("ajax-modal",)
icon = "plus"
policy_rules = (('identity', 'identity:create_domain'),)
def allowed(self, request, domain):
return api.keystone.keystone_can_edit_domain()
class EditDomainLink(tables.LinkAction):
name = "edit"
verbose_name = _("Edit")
url = constants.DOMAINS_UPDATE_URL
classes = ("ajax-modal",)
icon = "pencil"
policy_rules = (('identity', 'identity:update_domain'),)
def allowed(self, request, domain):
return api.keystone.keystone_can_edit_domain()
class DeleteDomainsAction(tables.DeleteAction):
name = "delete"
data_type_singular = _("Domain")
data_type_plural = _("Domains")
policy_rules = (('identity', 'identity:delete_domain'),)
def allowed(self, request, datum):
return api.keystone.keystone_can_edit_domain()
def delete(self, request, obj_id):
domain = self.table.get_object_by_id(obj_id)
if domain.enabled:
msg = _('Domain "%s" must be disabled before it can be deleted.') \
% domain.name
messages.error(request, msg)
raise exceptions.ClientException(409, msg)
else:
LOG.info('Deleting domain "%s".' % obj_id)
api.keystone.domain_delete(request, obj_id)
class DomainFilterAction(tables.FilterAction):
def allowed(self, request, datum):
multidomain_support = getattr(settings,
'OPENSTACK_KEYSTONE_MULTIDOMAIN_SUPPORT',
False)
return multidomain_support
def filter(self, table, domains, filter_string):
"""Naive case-insensitive search."""
q = filter_string.lower()
def comp(domain):
if q in domain.name.lower():
return True
return False
return filter(comp, domains)
class SetDomainContext(tables.Action):
name = "set_domain_context"
verbose_name = _("Set Domain Context")
url = constants.DOMAINS_INDEX_URL
preempt = True
policy_rules = (('identity', 'admin_required'),)
def allowed(self, request, datum):
multidomain_support = getattr(settings,
'OPENSTACK_KEYSTONE_MULTIDOMAIN_SUPPORT',
False)
if not multidomain_support:
return False
ctx = request.session.get("domain_context", None)
if ctx and datum.id == ctx:
return False
return True
def single(self, table, request, obj_id):
if ('domain_context' not in request.session or
request.session['domain_context'] != obj_id):
try:
domain = api.keystone.domain_get(request, obj_id)
request.session['domain_context'] = obj_id
request.session['domain_context_name'] = domain.name
messages.success(request,<|fim▁hole|> messages.error(request,
_('Unable to set Domain Context.'))
class UnsetDomainContext(tables.Action):
name = "clear_domain_context"
verbose_name = _("Clear Domain Context")
url = constants.DOMAINS_INDEX_URL
preempt = True
requires_input = False
policy_rules = (('identity', 'admin_required'),)
def allowed(self, request, datum):
ctx = request.session.get("domain_context", None)
return ctx is not None
def single(self, table, request, obj_id):
if 'domain_context' in request.session:
request.session.pop("domain_context")
request.session.pop("domain_context_name")
messages.success(request, _('Domain Context cleared.'))
class DomainsTable(tables.DataTable):
name = tables.Column('name', verbose_name=_('Name'))
description = tables.Column(lambda obj: getattr(obj, 'description', None),
verbose_name=_('Description'))
id = tables.Column('id', verbose_name=_('Domain ID'))
enabled = tables.Column('enabled', verbose_name=_('Enabled'), status=True)
class Meta:
name = "domains"
verbose_name = _("Domains")
row_actions = (SetDomainContext, ViewGroupsLink, EditDomainLink,
DeleteDomainsAction)
table_actions = (DomainFilterAction, CreateDomainLink,
DeleteDomainsAction, UnsetDomainContext)<|fim▁end|>
|
_('Domain Context updated to Domain %s.') %
domain.name)
except Exception:
|
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from customers.models import Client
from django.conf import settings
from django.db import utils
from django.views.generic import TemplateView
from tenant_schemas.utils import remove_www
class HomeView(TemplateView):
template_name = "index_public.html"
def get_context_data(self, **kwargs):
context = super(HomeView, self).get_context_data(**kwargs)
hostname_without_port = remove_www(self.request.get_host().split(':')[0])
try:
Client.objects.get(schema_name='public')
except utils.DatabaseError:
context['need_sync'] = True<|fim▁hole|> context['shared_apps'] = settings.SHARED_APPS
context['tenants_list'] = []
return context
except Client.DoesNotExist:
context['no_public_tenant'] = True
context['hostname'] = hostname_without_port
if Client.objects.count() == 1:
context['only_public_tenant'] = True
context['tenants_list'] = Client.objects.all()
return context<|fim▁end|>
| |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>###############################################################################
# Name: __init__.py #
# Purpose: Put the src package in the Editra packages namespace #
# Author: Cody Precord <[email protected]> #
# Copyright: (c) 2007 Cody Precord <[email protected]> #
# Licence: wxWindows Licence #
###############################################################################
"""Main package initializer"""
<|fim▁hole|>__author__ = "Cody Precord <[email protected]>"
__svnid__ = "$Id: __init__.py 49807 2007-11-10 07:08:33Z CJP $"
__revision__ = "$Revision: 49807 $"<|fim▁end|>
| |
<|file_name|>ListenerAction.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2005-2007 Maarten Billemont
*
* 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.
*/
package com.lyndir.lhunath.opal.gui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
/**
* <i>{@link ListenerAction} - [in short] (TODO).</i><br> <br> [description / usage].<br> <br>
*
* @author lhunath
*/
public class ListenerAction extends AbstractAction {
private final ActionListener listener;
/**
* Create a new {@link ListenerAction} instance.
*
* @param listener The listener that will be notified of this action.
*/
public ListenerAction(final ActionListener listener) {
this.listener = listener;
}
/**
* Create a new {@link ListenerAction} instance.
*
* @param name The name of the action.
* @param listener The listener that will be notified of this action.
*/
public ListenerAction(final String name, final ActionListener listener) {
super( name );
this.listener = listener;
}
/**
* Create a new {@link ListenerAction} instance.
*
* @param name The name of the action.
* @param command The string that will identify the action that must be taken.
* @param icon The icon of the action.
* @param listener The listener that will be notified of this action.
*/
public ListenerAction(final String name, final String command, final Icon icon, final ActionListener listener) {
super( name, icon );
this.listener = listener;
setActionCommand( command );
}
/**
* Specify an action command string for this action.<|fim▁hole|> *
* @param command The string that will identify the action that must be taken.
*/
public void setActionCommand(final String command) {
putValue( ACTION_COMMAND_KEY, command );
}
/**
* Specify an action command string for this action.
*
* @return The string that will identify the action that must be taken.
*/
public String getActionCommand() {
return getValue( ACTION_COMMAND_KEY ) == null? null: getValue( ACTION_COMMAND_KEY ).toString();
}
/**
* {@inheritDoc}
*/
@Override
public void actionPerformed(final ActionEvent e) {
if (listener != null)
listener.actionPerformed( e );
}
}<|fim▁end|>
| |
<|file_name|>TcSets.java<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2010 Herve Quiroz
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.trancecode.collection;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSet.Builder;
import com.google.common.collect.Iterables;
<|fim▁hole|>
/**
* Utility methods related to {@link Set}.
*
* @author Herve Quiroz
*/
public final class TcSets
{
public static <T> ImmutableSet<T> immutableSet(final Iterable<T> set, final T element)
{
Preconditions.checkNotNull(set);
Preconditions.checkNotNull(element);
if (set instanceof Set && ((Set<?>) set).contains(element))
{
return ImmutableSet.copyOf(set);
}
final Builder<T> builder = ImmutableSet.builder();
return builder.addAll(set).add(element).build();
}
public static <T> ImmutableSet<T> immutableSet(final Set<T> set1, final Set<T> set2)
{
Preconditions.checkNotNull(set1);
Preconditions.checkNotNull(set2);
if (set1.isEmpty())
{
return ImmutableSet.copyOf(set2);
}
if (set2.isEmpty())
{
return ImmutableSet.copyOf(set1);
}
final Builder<T> builder = ImmutableSet.builder();
return builder.addAll(set1).addAll(set2).build();
}
public static <T> ImmutableSet<T> immutableSetWithout(final Iterable<T> elements, final T element)
{
Preconditions.checkNotNull(elements);
Preconditions.checkNotNull(element);
if (elements instanceof Set && !((Set<?>) elements).contains(element))
{
return ImmutableSet.copyOf(elements);
}
return ImmutableSet.copyOf(Iterables.filter(elements, Predicates.not(Predicates.equalTo(element))));
}
private TcSets()
{
// No instantiation
}
}<|fim▁end|>
|
import java.util.Set;
|
<|file_name|>scheduler.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
AGO_SCHEDULER_VERSION = '0.0.1'
############################################
"""
Basic class for device and device group schedule
"""
__author__ = "Joakim Lindbom"
__copyright__ = "Copyright 2017, Joakim Lindbom"
__date__ = "2017-01-27"
__credits__ = ["Joakim Lindbom", "The ago control team"]
__license__ = "GPL Public License Version 3"
__maintainer__ = "Joakim Lindbom"
__email__ = '[email protected]'
__status__ = "Experimental"
__version__ = AGO_SCHEDULER_VERSION
############################################
import time
from datetime import date, datetime
import sys
import json
all_days = {"mo", "tu", "we", "th", "fr", "sa", "su"}
class Scheduler:
def __init__(self, app):
self.rules = None
self.schedules = []
self.log = None
self.app = app
try:
self.log = app.log
except AttributeError:
#We seem to be in test mode, need a local logger
self.log = llog()
def parseJSON(self, filename):
with open(filename) as schedule_file:
schedule = json.load(schedule_file)
self.log.info("JSON file: {}".format(schedule))
if "rules" in schedule:
self.rules = Rules(schedule["rules"])
if "items" in schedule:
self.schedules = Schedules(schedule["items"], self.rules)
def new_day(self, weekday):
""" Load the schedules for the new day
E.g. called when it's 00:00
"""
self.schedules.weekday = weekday
class Schedules:
def __init__(self, jsonstr, rules):
self.schedules = []
self.activities = []
self.weekday = None
for element in jsonstr:
# self.log.trace(element)
item = Schedule(element, rules)
self.schedules.append(item)
# print item
def find(self, uuid):
rule = None
for r in self.rules:
if r.uuid == uuid:
rule = r
return rule
@property
def weekday(self):
"""Weekday property."""
print "getter of weekday called"
return self._weekday
@weekday.setter
def weekday(self, day):
print "setter of weekday called"
if day not in all_days:
raise ValueError
if self._weekday != day:
self.new_day(day)
self._weekday = day
def new_day(self, weekday):
self.activities = []
for s in self.schedules:
if weekday in s.days:
#found a day to include
self.activities.append(s)
print self.activities
print " "
class Schedule:
def __init__(self, jsonstr, rules=None):
self.device = None
self.scenario = None
self.group = None
if "device" in jsonstr:
self.device= jsonstr["device"]
if "scenario" in jsonstr:
self.scenario = jsonstr["scenario"]
if "group-uuid" in jsonstr:
self.group = jsonstr["group"]
self.enabled = jsonstr["enabled"]
self.schedules = {}
seq = 0
for a in jsonstr["actions"]:
seq += 1
x = {"action": a["action"], # On/Off/Run etc
"time": a["time"],
"enabled": a["enabled"]}
if "days" in a:
if a["days"] == "weekdays":
x["days"] = ["mo", "tu", "we", "th", "fr"]
elif a["days"] == "weekends":
x["days"] = ["sa", "su"]
elif a["days"] == "all":<|fim▁hole|> x["days"] = a["days"]
if "level" in a:
x["level"] = a["level"]
if "tolevel" in a:
x["tolevel"] = a["tolevel"]
if "endtime" in a:
x["endtime"] = a["endtime"]
if "seq" in a:
x["seq"] = a["seq"]
if "rule" in a:
x["rule-uuid"] = a["rule"]
x["rule"] = rules.find(a["rule"])
#print x["rule"]
self.schedules[seq] = x
#print (seq, self.schedules[seq])
def __str__(self):
s = "Schedule: "
if self.device is not None:
s += "Device {}".format(self.device)
if self.scenario is not None:
s += "Scenario {}".format(self.scenario)
if self.group is not None:
s += "Group {}".format(self.group)
s += "Enaled" if self.enabled else "Disabled"
s += "# schedules: {}".format(len(self.schedules))
return s
class Rules:
def __init__(self, jsonstr):
self.rules = []
for element in jsonstr:
# self.log.trace(element)
rule = Rule(element)
self.rules.append(rule)
#print rule
def find(self, uuid):
rule = None
for r in self.rules:
if r.uuid == uuid:
rule = r
return rule
class Rule:
def __init__(self, jsonstr):
self.name = jsonstr["name"]
self.uuid = jsonstr["uuid"]
self.rules = {}
#print self.name
seq = 0
for r in jsonstr["rules"]:
seq += 1
x = {"type": r["type"],
"variable": r["variable"],
"operator": r["operator"],
"value": r["value"]}
#print x
self.rules[seq] = x
#print (seq, self.rules[seq])
def __str__(self):
"""Return a string representing content f the Rule object"""
s = "name={}, uuid={}, type={}, # rules: {} ".format(self.name, self.uuid, self.type, len(self.rules))
return s
def execute(self):
results = []
for k, r in self.rules.iteritems():
if r["type"] == "variable check":
if r["variable"] == "HouseMode":
vv = "At home" # TODO: Get variable from inventory using r["variable"]
if r["variable"] == "test":
vv = "True"
if r["operator"] == 'eq':
if vv == r["value"]:
results.append(True)
else:
results.append(False)
return False
if r["operator"] == 'lt':
if vv < r["value"]:
results.append(True)
else:
results.append(False)
return False
return True
return True
def addlog(self, log):
self.log = log
class Days:
def __init__(self):
pass
class llog:
def __init__(self):
pass
def info(self, msg):
print ("INFO: %s" % msg)
def trace(self, msg):
print ("TRACE: %s" % msg)
def debug(self, msg):
print ("DEBUG: %s" % msg)
def error(self, msg):
print ("ERROR: %s" % msg)<|fim▁end|>
|
x["days"] = ["mo", "tu", "we", "th", "fr", "sa", "su"]
else:
|
<|file_name|>PullRequestHandler.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2016 Shredder121.
*
* 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.
*/
package com.github.shredder121.gh_event_api.handler.pull_request;
/**
* The handler interface for receiving {@code pull_request} events.
*
* @author Shredder121
*/
@FunctionalInterface
public interface PullRequestHandler {
void handle(PullRequestPayload payload);<|fim▁hole|><|fim▁end|>
|
}
|
<|file_name|>buildsets.py<|end_file_name|><|fim▁begin|># This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
"""
Support for buildsets in the database
"""
import sqlalchemy as sa
from buildbot.db import base
from buildbot.util import datetime2epoch
from buildbot.util import epoch2datetime
from buildbot.util import json
from twisted.internet import reactor
class BsDict(dict):
pass
class BuildsetsConnectorComponent(base.DBConnectorComponent):
# Documentation is in developer/database.rst
def addBuildset(self, sourcestampsetid, reason, properties, builderNames,
external_idstring=None, _reactor=reactor):
def thd(conn):
buildsets_tbl = self.db.model.buildsets
submitted_at = _reactor.seconds()
self.check_length(buildsets_tbl.c.reason, reason)
self.check_length(buildsets_tbl.c.external_idstring,
external_idstring)
transaction = conn.begin()
# insert the buildset itself
r = conn.execute(buildsets_tbl.insert(), dict(
sourcestampsetid=sourcestampsetid, submitted_at=submitted_at,
reason=reason, complete=0, complete_at=None, results=-1,
external_idstring=external_idstring))
bsid = r.inserted_primary_key[0]
# add any properties
if properties:
bs_props_tbl = self.db.model.buildset_properties
inserts = [
dict(buildsetid=bsid, property_name=k,
property_value=json.dumps([v, s]))
for k, (v, s) in properties.iteritems()]
for i in inserts:
self.check_length(bs_props_tbl.c.property_name,
i['property_name'])
conn.execute(bs_props_tbl.insert(), inserts)
# and finish with a build request for each builder. Note that
# sqlalchemy and the Python DBAPI do not provide a way to recover
# inserted IDs from a multi-row insert, so this is done one row at
# a time.
brids = {}
br_tbl = self.db.model.buildrequests
ins = br_tbl.insert()
for buildername in builderNames:
self.check_length(br_tbl.c.buildername, buildername)
r = conn.execute(ins,
dict(buildsetid=bsid, buildername=buildername, priority=0,
claimed_at=0, claimed_by_name=None,
claimed_by_incarnation=None, complete=0, results=-1,
submitted_at=submitted_at, complete_at=None))
brids[buildername] = r.inserted_primary_key[0]
transaction.commit()
return (bsid, brids)
return self.db.pool.do(thd)
def completeBuildset(self, bsid, results, complete_at=None,
_reactor=reactor):
if complete_at is not None:
complete_at = datetime2epoch(complete_at)
else:
complete_at = _reactor.seconds()
def thd(conn):
tbl = self.db.model.buildsets
q = tbl.update(whereclause=(
(tbl.c.id == bsid) &
((tbl.c.complete == None) | (tbl.c.complete != 1))))
res = conn.execute(q,
complete=1,
results=results,
complete_at=complete_at)
if res.rowcount != 1:
raise KeyError
return self.db.pool.do(thd)
def getBuildset(self, bsid):
def thd(conn):
bs_tbl = self.db.model.buildsets
q = bs_tbl.select(whereclause=(bs_tbl.c.id == bsid))
res = conn.execute(q)
row = res.fetchone()
if not row:
return None
return self._row2dict(row)
return self.db.pool.do(thd)
def getBuildsets(self, complete=None):
def thd(conn):
bs_tbl = self.db.model.buildsets
q = bs_tbl.select()
if complete is not None:
if complete:
q = q.where(bs_tbl.c.complete != 0)
else:
q = q.where((bs_tbl.c.complete == 0) |
(bs_tbl.c.complete == None))
res = conn.execute(q)
return [self._row2dict(row) for row in res.fetchall()]
return self.db.pool.do(thd)
def getRecentBuildsets(self, count, branch=None, repository=None,
complete=None):
def thd(conn):
bs_tbl = self.db.model.buildsets
ss_tbl = self.db.model.sourcestamps
j = sa.join(self.db.model.buildsets,
self.db.model.sourcestampsets)
j = j.join(self.db.model.sourcestamps)
q = sa.select(columns=[bs_tbl], from_obj=[j],
distinct=True)
q = q.order_by(sa.desc(bs_tbl.c.submitted_at))
q = q.limit(count)
if complete is not None:
if complete:
q = q.where(bs_tbl.c.complete != 0)
else:
q = q.where((bs_tbl.c.complete == 0) |
(bs_tbl.c.complete == None))
if branch:
q = q.where(ss_tbl.c.branch == branch)
if repository:
q = q.where(ss_tbl.c.repository == repository)
res = conn.execute(q)
return list(reversed([self._row2dict(row)
for row in res.fetchall()]))
return self.db.pool.do(thd)
def getBuildsetProperties(self, buildsetid):
"""
Return the properties for a buildset, in the same format they were
given to L{addBuildset}.
Note that this method does not distinguish a nonexistent buildset from
a buildset with no properties, and returns C{{}} in either case.
@param buildsetid: buildset ID
@returns: dictionary mapping property name to (value, source), via
Deferred
"""
def thd(conn):
bsp_tbl = self.db.model.buildset_properties
q = sa.select(
[bsp_tbl.c.property_name, bsp_tbl.c.property_value],
whereclause=(bsp_tbl.c.buildsetid == buildsetid))
l = []
for row in conn.execute(q):
try:
properties = json.loads(row.property_value)
l.append((row.property_name,
tuple(properties)))
except ValueError:
pass
return dict(l)
return self.db.pool.do(thd)
def _row2dict(self, row):
def mkdt(epoch):
if epoch:
return epoch2datetime(epoch)
return BsDict(external_idstring=row.external_idstring,<|fim▁hole|> submitted_at=mkdt(row.submitted_at),
complete=bool(row.complete),
complete_at=mkdt(row.complete_at), results=row.results,
bsid=row.id)<|fim▁end|>
|
reason=row.reason, sourcestampsetid=row.sourcestampsetid,
|
<|file_name|>resizeUninitialized.cpp<|end_file_name|><|fim▁begin|>///
/// @file resizeUninitialized.cpp
/// @brief Test resizeUninitialized() which resizes a std::vector
/// without default initialization.
///
/// Copyright (C) 2022 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/resizeUninitialized.hpp>
#include <stdint.h>
#include <iostream>
#include <vector>
#include <cstdlib>
void check(bool OK)
{
std::cout << " " << (OK ? "OK" : "ERROR") << "\n";
if (!OK)
std::exit(1);
}
int main()
{
std::size_t size = 100000;
uint64_t val = (1ull << 60) - 3;
{
std::vector<uint64_t> vect;
vect.resize(size, val);
// After resizeUninitialized() the old vector
// content must still be the same.
vect.clear();
resizeUninitialized(vect, size);
std::cout << "vect.size() = " << vect.size();
check(vect.size() == size);
std::cout << "vect.capacity() = " << vect.capacity();
check(vect.capacity() == size);
for (std::size_t i = 0; i < size; i += 37)
{
std::cout << "vect[" << i << "] = " << vect[i];
check(vect[i] == val);
}
// After resizeUninitialized() to a smaller size
// there must be no reallocation. The capacity
// must still be the same as before.
std::size_t newSize = size / 67;
resizeUninitialized(vect, newSize);
std::cout << "vect.size() = " << vect.size();
check(vect.size() == newSize);
std::cout << "vect.capacity() = " << vect.capacity();
check(vect.capacity() == size);
for (std::size_t i = 0; i < newSize; i += 37)
{
std::cout << "vect[" << i << "] = " << vect[i];
check(vect[i] == val);
}
// Test that reallocation works correctly.
// First print the current vector address.
uintptr_t address1 = (uintptr_t) vect.data();
std::cout << "1st vector allocation: " << address1 << std::endl;
// There must be no reallocation here.
vect.clear();
resizeUninitialized(vect, size);
uintptr_t address2 = (uintptr_t) vect.data();
std::cout << "1st vector allocation: " << address2 << std::endl;
if (address1 != address2)
{
std::cout << "address2 = " << address2;
check(address2 == address1);
std::exit(1);
}
// This causes a reallocation, the old vector
// content must be copied into the new vector.
resizeUninitialized(vect, size * 50);
uintptr_t address3 = (uintptr_t) vect.data();
std::cout << "2nd vector allocation: " << address3 << std::endl;
std::cout << "vect.size() = " << vect.size();<|fim▁hole|> check(vect.capacity() == size * 50);
for (std::size_t i = 0; i < size; i++)
{
if (vect[i] != val)
{
std::cout << "vect[" << i << "] = " << vect[i];
check(vect[i] == val);
std::exit(1);
}
}
}
std::cout << std::endl;
std::cout << "All tests passed successfully!" << std::endl;
return 0;
}<|fim▁end|>
|
check(vect.size() == size * 50);
std::cout << "vect.capacity() = " << vect.capacity();
|
<|file_name|>shortcuts.py<|end_file_name|><|fim▁begin|>"""
This module collects helper functions and classes that "span" multiple levels
of MVC. In other words, these functions/classes introduce controlled coupling
for convenience's sake.
"""
from django.http import (
Http404, HttpResponse, HttpResponsePermanentRedirect, HttpResponseRedirect,
)
from django.template import loader
from django.urls import NoReverseMatch, reverse
from django.utils.functional import Promise
def render(request, template_name, context=None, content_type=None, status=None, using=None):
"""
Return a HttpResponse whose content is filled with the result of calling
django.template.loader.render_to_string() with the passed arguments.
"""
content = loader.render_to_string(template_name, context, request, using=using)
return HttpResponse(content, content_type, status)
def redirect(to, *args, permanent=False, **kwargs):
"""
Return an HttpResponseRedirect to the appropriate URL for the arguments
passed.
The arguments could be:
* A model: the model's `get_absolute_url()` function will be called.
* A view name, possibly with arguments: `urls.reverse()` will be used
to reverse-resolve the name.
* A URL, which will be used as-is for the redirect location.
Issues a temporary redirect by default; pass permanent=True to issue a
permanent redirect.
"""
redirect_class = HttpResponsePermanentRedirect if permanent else HttpResponseRedirect
return redirect_class(resolve_url(to, *args, **kwargs))
def _get_queryset(klass):
"""
Return a QuerySet or a Manager.
Duck typing in action: any class with a `get()` method (for
get_object_or_404) or a `filter()` method (for get_list_or_404) might do
the job.
"""
# If it is a model class or anything else with ._default_manager
if hasattr(klass, '_default_manager'):
return klass._default_manager.all()
return klass
def get_object_or_404(klass, *args, **kwargs):
"""
Use get() to return an object, or raise a Http404 exception if the object
does not exist.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the get() query.
Like with QuerySet.get(), MultipleObjectsReturned is raised if more than
one object is found.
"""
queryset = _get_queryset(klass)
if not hasattr(queryset, 'get'):
klass__name = klass.__name__ if isinstance(klass, type) else klass.__class__.__name__
raise ValueError(
"First argument to get_object_or_404() must be a Model, Manager, "
"or QuerySet, not '%s'." % klass__name
)
try:
return queryset.get(*args, **kwargs)
except queryset.model.DoesNotExist:
raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
def get_list_or_404(klass, *args, **kwargs):
"""
Use filter() to return a list of objects, or raise a Http404 exception if
the list is empty.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the filter() query.
"""
queryset = _get_queryset(klass)
if not hasattr(queryset, 'filter'):
klass__name = klass.__name__ if isinstance(klass, type) else klass.__class__.__name__
raise ValueError(
"First argument to get_list_or_404() must be a Model, Manager, or "
"QuerySet, not '%s'." % klass__name
)
obj_list = list(queryset.filter(*args, **kwargs))
if not obj_list:
raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
return obj_list
def resolve_url(to, *args, **kwargs):
"""
Return a URL appropriate for the arguments passed.<|fim▁hole|> * A model: the model's `get_absolute_url()` function will be called.
* A view name, possibly with arguments: `urls.reverse()` will be used
to reverse-resolve the name.
* A URL, which will be returned as-is.
"""
# If it's a model, use get_absolute_url()
if hasattr(to, 'get_absolute_url'):
return to.get_absolute_url()
if isinstance(to, Promise):
# Expand the lazy instance, as it can cause issues when it is passed
# further to some Python functions like urlparse.
to = str(to)
if isinstance(to, str):
# Handle relative URLs
if to.startswith(('./', '../')):
return to
# Next try a reverse URL resolution.
try:
return reverse(to, args=args, kwargs=kwargs)
except NoReverseMatch:
# If this is a callable, re-raise.
if callable(to):
raise
# If this doesn't "feel" like a URL, re-raise.
if '/' not in to and '.' not in to:
raise
# Finally, fall back and assume it's a URL
return to<|fim▁end|>
|
The arguments could be:
|
<|file_name|>JbossDeployBehavior.java<|end_file_name|><|fim▁begin|>package com.pahlsoft.ws.iaas.provision.deploy.behaviors;
import org.apache.log4j.Logger;
import com.pahlsoft.ws.iaas.provision.generated.InstructionType;
import com.pahlsoft.ws.iaas.provision.generated.ProvisionProperties;
import com.pahlsoft.ws.iaas.provision.generated.ProvisionResponse;
import com.pahlsoft.ws.iaas.utilities.PropertyParser;
public class JbossDeployBehavior implements DeployBehavior {
public Logger LOG = Logger.getLogger(JbossDeployBehavior.class);
public ProvisionResponse pr = new ProvisionResponse();
public ProvisionResponse deploy(String hostname, ProvisionProperties props) {
LOG.info("Deploying JBOSS :" + hostname);
PropertyParser.listProps(props);
pr.setHostname(hostname);
pr.setProperties(props);
pr.setInstruction(InstructionType.DEPLOY);
pr.setStatus(true);
return pr;
}
public ProvisionResponse redeploy(String hostname, ProvisionProperties props) {
LOG.info("Redeploying JBOSS :" + hostname);
PropertyParser.listProps(props);
pr.setHostname(hostname);
pr.setProperties(props);
pr.setInstruction(InstructionType.REDEPLOY);
pr.setStatus(true);
return pr;
}
public ProvisionResponse clean(String hostname, ProvisionProperties props) {
LOG.info("Cleaning JBOSS :" + hostname);
PropertyParser.listProps(props);
pr.setHostname(hostname);
pr.setProperties(props);
pr.setInstruction(InstructionType.CLEAN);
pr.setStatus(true);
return pr;
}
public ProvisionResponse backup(String hostname, ProvisionProperties props) {
LOG.info("Backing Up JBOSS :" + hostname);
PropertyParser.listProps(props);
pr.setHostname(hostname);
pr.setProperties(props);
pr.setInstruction(InstructionType.BACKUP);
pr.setStatus(true);
return pr;<|fim▁hole|> public ProvisionResponse configure(String hostname, ProvisionProperties props) {
LOG.info("Configuring JBOSS :" + hostname);
PropertyParser.listProps(props);
pr.setHostname(hostname);
pr.setProperties(props);
pr.setInstruction(InstructionType.CONFIGURE);
pr.setStatus(true);
return pr;
}
public ProvisionResponse install(String hostname, ProvisionProperties props) {
LOG.info("Installing JBOSS :" + hostname);
PropertyParser.listProps(props);
pr.setHostname(hostname);
pr.setProperties(props);
pr.setInstruction(InstructionType.INSTALL);
pr.setStatus(true);
return pr;
}
}<|fim▁end|>
|
}
|
<|file_name|>_vsrc.py<|end_file_name|><|fim▁begin|>import _plotly_utils.basevalidators
class VsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(self, plotly_name="vsrc", parent_name="cone", **kwargs):
super(VsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "none"),<|fim▁hole|><|fim▁end|>
|
role=kwargs.pop("role", "info"),
**kwargs
)
|
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>pub mod session;
pub mod templating;<|fim▁hole|><|fim▁end|>
|
pub mod util;
|
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>// Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use futures::{future::BoxFuture, Future, FutureExt, TryFutureExt};
use std::{
error, fmt, io,
pin::Pin,
process::{ExitStatus, Output},
};
pub use tokio::process::{Child, Command};
#[cfg(feature = "warp-errs")]
use warp::reject;
#[derive(Debug)]
pub enum CmdError {
Io(io::Error),
Output(Output),
}
#[cfg(feature = "warp-errs")]
impl reject::Reject for CmdError {}
impl fmt::Display for CmdError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
CmdError::Io(ref err) => write!(f, "{}", err),
CmdError::Output(ref err) => write!(
f,
"{}, stdout: {}, stderr: {}",
err.status,
String::from_utf8_lossy(&err.stdout),
String::from_utf8_lossy(&err.stderr)
),
}
}
}
impl std::error::Error for CmdError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match *self {
CmdError::Io(ref err) => Some(err),
CmdError::Output(_) => None,
}
}
}
impl From<io::Error> for CmdError {
fn from(err: io::Error) -> Self {
CmdError::Io(err)
}
}
impl From<Output> for CmdError {
fn from(output: Output) -> Self {
CmdError::Output(output)
}
}
fn handle_status(x: ExitStatus) -> Result<(), io::Error> {
if x.success() {
Ok(())
} else {
let err = io::Error::new(
io::ErrorKind::Other,
format!("process exited with code: {:?}", x.code()),
);
Err(err)
}
}
pub trait CheckedCommandExt {
fn checked_status(&mut self) -> BoxFuture<Result<(), CmdError>>;
fn checked_output(&mut self) -> BoxFuture<Result<Output, CmdError>>;
}
impl CheckedCommandExt for Command {
/// Similar to `status`, but returns `Err` if the exit code is non-zero.
fn checked_status(&mut self) -> BoxFuture<Result<(), CmdError>> {
tracing::debug!("Running cmd: {:?}", self);
self.status()
.and_then(|x| async move { handle_status(x) })
.err_into()
.boxed()
}
/// Similar to `output`, but returns `Err` if the exit code is non-zero.
fn checked_output(&mut self) -> BoxFuture<Result<Output, CmdError>> {
tracing::debug!("Running cmd: {:?}", self);
self.output()
.err_into()
.and_then(|x| async {
if x.status.success() {
Ok(x)
} else {
Err(x.into())
}
})
.boxed()
}
}
pub trait CheckedChildExt {
fn wait_with_checked_output(
self,
) -> Pin<Box<dyn Future<Output = Result<Output, CmdError>> + Send>>;
}
impl CheckedChildExt for Child {
fn wait_with_checked_output(
self,
) -> Pin<Box<dyn Future<Output = Result<Output, CmdError>> + Send>> {<|fim▁hole|> tracing::debug!("Child waiting for output: {:?}", self);
self.wait_with_output()
.err_into()
.and_then(|x| async {
if x.status.success() {
Ok(x)
} else {
Err(x.into())
}
})
.boxed()
}
}<|fim▁end|>
| |
<|file_name|>sweetalert.component.spec.ts<|end_file_name|><|fim▁begin|>import { SweetAlertComponent } from './sweetalert.component';
describe('Component: SweetAlert', () => {
it('should create an instance', () => {
const instance = new SweetAlertComponent();
expect(instance).toBeTruthy();
<|fim▁hole|><|fim▁end|>
|
});
});
|
<|file_name|>CNN.py<|end_file_name|><|fim▁begin|>import os
import sys
root_path = os.path.abspath("../../../")
if root_path not in sys.path:
sys.path.append(root_path)
import numpy as np
import tensorflow as tf
from _Dist.NeuralNetworks.Base import Generator4d
from _Dist.NeuralNetworks.h_RNN.RNN import Basic3d
from _Dist.NeuralNetworks.NNUtil import Activations
class Basic4d(Basic3d):
def _calculate(self, x, y=None, weights=None, tensor=None, n_elem=1e7, is_training=False):
return super(Basic4d, self)._calculate(x, y, weights, tensor, n_elem / 10, is_training)
class CNN(Basic4d):
def __init__(self, *args, **kwargs):
self.height, self.width = kwargs.pop("height", None), kwargs.pop("width", None)
super(CNN, self).__init__(*args, **kwargs)
self._name_appendix = "CNN"
self._generator_base = Generator4d
self.conv_activations = None
self.n_filters = self.filter_sizes = self.poolings = None
def init_model_param_settings(self):
super(CNN, self).init_model_param_settings()
self.conv_activations = self.model_param_settings.get("conv_activations", "relu")
def init_model_structure_settings(self):
super(CNN, self).init_model_structure_settings()
self.n_filters = self.model_structure_settings.get("n_filters", [32, 32])
self.filter_sizes = self.model_structure_settings.get("filter_sizes", [(3, 3), (3, 3)])
self.poolings = self.model_structure_settings.get("poolings", [None, "max_pool"])
if not len(self.filter_sizes) == len(self.poolings) == len(self.n_filters):
raise ValueError("Length of filter_sizes, n_filters & pooling should be the same")
if isinstance(self.conv_activations, str):
self.conv_activations = [self.conv_activations] * len(self.filter_sizes)<|fim▁hole|> if self.height is None or self.width is None:
assert len(x.shape) == 4, "height and width are not provided, hence len(x.shape) should be 4"
self.height, self.width = x.shape[1:3]
if len(x.shape) == 2:
x = x.reshape(len(x), self.height, self.width, -1)
else:
assert self.height == x.shape[1], "height is set to be {}, but {} found".format(self.height, x.shape[1])
assert self.width == x.shape[2], "width is set to be {}, but {} found".format(self.height, x.shape[2])
if x_test is not None and len(x_test.shape) == 2:
x_test = x_test.reshape(len(x_test), self.height, self.width, -1)
super(CNN, self).init_from_data(x, y, x_test, y_test, sample_weights, names)
def _define_input_and_placeholder(self):
self._is_training = tf.placeholder(tf.bool, name="is_training")
self._tfx = tf.placeholder(tf.float32, [None, self.height, self.width, self.n_dim], name="X")
self._tfy = tf.placeholder(tf.float32, [None, self.n_class], name="Y")
def _build_model(self, net=None):
self._model_built = True
if net is None:
net = self._tfx
for i, (filter_size, n_filter, pooling) in enumerate(zip(
self.filter_sizes, self.n_filters, self.poolings
)):
net = tf.layers.conv2d(net, n_filter, filter_size, padding="same")
net = tf.layers.batch_normalization(net, training=self._is_training)
activation = self.conv_activations[i]
if activation is not None:
net = getattr(Activations, activation)(net, activation)
net = tf.layers.dropout(net, training=self._is_training)
if pooling is not None:
net = tf.layers.max_pooling2d(net, 2, 2, name="pool")
fc_shape = np.prod([net.shape[i].value for i in range(1, 4)])
net = tf.reshape(net, [-1, fc_shape])
super(CNN, self)._build_model(net)<|fim▁end|>
|
def init_from_data(self, x, y, x_test, y_test, sample_weights, names):
|
<|file_name|>wsgi.py<|end_file_name|><|fim▁begin|>"""
WSGI config for pyday2016 project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/<|fim▁hole|>from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pyday2016.settings")
application = get_wsgi_application()<|fim▁end|>
|
"""
import os
|
<|file_name|>Invoker.java<|end_file_name|><|fim▁begin|>package net.butfly.bus.invoker;
import net.butfly.albacore.service.Service;
import net.butfly.albacore.utils.async.Options;
import net.butfly.bus.Request;
import net.butfly.bus.Response;
import net.butfly.bus.config.bean.InvokerConfig;
import net.butfly.bus.context.Token;
import net.butfly.bus.policy.Routeable;
public interface Invoker extends Routeable {
void initialize(InvokerConfig config, Token token);
void initialize();
Response invoke(Request request, Options... remoteOptions) throws Exception;
Object[] getBeanList();<|fim▁hole|>
<S extends Service> S awared(Class<S> awaredServiceClass);
Token token();
Options localOptions(Options... options);
Options[] remoteOptions(Options... options);
boolean lazy();
}<|fim▁end|>
| |
<|file_name|>loggedin.py<|end_file_name|><|fim▁begin|>import logging
from joj.lib.base import *<|fim▁hole|>
class LoggedinController(BaseController):
def index(self):
#self closes window
return '<html><head></head><body onload="window.close()"></body></html>'<|fim▁end|>
|
from paste.request import parse_querystring
import urllib2
log = logging.getLogger(__name__)
|
<|file_name|>util.py<|end_file_name|><|fim▁begin|># urllib3/util.py
# Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt)
#
# This module is part of urllib3 and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from __future__ import absolute_import
from base64 import b64encode
from socket import error as SocketError
from hashlib import md5, sha1
from binascii import hexlify, unhexlify
import sys
from core.backports.collections import namedtuple
try:
from select import poll, POLLIN
except ImportError: # `poll` doesn't exist on OSX and other platforms
poll = False
try:
from select import select
except ImportError: # `select` doesn't exist on AppEngine.
select = False
try: # Test for SSL features
SSLContext = None
HAS_SNI = False
import ssl
from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv23
from ssl import SSLContext # Modern SSL?
from ssl import HAS_SNI # Has SNI?
except ImportError:
pass
from .packages import six
from .exceptions import LocationParseError, SSLError
class Url(namedtuple('Url', ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'])):
"""
Datastructure for representing an HTTP URL. Used as a return value for
:func:`parse_url`.
"""
slots = ()
def __new__(cls, scheme=None, auth=None, host=None, port=None, path=None, query=None, fragment=None):
return super(Url, cls).__new__(cls, scheme, auth, host, port, path, query, fragment)
@property
def hostname(self):
"""For backwards-compatibility with urlparse. We're nice like that."""
return self.host
@property
def request_uri(self):
"""Absolute path including the query string."""
uri = self.path or '/'
if self.query is not None:
uri += '?' + self.query
return uri
def split_first(s, delims):
"""
Given a string and an iterable of delimiters, split on the first found
delimiter. Return two split parts and the matched delimiter.
If not found, then the first part is the full input string.
Example: ::
>>> split_first('foo/bar?baz', '?/=')
('foo', 'bar?baz', '/')
>>> split_first('foo/bar?baz', '123')
('foo/bar?baz', '', None)
Scales linearly with number of delims. Not ideal for large number of delims.
"""
min_idx = None
min_delim = None
for d in delims:
idx = s.find(d)
if idx < 0:
continue
if min_idx is None or idx < min_idx:
min_idx = idx
min_delim = d
if min_idx is None or min_idx < 0:
return s, '', None
return s[:min_idx], s[min_idx+1:], min_delim
def parse_url(url):
"""
Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is
performed to parse incomplete urls. Fields not provided will be None.
Partly backwards-compatible with :mod:`urlparse`.
Example: ::
>>> parse_url('http://google.com/mail/')
Url(scheme='http', host='google.com', port=None, path='/', ...)
>>> parse_url('google.com:80')
Url(scheme=None, host='google.com', port=80, path=None, ...)
>>> parse_url('/foo?bar')
Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)
"""
# While this code has overlap with stdlib's urlparse, it is much
# simplified for our needs and less annoying.
# Additionally, this imeplementations does silly things to be optimal
# on CPython.
scheme = None
auth = None
host = None
port = None
path = None
fragment = None
query = None
# Scheme
if '://' in url:
scheme, url = url.split('://', 1)
# Find the earliest Authority Terminator
# (http://tools.ietf.org/html/rfc3986#section-3.2)
url, path_, delim = split_first(url, ['/', '?', '#'])
if delim:
# Reassemble the path
path = delim + path_
# Auth
if '@' in url:
auth, url = url.split('@', 1)
# IPv6
if url and url[0] == '[':
host, url = url[1:].split(']', 1)
# Port
if ':' in url:
_host, port = url.split(':', 1)
if not host:
host = _host
if not port.isdigit():
raise LocationParseError("Failed to parse: %s" % url)
port = int(port)
elif not host and url:
host = url
if not path:
return Url(scheme, auth, host, port, path, query, fragment)
# Fragment
if '#' in path:
path, fragment = path.split('#', 1)
# Query
if '?' in path:
path, query = path.split('?', 1)
return Url(scheme, auth, host, port, path, query, fragment)
def get_host(url):
"""
Deprecated. Use :func:`.parse_url` instead.
"""
p = parse_url(url)
return p.scheme or 'http', p.hostname, p.port
def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,
basic_auth=None):
"""
Shortcuts for generating request headers.
:param keep_alive:
If ``True``, adds 'connection: keep-alive' header.
:param accept_encoding:
Can be a boolean, list, or string.
``True`` translates to 'gzip,deflate'.
List will get joined by comma.
String will be used as provided.
:param user_agent:
String representing the user-agent you want, such as
"python-urllib3/0.6"
:param basic_auth:
Colon-separated username:password string for 'authorization: basic ...'
auth header.
Example: ::
>>> make_headers(keep_alive=True, user_agent="Batman/1.0")
{'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}
>>> make_headers(accept_encoding=True)
{'accept-encoding': 'gzip,deflate'}
"""
headers = {}
if accept_encoding:
if isinstance(accept_encoding, str):
pass
elif isinstance(accept_encoding, list):
accept_encoding = ','.join(accept_encoding)
else:
accept_encoding = 'gzip,deflate'
headers['accept-encoding'] = accept_encoding
if user_agent:
headers['user-agent'] = user_agent
if keep_alive:
headers['connection'] = 'keep-alive'
if basic_auth:
headers['authorization'] = 'Basic ' + \
b64encode(six.b(basic_auth)).decode('utf-8')
return headers
def is_connection_dropped(conn): # Platform-specific
"""
Returns True if the connection is dropped and should be closed.
:param conn:
:class:`httplib.HTTPConnection` object.
Note: For platforms like AppEngine, this will always return ``False`` to
let the platform handle connection recycling transparently for us.
"""
sock = getattr(conn, 'sock', False)
if not sock: # Platform-specific: AppEngine
return False
if not poll:
if not select: # Platform-specific: AppEngine
return False
try:
return select([sock], [], [], 0.0)[0]
except SocketError:
return True
# This version is better on platforms that support it.
p = poll()
p.register(sock, POLLIN)
for (fno, ev) in p.poll(0.0):
if fno == sock.fileno():
# Either data is buffered (bad), or the connection is dropped.
return True
def resolve_cert_reqs(candidate):
"""
Resolves the argument to a numeric constant, which can be passed to
the wrap_socket function/method from the ssl module.
Defaults to :data:`ssl.CERT_NONE`.
If given a string it is assumed to be the name of the constant in the
:mod:`ssl` module or its abbrevation.
(So you can specify `REQUIRED` instead of `CERT_REQUIRED`.
If it's neither `None` nor a string we assume it is already the numeric
constant which can directly be passed to wrap_socket.
"""
if candidate is None:
return CERT_NONE
if isinstance(candidate, str):
res = getattr(ssl, candidate, None)
if res is None:
res = getattr(ssl, 'CERT_' + candidate)
return res
return candidate
def resolve_ssl_version(candidate):
"""
like resolve_cert_reqs
"""
if candidate is None:
return PROTOCOL_SSLv23
if isinstance(candidate, str):
res = getattr(ssl, candidate, None)
if res is None:
res = getattr(ssl, 'PROTOCOL_' + candidate)
return res
return candidate
def assert_fingerprint(cert, fingerprint):
"""
Checks if given fingerprint matches the supplied certificate.
:param cert:
Certificate as bytes object.
:param fingerprint:
Fingerprint as string of hexdigits, can be interspersed by colons.
"""
# Maps the length of a digest to a possible hash function producing
# this digest.
hashfunc_map = {
16: md5,
20: sha1
}
fingerprint = fingerprint.replace(':', '').lower()
digest_length, rest = divmod(len(fingerprint), 2)
if rest or digest_length not in hashfunc_map:
raise SSLError('Fingerprint is of invalid length.')
# We need encode() here for py32; works on py2 and p33.
fingerprint_bytes = unhexlify(fingerprint.encode())
hashfunc = hashfunc_map[digest_length]
cert_digest = hashfunc(cert).digest()
if not cert_digest == fingerprint_bytes:
raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".'
.format(hexlify(fingerprint_bytes),
hexlify(cert_digest)))
if SSLContext is not None: # Python 3.2+
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
ca_certs=None, server_hostname=None,
ssl_version=None):
"""
All arguments except `server_hostname` have the same meaning as for
:func:`ssl.wrap_socket`
:param server_hostname:
Hostname of the expected certificate
"""
context = SSLContext(ssl_version)<|fim▁hole|> try:
context.load_verify_locations(ca_certs)
# Py32 raises IOError
# Py33 raises FileNotFoundError
except Exception: # Reraise as SSLError
e = sys.exc_info()[1]
raise SSLError(e)
if certfile:
# FIXME: This block needs a test.
context.load_cert_chain(certfile, keyfile)
if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI
return context.wrap_socket(sock, server_hostname=server_hostname)
return context.wrap_socket(sock)
else: # Python 3.1 and earlier
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
ca_certs=None, server_hostname=None,
ssl_version=None):
return wrap_socket(sock, keyfile=keyfile, certfile=certfile,
ca_certs=ca_certs, cert_reqs=cert_reqs,
ssl_version=ssl_version)<|fim▁end|>
|
context.verify_mode = cert_reqs
if ca_certs:
|
<|file_name|>extern-yield.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate libc;<|fim▁hole|>
mod rustrt {
extern crate libc;
#[link(name = "rustrt")]
extern {
pub fn rust_dbg_call(cb: extern "C" fn (libc::uintptr_t) -> libc::uintptr_t,
data: libc::uintptr_t)
-> libc::uintptr_t;
}
}
extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t {
if data == 1u {
data
} else {
count(data - 1u) + count(data - 1u)
}
}
fn count(n: uint) -> uint {
unsafe {
task::deschedule();
rustrt::rust_dbg_call(cb, n)
}
}
pub fn main() {
for _ in range(0, 10u) {
task::spawn(proc() {
let result = count(5u);
println!("result = {}", result);
assert_eq!(result, 16u);
});
}
}<|fim▁end|>
|
use std::task;
|
<|file_name|>test_cli_config.py<|end_file_name|><|fim▁begin|>import click
import mock
import pytest
from click.testing import CliRunner
from sigopt.cli import cli
class TestRunCli(object):
@pytest.mark.parametrize('opt_into_log_collection', [False, True])
@pytest.mark.parametrize('opt_into_cell_tracking', [False, True])
def test_config_command(self, opt_into_log_collection, opt_into_cell_tracking):
runner = CliRunner()
log_collection_arg = '--enable-log-collection' if opt_into_log_collection else '--no-enable-log-collection'
cell_tracking_arg = '--enable-cell-tracking' if opt_into_cell_tracking else '--no-enable-cell-tracking'
with mock.patch('sigopt.cli.commands.config._config.persist_configuration_options') as persist_configuration_options:
result = runner.invoke(cli, [
'config',
'--api-token=some_test_token',
log_collection_arg,
cell_tracking_arg,
])
persist_configuration_options.assert_called_once_with({<|fim▁hole|> assert result.exit_code == 0
assert result.output == ''<|fim▁end|>
|
'api_token': 'some_test_token',
'code_tracking_enabled': opt_into_cell_tracking,
'log_collection_enabled': opt_into_log_collection,
})
|
<|file_name|>file_io.go<|end_file_name|><|fim▁begin|>package fakes
import "os"
type FileIO struct {
TempFileCall struct {
CallCount int
Receives struct {
Dir string
Prefix string
}
Returns struct {
File *os.File
Error error
}
}
ReadFileCall struct {
CallCount int
Receives struct {
Filename string
}
Returns struct {
Contents []byte
Error error
}
}
WriteFileCall struct {
CallCount int
Receives struct {
Filename string
Contents []byte<|fim▁hole|> }
Returns struct {
Error error
}
}
StatCall struct {
CallCount int
Receives struct {
Name string
}
Returns struct {
FileInfo os.FileInfo
Error error
}
}
}
func (fake *FileIO) TempFile(dir, prefix string) (f *os.File, err error) {
fake.TempFileCall.CallCount++
fake.TempFileCall.Receives.Dir = dir
fake.TempFileCall.Receives.Prefix = prefix
return fake.TempFileCall.Returns.File, fake.TempFileCall.Returns.Error
}
func (fake *FileIO) ReadFile(filename string) ([]byte, error) {
fake.ReadFileCall.CallCount++
fake.ReadFileCall.Receives.Filename = filename
return fake.ReadFileCall.Returns.Contents, fake.ReadFileCall.Returns.Error
}
func (fake *FileIO) WriteFile(filename string, contents []byte, perm os.FileMode) error {
fake.WriteFileCall.CallCount++
fake.WriteFileCall.Receives.Filename = filename
fake.WriteFileCall.Receives.Contents = contents
return fake.WriteFileCall.Returns.Error
}
func (fake *FileIO) Stat(name string) (os.FileInfo, error) {
fake.StatCall.CallCount++
fake.StatCall.Receives.Name = name
return fake.StatCall.Returns.FileInfo, fake.StatCall.Returns.Error
}<|fim▁end|>
| |
<|file_name|>OpenLayers.js<|end_file_name|><|fim▁begin|>// ----------------------------------------------------------------------------
// To provide some additional features for OpenLayers, portions of the OpenLayers support
// have been copied from 'mapstraction.js' [www.mapstraction.com] which includes the
// copyright included below.
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Copyright (c) 2006-7, Tom Carden, Steve Coast, Mikel Maron, Andrew Turner, Henri Bergius
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// * Neither the name of the Mapstraction nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific prior written
// permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Required funtions defined by this module:
// new JSMap(String mapID)
// JSClearLayers()
// JSSetCenter(JSMapPoint center)
// JSDrawPushpins(JSMapPushpin pushPin[], int recenterMode, int replay)
// JSDrawPOI(JSMapPushpin pushPin[])
// JSDrawRoute(JSMapPoint points[], String color)
// JSDrawShape(String type, double radius, JSMapPoint points[], String color, boolean zoomTo)
// JSDrawGeozone(int type, double radius, JSMapPoint points[], String color, int primaryIndex)
// JSShowPushpin(JSMapPushpin pushPin, boolean center)
// JSPauseReplay(int replay)
// JSUnload()
// ----------------------------------------------------------------------------
// UserAgents:
// - "/MSIE/.test(navigator.userAgent)"
// - "/Firefox/.test(navigator.userAgent)"
// - "/Safari/.test(navigator.userAgent)"
// ----------------------------------------------------------------------------
// References:
// - http://openlayers.org/dev/examples/
// OpenLayers Modify Feature Example
// Popup Matrix
// Drawing Simple Vector Features Example
// Wrapping the Date Line
// OpenLayers.Handler.Point
// ----------------------------------------------------------------------------
// Change History:
// 2008/07/08 Martin D. Flynn
// -Initial release
// 2008/07/27 Martin D. Flynn
// -Modified 'JSMap.prototype._addPushpin' to set the proper 'iconAnchor' value
// 2008/08/08 Martin D. Flynn
// -Added support for Geozones
// 2008/08/15 Martin D. Flynn
// -Many changes to make this work better with MS IE.
// 2008/08/24 Martin D. Flynn
// -Added 'replay' support.
// 2008/09/01 Martin D. Flynn
// -Modified Geozome mouse behavior (click to recenter, shift-drag to resize).
// 2008/10/16 Martin D. Flynn
// -Initial support for GeoServer
// 2008/12/01 Martin D. Flynn
// -Removed the 'short' zoom control display (both the zoom-drag bar and the
// short zoom bar were previously displayed on the map simultaneously).
// 2009/08/23 Martin D. Flynn
// -Added color argument to JSDrawRoute
// -Added option for drawing multiple points per device on fleet map
// 2010/04/11 Martin D. Flynn
// -Added support for drawing polygon and corridor geozones. However, in the
// case of corridor geozones, additional GTS features may be required to
// fully utilize this type of geozone.
// ----------------------------------------------------------------------------
var DRAG_NONE = 0x00;
var DRAG_RULER = 0x01;
var DRAG_GEOZONE = 0x10;
var DRAG_GEOZONE_CENTER = 0x11;
var DRAG_GEOZONE_RADIUS = 0x12;
// ----------------------------------------------------------------------------
function OpenLayersColorStyle(borderColor, borderOpacity, fillColor, fillOpacity)
{
this.strokeColor = borderColor;
this.strokeOpacity = borderOpacity;
this.strokeWidth = 1;
this.fillColor = fillColor;
this.fillOpacity = fillOpacity;
};
var GEOZONE_STYLE = [
new OpenLayersColorStyle("#CC1111", 0.80, "#11CC22", 0.28), /* primary */
new OpenLayersColorStyle("#11CC11", 0.80, "#11CC22", 0.18)
];
function GetGeozoneStyle(isPrimary, fillColor)
{
var s = GEOZONE_STYLE[isPrimary? 0 : 1];
if (fillColor && (fillColor != "")) {
return new OpenLayersColorStyle(
s.strokeColor, s.strokeOpacity,
fillColor, s.fillOpacity);
} else {
return s;
}
};
//var DRAW_ZONE_POINT_RADIUS_POLYGON = false;
// ----------------------------------------------------------------------------
/**
*** JSMap constructor
**/
function JSMap(mapElement)
{
/* custom fix for MSIE */
this.userAgent_MSIE = /MSIE/.test(navigator.userAgent);
/* crosshair mouse cursor */
mapElement.style.cursor = "crosshair";
/* OpenStreetMaps */
if (GEOSERVER_enable) {
this._initGeoServerCustom(mapElement);
} else {
this._initOpenStreetMaps(mapElement);
}
/* pan/zoom bar */
//this.openLayersMap.addControl(new OpenLayers.Control.PanZoomBar());
/* disable double-click zoom */
// this seems to also disable the shift-drag zoom.
var nav = new OpenLayers.Control.Navigation({
defaultDblClick: function(e) {/*no-op*/}
});
this.openLayersMap.addControl(nav);
/* "ruler" layer */
this.rulerFeatures = null;
this.rulerLayer = new OpenLayers.Layer.Vector('rulerLayer');
this.openLayersMap.addLayer(this.rulerLayer);
/* POI layer */
this.poiLayer = new OpenLayers.Layer.Markers('poiLayer');
this.openLayersMap.addLayer(this.poiLayer);
/* route/zone layer */
this.routeLines = []; // JSMapPoint[]
this.primaryIndex = -1;
this.primaryCenter = null; // OpenLayers.LonLat
this.geozonePoints = null; // JSMapPoint[]
this.dragZoneOffsetLat = 0.0;
this.dragZoneOffsetLon = 0.0;
this.drawFeatures = null;
this.drawShapes = [];
this.drawLayer = [];
// drawLayer0
this.drawLayer.push(new OpenLayers.Layer.Vector('drawLayer0'));
this.openLayersMap.addLayer(this.drawLayer[this.drawLayer.length - 1]);
// drawLayer1
//this.drawLayer.push(new OpenLayers.Layer.Vector('drawLayer0'));
//this.openLayersMap.addLayer(this.drawLayer[this.drawLayer.length - 1);
/* marker/pushpin layer */
this.markerLayer = new OpenLayers.Layer.Markers('markerLayer');
this.openLayersMap.addLayer(this.markerLayer);
this.visiblePopupInfoBox = null; // JSMapPushpin
/* replay vars */
this.replayTimer = null;
this.replayIndex = 0;
this.replayInterval = (REPLAY_INTERVAL < 100)? 100 : REPLAY_INTERVAL;
this.replayInProgress = false;
this.replayPushpins = [];
/* mouse event handlers */
this.dragType = DRAG_NONE;
this.dragRulerStart = null;
this.dragRulerEnd = null;
try {
this.openLayersMap.events.registerPriority("mousemove", this, this._event_OnMouseMove );
this.openLayersMap.events.registerPriority("mousedown", this, this._event_OnMouseDown );
this.openLayersMap.events.registerPriority("mouseup" , this, this._event_OnMouseUp );
} catch (e) {
//alert("Error: " + e);
}
/* "click" handler to recenter geozones */
try {
this.openLayersMap.events.register("click", this, this._event_OnClick);
} catch (e) {
//alert("Error: " + e);
}
/* init lat/lon display */
jsmSetLatLonDisplay(0,0);
/* zoom event */
this.lastMapZoom = 0;
this.lastMapSize = new OpenLayers.Size(0,0);
try {
//this.openLayersMap.events.register("zoomend", this, this._event_ZoomEnd);
this.openLayersMap.events.register("moveend", this, this._event_MoveEnd);
} catch (e) {
//alert("Error: " + e);
}
};
// ----------------------------------------------------------------------------
/* init OpenLayers with OpenStreetMaps */
JSMap.prototype._initOpenStreetMaps = function(mapElement)
{
/* bounds */
var bounds = new OpenLayers.Bounds(
-20037508.34, -20037508.34,
20037508.34, 20037508.34
);
/* see "http://wiki.openstreetmap.org/index.php/OpenLayers_Simple_Example" */
this.openLayersMap = new OpenLayers.Map(mapElement.id,
{
maxExtent: bounds,
maxResolution: 156543,
numZoomLevels: 18,
units: "meters",
projection: "EPSG:41001",
controls: [
//new OpenLayers.Control.MousePosition(),
//new OpenLayers.Control.OverviewMap(),
//new OpenLayers.Control.ScaleLine(),
//new OpenLayers.Control()
new OpenLayers.Control.PanZoomBar()
]
}
);
this.openLayersMap.addLayer(new OpenLayers.Layer.TMS(
"OSM Mapnik",
[
"http://a.tile.openstreetmap.org/",
"http://b.tile.openstreetmap.org/",
"http://c.tile.openstreetmap.org/"
],
{
type: 'png',
getURL: function (bounds) {
var res = this.map.getResolution();
var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
var y = Math.round((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
var z = this.map.getZoom();
var limit = Math.pow(2, z);
if ((y < 0) || (y >= limit)) {
return null;
} else {
x = ((x % limit) + limit) % limit;
var path = z + "/" + x + "/" + y + "." + this.type;
var url = this.url;
if (url instanceof Array) {
url = this.selectUrl(path, url);
}
return url + path;
}
},
displayOutsideMaxExtent: true
}
));
this.openLayersMap.addLayer(new OpenLayers.Layer.TMS(
"OSM",
[
"http://a.tah.openstreetmap.org/Tiles/tile.php/",
"http://b.tah.openstreetmap.org/Tiles/tile.php/",
"http://c.tah.openstreetmap.org/Tiles/tile.php/"
],
{
type: 'png',
getURL: function (bounds) {
var res = this.map.getResolution();
var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
var y = Math.round((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
var z = this.map.getZoom();
var limit = Math.pow(2, z);
if ((y < 0) || (y >= limit)) {
return null;
} else {
x = ((x % limit) + limit) % limit;
var path = z + "/" + x + "/" + y + "." + this.type;
var url = this.url;
if (url instanceof Array) {
url = this.selectUrl(path, url);
}
return url + path;
}
},
displayOutsideMaxExtent: true
}
));
/* convert OpenLayers point to JSMapPoint */
JSMap.prototype._toJSMapPointLatLon = function(olLat, olLon) {
var lon = olLon * (180.0 / 20037508.34);
var lat = olLat * (180.0 / 20037508.34);
lat = (180.0 / Math.PI) * (2.0 * Math.atan(Math.exp(lat * Math.PI / 180.0)) - (Math.PI / 2.0));
return new JSMapPoint(lat,lon);
};
/* convert OpenLayers point to JSMapPoint */
JSMap.prototype._toJSMapPoint = function(point) {
return this._toJSMapPointLatLon(point.lat, point.lon);
};
/* convert JSMapPoint to OpenLayers point */
JSMap.prototype._toOpenLayerPointLatLon = function(lat, lon) {
var ollon = lon * (20037508.34 / 180.0);
var ollat = Math.log(Math.tan((90.0 + lat) * Math.PI / 360.0)) / (Math.PI / 180.0);
ollat *= 20037508.34 / 180.0;
return new OpenLayers.LonLat(ollon, ollat);
};
/* convert JSMapPoint to OpenLayers point */
JSMap.prototype._toOpenLayerPoint = function(point) {
return this._toOpenLayerPointLatLon(point.lat, point.lon);
};
/* return map object */
return this.openLayersMap;
};
// ----------------------------------------------------------------------------
/* init OpenLayers with GeoServer */
JSMap.prototype._initGeoServerCustom = function(mapElement)
{
var GEOSERVER_TITLE = GEOSERVER_title;
var GEOSERVER_URL = GEOSERVER_url; // "http://localhost:8085/geoserver/wms";
var MAX_RESOLUTION = GEOSERVER_maxResolution; // 0.0007907421875;
var MAP_WIDTH = GEOSERVER_size.width; // "431";
var MAP_HEIGHT = GEOSERVER_size.height; // "550";
var MAP_STYLES = "";
var MAP_BOUNDS = new OpenLayers.Bounds(GEOSERVER_bounds.left, GEOSERVER_bounds.bottom, GEOSERVER_bounds.right, GEOSERVER_bounds.top); // -74.047185, 40.679648, -73.907005, 40.882078);
var TILE_ORIGIN = MAP_BOUNDS.left + "," + MAP_BOUNDS.bottom; // "-74.047185,40.679648"
var PROJECTION = GEOSERVER_projection; // "EPSG:4326";
var TILE_FORMAT = "image/png";
var TILE_STATE = "true"; // may need to be "false" ???
var DATA_LAYERS = GEOSERVER_layers; // "tiger-ny";
var COORD_UNITS = (GEOSERVER_units != "")? GEOSERVER_units : "degrees";
var LAYER_TYPE = GEOSERVER_layerType;
/* map */
this.openLayersMap = new OpenLayers.Map(
mapElement.id,
{
maxExtent: MAP_BOUNDS,
maxResolution: MAX_RESOLUTION,
projection: PROJECTION,
units: COORD_UNITS,
controls: [
//new OpenLayers.Control.MousePosition(),
//new OpenLayers.Control.OverviewMap(),
//new OpenLayers.Control.ScaleLine(),
new OpenLayers.Control.PanZoomBar()
]
}
);
/* simple layer */
if (LAYER_TYPE == "simple") {
this.openLayersMap.addLayer(new OpenLayers.Layer.WMS(
GEOSERVER_TITLE,
GEOSERVER_URL,
{
layers: DATA_LAYERS
}
));
}
/* tiled layer */
if (LAYER_TYPE == "tiled") {
this.openLayersMap.addLayer(new OpenLayers.Layer.WMS(
GEOSERVER_TITLE, // + " (tiled)",
GEOSERVER_URL,
{
width: MAP_WIDTH,
height: MAP_HEIGHT,
styles: MAP_STYLES,
layers: DATA_LAYERS,
srs: PROJECTION,
format: TILE_FORMAT,
tiled: TILE_STATE,
tilesOrigin: TILE_ORIGIN
},
{
buffer: 0
}
));
}
/* untiled layer */
if (LAYER_TYPE == "untiled") {
this.openLayersMap.addLayer(new OpenLayers.Layer.WMS(
GEOSERVER_TITLE, // + " (untiled)",
GEOSERVER_URL,
{
width: MAP_WIDTH,
styles: MAP_STYLES,
height: MAP_HEIGHT,
layers: DATA_LAYERS,
srs: PROJECTION,
format: TILE_FORMAT
},
{
singleTile: true,
ratio: 1
}
));
}
/* initial zoom */
this.openLayersMap.zoomToExtent(MAP_BOUNDS);
/* convert OpenLayers point to JSMapPoint */
JSMap.prototype._toJSMapPoint = function(point) {
var lon = point.lon;
var lat = point.lat;
return new JSMapPoint(lat,lon);
};
/* convert JSMapPoint to OpenLayers point */
JSMap.prototype._toOpenLayerPointLatLon = function(lat, lon) {
var ollon = lon;
var ollat = lat;
return new OpenLayers.LonLat(ollon, ollat);
};
/* convert JSMapPoint to OpenLayers point */
JSMap.prototype._toOpenLayerPoint = function(point) {
return this._toOpenLayerPointLatLon(point.lat, point.lon);
};
/* return map object */
return this.openLayersMap;
};
// ----------------------------------------------------------------------------
/**
*** Unload/release resources
**/
JSMap.prototype.JSUnload = function()
{
// nothing to do?
};
// ----------------------------------------------------------------------------
/**
*** Clear all pushpins and drawn lines
**/
JSMap.prototype.JSClearLayers = function()
{
this._clearPoiLayer();
this._clearMarkerLayer();
this._clearDrawLayer();
this._clearRulerLayer(true);
this.centerBounds = new OpenLayers.Bounds();
this.routeLines = [];
};
/**
*** Clear the POI layer
**/
JSMap.prototype._clearPoiLayer = function()
{
if (this.poiLayer !== null) {
try { this.poiLayer.clearMarkers(); } catch (e) {}
try { this.openLayersMap.removeLayer(this.poiLayer); } catch (e) {}
}
};
/**
*** Clear the marker layer
**/
JSMap.prototype._clearMarkerLayer = function()
{
if (this.markerLayer !== null) {
try { this.markerLayer.clearMarkers(); } catch (e) {}
try { this.openLayersMap.removeLayer(this.markerLayer); } catch (e) {}
}
this._clearReplay();
};
// ----------------------------------------------------------------------------
/**
*** Pause/Resume replay
**/
JSMap.prototype.JSPauseReplay = function(replay)
{
/* stop replay? */
if (!replay || (replay <= 0) || !this.replayInProgress) {
// stopping replay
this._clearReplay();
return REPLAY_STOPPED;
} else {
// replay currently in progress
if (this.replayTimer === null) {
// replay is "PAUSED" ... resuming replay
this._hidePushpinPopup(this.visiblePopupInfoBox);
jsmHighlightDetailRow(-1, false);
this._startReplayTimer(replay, 100);
return REPLAY_RUNNING;
} else {
// replaying "RUNNING" ... pausing replay
this._stopReplayTimer();
return REPLAY_PAUSED;
}
}
};
/**
*** Start the replay timer
*** @param replay 0=off, 1=pushpin_only, 2=pushpin&balloon
**/
JSMap.prototype._startReplayTimer = function(replay, interval)
{
if (this.replayInProgress) {<|fim▁hole|> }
jsmSetReplayState(REPLAY_RUNNING);
};
/**
*** Stop the current replay timer
**/
JSMap.prototype._stopReplayTimer = function()
{
if (this.replayTimer !== null) {
clearTimeout(this.replayTimer);
this.replayTimer = null;
}
jsmSetReplayState(this.replayInProgress? REPLAY_PAUSED : REPLAY_STOPPED);
};
/**
*** Clear any current replay in process
**/
JSMap.prototype._clearReplay = function()
{
this.replayPushpins = [];
this.replayInProgress = false;
this._stopReplayTimer();
this.replayIndex = 0;
jsmHighlightDetailRow(-1, false);
};
/**
*** Gets the current replay state
**/
JSMap.prototype._getReplayState = function()
{
if (this.replayInProgress) {
if (this.replayTimer === null) {
return REPLAY_PAUSED;
} else {
return REPLAY_RUNNING;
}
} else {
return REPLAY_STOPPED;
}
};
// ----------------------------------------------------------------------------
/**
*** Clear the draw layer
**/
JSMap.prototype._clearRulerLayer = function(clearStart)
{
if ((this.rulerLayer !== null) && (this.rulerFeatures !== null)) {
try { this.rulerLayer.removeFeatures(this.rulerFeatures); } catch (e) {}
this.rulerFeatures = null;
}
if (clearStart) {
this.dragRulerStart = null;
this.dragRulerEnd = null;
}
};
/**
*** Draw Ruler
**/
JSMap.prototype._drawRuler = function(features)
{
this._clearRulerLayer(false);
this.rulerFeatures = features;
if (this.rulerFeatures !== null) {
if (this.rulerLayer === null) {
this.rulerLayer = new OpenLayers.Layer.Vector('rulerLayer');
this.openLayersMap.addLayer(this.rulerLayer);
}
this.rulerLayer.addFeatures(this.rulerFeatures);
//this.rulerLayer.display(true);
//this.rulerLayer.drawFeature(this.rulerFeatures[0]);
}
};
/**
*** Create/return ruler feature
**/
JSMap.prototype._createRulerFeature = function(lat, lon)
{
if ((lat !== null) && (lon !== null)) {
var rulerStyle = {
strokeColor: "#FF6422",
strokeOpacity: 1,
strokeWidth: 2,
fillColor: "#FF2222",
fillOpacity: 0.2
};
var rulerPoints = [];
rulerPoints.push(this._createGeometryPoint(this._toOpenLayerPoint(lat)));
rulerPoints.push(this._createGeometryPoint(this._toOpenLayerPoint(lon)));
var line = new OpenLayers.Geometry.LineString(rulerPoints);
return new OpenLayers.Feature.Vector(line, null, rulerStyle);
} else {
return null;
}
};
// ----------------------------------------------------------------------------
/**
*** Clear the draw layer
**/
JSMap.prototype._clearDrawLayer = function()
{
if (this.drawFeatures !== null) {
try { this.drawLayer[0].removeFeatures(this.drawFeatures); } catch (e) {}
this.drawFeatures = null;
}
};
/**
*** Draw Feature
**/
JSMap.prototype._drawFeatures = function(clear, features)
{
/* clear existing features */
if (clear) {
this._clearDrawLayer();
}
/* add features */
if (features) {
if (!this.drawFeatures) { this.drawFeatures = []; }
for (var i = 0; i < features.length; i++) {
this.drawFeatures.push(features[i]);
}
}
/* draw features */
if (this.drawFeatures && (this.drawFeatures.length > 0)) {
//if (this.drawLayer === null) {
// this.drawLayer = new OpenLayers.Layer.Vector('drawLayer0');
// this.openLayersMap.addLayer(this.drawLayer);
//}
this.drawLayer[0].addFeatures(this.drawFeatures);
//this.drawLayer[0].display(true);
//this.drawLayer[0].drawFeature(this.drawFeatures[0]);
}
};
// ----------------------------------------------------------------------------
/**
*** Sets the center of the map
**/
JSMap.prototype.JSSetCenter = function(center)
{
try {
this.openLayersMap.setCenter(this._toOpenLayerPoint(center));
} catch (e) {
//
}
};
/**
*** Draw the specified pushpins on the map
*** @param pushPins An array of JSMapPushpin objects
*** @param recenter 0=no-recenter, 1=last-pushpin, 2=all-pushpins
*** @param replay 0=off, 1=pushpin_only, 2=pushpin&balloon
**/
JSMap.prototype.JSDrawPushpins = function(pushPins, recenterMode, replay)
{
/* reset pushpin layer */
//this.markerLayer.display(false);
this._hidePushpinPopup(this.visiblePopupInfoBox);
/* drawn pushpins */
var drawPushpins = [];
/* recenter map on points */
var pointCount = 0;
if ((pushPins !== null) && (pushPins.length > 0)) {
for (var i = 0; i < pushPins.length; i++) {
var pp = pushPins[i]; // JSMapPushpin
if ((pp.lat != 0.0) || (pp.lon != 0.0)) {
pointCount++;
this.centerBounds.extend(this._toOpenLayerPoint(pp));
drawPushpins.push(pp);
}
}
}
if (recenterMode > 0) {
try {
if (pointCount <= 0) {
var centerPt = this._toOpenLayerPoint(DEFAULT_CENTER);
var zoomFactor = DEFAULT_ZOOM;
this.openLayersMap.setCenter(centerPt, zoomFactor);
} else
if (recenterMode == RECENTER_LAST) { // center on last point
var pp = drawPushpins[drawPushpins.length - 1];
var centerPt = this._toOpenLayerPoint(pp);
this.openLayersMap.setCenter(centerPt);
} else
if (recenterMode == RECENTER_PAN) { // pan to last point
var pp = drawPushpins[drawPushpins.length - 1];
var centerPt = this._toOpenLayerPoint(pp);
this.openLayersMap.setCenter(centerPt);
} else {
var centerPt = this.centerBounds.getCenterLonLat();
var zoomFactor = this.openLayersMap.getZoomForExtent(this.centerBounds);
this.openLayersMap.setCenter(centerPt, zoomFactor);
}
} catch (e) {
//alert("Error: [JSDrawPushpins] " + e);
return;
}
}
if (pointCount <= 0) {
return;
}
/* replay pushpins? */
if (replay && (replay >= 1)) {
this.openLayersMap.addLayer(this.markerLayer); // must re-add layer
this.replayIndex = 0;
this.replayInProgress = true;
this.replayPushpins = drawPushpins;
this._startReplayTimer(replay, 100);
return;
}
/* draw pushpins now */
var pushpinErr = null;
for (var i = 0; i < drawPushpins.length; i++) {
var pp = drawPushpins[i]; // JSMapPushpin
try {
pp.hoverPopup = true;
this._addPushpin(pp, this.markerLayer);
} catch (e) {
if (pushpinErr === null) { pushpinErr = e; }
}
}
try {
this.openLayersMap.addLayer(this.markerLayer); // must re-add layer
//this.markerLayer.display(true);
} catch (e) {
if (pushpinErr === null) { pushpinErr = e; }
}
if (pushpinErr !== null) {
alert("Error: adding pushpins:\n" + pushpinErr);
}
};
/**
*** Draw the specified PointsOfInterest pushpins on the map
*** @param pushPins An array of JSMapPushpin objects
**/
JSMap.prototype.JSDrawPOI = function(pushPins)
{
/* reset pushpin layer */
this._clearPoiLayer();
//this.poiLayer.display(false);
this._hidePushpinPopup(this.visiblePopupInfoBox);
/* draw pushpins */
if ((pushPins !== null) && (pushPins.length > 0)) {
var pushpinErr = null;
for (var i = 0; i < pushPins.length; i++) {
var pp = pushPins[i]; // JSMapPushpin
try {
pp.hoverPopup = true;
this._addPushpin(pp, this.poiLayer);
} catch (e) {
if (pushpinErr === null) { pushpinErr = e; }
}
}
try {
this.openLayersMap.addLayer(this.poiLayer); // must re-add layer
//this.poiLayer.display(true);
} catch (e) {
if (pushpinErr === null) { pushpinErr = e; }
}
if (pushpinErr !== null) {
alert("Error: adding pushpins:\n" + pushpinErr);
}
}
};
/**
*** Adds a single pushpin to the map
*** @param pp The JSMapPushpin object to add to the map
**/
JSMap.prototype._addPushpin = function(pp, layer)
{
try {
var self = this;
pp.map = this.openLayersMap;
var size = new OpenLayers.Size(pp.iconSize[0], pp.iconSize[1]);
var anchor = new OpenLayers.Pixel(-pp.iconOffset[0], -pp.iconOffset[1]);
var icon = new OpenLayers.Icon(pp.iconUrl, size, anchor);
var marker = new OpenLayers.Marker(this._toOpenLayerPoint(pp), icon);
if (pp.html) {
pp.popup = new OpenLayers.Popup(null,
this._toOpenLayerPoint(pp),
new OpenLayers.Size(100,100),
pp.html,
true);
pp.popup.autoSize = true;
if (pp.hoverPopup) {
marker.events.register("mouseover", marker, function(event) {
self._showPushpinPopup(pp);
});
marker.events.register("mouseout", marker, function(event) {
self._hidePushpinPopup(pp);
});
} else {
marker.events.register("mousedown", marker, function(event) {
if (pp.popupShown) {
self._hidePushpinPopup(pp);
} else {
self._showPushpinPopup(pp);
}
});
}
}
pp.marker = marker;
layer.addMarker(marker);
/*
if (pp.label) {
var labelPopup = new OpenLayers.Popup(null,
this._toOpenLayerPoint(pp),
new OpenLayers.Size(30,12),
"<span>"+pp.label+"</span>",
false);
labelPopup.autoSize = true;
this.openLayersMap.addPopup(labelPopup);
labelPopup.show();
}
*/
} catch(e) {
//alert("Error: " + e);
}
};
/**
*** Replays the list of pushpins on the map
*** @param replay 0=off, 1=pushpin_only, 2=pushpin&balloon
**/
JSMap.prototype._replayPushpins = function(replay)
{
/* no replay pushpins? */
if (this.replayPushpins === null) {
this._clearReplay();
jsmHighlightDetailRow(-1, false);
return; // stop
}
/* advance to next valid point */
while (true) {
if (this.replayIndex >= this.replayPushpins.length) {
this._clearReplay();
jsmHighlightDetailRow(-1, false);
return; // stop
}
var pp = this.replayPushpins[this.replayIndex]; // JSMapPushpin
if ((pp.lat != 0.0) || (pp.lon != 0.0)) {
break; // valid point
}
this.replayIndex++;
}
/* add pushpin */
try {
var lastNdx = this.replayIndex - 1;
var pp = this.replayPushpins[this.replayIndex++]; // JSMapPushpin
pp.hoverPopup = true;
if (REPLAY_SINGLE && (lastNdx >= 0)) {
try { this.markerLayer.clearMarkers(); } catch (e) {}
}
this._addPushpin(pp, this.markerLayer);
if (replay && (replay >= 2)) {
this._showPushpinPopup(pp);
} else {
jsmHighlightDetailRow(pp.rcdNdx, true);
}
this._startReplayTimer(replay, this.replayInterval);
} catch (e) {
// ignore
}
};
// ----------------------------------------------------------------------------
/**
*** This method should cause the info-bubble popup for the specified pushpin to display
*** @param pp The JSMapPushpin object to popup its info-bubble
**/
JSMap.prototype.JSShowPushpin = function(pp, center)
{
if (pp) {
if (pp.popupShown) {
this._hidePushpinPopup(pp);
} else {
if (center || !this._isPointOnMap(pp.lat,pp.lon,7,7,50,100)) {
this.JSSetCenter(new JSMapPoint(pp.lat, pp.lon));
}
this._showPushpinPopup(pp);
}
}
};
JSMap.prototype._isPointOnMap = function(lat, lon, margTop, margLeft, margBott, margRght)
{
var size = this.openLayersMap.getSize();
var top = 0 + margTop;
var left = 0 + margLeft;
var bott = top + size.h - margBott;
var rght = left + size.w - margRght;
var TL = this._toJSMapPoint(this.openLayersMap.getLonLatFromViewPortPx(new OpenLayers.Pixel(left, top )));
var BR = this._toJSMapPoint(this.openLayersMap.getLonLatFromViewPortPx(new OpenLayers.Pixel(rght, bott)));
//alert("_isPointOnMap "+lat+"/"+lon+", TL:"+TL.lat+"/"+TL.lon+", BR:"+BR.lat+"/"+BR.lon);
if ((lat > TL.lat) || (lat < BR.lat)) {
return false;
} else
if ((lon < TL.lon) || (lon > BR.lon)) {
return false;
} else {
return true;
}
};
JSMap.prototype._showPushpinPopup = function(pp)
{
this._hidePushpinPopup(this.visiblePopupInfoBox);
if (pp && !pp.popupShown && pp.map) {
pp.map.addPopup(pp.popup);
pp.popup.show();
pp.popupShown = true;
this.visiblePopupInfoBox = pp;
jsmHighlightDetailRow(pp.rcdNdx, true);
} else {
this.visiblePopupInfoBox = null;
}
};
JSMap.prototype._hidePushpinPopup = function(pp)
{
if (pp && pp.popupShown) {
pp.popup.hide();
pp.map.removePopup(pp.popup);
pp.popupShown = false;
jsmHighlightDetailRow(pp.rcdNdx, false);
}
};
// ----------------------------------------------------------------------------
/**
*** Draws a line between the specified points on the map.
*** @param points An array of JSMapPoint objects
**/
JSMap.prototype.JSDrawRoute = function(points, color)
{
if ((points !== null) && (points.length > 0)) {
var route = {
points: points,
color: color
};
this.routeLines.push(route);
var routeFeatures = [];
for (var i = 0; i < this.routeLines.length; i++) {
var r = this.routeLines[i];
routeFeatures.push(this._createRouteFeature(r.points,r.color));
}
this._drawFeatures(true, routeFeatures);
} else {
//this.routeLines = [];
//this._clearDrawLayer();
}
};
/**
*** Create/Return route feature
**/
JSMap.prototype._createRouteFeature = function(points, color) // JSMapPoint
{
if ((points !== null) && (points.length > 0)) {
var routeStyle = {
strokeColor: color,
strokeOpacity: 1,
strokeWidth: 2,
fillColor: color,
fillOpacity: 0.2
};
var rp = [];
for (var i = 0; i < points.length; i++) {
var olpt = this._toOpenLayerPoint(points[i]); // OpenLayers.LonLat
rp.push(this._createGeometryPoint(olpt));
}
var line = new OpenLayers.Geometry.LineString(rp);
return new OpenLayers.Feature.Vector(line, null, routeStyle);
} else {
return null;
}
};
// ----------------------------------------------------------------------------
/**
*** Remove previously drawn shapes
**/
JSMap.prototype._removeShapes = function()
{
this._clearDrawLayer();
this.drawShapes = [];
};
/**
*** Draws a Shape on the map at the specified location
*** @param type The Geozone shape type
*** @param radiusM The circle radius, in meters
*** @param points An array of points (JSMapPoint[])
*** @param color shape color
*** @param zoomTo rue to zoom to drawn shape
*** @return True if shape was drawn, false otherwise
**/
JSMap.prototype.JSDrawShape = function(type, radiusM, verticePts, color, zoomTo)
{
/* no type? */
if (!type || (type == "") || (type == "!")) {
this._removeShapes();
return false;
}
/* clear existing shapes? */
if (type.startsWith("!")) {
this._removeShapes();
type = type.substr(1);
}
/* no geopoints? */
if (!verticePts || (verticePts.length == 0)) {
return false;
}
/* color */
if (!color || (color == "")) {
color = "#0000FF";
}
/* zoom bounds */
var mapBounds = zoomTo? new OpenLayers.Bounds() : null;
/* color/style */
var colorStyle = new OpenLayersColorStyle(color, 0.75, color, 0.08);
/* draw shape */
var didDrawShape = false;
if (type == "circle") { // ZONE_POINT_RADIUS
var circleList = [];
for (var p = 0; p < verticePts.length; p++) {
var jsPt = verticePts[p]; // JSMapPoint
var center = this._toOpenLayerPoint(jsPt); // OpenLayers.LonLat
var circle = this._createCircleFeature(center, radiusM, colorStyle);
if (mapBounds) {
mapBounds.extend(center);
mapBounds.extend(this._toOpenLayerPoint(this._calcRadiusPoint(jsPt, radiusM, 0.0)));
mapBounds.extend(this._toOpenLayerPoint(this._calcRadiusPoint(jsPt, radiusM, 90.0)));
mapBounds.extend(this._toOpenLayerPoint(this._calcRadiusPoint(jsPt, radiusM, 180.0)));
mapBounds.extend(this._toOpenLayerPoint(this._calcRadiusPoint(jsPt, radiusM, 270.0)));
}
this.drawShapes.push(circle);
}
if (this.drawShapes.length > 0) {
this._drawFeatures(false, this.drawShapes);
didDrawShape = true;
}
} else
if (type == "rectangle") { // ZONE_BOUNDED_RECT
if (verticePts.length >= 2) {
/* create rectangle */
var vp0 = verticePts[0];
var vp1 = verticePts[1];
var TL = this._toOpenLayerPointLatLon(((vp0.lat>vp1.lat)?vp0.lat:vp1.lat),((vp0.lon<vp1.lon)?vp0.lon:vp1.lon));
var TR = this._toOpenLayerPointLatLon(((vp0.lat>vp1.lat)?vp0.lat:vp1.lat),((vp0.lon>vp1.lon)?vp0.lon:vp1.lon));
var BL = this._toOpenLayerPointLatLon(((vp0.lat<vp1.lat)?vp0.lat:vp1.lat),((vp0.lon<vp1.lon)?vp0.lon:vp1.lon));
var BR = this._toOpenLayerPointLatLon(((vp0.lat<vp1.lat)?vp0.lat:vp1.lat),((vp0.lon>vp1.lon)?vp0.lon:vp1.lon));
var crPts = [ TL, TR, BR, BL, TL ];
var poly = this._createPolygonFeature(crPts, colorStyle);
if (mapBounds) { for (var b = 0; b < crPts.length; b++) { mapBounds.extend(crPts[b]); } }
this.drawShapes.push(poly);
this._drawFeatures(false, this.drawShapes);
didDrawShape = true;
}
} else
if (type == "polygon") { // ZONE_POLYGON
if (verticePts.length >= 3) {
var crPts = [];
for (var p = 0; p < verticePts.length; p++) {
var olPt = this._toOpenLayerPointLatLon(verticePts[p].lat, verticePts[p].lon);
crPts.push(olPt);
if (mapBounds) { mapBounds.extend(olPt); }
}
var poly = this._createPolygonFeature(crPts, colorStyle);
this.drawShapes.push(poly);
this._drawFeatures(false, this.drawShapes);
didDrawShape = true;
}
} else
if (type == "corridor") { // ZONE_SWEPT_POINT_RADIUS
// TODO:
} else
if (type == "center") {
if (mapBounds) {
for (var p = 0; p < verticePts.length; p++) {
var olPt = this._toOpenLayerPointLatLon(verticePts[p].lat, verticePts[p].lon);
mapBounds.extend(olPt);
}
didDrawShape = true;
}
}
/* center on shape */
if (didDrawShape && zoomTo && mapBounds) {
var centerPt = mapBounds.getCenterLonLat(); // OpenLayers.LonLat
var zoomFactor = this.openLayersMap.getZoomForExtent(mapBounds);
try { this.openLayersMap.setCenter(centerPt, zoomFactor); } catch (e) { /*alert("Error[JSDrawGeozone]:"+e);*/ }
}
/* shape not supported */
return didDrawShape;
};
// ----------------------------------------------------------------------------
/**
*** Draws a Geozone on the map at the specified location
*** @param type The Geozone type
*** @param radiusM The circle radius, in meters
*** @param points An array of JSMapPoints
*** @return An object representing the Circle.
**/
JSMap.prototype.JSDrawGeozone = function(type, radiusM, points, color, primNdx)
{
// type:
// 0 - ZONE_POINT_RADIUS
// 1 - ZONE_BOUNDED_RECT
// 2 - ZONE_SWEPT_POINT_RADIUS
// 3 - ZONE_POLYGON
// (type ZONE_POINT_RADIUS may only be currently supported)
this._JSDrawGeozone(type, radiusM, points, color, primNdx, false)
};
/**
*** Draws a Geozone on the map at the specified location
*** @param type The Geozone type
*** @param radiusM The circle radius, in meters
*** @param points An array of JSMapPoints
*** @return An object representing the Circle.
**/
JSMap.prototype._JSDrawGeozone = function(type, radiusM, points, color, primNdx, isDragging)
{
// (type ZONE_POINT_RADIUS may only be currently supported)
/* Geozone mode */
jsvGeozoneMode = true;
/* remove old primary */
if (!isDragging) {
this.primaryCenter = null;
this.primaryIndex = primNdx;
}
/* save geozone points */
this.geozonePoints = points;
/* no points? */
if ((points === null) || (points.length <= 0)) {
//alert("No Zone center!");
this._clearDrawLayer();
return null;
}
/* point-radius */
if (type == ZONE_POINT_RADIUS) {
/* adjust radius */
if (isNaN(radiusM)) { radiusM = 5000; }
if (radiusM > MAX_ZONE_RADIUS_M) { radiusM = MAX_ZONE_RADIUS_M; }
if (radiusM < MIN_ZONE_RADIUS_M) { radiusM = MIN_ZONE_RADIUS_M; }
jsvZoneRadiusMeters = radiusM;
/* draw points */
var count = 0;
var zoneFeatures = new Array();
var mapBounds = new OpenLayers.Bounds();
var polyPts = [];
for (var i = 0; i < points.length; i++) {
var c = points[i]; // JSMapPoint
if ((c.lat != 0.0) || (c.lon != 0.0)) {
var isPrimary = (i == primNdx);
var center = (isPrimary && isDragging)? this.primaryCenter : this._toOpenLayerPoint(c); // OpenLayers.LonLat
var circStyle = GetGeozoneStyle(isPrimary,color);
zoneFeatures.push(this._createCircleFeature(center, radiusM, circStyle));
if (isPrimary && !isDragging) {
this.primaryCenter = center; // OpenLayers.LonLat
}
polyPts.push(center);
mapBounds.extend(center);
mapBounds.extend(this._toOpenLayerPoint(this._calcRadiusPoint(c, radiusM, 0.0)));
mapBounds.extend(this._toOpenLayerPoint(this._calcRadiusPoint(c, radiusM, 90.0)));
mapBounds.extend(this._toOpenLayerPoint(this._calcRadiusPoint(c, radiusM, 180.0)));
mapBounds.extend(this._toOpenLayerPoint(this._calcRadiusPoint(c, radiusM, 270.0)));
count++;
}
}
//if (DRAW_ZONE_POINT_RADIUS_POLYGON && (polyPts.length >= 3)) {
// var style = new OpenLayersColorStyle("#1111CC", 0.15, "#1111CC", 0.04);
// zoneFeatures.push(this._createPolygonFeature(polyPts, style));
//}
/* center on geozone */
if (!isDragging) {
var centerPt = this._toOpenLayerPoint(DEFAULT_CENTER); // OpenLayers.LonLat
var zoomFactor = DEFAULT_ZOOM;
if (count > 0) {
centerPt = mapBounds.getCenterLonLat(); // OpenLayers.LonLat
zoomFactor = this.openLayersMap.getZoomForExtent(mapBounds);
}
try { this.openLayersMap.setCenter(centerPt, zoomFactor); } catch (e) { /*alert("Error[JSDrawGeozone]:"+e);*/ }
}
/* create zone feature */
this._drawFeatures(true, zoneFeatures);
/*
var self = this;
var m = new OpenLayers.Marker(olpt);
this.markerLayer.addMarker(m);
var dragMarkers = this.markerLayer;
var dragging = false;
m.events.register("mousedown", m, function(e) {
dragging = true;
});
m.events.register("mousemove", m, function(e) {
if (dragging) {
m.moveTo(self.openLayersMap.getLayerPxFromViewPortPx(e.xy));
}
});
m.events.register("mouseup", m, function(e) {
dragging = false;
});
*/
/*
var controls = {
drag: new OpenLayers.Control.DragMarker(dragMarkers, { 'onComplete': function() { alert('foo'); } })
}
for(var key in controls) {
this.openLayersMap.addControl(controls[key]);
}
*/
} else
if (type == ZONE_POLYGON) {
/* set radius (should be about 30 pixels radius) */
jsvZoneRadiusMeters = radiusM;
/* draw points */
var count = 0;
var zoneFeatures = new Array();
var mapBounds = new OpenLayers.Bounds();
var polyPts = [];
var polyPtPrim = -1;
for (var i = 0; i < points.length; i++) {
var c = points[i]; // JSMapPoint
if ((c.lat != 0.0) || (c.lon != 0.0)) {
var isPrimary = (i == primNdx);
var center = (isPrimary && isDragging)? this.primaryCenter : this._toOpenLayerPoint(c); // OpenLayers.LonLat
if (isPrimary) {
this.primaryCenter = center; // OpenLayers.LonLat
polyPtsPrim = polyPts.length;
}
polyPts.push(center);
mapBounds.extend(center);
count++;
}
}
if (polyPts.length >= 3) {
zoneFeatures.push(this._createPolygonFeature(polyPts, GetGeozoneStyle(false,color)));
}
/* center on geozone */
if (!isDragging) {
var centerPt = this._toOpenLayerPoint(DEFAULT_CENTER); // OpenLayers.LonLat
var zoomFactor = DEFAULT_ZOOM;
if (count > 0) {
centerPt = mapBounds.getCenterLonLat(); // OpenLayers.LonLat
zoomFactor = this.openLayersMap.getZoomForExtent(mapBounds);
}
try { this.openLayersMap.setCenter(centerPt, zoomFactor); } catch (e) { /*alert("Error[JSDrawGeozone]:"+e);*/ }
}
/* current MPP */
//var zoom = this.openLayersMap.getZoom();
//var DPP = this.openLayersMap.getResolution(); // degrees per pixel
radiusM = 10.0 * this.openLayersMap.getResolution();
//alert("Radius = "+radiusM + ", Zoom="+this.openLayersMap.getZoom() + ", Resolution="+this.openLayersMap.getResolution());
jsvZoneRadiusMeters = radiusM;
/* draw drag circles at vertices */
for (var i = 0; i < polyPts.length; i++) {
var center = polyPts[i]; // OpenLayers.LonLat
var dragStyle = GetGeozoneStyle((i == polyPtsPrim), color);
zoneFeatures.push(this._createCircleFeature(center, radiusM, dragStyle));
}
/* create zone feature */
this._drawFeatures(true, zoneFeatures);
} else
if (type == ZONE_SWEPT_POINT_RADIUS) {
/* adjust radius */
if (isNaN(radiusM)) { radiusM = 1000; }
if (radiusM > MAX_ZONE_RADIUS_M) { radiusM = MAX_ZONE_RADIUS_M; }
if (radiusM < MIN_ZONE_RADIUS_M) { radiusM = MIN_ZONE_RADIUS_M; }
jsvZoneRadiusMeters = radiusM;
/* draw vertices */
var count = 0;
var zoneFeatures = new Array();
var mapBounds = new OpenLayers.Bounds();
var polyPts = []; // OpenLayers.LonLat[]
for (var i = 0; i < points.length; i++) {
var c = points[i]; // JSMapPoint
if ((c.lat != 0.0) || (c.lon != 0.0)) {
var isPrimary = (i == primNdx);
var center = (isPrimary && isDragging)? this.primaryCenter : this._toOpenLayerPoint(c); // OpenLayers.LonLat
var circStyle = GetGeozoneStyle(isPrimary,color);
zoneFeatures.push(this._createCircleFeature(center, radiusM, circStyle));
if (isPrimary && !isDragging) {
this.primaryCenter = center; // OpenLayers.LonLat
}
polyPts.push(center); // OpenLayers.LonLat
mapBounds.extend(center);
mapBounds.extend(this._toOpenLayerPoint(this._calcRadiusPoint(c, radiusM, 0.0)));
mapBounds.extend(this._toOpenLayerPoint(this._calcRadiusPoint(c, radiusM, 90.0)));
mapBounds.extend(this._toOpenLayerPoint(this._calcRadiusPoint(c, radiusM, 180.0)));
mapBounds.extend(this._toOpenLayerPoint(this._calcRadiusPoint(c, radiusM, 270.0)));
count++;
}
}
/* draw corridors */
if (polyPts.length >= 2) {
// routeline "_createRouteFeature"
for (var i = 0; i < (polyPts.length - 1); i++) {
var ptA = this._toJSMapPoint(polyPts[i ]);
var ptB = this._toJSMapPoint(polyPts[i+1]);
var hAB = geoHeading(ptA.lat, ptA.lon, ptB.lat, ptB.lon) - 90.0; // perpendicular
var rp1 = this._toOpenLayerPoint(this._calcRadiusPoint(ptA, radiusM, hAB ));
var rp2 = this._toOpenLayerPoint(this._calcRadiusPoint(ptB, radiusM, hAB ));
var rp3 = this._toOpenLayerPoint(this._calcRadiusPoint(ptB, radiusM, hAB + 180.0));
var rp4 = this._toOpenLayerPoint(this._calcRadiusPoint(ptA, radiusM, hAB + 180.0));
var rectPts = [ rp1, rp2, rp3, rp4 ];
zoneFeatures.push(this._createPolygonFeature(rectPts, GetGeozoneStyle(false,color)));
}
}
/* center on geozone */
if (!isDragging) {
var centerPt = this._toOpenLayerPoint(DEFAULT_CENTER); // OpenLayers.LonLat
var zoomFactor = DEFAULT_ZOOM;
if (count > 0) {
centerPt = mapBounds.getCenterLonLat(); // OpenLayers.LonLat
zoomFactor = this.openLayersMap.getZoomForExtent(mapBounds);
}
try { this.openLayersMap.setCenter(centerPt, zoomFactor); } catch (e) { /*alert("Error[JSDrawGeozone]:"+e);*/ }
}
/* create zone feature */
this._drawFeatures(true, zoneFeatures);
} else {
alert("Geozone type not supported: " + type);
}
return null;
};
// ----------------------------------------------------------------------------
/**
*** Returns a circle shape (OpenLayers.Feature.Vector)
*** @param center The center point (OpenLayers.LonLat) of the circle
*** @param radiusM The radius of the circle in meters
*** @return The circle OpenLayers.Feature.Vector object
**/
JSMap.prototype._createCircleFeature = function(center, radiusM, circleStyle)
{
if ((center !== null) && (radiusM > 0)) {
//var circleShape = OpenLayers.Geometry.Polygon.createRegularPolygpm(center, radiusM, 30, 0);
var circlePoints = this._getCirclePoints(center, radiusM); // OpenLayers.Geometry.Point[]
var circleShape = new OpenLayers.Geometry.LinearRing(circlePoints);
return new OpenLayers.Feature.Vector(circleShape, null, circleStyle);
} else {
return null;
}
};
/**
*** Returns an array of points (OpenLayers.LonLat) representing a circle polygon
*** @param center The center point (OpenLayers.LonLat) of the circle
*** @param radiusM The radius of the circle in meters
*** @return An array of points (OpenLayers.LonLat) representing a circle polygon
**/
JSMap.prototype._getCirclePoints = function(center, radiusM)
{
var jspt = this._toJSMapPoint(center);
var rLat = geoRadians(jspt.lat); // radians
var rLon = geoRadians(jspt.lon); // radians
var d = radiusM / EARTH_RADIUS_METERS;
var circlePoints = new Array();
for (x = 0; x <= 360; x += 12) {
var xrad = geoRadians(x);
var tLat = Math.asin(Math.sin(rLat) * Math.cos(d) + Math.cos(rLat) * Math.sin(d) * Math.cos(xrad));
var tLon = rLon + Math.atan2(Math.sin(xrad) * Math.sin(d) * Math.cos(rLat), Math.cos(d) - Math.sin(rLat) * Math.sin(tLat));
var olpt = this._toOpenLayerPointLatLon(geoDegrees(tLat),geoDegrees(tLon));
circlePoints.push(this._createGeometryPoint(olpt));
}
return circlePoints;
};
/**
*** Calculate the lat/lon on the radius of the circle in the 'heading' direction
**/
JSMap.prototype._calcRadiusPoint = function(center/*JSMapPoint*/, radiusM, heading)
{
var pt = geoRadiusPoint(center.lat, center.lon, radiusM, heading); // { lat: <>, lon: <> }
return new JSMapPoint(pt.lat, pt.lon);
};
// ----------------------------------------------------------------------------
/**
*** Returns a polygon shape (OpenLayers.Feature.Vector)
*** @param vertices An array of polygon vertice points (OpenLayers.LonLat) of the circle
*** @return The polygon OpenLayers.Feature.Vector object
**/
JSMap.prototype._createPolygonFeature = function(vertices, colorStyle)
{
if ((vertices !== null) && (vertices.length >= 3)) {
var polyStyle = colorStyle;
var polyPoints = [];
for (var i = 0; i < vertices.length; i++) {
polyPoints.push(this._createGeometryPoint(vertices[i]));
}
var polyShape = new OpenLayers.Geometry.LinearRing(polyPoints);
return new OpenLayers.Feature.Vector(polyShape, null, polyStyle);
} else {
return null;
}
};
// ----------------------------------------------------------------------------
/**
*** Create/Adjust feature points
*** @param olpt The OpenLayers.LonLat point
**/
JSMap.prototype._createGeometryPoint = function(olpt) // OpenLayers.LonLat
{
/* This seems to be fixed (as of 2008/09/28)
if (this.userAgent_MSIE) {
// TODO: find out why this is needed and fix it at the source.
var px = this.openLayersMap.getViewPortPxFromLonLat(olpt);
px.x -= (this.openLayersMap.size.w / 2);
olpt = this.openLayersMap.getLonLatFromViewPortPx(px);
}
*/
return new OpenLayers.Geometry.Point(olpt.lon, olpt.lat);
};
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Mouse modifier keys: e.shiftKey, e.altKey, e.ctrlKey
// Mouse buttons: OpenLayers.Event.isLeftClick(e)
/**
*** Retrun adjusted mouse cursor hotspot
**/
JSMap.prototype._mouseLocation = function(xy)
{
if (this.userAgent_MSIE) {
// the "crosshair" cursor hotpsot is off by 4px
return new OpenLayers.Pixel(xy.x - 4, xy.y - 4);
} else {
return xy;
}
};
/**
*** Mouse event handler to draw circles/lines on the map
*** @param e The mouse event
**/
JSMap.prototype._event_OnMouseDown = function(e)
{
/* quick exits */
if (!OpenLayers.Event.isLeftClick(e) || e.altKey || (e.ctrlKey && e.shiftKey)) {
return true;
}
/* mouse down point */
var LL = this._toJSMapPoint(this.openLayersMap.getLonLatFromViewPortPx(this._mouseLocation(e.xy)));
jsmapElem.style.cursor = 'crosshair';
/* start distance ruler drag */
if (e.ctrlKey) {
this.dragType = DRAG_RULER;
this._clearRulerLayer(true);
this.dragRulerStart = LL; // JSMapPoint
jsmSetDistanceDisplay(0);
OpenLayers.Event.stop(e);
return false;
}
/* geozone mode */
if (jsvGeozoneMode && jsvZoneEditable) {
var radiusM = zoneMapGetRadius(false);
// check primary point
if (this.primaryCenter !== null) {
var CC = this._toJSMapPoint(this.primaryCenter);
if (geoDistanceMeters(CC.lat, CC.lon, LL.lat, LL.lon) <= radiusM) {
if (e.shiftKey) {
// resize
this.dragType = DRAG_GEOZONE_RADIUS;
this._clearRulerLayer(true);
} else {
// inside geozone, move
this.dragType = DRAG_GEOZONE_CENTER;
this.dragZoneOffsetLat = LL.lat - CC.lat;
this.dragZoneOffsetLon = LL.lon - CC.lon;
}
OpenLayers.Event.stop(e);
return false;
}
}
// check other points
if (!e.shiftKey && this.geozonePoints && (this.geozonePoints.length > 0)) {
for (var i = 0; i < this.geozonePoints.length; i++) {
if (geoDistanceMeters(this.geozonePoints[i].lat, this.geozonePoints[i].lon, LL.lat, LL.lon) <= radiusM) {
this.primaryIndex = i;
this.primaryCenter = this.geozonePoints[i];
zoneMapSetIndex(this.primaryIndex);
this._JSDrawGeozone(jsvZoneType, jsvZoneRadiusMeters, this.geozonePoints, jsvZoneColor, this.primaryIndex, false);
// inside geozone, move
CC = this._toJSMapPoint(this.primaryCenter);
this.dragType = DRAG_GEOZONE_CENTER;
this.dragZoneOffsetLat = LL.lat - CC.lat;
this.dragZoneOffsetLon = LL.lon - CC.lon;
OpenLayers.Event.stop(e);
return false;
}
}
}
}
this.dragType = DRAG_NONE;
return true;
};
/**
*** Mouse event handler to draw circles on the map
*** @param e The mouse event
**/
JSMap.prototype._event_OnMouseUp = function(e)
{
/* geozone mode */
if (jsvGeozoneMode && ((this.dragType & DRAG_GEOZONE) != 0)) {
var CC = this._toJSMapPoint(this.primaryCenter);
var radiusM = zoneMapGetRadius(false);
jsmSetPointZoneValue(CC.lat, CC.lon, radiusM);
this.dragType = DRAG_NONE;
mapProviderParseZones(jsvZoneList);
OpenLayers.Event.stop(e);
return false;
}
/* normal mode */
this.dragType = DRAG_NONE;
return true;
};
/**
*** Mouse event handler to detect lat/lon changes and draw circles/lines on the map
*** @param e The mouse event
**/
JSMap.prototype._event_OnMouseMove = function(e)
{
var olpt = this.openLayersMap.getLonLatFromViewPortPx(this._mouseLocation(e.xy));
if (!olpt) { return true; }
var LL = this._toJSMapPoint(olpt);
/* Latitude/Longitude change */
jsmSetLatLonDisplay(LL.lat, LL.lon);
jsmapElem.style.cursor = 'crosshair';
/* distance ruler */
if (this.dragType == DRAG_RULER) {
this.dragRulerEnd = LL;
var CC = this.dragRulerStart;
jsmSetDistanceDisplay(geoDistanceMeters(CC.lat, CC.lon, LL.lat, LL.lon));
this._drawRuler([ this._createRulerFeature(this.dragRulerStart, this.dragRulerEnd) ]);
OpenLayers.Event.stop(e);
return false;
}
/* geozone mode */
if (this.dragType == DRAG_GEOZONE_RADIUS) {
var CC = this._toJSMapPoint(this.primaryCenter);
jsvZoneRadiusMeters = Math.round(geoDistanceMeters(CC.lat, CC.lon, LL.lat, LL.lon));
if (jsvZoneRadiusMeters > MAX_ZONE_RADIUS_M) { jsvZoneRadiusMeters = MAX_ZONE_RADIUS_M; }
if (jsvZoneRadiusMeters < MIN_ZONE_RADIUS_M) { jsvZoneRadiusMeters = MIN_ZONE_RADIUS_M; }
var features = [ this._createCircleFeature(this.primaryCenter,jsvZoneRadiusMeters,GetGeozoneStyle(true,jsvZoneColor)) ];
this._drawFeatures(true, features);
jsmSetDistanceDisplay(jsvZoneRadiusMeters);
//mapProviderParseZones(jsvZoneList);
OpenLayers.Event.stop(e);
return false;
}
/* geozone mode */
if (this.dragType == DRAG_GEOZONE_CENTER) {
var CC = new JSMapPoint(LL.lat - this.dragZoneOffsetLat, LL.lon - this.dragZoneOffsetLon);
this.primaryCenter = this._toOpenLayerPoint(CC);
var REDRAW_GEOZONE = true;
if (REDRAW_GEOZONE) {
// redraw the entire Geozone
this._JSDrawGeozone(jsvZoneType, jsvZoneRadiusMeters, this.geozonePoints, jsvZoneColor, this.primaryIndex, true);
//mapProviderParseZones(jsvZoneList);
} else {
// just draw the single point-radius [zoneFeatures]
var feature = [ this._createCircleFeature(this.primaryCenter, jsvZoneRadiusMeters, GetGeozoneStyle(true,jsvZoneColor)) ];
this._drawFeatures(true, feature);
}
OpenLayers.Event.stop(e);
return false;
}
return true;
};
/**
*** Mouse event handler to recenter map
*** @param e The mouse event
**/
JSMap.prototype._event_OnClick = function(e)
{
/* geozone mode */
if (jsvGeozoneMode && jsvZoneEditable && !e.ctrlKey && !e.shiftKey && !e.altKey) {
var LL = this._toJSMapPoint(this.openLayersMap.getLonLatFromViewPortPx(this._mouseLocation(e.xy))); // where you clicked
var CC = (this.primaryCenter !== null)? this._toJSMapPoint(this.primaryCenter) : new JSMapPoint(0.0,0.0); // where the primary center is
var CCIsValid = ((CC.lat != 0.0) || (CC.lon != 0.0));
var CCLLDistKM = geoDistanceMeters(CC.lat, CC.lon, LL.lat, LL.lon);
if (jsvZoneType == ZONE_POINT_RADIUS) {
var radiusM = zoneMapGetRadius(false);
// inside primary zone?
if (CCLLDistKM <= radiusM) {
return false;
}
// inside any zone?
if (this.geozonePoints && (this.geozonePoints.length > 0)) {
for (var i = 0; i < this.geozonePoints.length; i++) {
if (i == this.primaryIndex) { continue; }
var gpt = this.geozonePoints[i];
if (geoDistanceMeters(gpt.lat, gpt.lon, LL.lat, LL.lon) <= radiusM) {
return false;
}
}
}
// outside geozone, recenter
jsmSetPointZoneValue(LL.lat, LL.lon, radiusM);
mapProviderParseZones(jsvZoneList);
OpenLayers.Event.stop(e);
return true;
} else
if (jsvZoneType == ZONE_POLYGON) {
var radiusM = jsvZoneRadiusMeters;
// inside primary zone?
if (CCLLDistKM <= radiusM) {
return false;
}
// inside any zone?
if (this.geozonePoints && (this.geozonePoints.length > 0)) {
for (var i = 0; i < this.geozonePoints.length; i++) {
if (i == this.primaryIndex) { continue; }
var gpt = this.geozonePoints[i];
if (geoDistanceMeters(gpt.lat, gpt.lon, LL.lat, LL.lon) <= radiusM) {
return false;
}
}
}
// count number of valid points
var count = 0;
for (var z = 0; z < jsvZoneList.length; z++) {
if ((jsvZoneList[z].lat != 0.0) || (jsvZoneList[z].lon != 0.0)) {
count++;
}
}
if (count == 0) {
// no valid points - create default polygon
var radiusM = 450;
var crLat = geoRadians(LL.lat); // radians
var crLon = geoRadians(LL.lon); // radians
for (x = 0; x < jsvZoneList.length; x++) {
var deg = x * (360.0 / jsvZoneList.length);
var radM = radiusM / EARTH_RADIUS_METERS;
if ((deg == 0.0) || ((deg > 170.0) && (deg < 190.0))) { radM *= 0.8; }
var xrad = geoRadians(deg); // radians
var rrLat = Math.asin(Math.sin(crLat) * Math.cos(radM) + Math.cos(crLat) * Math.sin(radM) * Math.cos(xrad));
var rrLon = crLon + Math.atan2(Math.sin(xrad) * Math.sin(radM) * Math.cos(crLat), Math.cos(radM)-Math.sin(crLat) * Math.sin(rrLat));
_jsmSetPointZoneValue(x, geoDegrees(rrLat), geoDegrees(rrLon), 0);
}
} else {
// move valid points to new location
var deltaLat = LL.lat - CC.lat;
var deltaLon = LL.lon - CC.lon;
for (var x = 0; x < jsvZoneList.length; x++) {
var pt = jsvZoneList[x];
if ((pt.lat != 0.0) || (pt.lon != 0.0)) {
_jsmSetPointZoneValue(x, (pt.lat + deltaLat), (pt.lon + deltaLon), 0);
}
}
}
mapProviderParseZones(jsvZoneList);
OpenLayers.Event.stop(e);
return true;
} else
if (jsvZoneType == ZONE_SWEPT_POINT_RADIUS) {
var radiusM = jsvZoneRadiusMeters;
// inside primary zone?
if (CCLLDistKM <= radiusM) {
return false;
}
// inside any zone?
if (this.geozonePoints && (this.geozonePoints.length > 0)) {
for (var i = 0; i < this.geozonePoints.length; i++) {
if (i == this.primaryIndex) { continue; }
var gpt = this.geozonePoints[i];
if (geoDistanceMeters(gpt.lat, gpt.lon, LL.lat, LL.lon) <= radiusM) {
return false;
}
}
}
// count number of valid points
var count = 0;
var maxDistKM = 0.0;
var lastPT = null;
for (var z = 0; z < jsvZoneList.length; z++) {
if ((jsvZoneList[z].lat != 0.0) || (jsvZoneList[z].lon != 0.0)) {
count++;
if (lastPT !== null) {
var dkm = geoDistanceMeters(lastPT.lat, lastPT.lon, jsvZoneList[z].lat, jsvZoneList[z].lon);
if (dkm > maxDistKM) {
maxDistKM = dkm;
}
} else {
lastPT = jsvZoneList[z]; // first valid point
}
}
}
var maxDeltaKM = ((maxDistKM > 5000)? maxDistKM : 5000) * 1.5;
if (!CCIsValid || (count <= 0) || (CCLLDistKM <= maxDeltaKM)) {
jsmSetPointZoneValue(LL.lat, LL.lon, radiusM);
}
// reparse zone
mapProviderParseZones(jsvZoneList);
OpenLayers.Event.stop(e);
return true;
} else {
return false;
}
}
};
// ----------------------------------------------------------------------------
/**
*** map zoomed
**/
JSMap.prototype._event_ZoomEnd = function()
{
this._event_MoveEnd();
};
/**
*** map zoomed/panned
**/
JSMap.prototype._event_MoveEnd = function()
{
if (this.userAgent_MSIE) {
var zm = this.openLayersMap.getZoom();
var sz = this.openLayersMap.getSize();
if ((this.lastMapZoom != zm) || (sz.w != this.lastMapSize.w) || (sz.h != this.lastMapSize.h)) {
// TODO: (see '_createGeometryPoint' above) This is necessary because everything seems to be
// shifted by MapWidth/2 pixels.
if (jsvGeozoneMode) {
// redraw the Geozone
var features = [ this._createCircleFeature(this.primaryCenter, jsvZoneRadiusMeters, GetGeozoneStyle(true,jsvZoneColor)) ];
this._drawFeatures(true, features);
} else
if (this.routeLines && (this.routeLines.length > 0)) {
// redraw the route
var routeFeatures = [];
for (var i = 0; i < this.routeLines.length; i++) {
var r = this.routeLines[i];
routeFeatures.push(this._createRouteFeature(r.points,r.color));
}
this._drawFeatures(true, routeFeatures);
}
if ((this.dragRulerStart !== null) && (this.dragRulerEnd !== null)) {
// redraw the ruler
this._drawRuler([ this._createRulerFeature(this.dragRulerStart, this.dragRulerEnd) ]);
}
this.lastMapZoom = zm;
this.lastMapSize = sz;
}
}
};
// ----------------------------------------------------------------------------<|fim▁end|>
|
this.replayTimer = setTimeout("jsmap._replayPushpins("+replay+")", interval);
|
<|file_name|>test_ddl_stress.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
import re
import uuid
from subprocess import call
from tests.common.test_vector import TestDimension
from tests.common.impala_test_suite import ImpalaTestSuite
# Number of tables to create per thread
NUM_TBLS_PER_THREAD = 10
# Each client will get a different test id.
TEST_IDS = xrange(0, 10)<|fim▁hole|># uncache, then drop many different tables in parallel.
class TestDdlStress(ImpalaTestSuite):
@classmethod
def get_workload(self):
return 'targeted-stress'
@classmethod
def add_test_dimensions(cls):
super(TestDdlStress, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(TestDimension('test_id', *TEST_IDS))
cls.TestMatrix.add_constraint(lambda v: v.get_value('exec_option')['batch_size'] == 0)
cls.TestMatrix.add_constraint(lambda v:\
v.get_value('table_format').file_format == 'text' and\
v.get_value('table_format').compression_codec == 'none')
@pytest.mark.stress
def test_create_cache_many_tables(self, vector):
self.client.set_configuration(vector.get_value('exec_option'))
self.client.execute("create database if not exists ddl_stress_testdb")
self.client.execute("use ddl_stress_testdb")
tbl_uniquifier = str(uuid.uuid4()).replace('-', '')
for i in xrange(NUM_TBLS_PER_THREAD):
tbl_name = "tmp_%s_%s" % (tbl_uniquifier, i)
# Create a partitioned and unpartitioned table
self.client.execute("create table %s (i int)" % tbl_name)
self.client.execute("create table %s_part (i int) partitioned by (j int)" %\
tbl_name)
# Add some data to each
self.client.execute("insert overwrite table %s select int_col from "\
"functional.alltypestiny" % tbl_name)
self.client.execute("insert overwrite table %s_part partition(j) "\
"values (1, 1), (2, 2), (3, 3), (4, 4), (4, 4)" % tbl_name)
# Cache the data the unpartitioned table
self.client.execute("alter table %s set cached in 'testPool'" % tbl_name)
# Cache, uncache, then re-cache the data in the partitioned table.
self.client.execute("alter table %s_part set cached in 'testPool'" % tbl_name)
self.client.execute("alter table %s_part set uncached" % tbl_name)
self.client.execute("alter table %s_part set cached in 'testPool'" % tbl_name)
# Drop the tables, this should remove the cache requests.
self.client.execute("drop table %s" % tbl_name)
self.client.execute("drop table %s_part" % tbl_name)<|fim▁end|>
|
# Simple stress test for DDL operations. Attempts to create, cache,
|
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>use core;
#[repr(C)]
#[derive(Debug,Clone,Copy, PartialEq)]
pub enum BroCatliResult {
Success = 0,
NeedsMoreInput = 1,
NeedsMoreOutput = 2,
BrotliFileNotCraftedForAppend = 124,
InvalidWindowSize = 125,
WindowSizeLargerThanPreviousFile = 126,
BrotliFileNotCraftedForConcatenation = 127,
}
const NUM_STREAM_HEADER_BYTES: usize = 5;
#[derive(Clone,Copy)]
struct NewStreamData {
bytes_so_far: [u8;NUM_STREAM_HEADER_BYTES],
num_bytes_read: u8,
num_bytes_written: Option<u8>,
}
impl NewStreamData {
pub fn new() -> NewStreamData{
NewStreamData{
bytes_so_far:[0,0,0,0,0],
num_bytes_read:0,
num_bytes_written:None,
}
}
fn sufficient(&self) -> bool {
if self.num_bytes_read == 4 && (127&self.bytes_so_far[0]) != 17 {
return true;
}
self.num_bytes_read == 5
}
}
fn parse_window_size(bytes_so_far:&[u8]) -> Result<(u8, usize), ()> { // returns window_size and offset in stream in bits
if bytes_so_far[0] & 1 == 0 {
return Ok((16, 1));
}
match bytes_so_far[0] & 15 {
0x3 => return Ok((18, 4)),
0x5 => return Ok((19, 4)),
0x7 => return Ok((20, 4)),
0x9 => return Ok((21, 4)),
0xb => return Ok((22, 4)),
0xd => return Ok((23, 4)),
0xf => return Ok((24, 4)),
_ => match bytes_so_far[0] & 127 {
0x71 => return Ok((15, 7)),
0x61 => return Ok((14, 7)),
0x51 => return Ok((13, 7)),
0x41 => return Ok((12, 7)),
0x31 => return Ok((11, 7)),
0x21 => return Ok((10, 7)),
0x1 => return Ok((17, 7)),
_ => {},
}
}
if (bytes_so_far[0] & 0x80) != 0 {
return Err(());
}
let ret = bytes_so_far[1] & 0x3f;
if ret < 10 || ret > 30 {
return Err(());
}
Ok((ret, 14))
}
fn detect_varlen_offset(bytes_so_far:&[u8]) -> Result<(usize), ()> { // returns offfset in bits
let (_, mut offset) = match parse_window_size(bytes_so_far) {
Ok(x) => x,
Err(_) => return Err(()),
};
let mut bytes = 0u64;
for (index, item) in bytes_so_far.iter().enumerate() {
bytes |= u64::from(*item) << (index * 8);
}
bytes >>= offset;
offset += 1;
if (bytes & 1) != 0 { // ISLAST
bytes >>= 1;
offset += 1;
if (bytes & 1) != 0 { // ISLASTEMPTY
return Ok(offset);
}
}
bytes >>= 1;
let mut mnibbles = bytes & 3;
bytes >>= 2;
offset += 2;
if mnibbles == 3 { // metadata block
if (bytes & 1) != 0 {
return Err(()); // reserved, must be zero
}
bytes >>= 1;
offset += 1;
let mskipbytes = bytes & ((1 << 2) - 1);
offset += 2;
offset += usize::from(mskipbytes as usize) * 8; // next item is byte aligned
return Ok(offset);
}
mnibbles += 4;
offset += usize::from(mnibbles as usize) * 4;
bytes >>= mnibbles * 4;
offset += 1;
if (bytes & 1) == 0 { // not UNCOMPRESSED
Err(()) // not valid bitstream for concatenation
} else { // UNCOMPRESSED: now things are aligend
Ok(offset)
}
}
// eat your vegetables
pub struct BroCatli {
last_bytes: [u8; 2],
last_bytes_len: u8,
last_byte_sanitized: bool,
any_bytes_emitted: bool,
last_byte_bit_offset: u8,
// need to make sure that window sizes stay similar or get smaller
window_size: u8,
new_stream_pending: Option<NewStreamData>,
}
impl Default for BroCatli {
fn default() -> BroCatli {
BroCatli::new()
}
}
impl BroCatli {<|fim▁hole|> last_bytes: [0,0],
last_bytes_len: 0,
last_byte_bit_offset: 0,
last_byte_sanitized: false,
any_bytes_emitted: false,
new_stream_pending: None,
window_size:0,
}
}
pub fn deserialize_from_buffer(buffer: &[u8]) -> Result<BroCatli, ()> {
if 16+NUM_STREAM_HEADER_BYTES > buffer.len() {
return Err(());
}
let mut possible_new_stream_pending = NewStreamData{
num_bytes_read: buffer[12],
num_bytes_written: if (buffer[9] & (1<<7)) != 0 {Some(buffer[13])} else {None},
bytes_so_far: [0;NUM_STREAM_HEADER_BYTES],
};
let xlen = possible_new_stream_pending.bytes_so_far.len();
possible_new_stream_pending.bytes_so_far.clone_from_slice(
&buffer[16..16+xlen]);
let new_stream_pending: Option<NewStreamData> = if (buffer[9] & (1 << 6)) != 0 {
Some(possible_new_stream_pending)
} else {
None
};
let mut ret = BroCatli {
last_bytes: [0,0],
last_bytes_len: buffer[8],
last_byte_sanitized: (buffer[9] & 0x1) != 0,
last_byte_bit_offset: buffer[10],
any_bytes_emitted: (buffer[9] & (1 << 5)) != 0,
window_size: buffer[11],
new_stream_pending:new_stream_pending,
};
if ret.last_bytes.len() > 8 {
return Err(());
}
let xlen = ret.last_bytes.len();
ret.last_bytes.clone_from_slice(&buffer[..xlen]);
Ok(ret)
}
#[inline(always)]
pub fn serialize_to_buffer(&self, buffer: &mut [u8]) -> Result<(), ()> {
if 16+NUM_STREAM_HEADER_BYTES > buffer.len() {
return Err(());
}
buffer[..self.last_bytes.len()].clone_from_slice(
&self.last_bytes[..]);
buffer[8] = self.last_bytes_len;
buffer[9] = (self.last_byte_sanitized as u8) | ((self.new_stream_pending.is_some() as u8) << 6) | ((self.any_bytes_emitted as u8) << 5);
buffer[10] = self.last_byte_bit_offset;
buffer[11] = self.window_size;
if let Some(new_stream_pending) = self.new_stream_pending {
if new_stream_pending.num_bytes_written.is_some() {
buffer[9] |= (1<<7);
}
buffer[12] = new_stream_pending.num_bytes_read;
buffer[13] = new_stream_pending.num_bytes_written.unwrap_or(0);
// 14, 15 reserved
buffer[16..16+new_stream_pending.bytes_so_far.len()].clone_from_slice(
&new_stream_pending.bytes_so_far[..]);
}
Ok(())
}
pub fn new_with_window_size(log_window_size: u8) -> BroCatli {
// in this case setup the last_bytes of the stream to perfectly mimic what would
// appear in an empty stream with the selected window size...
// this means the window size followed by 2 sequential 1 bits (LAST_METABLOCK, EMPTY)
// the new_stream code should naturally find the sequential 1 bits and mask them
// out and then prepend the window size... then the following window sizes should
// be checked to be shorter
let last_bytes_len;
let last_bytes;
if log_window_size > 24 {
last_bytes = [17u8, log_window_size | 64 | 128];
last_bytes_len = 2;
} else if log_window_size == 16 {
last_bytes = [1 | 2 | 4, 0];
last_bytes_len = 1;
} else if log_window_size > 17 {
last_bytes = [(3 + (log_window_size - 18) * 2) | (16 | 32), 0];
last_bytes_len = 1;
} else {
match log_window_size {
15 => last_bytes = [0x71 | 0x80, 1],
14 => last_bytes = [0x61 | 0x80, 1],
13 => last_bytes = [0x51 | 0x80, 1],
12 => last_bytes = [0x41 | 0x80, 1],
11 => last_bytes = [0x31 | 0x80, 1],
10 => last_bytes = [0x21 | 0x80, 1],
_ => {assert_eq!(log_window_size, 17); last_bytes = [0x1 | 0x80, 1];} // 17
}
last_bytes_len = 2;
}
BroCatli {
last_bytes: last_bytes,
last_bytes_len: last_bytes_len,
last_byte_bit_offset: 0,
last_byte_sanitized: false,
any_bytes_emitted: false,
new_stream_pending: None,
window_size:log_window_size,
}
}
pub fn new_brotli_file(&mut self) {
self.new_stream_pending = Some(NewStreamData::new());
}
fn flush_previous_stream(&mut self, out_bytes: &mut [u8], out_offset: &mut usize) -> BroCatliResult {
if !self.last_byte_sanitized { // if the previous stream hasn't had the last metablock (bit 1,1) sanitized
if self.last_bytes_len == 0 { // first stream or otherwise sanitized
self.last_byte_sanitized = true;
return BroCatliResult::Success;
}
// create a 16 bit integer with the last 2 bytes of data
let mut last_bytes = self.last_bytes[0] as u16 + ((self.last_bytes[1] as u16) << 8);
let max = self.last_bytes_len * 8;
let mut index = max - 1;
for i in 0..max {
index = max - 1 - i;
if ((1<<index) & last_bytes) != 0 {
break; // find the highest set bit
}
}
if index == 0 { // if the bit is too low, return failure, since both bits could not possibly have been set
return BroCatliResult::BrotliFileNotCraftedForAppend;
}
if (last_bytes >> (index - 1)) != 3 { // last two bits need to be set for the final metablock
return BroCatliResult::BrotliFileNotCraftedForAppend;
}
index -= 1; // discard the final two bits
last_bytes &= (1 << index) - 1; // mask them out
self.last_bytes[0] = last_bytes as u8 & 0xff; // reset the last_bytes pair
self.last_bytes[1] = (last_bytes >> 8) as u8 & 0xff;
if index >= 8 { // if both bits and one useful bit were in the second block, then write that
if out_bytes.len() > *out_offset {
out_bytes[*out_offset] = self.last_bytes[0];
self.last_bytes[0] = self.last_bytes[1];
*out_offset += 1;
self.any_bytes_emitted = true;
index -= 8;
self.last_bytes_len -= 1;
} else {
return BroCatliResult::NeedsMoreOutput;
}
}
self.last_byte_bit_offset = index;
assert!(index < 8);
self.last_byte_sanitized = true;
}
BroCatliResult::Success
}
fn shift_and_check_new_stream_header(&mut self, mut new_stream_pending: NewStreamData, out_bytes: &mut [u8], out_offset: &mut usize) -> BroCatliResult {
if new_stream_pending.num_bytes_written.is_none() {
let (window_size, window_offset) = if let Ok(results) = parse_window_size(
&new_stream_pending.bytes_so_far[..usize::from(new_stream_pending.num_bytes_read)],
) {
results
} else {
return BroCatliResult::InvalidWindowSize;
};
if self.window_size == 0 { // parse window size and just copy everything
self.window_size = window_size;
assert_eq!(self.last_byte_bit_offset, 0); // we are first stream
out_bytes[*out_offset] = new_stream_pending.bytes_so_far[0];
new_stream_pending.num_bytes_written = Some(1);
self.any_bytes_emitted = true;
*out_offset += 1;
} else {
if window_size > self.window_size {
return BroCatliResult::WindowSizeLargerThanPreviousFile;
}
let mut realigned_header:[u8;NUM_STREAM_HEADER_BYTES + 1] = [self.last_bytes[0],
0,0,0,0,0,
];
let varlen_offset = if let Ok(voffset) = detect_varlen_offset(
&new_stream_pending.bytes_so_far[..usize::from(new_stream_pending.num_bytes_read)],
) {
voffset
} else {
return BroCatliResult::BrotliFileNotCraftedForConcatenation;
};
let mut bytes_so_far = 0u64;
for index in 0..usize::from(new_stream_pending.num_bytes_read) {
bytes_so_far |= u64::from(new_stream_pending.bytes_so_far[index]) << (index * 8);
}
bytes_so_far >>= window_offset; // mask out the window size
bytes_so_far &= (1u64 << (varlen_offset - window_offset)) - 1;
let var_len_bytes = ((usize::from(varlen_offset - window_offset) + 7) / 8);
for byte_index in 0..var_len_bytes {
let cur_byte = (bytes_so_far >> (byte_index *8));
realigned_header[byte_index] |= ((cur_byte & ((1 << (8 - self.last_byte_bit_offset)) - 1)) << self.last_byte_bit_offset) as u8;
realigned_header[byte_index + 1] = (cur_byte >> (8 - self.last_byte_bit_offset)) as u8;
}
let whole_byte_destination = ((usize::from(self.last_byte_bit_offset) + varlen_offset - window_offset) + 7) / 8;
let whole_byte_source = (varlen_offset + 7) / 8;
let num_whole_bytes_to_copy = usize::from(new_stream_pending.num_bytes_read) - whole_byte_source;
for aligned_index in 0..num_whole_bytes_to_copy {
realigned_header[whole_byte_destination + aligned_index] = new_stream_pending.bytes_so_far[whole_byte_source + aligned_index];
}
out_bytes[*out_offset] = realigned_header[0];
self.any_bytes_emitted = true;
*out_offset += 1;
// subtract one since that has just been written out and we're only copying realigned_header[1..]
new_stream_pending.num_bytes_read = (whole_byte_destination + num_whole_bytes_to_copy) as u8 - 1;
new_stream_pending.num_bytes_written = Some(0);
new_stream_pending.bytes_so_far.clone_from_slice(&realigned_header[1..]);
}
} else {
assert!(self.window_size != 0);
}
let to_copy = core::cmp::min(out_bytes.len() - *out_offset,
usize::from(new_stream_pending.num_bytes_read - new_stream_pending.num_bytes_written.unwrap()));
out_bytes.split_at_mut(*out_offset).1.split_at_mut(to_copy).0.clone_from_slice(
&new_stream_pending.bytes_so_far.split_at(usize::from(new_stream_pending.num_bytes_written.unwrap())).1.split_at(to_copy).0);
*out_offset += to_copy;
if to_copy != 0 {
self.any_bytes_emitted = true;
}
new_stream_pending.num_bytes_written = Some((new_stream_pending.num_bytes_written.unwrap() + to_copy as u8));
if new_stream_pending.num_bytes_written.unwrap() != new_stream_pending.num_bytes_read {
self.new_stream_pending = Some(new_stream_pending);
return BroCatliResult::NeedsMoreOutput;
}
self.new_stream_pending = None;
self.last_byte_sanitized = false;
self.last_byte_bit_offset = 0;
self.last_bytes_len = 0;
self.last_bytes = [0,0];
//now unwrite from the stream, since the last byte may need to be adjusted to be EOF
*out_offset -= 1;
self.last_bytes[0] = out_bytes[*out_offset];
self.last_bytes_len = 1;
BroCatliResult::Success
}
pub fn stream(&mut self, in_bytes: &[u8], in_offset: &mut usize, out_bytes: &mut [u8], out_offset: &mut usize) -> BroCatliResult {
if let Some(mut new_stream_pending) = self.new_stream_pending.clone() {
let flush_result = self.flush_previous_stream(out_bytes, out_offset);
if let BroCatliResult::Success = flush_result {
if usize::from(new_stream_pending.num_bytes_read) < new_stream_pending.bytes_so_far.len() {
{
let dst = &mut new_stream_pending.bytes_so_far[usize::from(new_stream_pending.num_bytes_read)..];
let to_copy = core::cmp::min(dst.len(), in_bytes.len() - *in_offset);
dst[..to_copy].clone_from_slice(in_bytes.split_at(*in_offset).1.split_at(to_copy).0);
*in_offset += to_copy;
new_stream_pending.num_bytes_read += to_copy as u8;
}
self.new_stream_pending = Some(new_stream_pending); // write back changes
}
if !new_stream_pending.sufficient() {
return BroCatliResult::NeedsMoreInput;
}
if out_bytes.len() == *out_offset {
return BroCatliResult::NeedsMoreOutput;
}
let shift_result = self.shift_and_check_new_stream_header(new_stream_pending, out_bytes, out_offset);
if let BroCatliResult::Success = shift_result {
} else {
return shift_result;
}
} else {
return flush_result;
}
if *out_offset == out_bytes.len() {
return BroCatliResult::NeedsMoreOutput; // need to be able to write at least one byte of data to make progress
}
}
assert!(self.new_stream_pending.is_none());// this should have been handled above
if self.last_bytes_len != 2 {
if out_bytes.len() == *out_offset{
return BroCatliResult::NeedsMoreOutput;
}
if in_bytes.len() == *in_offset {
return BroCatliResult::NeedsMoreInput;
}
self.last_bytes[usize::from(self.last_bytes_len)] = in_bytes[*in_offset];
*in_offset += 1;
self.last_bytes_len += 1;
if self.last_bytes_len != 2 {
if out_bytes.len() == *out_offset{
return BroCatliResult::NeedsMoreOutput;
}
if in_bytes.len() == *in_offset {
return BroCatliResult::NeedsMoreInput;
}
self.last_bytes[usize::from(self.last_bytes_len)] = in_bytes[*in_offset];
self.last_bytes_len += 1;
*in_offset += 1;
}
}
if out_bytes.len() == *out_offset{
return BroCatliResult::NeedsMoreOutput;
}
if in_bytes.len() == *in_offset{
return BroCatliResult::NeedsMoreInput;
}
let mut to_copy = core::cmp::min(out_bytes.len() - *out_offset,
in_bytes.len() - *in_offset);
assert!(to_copy != 0);
if to_copy == 1 {
out_bytes[*out_offset] = self.last_bytes[0];
self.last_bytes[0] = self.last_bytes[1];
self.last_bytes[1] = in_bytes[*in_offset];
*in_offset += 1;
*out_offset += 1;
if *out_offset == out_bytes.len() {
return BroCatliResult::NeedsMoreOutput;
}
return BroCatliResult::NeedsMoreInput;
}
out_bytes.split_at_mut(*out_offset).1.split_at_mut(2).0.clone_from_slice(&self.last_bytes[..]);
*out_offset += 2;
let (new_in_offset, last_two) = in_bytes.split_at(*in_offset).1.split_at(to_copy).0.split_at(to_copy-2);
self.last_bytes.clone_from_slice(last_two);
*in_offset += 2; // add this after the clone since we grab the last 2 bytes, not the first
to_copy -= 2;
out_bytes.split_at_mut(*out_offset).1.split_at_mut(to_copy).0.clone_from_slice(
new_in_offset);
*out_offset += to_copy;
*in_offset += to_copy;
if *out_offset == out_bytes.len() {
return BroCatliResult::NeedsMoreOutput;
}
return BroCatliResult::NeedsMoreInput;
}
fn append_eof_metablock_to_last_bytes(&mut self) {
assert!(self.last_byte_sanitized);
let mut last_bytes = self.last_bytes[0] as u16 | ((self.last_bytes[1] as u16) << 8);
let bit_end = (self.last_bytes_len - 1) * 8 + self.last_byte_bit_offset;
last_bytes |= 3 << bit_end;
self.last_bytes[0] = last_bytes as u8 & 0xff;
self.last_bytes[1] = (last_bytes >> 8) as u8 & 0xff;
self.last_byte_sanitized = false;
self.last_byte_bit_offset += 2;
if self.last_byte_bit_offset >= 8 {
self.last_byte_bit_offset -= 8;
self.last_bytes_len += 1;
}
}
pub fn finish(&mut self, out_bytes: &mut [u8], out_offset: &mut usize) -> BroCatliResult {
if self.last_byte_sanitized && self.last_bytes_len != 0 {
self.append_eof_metablock_to_last_bytes();
}
while self.last_bytes_len != 0 {
if *out_offset == out_bytes.len() {
return BroCatliResult::NeedsMoreOutput;
}
out_bytes[*out_offset] = self.last_bytes[0];
*out_offset += 1;
self.last_bytes_len -= 1;
self.last_bytes[0] = self.last_bytes[1];
self.any_bytes_emitted = true;
}
if !self.any_bytes_emitted {
if out_bytes.len() == *out_offset{
return BroCatliResult::NeedsMoreOutput;
}
self.any_bytes_emitted = true;
out_bytes[*out_offset] = b';';
*out_offset += 1;
}
BroCatliResult::Success
}
}
mod test {
#[cfg(test)]
use super::{BroCatli};
#[test]
fn test_deserialization() {
let broccoli = BroCatli{
new_stream_pending:Some(super::NewStreamData {
bytes_so_far: [0x33; super::NUM_STREAM_HEADER_BYTES],
num_bytes_read: 16,
num_bytes_written: Some(3),
}),
last_bytes: [0x45, 0x46],
last_bytes_len: 1,
last_byte_sanitized: true,
any_bytes_emitted: false,
last_byte_bit_offset: 7,
window_size:22,
};
let mut buffer = [0u8;248];
broccoli.serialize_to_buffer(&mut buffer[..]).unwrap();
let bc = BroCatli::deserialize_from_buffer(&buffer[..]).unwrap();
assert_eq!(broccoli.last_bytes, bc.last_bytes);
assert_eq!(broccoli.last_bytes_len, bc.last_bytes_len);
assert_eq!(broccoli.last_byte_sanitized, bc.last_byte_sanitized);
assert_eq!(broccoli.last_byte_bit_offset, bc.last_byte_bit_offset);
assert_eq!(broccoli.window_size, bc.window_size);
assert_eq!(broccoli.new_stream_pending.unwrap().bytes_so_far,
bc.new_stream_pending.unwrap().bytes_so_far);
assert_eq!(broccoli.new_stream_pending.unwrap().num_bytes_read,
bc.new_stream_pending.unwrap().num_bytes_read);
assert_eq!(broccoli.new_stream_pending.unwrap().num_bytes_written,
bc.new_stream_pending.unwrap().num_bytes_written);
}
#[test]
fn test_deserialization_any_written() {
let broccoli = BroCatli{
new_stream_pending:Some(super::NewStreamData {
bytes_so_far: [0x33; super::NUM_STREAM_HEADER_BYTES],
num_bytes_read: 16,
num_bytes_written: Some(3),
}),
last_bytes: [0x45, 0x46],
last_bytes_len: 1,
last_byte_sanitized: true,
any_bytes_emitted: true,
last_byte_bit_offset: 7,
window_size:22,
};
let mut buffer = [0u8;248];
broccoli.serialize_to_buffer(&mut buffer[..]).unwrap();
let bc = BroCatli::deserialize_from_buffer(&buffer[..]).unwrap();
assert_eq!(broccoli.last_bytes, bc.last_bytes);
assert_eq!(broccoli.last_bytes_len, bc.last_bytes_len);
assert_eq!(broccoli.last_byte_sanitized, bc.last_byte_sanitized);
assert_eq!(broccoli.last_byte_bit_offset, bc.last_byte_bit_offset);
assert_eq!(broccoli.window_size, bc.window_size);
assert_eq!(broccoli.new_stream_pending.unwrap().bytes_so_far,
bc.new_stream_pending.unwrap().bytes_so_far);
assert_eq!(broccoli.new_stream_pending.unwrap().num_bytes_read,
bc.new_stream_pending.unwrap().num_bytes_read);
assert_eq!(broccoli.new_stream_pending.unwrap().num_bytes_written,
bc.new_stream_pending.unwrap().num_bytes_written);
}
#[test]
fn test_serialization() {
let mut buffer = [0u8;248];
let mut broccoli = BroCatli::deserialize_from_buffer(&buffer).unwrap();
let mut buffer2 = [0u8;248];
broccoli.serialize_to_buffer(&mut buffer2[..]).unwrap();
assert_eq!(&buffer[..], &buffer2[..]);
for (index, item) in buffer.iter_mut().enumerate() {
*item = index as u8;
}
broccoli = BroCatli::deserialize_from_buffer(&buffer).unwrap();
broccoli.serialize_to_buffer(&mut buffer2[..]).unwrap();
broccoli = BroCatli::deserialize_from_buffer(&buffer2).unwrap();
for (_index, item) in buffer.iter_mut().enumerate() {
*item = 0;
}
broccoli.serialize_to_buffer(&mut buffer[..]).unwrap();
assert_eq!(&buffer[..], &buffer2[..]);
for (index, item) in buffer.iter_mut().enumerate() {
*item = 0xff ^ index as u8;
}
broccoli = BroCatli::deserialize_from_buffer(&buffer).unwrap();
broccoli.serialize_to_buffer(&mut buffer2[..]).unwrap();
broccoli = BroCatli::deserialize_from_buffer(&buffer2).unwrap();
for (_index, item) in buffer.iter_mut().enumerate() {
*item = 0;
}
broccoli.serialize_to_buffer(&mut buffer[..]).unwrap();
assert_eq!(&buffer[..], &buffer2[..]);
}
#[test]
fn test_cat_empty_stream() {
let empty_catable = [b';'];
let mut bcat = super::BroCatli::default();
let mut in_offset = 0usize;
let mut out_bytes = [0u8;32];
let mut out_offset = 0usize;
bcat.new_brotli_file();
let mut res = bcat.stream(&empty_catable[..],
&mut in_offset,
&mut out_bytes[..],
&mut out_offset);
assert_eq!(res, super::BroCatliResult::NeedsMoreInput);
bcat.new_brotli_file();
in_offset = 0;
res = bcat.stream(&empty_catable[..],
&mut in_offset,
&mut out_bytes[..],
&mut out_offset);
assert_eq!(res, super::BroCatliResult::NeedsMoreInput);
res = bcat.finish(&mut out_bytes[..],
&mut out_offset);
assert_eq!(res, super::BroCatliResult::Success);
assert!(out_offset != 0);
assert_eq!(&out_bytes[..out_offset], &[b';']);
}
}<|fim▁end|>
|
pub fn new() -> BroCatli {
BroCatli {
|
<|file_name|>api_command_test.go<|end_file_name|><|fim▁begin|>package v2_test
import (
"errors"
"code.cloudfoundry.org/cli/api/cloudcontroller/ccerror"
"code.cloudfoundry.org/cli/command"
"code.cloudfoundry.org/cli/command/commandfakes"
. "code.cloudfoundry.org/cli/command/v2"
"code.cloudfoundry.org/cli/command/v2/v2fakes"
"code.cloudfoundry.org/cli/util/configv3"
"code.cloudfoundry.org/cli/util/ui"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/gbytes"
)
var _ = Describe("api Command", func() {
var (
cmd ApiCommand
testUI *ui.UI
fakeActor *v2fakes.FakeAPIActor
fakeConfig *commandfakes.FakeConfig
err error
)
BeforeEach(func() {
testUI = ui.NewTestUI(nil, NewBuffer(), NewBuffer())
fakeActor = new(v2fakes.FakeAPIActor)
fakeConfig = new(commandfakes.FakeConfig)
fakeConfig.BinaryNameReturns("faceman")
cmd = ApiCommand{
UI: testUI,
Actor: fakeActor,
Config: fakeConfig,
}
})
JustBeforeEach(func() {
err = cmd.Execute(nil)
})
Context("when the API endpoint is not provided", func() {
Context("when the API is not set", func() {
It("displays a tip", func() {
Expect(err).ToNot(HaveOccurred())
Expect(testUI.Out).To(Say("No api endpoint set. Use 'cf api' to set an endpoint"))
})
})
Context("when the API is set, the user is logged in and an org and space are targeted", func() {
BeforeEach(func() {
fakeConfig.TargetReturns("some-api-target")
fakeConfig.APIVersionReturns("some-version")
fakeConfig.CurrentUserReturns(configv3.User{
Name: "admin",
}, nil)
fakeConfig.TargetedOrganizationReturns(configv3.Organization{
Name: "some-org",
})
fakeConfig.TargetedSpaceReturns(configv3.Space{
Name: "some-space",
})
})
It("outputs target information", func() {
Expect(err).ToNot(HaveOccurred())
Expect(testUI.Out).To(Say("api endpoint:\\s+some-api-target"))
Expect(testUI.Out).To(Say("api version:\\s+some-version"))
})
})
Context("when passed a --unset", func() {
BeforeEach(func() {
cmd.Unset = true
})
It("clears the target", func() {
Expect(err).ToNot(HaveOccurred())
Expect(testUI.Out).To(Say("Unsetting api endpoint..."))
Expect(testUI.Out).To(Say("OK"))
Expect(fakeActor.ClearTargetCallCount()).To(Equal(1))
})
})
})
Context("when a valid API endpoint is provided", func() {
Context("when the API has SSL", func() {
Context("with no protocol", func() {
var (
CCAPI string
)
BeforeEach(func() {
CCAPI = "api.foo.com"
cmd.OptionalArgs.URL = CCAPI
fakeConfig.TargetReturns("some-api-target")
fakeConfig.APIVersionReturns("some-version")
})
Context("when the url has verified SSL", func() {
It("sets the target", func() {
Expect(err).ToNot(HaveOccurred())
Expect(fakeActor.SetTargetCallCount()).To(Equal(1))
_, settings := fakeActor.SetTargetArgsForCall(0)
Expect(settings.URL).To(Equal("https://" + CCAPI))
Expect(settings.SkipSSLValidation).To(BeFalse())
Expect(testUI.Out).To(Say("Setting api endpoint to %s...", CCAPI))
Expect(testUI.Out).To(Say(`OK
api endpoint: some-api-target
api version: some-version`,
))
})
})
Context("when the url has unverified SSL", func() {
Context("when --skip-ssl-validation is passed", func() {
BeforeEach(func() {
cmd.SkipSSLValidation = true
})
It("sets the target", func() {
Expect(err).ToNot(HaveOccurred())
Expect(fakeActor.SetTargetCallCount()).To(Equal(1))
_, settings := fakeActor.SetTargetArgsForCall(0)
Expect(settings.URL).To(Equal("https://" + CCAPI))
Expect(settings.SkipSSLValidation).To(BeTrue())
Expect(testUI.Out).To(Say("Setting api endpoint to %s...", CCAPI))
Expect(testUI.Out).To(Say(`OK
api endpoint: some-api-target
api version: some-version`,
))
})
})
Context("when no additional flags are passed", func() {
BeforeEach(func() {
fakeActor.SetTargetReturns(nil, ccerror.UnverifiedServerError{URL: CCAPI})
})
It("returns an error with a --skip-ssl-validation tip", func() {
Expect(err).To(MatchError(command.InvalidSSLCertError{API: CCAPI}))
Expect(testUI.Out).ToNot(Say("api endpoint:\\s+some-api-target"))
})
})
})
})
})
Context("when the API does not have SSL", func() {
var CCAPI string
BeforeEach(func() {
CCAPI = "http://api.foo.com"
cmd.OptionalArgs.URL = CCAPI
})
<|fim▁hole|> _, settings := fakeActor.SetTargetArgsForCall(0)
Expect(settings.URL).To(Equal(CCAPI))
Expect(settings.SkipSSLValidation).To(BeFalse())
Expect(testUI.Out).To(Say("Setting api endpoint to %s...", CCAPI))
Expect(testUI.Out).To(Say("Warning: Insecure http API endpoint detected: secure https API endpoints are recommended"))
Expect(testUI.Out).To(Say("OK"))
})
})
Context("when the API is set but the user is not logged in", func() {
BeforeEach(func() {
cmd.OptionalArgs.URL = "https://api.foo.com"
fakeConfig.TargetReturns("something")
})
It("outputs a 'not logged in' message", func() {
Expect(err).ToNot(HaveOccurred())
Expect(testUI.Out).To(Say("Not logged in. Use 'faceman login' to log in."))
})
})
Context("when the API is set but the user is logged in", func() {
BeforeEach(func() {
cmd.OptionalArgs.URL = "https://api.foo.com"
fakeConfig.TargetReturns("something")
fakeConfig.CurrentUserReturns(configv3.User{Name: "banana"}, nil)
})
It("does not output a 'not logged in' message", func() {
Expect(err).ToNot(HaveOccurred())
Expect(testUI.Out).ToNot(Say("Not logged in. Use 'faceman login' to log in."))
})
})
Context("when the URL host does not exist", func() {
var (
CCAPI string
requestErr ccerror.RequestError
)
BeforeEach(func() {
CCAPI = "i.do.not.exist.com"
cmd.OptionalArgs.URL = CCAPI
requestErr = ccerror.RequestError{Err: errors.New("I am an error")}
fakeActor.SetTargetReturns(nil, requestErr)
})
It("returns an APIRequestError", func() {
Expect(err).To(MatchError(command.APIRequestError{Err: requestErr.Err}))
})
})
})
})<|fim▁end|>
|
It("sets the target with a warning", func() {
Expect(err).ToNot(HaveOccurred())
Expect(fakeActor.SetTargetCallCount()).To(Equal(1))
|
<|file_name|>mediaconvert.rs<|end_file_name|><|fim▁begin|>#![cfg(feature = "mediaconvert")]
extern crate rusoto_core;
extern crate rusoto_mediaconvert;<|fim▁hole|>use rusoto_mediaconvert::{MediaConvert, MediaConvertClient, ListJobsRequest};
use rusoto_core::Region;
#[test]
fn should_list_jobs() {
let client = MediaConvertClient::new(Region::UsEast1);
let request = ListJobsRequest::default();
match client.list_jobs(request).sync() {
Ok(resp) => println!("Got success response of {:?}", resp),
Err(err) => assert!(format!("{}", err).contains("You must use the subscription API")), // needs to be enabled per account
}
}<|fim▁end|>
| |
<|file_name|>monitor.js<|end_file_name|><|fim▁begin|>var Thoonk = require('../thoonk').Thoonk;
var thoonk = new Thoonk();
var jobs = {};
var stats = thoonk.feed('thoonk_job_stats');
thoonk.mredis.smembers('feeds', function(err, feeds) {
feeds.forEach(function(name) {
thoonk.mredis.hget('feed.config:' + name, 'type', function(err, reply) {
if(reply == 'job') {
jobs[name] = thoonk.job(name);
}
});
});
});
thoonk.on('create', function(name, instance) {
thoonk.mredis.hget('feed.config:' + name, 'type', function(err, reply) {
if(reply == 'job') {
jobs[name] = thoonk.job(name);
}
});
});
thoonk.on('delete', function(name, instance) {
if(jobs.hasOwnProperty(name)) {
jobs[name].quit();
delete jobs[name];
};<|fim▁hole|>});
var update = function() {
for(key in jobs) { //function(job, key) {
(function(key, jobs) {
var multi = thoonk.mredis.multi();
multi.llen('feed.ids:' + key);
multi.getset('feed.publishes:' + key, '0');
multi.getset('feed.finishes:' + key, '0');
multi.zcount('feed.claimed:' + key,'0', '999999999999999');
multi.hlen('feed.items:' + key);
multi.exec(function(err, reply) {
console.log('----' + key + '----');
console.log('available:', reply[0]);
console.log('publishes:', reply[1]);
console.log('finishes:', reply[1]);
console.log('claimed:', reply[3]);
console.log('total:', reply[4]);
stats.publish(JSON.stringify({available: reply[0], publishes: reply[1], finishes: reply[2], claimed: reply[3], total:reply[4]}), key)
});
})(key, jobs);
}
setTimeout(update, 1000);
};
update();
var http = require('http');
var static = require('node-static');
var fileServer = new(static.Server)('./monitor-html');
var server = http.createServer(function(request, response) {
request.addListener('end', function () {
fileServer.serve(request, response);
});
});
server.listen(8000);
var io = require('socket.io').listen(8001);
io.sockets.on('connection', function (socket) {
var thissocket = socket;
var statupdate = function(feed, id, item) {
var uitem = JSON.parse(item);
uitem.id = id;
console.log('msg', feed, item, id);
socket.emit('message', uitem);
};
stats.subscribe({
edit: statupdate,
publish: statupdate
});
socket.once('disconnect', function() {
stats.unsubscribe({edit: statupdate, publish: statupdate});
});
});<|fim▁end|>
| |
<|file_name|>transformed_distribution.py<|end_file_name|><|fim▁begin|># Copyright 2016 The TensorFlow 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.
# ==============================================================================
"""A Transformed Distribution class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import check_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops.distributions import distribution as distribution_lib
from tensorflow.python.ops.distributions import identity_bijector
from tensorflow.python.ops.distributions import util as distribution_util
from tensorflow.python.util import deprecation
__all__ = [
"TransformedDistribution",
]
# The following helper functions attempt to statically perform a TF operation.
# These functions make debugging easier since we can do more validation during
# graph construction.
def _static_value(x):
"""Returns the static value of a `Tensor` or `None`."""
return tensor_util.constant_value(ops.convert_to_tensor(x))
def _logical_and(*args):
"""Convenience function which attempts to statically `reduce_all`."""
args_ = [_static_value(x) for x in args]
if any(x is not None and not bool(x) for x in args_):
return constant_op.constant(False)
if all(x is not None and bool(x) for x in args_):
return constant_op.constant(True)
if len(args) == 2:
return math_ops.logical_and(*args)
return math_ops.reduce_all(args)
def _logical_equal(x, y):
"""Convenience function which attempts to statically compute `x == y`."""
x_ = _static_value(x)
y_ = _static_value(y)
if x_ is None or y_ is None:
return math_ops.equal(x, y)
return constant_op.constant(np.array_equal(x_, y_))
def _logical_not(x):
"""Convenience function which attempts to statically apply `logical_not`."""
x_ = _static_value(x)
if x_ is None:
return math_ops.logical_not(x)
return constant_op.constant(np.logical_not(x_))
def _concat_vectors(*args):
"""Convenience function which concatenates input vectors."""
args_ = [_static_value(x) for x in args]
if any(x_ is None for x_ in args_):
return array_ops.concat(args, 0)
return constant_op.constant([x_ for vec_ in args_ for x_ in vec_])
def _pick_scalar_condition(pred, cond_true, cond_false):
"""Convenience function which chooses the condition based on the predicate."""
# Note: This function is only valid if all of pred, cond_true, and cond_false
# are scalars. This means its semantics are arguably more like tf.cond than
# tf.select even though we use tf.select to implement it.
pred_ = _static_value(pred)
if pred_ is None:
return array_ops.where(pred, cond_true, cond_false)
return cond_true if pred_ else cond_false
def _ones_like(x):
"""Convenience function attempts to statically construct `ones_like`."""
# Should only be used for small vectors.
if x.get_shape().is_fully_defined():
return array_ops.ones(x.get_shape().as_list(), dtype=x.dtype)
return array_ops.ones_like(x)
def _ndims_from_shape(shape):
"""Returns `Tensor`'s `rank` implied by a `Tensor` shape."""
if shape.get_shape().ndims not in (None, 1):
raise ValueError("input is not a valid shape: not 1D")
if not shape.dtype.is_integer:
raise TypeError("input is not a valid shape: wrong dtype")
if shape.get_shape().is_fully_defined():
return constant_op.constant(shape.get_shape().as_list()[0])
return array_ops.shape(shape)[0]
def _is_scalar_from_shape(shape):
"""Returns `True` `Tensor` if `Tensor` shape implies a scalar."""
return _logical_equal(_ndims_from_shape(shape), 0)
class TransformedDistribution(distribution_lib.Distribution):
"""A Transformed Distribution.
A `TransformedDistribution` models `p(y)` given a base distribution `p(x)`,
and a deterministic, invertible, differentiable transform, `Y = g(X)`. The
transform is typically an instance of the `Bijector` class and the base
distribution is typically an instance of the `Distribution` class.
A `Bijector` is expected to implement the following functions:
- `forward`,
- `inverse`,
- `inverse_log_det_jacobian`.
The semantics of these functions are outlined in the `Bijector` documentation.
We now describe how a `TransformedDistribution` alters the input/outputs of a
`Distribution` associated with a random variable (rv) `X`.
Write `cdf(Y=y)` for an absolutely continuous cumulative distribution function
of random variable `Y`; write the probability density function `pdf(Y=y) :=
d^k / (dy_1,...,dy_k) cdf(Y=y)` for its derivative wrt to `Y` evaluated at
`y`. Assume that `Y = g(X)` where `g` is a deterministic diffeomorphism,
i.e., a non-random, continuous, differentiable, and invertible function.
Write the inverse of `g` as `X = g^{-1}(Y)` and `(J o g)(x)` for the Jacobian
of `g` evaluated at `x`.
A `TransformedDistribution` implements the following operations:
* `sample`
Mathematically: `Y = g(X)`
Programmatically: `bijector.forward(distribution.sample(...))`
* `log_prob`
Mathematically: `(log o pdf)(Y=y) = (log o pdf o g^{-1})(y)
+ (log o abs o det o J o g^{-1})(y)`
Programmatically: `(distribution.log_prob(bijector.inverse(y))
+ bijector.inverse_log_det_jacobian(y))`
* `log_cdf`
Mathematically: `(log o cdf)(Y=y) = (log o cdf o g^{-1})(y)`
Programmatically: `distribution.log_cdf(bijector.inverse(x))`
* and similarly for: `cdf`, `prob`, `log_survival_function`,
`survival_function`.
A simple example constructing a Log-Normal distribution from a Normal
distribution:
```python
ds = tfp.distributions
log_normal = ds.TransformedDistribution(
distribution=ds.Normal(loc=0., scale=1.),
bijector=ds.bijectors.Exp(),
name="LogNormalTransformedDistribution")
```
A `LogNormal` made from callables:
```python
ds = tfp.distributions
log_normal = ds.TransformedDistribution(
distribution=ds.Normal(loc=0., scale=1.),
bijector=ds.bijectors.Inline(
forward_fn=tf.exp,
inverse_fn=tf.log,
inverse_log_det_jacobian_fn=(
lambda y: -tf.reduce_sum(tf.log(y), axis=-1)),
name="LogNormalTransformedDistribution")
```
Another example constructing a Normal from a StandardNormal:
```python
ds = tfp.distributions
normal = ds.TransformedDistribution(
distribution=ds.Normal(loc=0., scale=1.),
bijector=ds.bijectors.Affine(
shift=-1.,
scale_identity_multiplier=2.)
name="NormalTransformedDistribution")
```
A `TransformedDistribution`'s batch- and event-shape are implied by the base
distribution unless explicitly overridden by `batch_shape` or `event_shape`
arguments. Specifying an overriding `batch_shape` (`event_shape`) is
permitted only if the base distribution has scalar batch-shape (event-shape).
The bijector is applied to the distribution as if the distribution possessed
the overridden shape(s). The following example demonstrates how to construct a
multivariate Normal as a `TransformedDistribution`.
```python
ds = tfp.distributions
# We will create two MVNs with batch_shape = event_shape = 2.
mean = [[-1., 0], # batch:0
[0., 1]] # batch:1
chol_cov = [[[1., 0],
[0, 1]], # batch:0
[[1, 0],
[2, 2]]] # batch:1
mvn1 = ds.TransformedDistribution(
distribution=ds.Normal(loc=0., scale=1.),
bijector=ds.bijectors.Affine(shift=mean, scale_tril=chol_cov),
batch_shape=[2], # Valid because base_distribution.batch_shape == [].
event_shape=[2]) # Valid because base_distribution.event_shape == [].
mvn2 = ds.MultivariateNormalTriL(loc=mean, scale_tril=chol_cov)
# mvn1.log_prob(x) == mvn2.log_prob(x)
```
"""
@deprecation.deprecated(
"2019-01-01",
"The TensorFlow Distributions library has moved to "
"TensorFlow Probability "
"(https://github.com/tensorflow/probability). You "
"should update all references to use `tfp.distributions` "
"instead of `tf.distributions`.",
warn_once=True)
def __init__(self,
distribution,
bijector=None,
batch_shape=None,
event_shape=None,
validate_args=False,
name=None):
"""Construct a Transformed Distribution.
Args:
distribution: The base distribution instance to transform. Typically an
instance of `Distribution`.
bijector: The object responsible for calculating the transformation.
Typically an instance of `Bijector`. `None` means `Identity()`.
batch_shape: `integer` vector `Tensor` which overrides `distribution`
`batch_shape`; valid only if `distribution.is_scalar_batch()`.
event_shape: `integer` vector `Tensor` which overrides `distribution`
`event_shape`; valid only if `distribution.is_scalar_event()`.
validate_args: Python `bool`, default `False`. When `True` distribution
parameters are checked for validity despite possibly degrading runtime
performance. When `False` invalid inputs may silently render incorrect
outputs.
name: Python `str` name prefixed to Ops created by this class. Default:
`bijector.name + distribution.name`.
"""
parameters = dict(locals())
name = name or (("" if bijector is None else bijector.name) +
distribution.name)
with ops.name_scope(name, values=[event_shape, batch_shape]) as name:
# For convenience we define some handy constants.
self._zero = constant_op.constant(0, dtype=dtypes.int32, name="zero")
self._empty = constant_op.constant([], dtype=dtypes.int32, name="empty")
if bijector is None:
bijector = identity_bijector.Identity(validate_args=validate_args)
# We will keep track of a static and dynamic version of
# self._is_{batch,event}_override. This way we can do more prior to graph
# execution, including possibly raising Python exceptions.
self._override_batch_shape = self._maybe_validate_shape_override(
batch_shape, distribution.is_scalar_batch(), validate_args,
"batch_shape")
self._is_batch_override = _logical_not(_logical_equal(
_ndims_from_shape(self._override_batch_shape), self._zero))
self._is_maybe_batch_override = bool(
tensor_util.constant_value(self._override_batch_shape) is None or
tensor_util.constant_value(self._override_batch_shape).size != 0)
self._override_event_shape = self._maybe_validate_shape_override(
event_shape, distribution.is_scalar_event(), validate_args,
"event_shape")
self._is_event_override = _logical_not(_logical_equal(
_ndims_from_shape(self._override_event_shape), self._zero))
self._is_maybe_event_override = bool(
tensor_util.constant_value(self._override_event_shape) is None or
tensor_util.constant_value(self._override_event_shape).size != 0)
# To convert a scalar distribution into a multivariate distribution we
# will draw dims from the sample dims, which are otherwise iid. This is
# easy to do except in the case that the base distribution has batch dims
# and we're overriding event shape. When that case happens the event dims
# will incorrectly be to the left of the batch dims. In this case we'll
# cyclically permute left the new dims.
self._needs_rotation = _logical_and(
self._is_event_override,
_logical_not(self._is_batch_override),
_logical_not(distribution.is_scalar_batch()))
override_event_ndims = _ndims_from_shape(self._override_event_shape)
self._rotate_ndims = _pick_scalar_condition(
self._needs_rotation, override_event_ndims, 0)
# We'll be reducing the head dims (if at all), i.e., this will be []
# if we don't need to reduce.
self._reduce_event_indices = math_ops.range(
self._rotate_ndims - override_event_ndims, self._rotate_ndims)
self._distribution = distribution
self._bijector = bijector
super(TransformedDistribution, self).__init__(
dtype=self._distribution.dtype,
reparameterization_type=self._distribution.reparameterization_type,
validate_args=validate_args,
allow_nan_stats=self._distribution.allow_nan_stats,
parameters=parameters,
# We let TransformedDistribution access _graph_parents since this class
# is more like a baseclass than derived.
graph_parents=(distribution._graph_parents + # pylint: disable=protected-access
bijector.graph_parents),
name=name)
@property
def distribution(self):
"""Base distribution, p(x)."""
return self._distribution
@property
def bijector(self):
"""Function transforming x => y."""
return self._bijector
def _event_shape_tensor(self):
return self.bijector.forward_event_shape_tensor(
distribution_util.pick_vector(
self._is_event_override,
self._override_event_shape,
self.distribution.event_shape_tensor()))
def _event_shape(self):
# If there's a chance that the event_shape has been overridden, we return
# what we statically know about the `event_shape_override`. This works
# because: `_is_maybe_event_override` means `static_override` is `None` or a
# non-empty list, i.e., we don't statically know the `event_shape` or we do.
#
# Since the `bijector` may change the `event_shape`, we then forward what we
# know to the bijector. This allows the `bijector` to have final say in the
# `event_shape`.
static_override = tensor_util.constant_value_as_shape(
self._override_event_shape)
return self.bijector.forward_event_shape(
static_override
if self._is_maybe_event_override
else self.distribution.event_shape)
def _batch_shape_tensor(self):
return distribution_util.pick_vector(
self._is_batch_override,
self._override_batch_shape,
self.distribution.batch_shape_tensor())
def _batch_shape(self):
# If there's a chance that the batch_shape has been overridden, we return
# what we statically know about the `batch_shape_override`. This works
# because: `_is_maybe_batch_override` means `static_override` is `None` or a
# non-empty list, i.e., we don't statically know the `batch_shape` or we do.
#
# Notice that this implementation parallels the `_event_shape` except that
# the `bijector` doesn't get to alter the `batch_shape`. Recall that
# `batch_shape` is a property of a distribution while `event_shape` is
# shared between both the `distribution` instance and the `bijector`.
static_override = tensor_util.constant_value_as_shape(
self._override_batch_shape)
return (static_override
if self._is_maybe_batch_override
else self.distribution.batch_shape)
def _sample_n(self, n, seed=None):
sample_shape = _concat_vectors(
distribution_util.pick_vector(self._needs_rotation, self._empty, [n]),
self._override_batch_shape,
self._override_event_shape,
distribution_util.pick_vector(self._needs_rotation, [n], self._empty))
x = self.distribution.sample(sample_shape=sample_shape, seed=seed)
x = self._maybe_rotate_dims(x)
# We'll apply the bijector in the `_call_sample_n` function.
return x
def _call_sample_n(self, sample_shape, seed, name, **kwargs):<|fim▁hole|> # works).
with self._name_scope(name, values=[sample_shape]):
sample_shape = ops.convert_to_tensor(
sample_shape, dtype=dtypes.int32, name="sample_shape")
sample_shape, n = self._expand_sample_shape_to_vector(
sample_shape, "sample_shape")
# First, generate samples. We will possibly generate extra samples in the
# event that we need to reinterpret the samples as part of the
# event_shape.
x = self._sample_n(n, seed, **kwargs)
# Next, we reshape `x` into its final form. We do this prior to the call
# to the bijector to ensure that the bijector caching works.
batch_event_shape = array_ops.shape(x)[1:]
final_shape = array_ops.concat([sample_shape, batch_event_shape], 0)
x = array_ops.reshape(x, final_shape)
# Finally, we apply the bijector's forward transformation. For caching to
# work, it is imperative that this is the last modification to the
# returned result.
y = self.bijector.forward(x, **kwargs)
y = self._set_sample_static_shape(y, sample_shape)
return y
def _log_prob(self, y):
# For caching to work, it is imperative that the bijector is the first to
# modify the input.
x = self.bijector.inverse(y)
event_ndims = self._maybe_get_static_event_ndims()
ildj = self.bijector.inverse_log_det_jacobian(y, event_ndims=event_ndims)
if self.bijector._is_injective: # pylint: disable=protected-access
return self._finish_log_prob_for_one_fiber(y, x, ildj, event_ndims)
lp_on_fibers = [
self._finish_log_prob_for_one_fiber(y, x_i, ildj_i, event_ndims)
for x_i, ildj_i in zip(x, ildj)]
return math_ops.reduce_logsumexp(array_ops.stack(lp_on_fibers), axis=0)
def _finish_log_prob_for_one_fiber(self, y, x, ildj, event_ndims):
"""Finish computation of log_prob on one element of the inverse image."""
x = self._maybe_rotate_dims(x, rotate_right=True)
log_prob = self.distribution.log_prob(x)
if self._is_maybe_event_override:
log_prob = math_ops.reduce_sum(log_prob, self._reduce_event_indices)
log_prob += math_ops.cast(ildj, log_prob.dtype)
if self._is_maybe_event_override and isinstance(event_ndims, int):
log_prob.set_shape(
array_ops.broadcast_static_shape(
y.get_shape().with_rank_at_least(1)[:-event_ndims],
self.batch_shape))
return log_prob
def _prob(self, y):
x = self.bijector.inverse(y)
event_ndims = self._maybe_get_static_event_ndims()
ildj = self.bijector.inverse_log_det_jacobian(y, event_ndims=event_ndims)
if self.bijector._is_injective: # pylint: disable=protected-access
return self._finish_prob_for_one_fiber(y, x, ildj, event_ndims)
prob_on_fibers = [
self._finish_prob_for_one_fiber(y, x_i, ildj_i, event_ndims)
for x_i, ildj_i in zip(x, ildj)]
return sum(prob_on_fibers)
def _finish_prob_for_one_fiber(self, y, x, ildj, event_ndims):
"""Finish computation of prob on one element of the inverse image."""
x = self._maybe_rotate_dims(x, rotate_right=True)
prob = self.distribution.prob(x)
if self._is_maybe_event_override:
prob = math_ops.reduce_prod(prob, self._reduce_event_indices)
prob *= math_ops.exp(math_ops.cast(ildj, prob.dtype))
if self._is_maybe_event_override and isinstance(event_ndims, int):
prob.set_shape(
array_ops.broadcast_static_shape(
y.get_shape().with_rank_at_least(1)[:-event_ndims],
self.batch_shape))
return prob
def _log_cdf(self, y):
if self._is_maybe_event_override:
raise NotImplementedError("log_cdf is not implemented when overriding "
"event_shape")
if not self.bijector._is_injective: # pylint: disable=protected-access
raise NotImplementedError("log_cdf is not implemented when "
"bijector is not injective.")
x = self.bijector.inverse(y)
return self.distribution.log_cdf(x)
def _cdf(self, y):
if self._is_maybe_event_override:
raise NotImplementedError("cdf is not implemented when overriding "
"event_shape")
if not self.bijector._is_injective: # pylint: disable=protected-access
raise NotImplementedError("cdf is not implemented when "
"bijector is not injective.")
x = self.bijector.inverse(y)
return self.distribution.cdf(x)
def _log_survival_function(self, y):
if self._is_maybe_event_override:
raise NotImplementedError("log_survival_function is not implemented when "
"overriding event_shape")
if not self.bijector._is_injective: # pylint: disable=protected-access
raise NotImplementedError("log_survival_function is not implemented when "
"bijector is not injective.")
x = self.bijector.inverse(y)
return self.distribution.log_survival_function(x)
def _survival_function(self, y):
if self._is_maybe_event_override:
raise NotImplementedError("survival_function is not implemented when "
"overriding event_shape")
if not self.bijector._is_injective: # pylint: disable=protected-access
raise NotImplementedError("survival_function is not implemented when "
"bijector is not injective.")
x = self.bijector.inverse(y)
return self.distribution.survival_function(x)
def _quantile(self, value):
if self._is_maybe_event_override:
raise NotImplementedError("quantile is not implemented when overriding "
"event_shape")
if not self.bijector._is_injective: # pylint: disable=protected-access
raise NotImplementedError("quantile is not implemented when "
"bijector is not injective.")
# x_q is the "qth quantile" of X iff q = P[X <= x_q]. Now, since X =
# g^{-1}(Y), q = P[X <= x_q] = P[g^{-1}(Y) <= x_q] = P[Y <= g(x_q)],
# implies the qth quantile of Y is g(x_q).
inv_cdf = self.distribution.quantile(value)
return self.bijector.forward(inv_cdf)
def _entropy(self):
if not self.bijector.is_constant_jacobian:
raise NotImplementedError("entropy is not implemented")
if not self.bijector._is_injective: # pylint: disable=protected-access
raise NotImplementedError("entropy is not implemented when "
"bijector is not injective.")
# Suppose Y = g(X) where g is a diffeomorphism and X is a continuous rv. It
# can be shown that:
# H[Y] = H[X] + E_X[(log o abs o det o J o g)(X)].
# If is_constant_jacobian then:
# E_X[(log o abs o det o J o g)(X)] = (log o abs o det o J o g)(c)
# where c can by anything.
entropy = self.distribution.entropy()
if self._is_maybe_event_override:
# H[X] = sum_i H[X_i] if X_i are mutually independent.
# This means that a reduce_sum is a simple rescaling.
entropy *= math_ops.cast(math_ops.reduce_prod(self._override_event_shape),
dtype=entropy.dtype.base_dtype)
if self._is_maybe_batch_override:
new_shape = array_ops.concat([
_ones_like(self._override_batch_shape),
self.distribution.batch_shape_tensor()
], 0)
entropy = array_ops.reshape(entropy, new_shape)
multiples = array_ops.concat([
self._override_batch_shape,
_ones_like(self.distribution.batch_shape_tensor())
], 0)
entropy = array_ops.tile(entropy, multiples)
dummy = array_ops.zeros(
shape=array_ops.concat(
[self.batch_shape_tensor(), self.event_shape_tensor()],
0),
dtype=self.dtype)
event_ndims = (self.event_shape.ndims if self.event_shape.ndims is not None
else array_ops.size(self.event_shape_tensor()))
ildj = self.bijector.inverse_log_det_jacobian(
dummy, event_ndims=event_ndims)
entropy -= math_ops.cast(ildj, entropy.dtype)
entropy.set_shape(self.batch_shape)
return entropy
def _maybe_validate_shape_override(self, override_shape, base_is_scalar,
validate_args, name):
"""Helper to __init__ which ensures override batch/event_shape are valid."""
if override_shape is None:
override_shape = []
override_shape = ops.convert_to_tensor(override_shape, dtype=dtypes.int32,
name=name)
if not override_shape.dtype.is_integer:
raise TypeError("shape override must be an integer")
override_is_scalar = _is_scalar_from_shape(override_shape)
if tensor_util.constant_value(override_is_scalar):
return self._empty
dynamic_assertions = []
if override_shape.get_shape().ndims is not None:
if override_shape.get_shape().ndims != 1:
raise ValueError("shape override must be a vector")
elif validate_args:
dynamic_assertions += [check_ops.assert_rank(
override_shape, 1,
message="shape override must be a vector")]
if tensor_util.constant_value(override_shape) is not None:
if any(s <= 0 for s in tensor_util.constant_value(override_shape)):
raise ValueError("shape override must have positive elements")
elif validate_args:
dynamic_assertions += [check_ops.assert_positive(
override_shape,
message="shape override must have positive elements")]
is_both_nonscalar = _logical_and(_logical_not(base_is_scalar),
_logical_not(override_is_scalar))
if tensor_util.constant_value(is_both_nonscalar) is not None:
if tensor_util.constant_value(is_both_nonscalar):
raise ValueError("base distribution not scalar")
elif validate_args:
dynamic_assertions += [check_ops.assert_equal(
is_both_nonscalar, False,
message="base distribution not scalar")]
if not dynamic_assertions:
return override_shape
return control_flow_ops.with_dependencies(
dynamic_assertions, override_shape)
def _maybe_rotate_dims(self, x, rotate_right=False):
"""Helper which rolls left event_dims left or right event_dims right."""
needs_rotation_const = tensor_util.constant_value(self._needs_rotation)
if needs_rotation_const is not None and not needs_rotation_const:
return x
ndims = array_ops.rank(x)
n = (ndims - self._rotate_ndims) if rotate_right else self._rotate_ndims
return array_ops.transpose(
x, _concat_vectors(math_ops.range(n, ndims), math_ops.range(0, n)))
def _maybe_get_static_event_ndims(self):
if self.event_shape.ndims is not None:
return self.event_shape.ndims
event_ndims = array_ops.size(self.event_shape_tensor())
event_ndims_ = distribution_util.maybe_get_static_value(event_ndims)
if event_ndims_ is not None:
return event_ndims_
return event_ndims<|fim▁end|>
|
# We override `_call_sample_n` rather than `_sample_n` so we can ensure that
# the result of `self.bijector.forward` is not modified (and thus caching
|
<|file_name|>graph.py<|end_file_name|><|fim▁begin|>import re
CJDNS_IP_REGEX = re.compile(r'^fc[0-9a-f]{2}(:[0-9a-f]{4}){7}$', re.IGNORECASE)
class Node(object):
def __init__(self, ip, version=None, label=None):
if not valid_cjdns_ip(ip):
raise ValueError('Invalid IP address')
if not valid_version(version):<|fim▁hole|>
self.ip = ip
self.version = int(version)
self.label = ip[-4:] or label
def __lt__(self, b):
return self.ip < b.ip
def __repr__(self):
return 'Node(ip="%s", version=%s, label="%s")' % (
self.ip,
self.version,
self.label)
class Edge(object):
def __init__(self, a, b):
self.a, self.b = sorted([a, b])
def __eq__(self, that):
return self.a.ip == that.a.ip and self.b.ip == that.b.ip
def __repr__(self):
return 'Edge(a.ip="{}", b.ip="{}")'.format(self.a.ip, self.b.ip)
def valid_cjdns_ip(ip):
return CJDNS_IP_REGEX.match(ip)
def valid_version(version):
try:
return int(version) < 30
except ValueError:
return False<|fim▁end|>
|
raise ValueError('Invalid version')
|
<|file_name|>funct.py<|end_file_name|><|fim▁begin|>import codecs
def funct(f_name):
"""Remove leading and trailing whitespace from file."""
f_read = codecs.open(f_name, 'r')
f_lines = f_read.readlines()
out_lines = map(str.strip, f_lines)
f_read.close()
while True:
o_write = raw_input("Create new file (c) or overwrite existing (o): ")
if o_write.lower() == 'o':
# f_name stays the same
break
elif o_write.lower() == 'c':
f_name = raw_input("What is new file name? ")
break<|fim▁hole|>
for line in out_lines:
f_write.write(line + '\n')
print '"{}" has been written with no leading or trailing \
whitespace.'.format(f_name)
def funct_comp(f_name):
"""Remove leading and trailing whitespace from file w/ comprehension."""
f_read = codecs.open(f_name, 'r')
f_lines = f_read.readlines()
print f_lines
# out_lines = map(str.strip, f_lines)
out_lines = [line.strip() for line in f_lines]
print out_lines
f_read.close()
while True:
o_write = raw_input("Create new file (c) or overwrite existing (o): ")
if o_write.lower() == 'o':
# f_name stays the same
break
elif o_write.lower() == 'c':
f_name = raw_input("What is new file name? ")
break
f_write = codecs.open(f_name, 'w')
for line in out_lines:
f_write.write(line + '\n')
print '"{}" has been written with no leading or trailing \
whitespace.'.format(f_name)<|fim▁end|>
|
f_write = codecs.open(f_name, 'w')
|
<|file_name|>NormalModuleFactory.js<|end_file_name|><|fim▁begin|>/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const asyncLib = require("neo-async");
const Tapable = require("tapable").Tapable;
const AsyncSeriesWaterfallHook = require("tapable").AsyncSeriesWaterfallHook;
const SyncWaterfallHook = require("tapable").SyncWaterfallHook;
const SyncBailHook = require("tapable").SyncBailHook;
const SyncHook = require("tapable").SyncHook;
const HookMap = require("tapable").HookMap;
const NormalModule = require("./NormalModule");
const RawModule = require("./RawModule");
const RuleSet = require("./RuleSet");
const cachedMerge = require("./util/cachedMerge");
const EMPTY_RESOLVE_OPTIONS = {};
const loaderToIdent = data => {
if (!data.options) return data.loader;
if (typeof data.options === "string") return data.loader + "?" + data.options;
if (typeof data.options !== "object")
throw new Error("loader options must be string or object");
if (data.ident) return data.loader + "??" + data.ident;
return data.loader + "?" + JSON.stringify(data.options);
};
const identToLoaderRequest = resultString => {
const idx = resultString.indexOf("?");
let options;
if (idx >= 0) {
options = resultString.substr(idx + 1);
resultString = resultString.substr(0, idx);
return {
loader: resultString,
options
};
} else {
return {
loader: resultString
};
}
};
class NormalModuleFactory extends Tapable {
constructor(context, resolverFactory, options) {
super();
this.hooks = {
resolver: new SyncWaterfallHook(["resolver"]),
factory: new SyncWaterfallHook(["factory"]),
beforeResolve: new AsyncSeriesWaterfallHook(["data"]),
afterResolve: new AsyncSeriesWaterfallHook(["data"]),
createModule: new SyncBailHook(["data"]),
module: new SyncWaterfallHook(["module", "data"]),
createParser: new HookMap(() => new SyncBailHook(["parserOptions"])),
parser: new HookMap(() => new SyncHook(["parser", "parserOptions"])),
createGenerator: new HookMap(
() => new SyncBailHook(["generatorOptions"])
),
generator: new HookMap(
() => new SyncHook(["generator", "generatorOptions"])
)
};
this._pluginCompat.tap("NormalModuleFactory", options => {
switch (options.name) {
case "before-resolve":
case "after-resolve":
options.async = true;
break;
case "parser":
this.hooks.parser
.for("javascript/auto")
.tap(options.fn.name || "unnamed compat plugin", options.fn);
return true;
}
let match;
match = /^parser (.+)$/.exec(options.name);
if (match) {
this.hooks.parser
.for(match[1])
.tap(
options.fn.name || "unnamed compat plugin",
options.fn.bind(this)
);
return true;
}
match = /^create-parser (.+)$/.exec(options.name);
if (match) {
this.hooks.createParser
.for(match[1])
.tap(
options.fn.name || "unnamed compat plugin",
options.fn.bind(this)
);
return true;
}
});
this.resolverFactory = resolverFactory;
this.ruleSet = new RuleSet(options.defaultRules.concat(options.rules));
this.cachePredicate =
typeof options.unsafeCache === "function"
? options.unsafeCache
: Boolean.bind(null, options.unsafeCache);
this.context = context || "";
this.parserCache = Object.create(null);
this.generatorCache = Object.create(null);
this.hooks.factory.tap("NormalModuleFactory", () => (result, callback) => {
let resolver = this.hooks.resolver.call(null);
// Ignored
if (!resolver) return callback();
resolver(result, (err, data) => {
if (err) return callback(err);
// Ignored
if (!data) return callback();
// direct module
if (typeof data.source === "function") return callback(null, data);
this.hooks.afterResolve.callAsync(data, (err, result) => {
if (err) return callback(err);
// Ignored
if (!result) return callback();
let createdModule = this.hooks.createModule.call(result);
if (!createdModule) {
if (!result.request) {
return callback(new Error("Empty dependency (no request)"));
}
createdModule = new NormalModule(result);
}
createdModule = this.hooks.module.call(createdModule, result);
return callback(null, createdModule);
});
});
});
this.hooks.resolver.tap("NormalModuleFactory", () => (data, callback) => {
const contextInfo = data.contextInfo;
const context = data.context;
const request = data.request;
const noPreAutoLoaders = request.startsWith("-!");
const noAutoLoaders = noPreAutoLoaders || request.startsWith("!");
const noPrePostAutoLoaders = request.startsWith("!!");
let elements = request
.replace(/^-?!+/, "")
.replace(/!!+/g, "!")
.split("!");
let resource = elements.pop();
elements = elements.map(identToLoaderRequest);
const loaderResolver = this.getResolver("loader");
const normalResolver = this.getResolver("normal", data.resolveOptions);
asyncLib.parallel(
[
callback =>
this.resolveRequestArray(
contextInfo,
context,
elements,
loaderResolver,
callback
),
callback => {
if (resource === "" || resource[0] === "?") {
return callback(null, {
resource
});
}
normalResolver.resolve(
contextInfo,
context,
resource,
{},
(err, resource, resourceResolveData) => {
if (err) return callback(err);
callback(null, {
resourceResolveData,
resource
});
}
);
}
],
(err, results) => {
if (err) return callback(err);
let loaders = results[0];
const resourceResolveData = results[1].resourceResolveData;
resource = results[1].resource;
// translate option idents
try {
for (const item of loaders) {
if (typeof item.options === "string" && item.options[0] === "?") {
const ident = item.options.substr(1);
item.options = this.ruleSet.findOptionsByIdent(ident);
item.ident = ident;
}
}
} catch (e) {
return callback(e);
}
if (resource === false) {
// ignored
return callback(
null,
new RawModule(
"/* (ignored) */",
`ignored ${context} ${request}`,
`${request} (ignored)`
)
);
}
const userRequest = loaders
.map(loaderToIdent)
.concat([resource])
.join("!");
let resourcePath = resource;
let resourceQuery = "";
const queryIndex = resourcePath.indexOf("?");
if (queryIndex >= 0) {
resourceQuery = resourcePath.substr(queryIndex);
resourcePath = resourcePath.substr(0, queryIndex);
}
const result = this.ruleSet.exec({
resource: resourcePath,
resourceQuery,
issuer: contextInfo.issuer,
compiler: contextInfo.compiler
});
const settings = {};
const useLoadersPost = [];
const useLoaders = [];
const useLoadersPre = [];
for (const r of result) {
if (r.type === "use") {
if (r.enforce === "post" && !noPrePostAutoLoaders)
useLoadersPost.push(r.value);
else if (
r.enforce === "pre" &&
!noPreAutoLoaders &&
!noPrePostAutoLoaders
)
useLoadersPre.push(r.value);
else if (!r.enforce && !noAutoLoaders && !noPrePostAutoLoaders)
useLoaders.push(r.value);
} else if (
typeof r.value === "object" &&
r.value !== null &&
typeof settings[r.type] === "object" &&
settings[r.type] !== null
) {
settings[r.type] = cachedMerge(settings[r.type], r.value);
} else {
settings[r.type] = r.value;
}
}
asyncLib.parallel(
[
this.resolveRequestArray.bind(
this,
contextInfo,
this.context,
useLoadersPost,
loaderResolver
),
this.resolveRequestArray.bind(
this,
contextInfo,
this.context,
useLoaders,
loaderResolver
),
this.resolveRequestArray.bind(
this,
contextInfo,
this.context,
useLoadersPre,
loaderResolver
)
],
(err, results) => {
if (err) return callback(err);
loaders = results[0].concat(loaders, results[1], results[2]);
process.nextTick(() => {
const type = settings.type;
<|fim▁hole|> .map(loaderToIdent)
.concat([resource])
.join("!"),
dependencies: data.dependencies,
userRequest,
rawRequest: request,
loaders,
resource,
resourceResolveData,
settings,
type,
parser: this.getParser(type, settings.parser),
generator: this.getGenerator(type, settings.generator),
resolveOptions
});
});
}
);
}
);
});
}
create(data, callback) {
const dependencies = data.dependencies;
const cacheEntry = dependencies[0].__NormalModuleFactoryCache;
if (cacheEntry) return callback(null, cacheEntry);
const context = data.context || this.context;
const resolveOptions = data.resolveOptions || EMPTY_RESOLVE_OPTIONS;
const request = dependencies[0].request;
const contextInfo = data.contextInfo || {};
this.hooks.beforeResolve.callAsync(
{
contextInfo,
resolveOptions,
context,
request,
dependencies
},
(err, result) => {
if (err) return callback(err);
// Ignored
if (!result) return callback();
const factory = this.hooks.factory.call(null);
// Ignored
if (!factory) return callback();
factory(result, (err, module) => {
if (err) return callback(err);
if (module && this.cachePredicate(module)) {
for (const d of dependencies) {
d.__NormalModuleFactoryCache = module;
}
}
callback(null, module);
});
}
);
}
resolveRequestArray(contextInfo, context, array, resolver, callback) {
if (array.length === 0) return callback(null, []);
asyncLib.map(
array,
(item, callback) => {
resolver.resolve(
contextInfo,
context,
item.loader,
{},
(err, result) => {
if (
err &&
/^[^/]*$/.test(item.loader) &&
!/-loader$/.test(item.loader)
) {
return resolver.resolve(
contextInfo,
context,
item.loader + "-loader",
{},
err2 => {
if (!err2) {
err.message =
err.message +
"\n" +
"BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders.\n" +
` You need to specify '${
item.loader
}-loader' instead of '${item.loader}',\n` +
" see https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed";
}
callback(err);
}
);
}
if (err) return callback(err);
const optionsOnly = item.options
? {
options: item.options
}
: undefined;
return callback(
null,
Object.assign({}, item, identToLoaderRequest(result), optionsOnly)
);
}
);
},
callback
);
}
getParser(type, parserOptions) {
let ident = type;
if (parserOptions) {
if (parserOptions.ident) ident = `${type}|${parserOptions.ident}`;
else ident = JSON.stringify([type, parserOptions]);
}
if (ident in this.parserCache) {
return this.parserCache[ident];
}
return (this.parserCache[ident] = this.createParser(type, parserOptions));
}
createParser(type, parserOptions = {}) {
const parser = this.hooks.createParser.for(type).call(parserOptions);
if (!parser) {
throw new Error(`No parser registered for ${type}`);
}
this.hooks.parser.for(type).call(parser, parserOptions);
return parser;
}
getGenerator(type, generatorOptions) {
let ident = type;
if (generatorOptions) {
if (generatorOptions.ident) ident = `${type}|${generatorOptions.ident}`;
else ident = JSON.stringify([type, generatorOptions]);
}
if (ident in this.generatorCache) {
return this.generatorCache[ident];
}
return (this.generatorCache[ident] = this.createGenerator(
type,
generatorOptions
));
}
createGenerator(type, generatorOptions = {}) {
const generator = this.hooks.createGenerator
.for(type)
.call(generatorOptions);
if (!generator) {
throw new Error(`No generator registered for ${type}`);
}
this.hooks.generator.for(type).call(generator, generatorOptions);
return generator;
}
getResolver(type, resolveOptions) {
return this.resolverFactory.get(
type,
resolveOptions || EMPTY_RESOLVE_OPTIONS
);
}
}
module.exports = NormalModuleFactory;<|fim▁end|>
|
const resolveOptions = settings.resolve;
callback(null, {
context: context,
request: loaders
|
<|file_name|>polyfill.intersection-observer.js<|end_file_name|><|fim▁begin|>import IntersectionObserverPolyfill from './resources/IntersectionObserverPolyfill';
import IntersectionObserverEntryPolyfill from './resources/IntersectionObserverEntryPolyfill';
export {
IntersectionObserverEntryPolyfill,
IntersectionObserverPolyfill,<|fim▁hole|><|fim▁end|>
|
};
|
<|file_name|>ftfilemapper.cc<|end_file_name|><|fim▁begin|>#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <errno.h>
#include <iostream>
#include "ftfilemapper.h"
//#define DEBUG_FILEMAPPER
ftFileMapper::ftFileMapper(uint64_t file_size,uint32_t chunk_size)
: _file_size(file_size),_chunk_size(chunk_size)
{
int nb_chunks = (int)(file_size / (uint64_t)chunk_size) + ( (file_size % chunk_size)==0 ?0:1 ) ;
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) Creating ftFileMapper for file of size " << file_size << ", with " << nb_chunks << " chunks." << std::endl;
#endif
_first_free_chunk = 0 ;
_mapped_chunks.clear() ;
_mapped_chunks.resize(nb_chunks,-1) ;
_data_chunks.clear() ;
_data_chunks.resize(nb_chunks,-1) ;
}
bool ftFileMapper::computeStorageOffset(uint64_t offset,uint64_t& storage_offset) const
{
// Compute the chunk number for this offset
//
uint32_t cid = (uint32_t)(offset / (uint64_t)_chunk_size) ;
// Check that the cid is in the allowed range. That should always be the case.
//
if(cid < _mapped_chunks.size() && _mapped_chunks[cid] >= 0)
{
storage_offset = _mapped_chunks[cid]*_chunk_size + (offset % (uint64_t)_chunk_size) ;
return true ;
}
else
{
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) ftFileMapper::computeStorageOffset(): offset " << offset << " corresponds to chunk number " << cid << " which is not mapped!!" << std::endl;
#endif
return false ;
}
}
bool ftFileMapper::writeData(uint64_t offset,uint32_t size,void *data,FILE *fd) const
{
if (0 != fseeko64(fd, offset, SEEK_SET))
{
std::cerr << "(EE) ftFileMapper::ftFileMapper::writeData() Bad fseek at offset " << offset << ", fd=" << (void*)fd << ", size=" << size << ", errno=" << errno << std::endl;
return false;
}
if (1 != fwrite(data, size, 1, fd))
{
std::cerr << "(EE) ftFileMapper::ftFileCreator::addFileData() Bad fwrite." << std::endl;
std::cerr << "ERRNO: " << errno << std::endl;
return false;
}
fflush(fd) ;
return true ;
}
bool ftFileMapper::storeData(void *data, uint32_t data_size, uint64_t offset,FILE *fd)
{
uint64_t real_offset = 0;
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) ftFileMapper::storeData(): storing data size " << data_size << " for offset "<< offset << std::endl;
#endif
// we compute the real place of the data in the mapped file. Several cases:
//
// 1 - the place corresponds to a mapped place
// => write there.
// 2 - the place does not correspond to a mapped place.
// 2.0 - we allocate a new chunk at the end of the file.
// 2.0.1 - the chunk corresponds to a mapped chunk somewhere before
// => we move it, and use the other chunk as writing position
// 2.0.2 - the chunk does not correspond to a mapped chunk somewhere before
// => we use it
// 2.1 - the place is in the range of existing data
// => we move the existing data at the end of the file, and update the mapping
// 2.2 - the place is outside the range of existing data
// => we allocate a new chunk at the end of the file, and write there.
// 2.2.1 - we look for the first chunk that is not already mapped before.
//
if(!computeStorageOffset(offset,real_offset))
{
uint32_t cid = (uint32_t)(offset / (uint64_t)_chunk_size) ;
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) real offset unknown. chunk id is " << cid << std::endl;
#endif
uint32_t empty_chunk = allocateNewEmptyChunk(fd) ;
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) allocated new empty chunk " << empty_chunk << std::endl;
#endif
if(cid < _first_free_chunk && cid != empty_chunk) // the place is already occupied by some data
{
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) chunk already in use. " << std::endl;
std::cerr << "(DD) swapping with first free chunk: " << empty_chunk << std::endl;
#endif
if(!moveChunk(cid, empty_chunk,fd))
{
std::cerr << "(EE) ftFileMapper::writeData(): cannot move chunk " << empty_chunk << " and " << cid << std::endl ;
return false ;
}
// Get the old chunk id that was mapping to this place
//
int oid = _data_chunks[cid] ;
if(oid < 0)
{
std::cerr << "(EE) ftFileMapper::writeData(): cannot find chunk that was previously mapped to place " << cid << std::endl ;
return false ;
}
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) old chunk now pointing to: " << empty_chunk << std::endl;
std::cerr << "(DD) new chunk now pointing to: " << cid << std::endl;
#endif
_mapped_chunks[cid] = cid ; // this one is in place, since we swapped it
_mapped_chunks[oid] = empty_chunk ;
_data_chunks[cid] = cid ;
_data_chunks[empty_chunk] = oid ;
}
else // allocate a new chunk at end of the file.
{
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) allocating new storage place at first free chunk: " << empty_chunk << std::endl;
#endif
_mapped_chunks[cid] = empty_chunk ;
_data_chunks[empty_chunk] = cid ;
}
real_offset = _mapped_chunks[cid]*_chunk_size + (offset % (uint64_t)_chunk_size) ;
}
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) real offset = " << real_offset << ", data size=" << data_size << std::endl;
std::cerr << "(DD) writing data " << std::endl;
#endif
return writeData(real_offset,data_size,data,fd) ;
}
uint32_t ftFileMapper::allocateNewEmptyChunk(FILE *fd_out)
{
// look into _first_free_chunk. Is it the place of a chunk already mapped before?
//
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) ftFileMapper::getFirstEmptyChunk()" << std::endl;
#endif
if(_mapped_chunks[_first_free_chunk] >= 0 && _mapped_chunks[_first_free_chunk] < (int)_first_free_chunk)
{
uint32_t old_chunk = _mapped_chunks[_first_free_chunk] ;
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) first free chunk " << _first_free_chunk << " is actually mapped to " << old_chunk << ". Moving it." << std::endl;
#endif
moveChunk(_mapped_chunks[_first_free_chunk],_first_free_chunk,fd_out) ;
_mapped_chunks[_first_free_chunk] = _first_free_chunk ;
_data_chunks[_first_free_chunk] = _first_free_chunk ;
_first_free_chunk++ ;
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) Returning " << old_chunk << std::endl;
#endif
return old_chunk ;
}
else
{
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) first free chunk is fine. Returning " << _first_free_chunk << ", and making room" << std::endl;
#endif
// We need to wipe the entire chunk, since it might be moved before beign completely written, which would cause
// a fread error.
//
wipeChunk(_first_free_chunk,fd_out) ;
return _first_free_chunk++ ;
}
}
bool ftFileMapper::wipeChunk(uint32_t cid,FILE *fd) const
{
uint32_t size = (cid == _mapped_chunks.size()-1)?(_file_size - cid*_chunk_size) : _chunk_size ;
void *buf = malloc(size) ;
if(buf == NULL)
{
std::cerr << "(EE) ftFileMapper::wipeChunk(): cannot allocate temporary buf of size " << size << std::endl;
return false ;
}
if(fseeko64(fd, cid*_chunk_size, SEEK_SET)!= 0)
{
std::cerr << "(EE) ftFileMapper::wipeChunk(): cannot fseek file at position " << cid*_chunk_size << std::endl;
free(buf) ;
return false ;
}
if(1 != fwrite(buf, size, 1, fd))
{
std::cerr << "(EE) ftFileMapper::wipeChunk(): cannot write to file" << std::endl;
free(buf) ;
return false ;
}
free(buf) ;
return true ;
}
bool ftFileMapper::moveChunk(uint32_t to_move, uint32_t new_place,FILE *fd_out)
{
// Read the old chunk, write at the new place
assert(to_move != new_place) ;
fflush(fd_out) ;
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) ftFileMapper::moveChunk(): moving chunk " << to_move << " to place " << new_place << std::endl ;
#endif
uint32_t new_place_size = (new_place == _mapped_chunks.size()-1)?(_file_size - (_mapped_chunks.size()-1)*_chunk_size) : _chunk_size ;
uint32_t to_move_size = (new_place == _mapped_chunks.size()-1)?(_file_size - (_mapped_chunks.size()-1)*_chunk_size) : _chunk_size ;
uint32_t size = std::min(new_place_size,to_move_size) ;<|fim▁hole|>
if(buff == NULL)
{
std::cerr << "(EE) ftFileMapper::moveChunk(): cannot open temporary buffer. Out of memory??" << std::endl;
return false ;
}
if(fseeko64(fd_out, to_move*_chunk_size, SEEK_SET) != 0)
{
std::cerr << "(EE) ftFileMapper::moveChunk(): cannot fseek file at position " << to_move*_chunk_size << std::endl;
return false ;
}
size_t rd ;
if(size != (rd = fread(buff, 1, size, fd_out)))
{
std::cerr << "(EE) ftFileMapper::moveChunk(): cannot read from file" << std::endl;
std::cerr << "(EE) errno = " << errno << std::endl;
std::cerr << "(EE) feof = " << feof(fd_out) << std::endl;
std::cerr << "(EE) size = " << size << std::endl;
std::cerr << "(EE) rd = " << rd << std::endl;
return false ;
}
if(fseeko64(fd_out, new_place*_chunk_size, SEEK_SET)!= 0)
{
std::cerr << "(EE) ftFileMapper::moveChunk(): cannot fseek file at position " << new_place*_chunk_size << std::endl;
return false ;
}
if(1 != fwrite(buff, size, 1, fd_out))
{
std::cerr << "(EE) ftFileMapper::moveChunk(): cannot write to file" << std::endl;
return false ;
}
free(buff) ;
return true ;
}
void ftFileMapper::print() const
{
std::cerr << "ftFileMapper:: [ " ;
for(uint32_t i=0;i<_mapped_chunks.size();++i)
{
std::cerr << _mapped_chunks[i] << " " ;
}
std::cerr << "] - ffc = " << _first_free_chunk << " - [ ";
for(uint32_t i=0;i<_data_chunks.size();++i)
std::cerr << _data_chunks[i] << " " ;
std::cerr << " ] " << std::endl;
}<|fim▁end|>
|
void *buff = malloc(size) ;
|
<|file_name|>bsla_scanf.cpp<|end_file_name|><|fim▁begin|>// bsla_scanf.cpp -*-C++-*-
#include <bsla_scanf.h>
#include <bsls_ident.h>
BSLS_IDENT("$Id$ $CSID$")
// ----------------------------------------------------------------------------
// Copyright 2019 Bloomberg Finance L.P.
//
// 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<|fim▁hole|>// 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.
// ----------------------------- END-OF-FILE ----------------------------------<|fim▁end|>
|
//
|
<|file_name|>constants.go<|end_file_name|><|fim▁begin|>package v1
const (
MODULE_NAME = "node/croncache/v1"<|fim▁hole|><|fim▁end|>
|
)
|
<|file_name|>client.go<|end_file_name|><|fim▁begin|>package autorest
import (<|fim▁hole|>)
const (
// The default delay between polling requests (only used if the http.Request lacks a well-formed
// Retry-After header).
DefaultPollingDelay = 60 * time.Second
// The default total polling duration.
DefaultPollingDuration = 10 * time.Minute
)
// PollingMode sets how, if at all, clients composed with Client will poll.
type PollingMode string
const (
// Poll until reaching a maximum number of attempts
PollUntilAttempts PollingMode = "poll-until-attempts"
// Poll until a specified time.Duration has passed
PollUntilDuration PollingMode = "poll-until-duration"
// Do not poll at all
DoNotPoll PollingMode = "not-at-all"
)
// RequestInspector defines a single method that returns a PrepareDecorator used to inspect the
// http.Request prior to sending.
type RequestInspector interface {
WithInspection() PrepareDecorator
}
// ResponseInspector defines a single method that returns a ResponseDecorator used to inspect the
// http.Response prior to responding.
type ResponseInspector interface {
ByInspecting() RespondDecorator
}
var (
// Generated clients should compose using the DefaultClient instead of allocating a new Client
// instance. Users can then established widely used Client defaults by replacing or modifying the
// DefaultClient before instantiating a generated client.
DefaultClient = &Client{PollingMode: PollUntilDuration, PollingDuration: DefaultPollingDuration}
)
// Client is the base for autorest generated clients. It provides default, "do nothing"
// implementations of an Authorizer, RequestInspector, and ResponseInspector. It also returns the
// standard, undecorated http.Client as a default Sender. Lastly, it supports basic request polling,
// limited to a maximum number of attempts or a specified duration.
//
// Most customization of generated clients is best achieved by supplying a custom Authorizer, custom
// RequestInspector, and / or custom ResponseInspector. Users may log requests, implement circuit
// breakers (see https://msdn.microsoft.com/en-us/library/dn589784.aspx) or otherwise influence
// sending the request by providing a decorated Sender.
type Client struct {
Authorizer Authorizer
Sender Sender
RequestInspector RequestInspector
ResponseInspector ResponseInspector
PollingMode PollingMode
PollingAttempts int
PollingDuration time.Duration
}
// ShouldPoll returns true if the client allows polling and the passed http.Response requires it,
// otherwise it returns false.
func (c *Client) ShouldPoll(resp *http.Response, codes ...int) bool {
return !c.DoNotPoll() && ResponseRequiresPolling(resp, codes...)
}
// PollAsNeeded is a convenience method that will poll if the passed http.Response requires it.
func (c *Client) PollAsNeeded(resp *http.Response, codes ...int) (*http.Response, error) {
if !ResponseRequiresPolling(resp, codes...) {
return resp, nil
}
req, err := CreatePollingRequest(resp, c)
if err != nil {
return resp, fmt.Errorf("autorest: Unable to create polling request for response to %s (%v)",
resp.Request.URL, err)
}
delay := GetRetryDelay(resp, DefaultPollingDelay)
if c.PollForAttempts() {
return PollForAttempts(c, req, delay, c.PollingAttempts, codes...)
} else if c.PollForDuration() {
return PollForDuration(c, req, delay, c.PollingDuration, codes...)
} else {
return resp, fmt.Errorf("autorest: Polling for %s is required, but polling is disabled", req.URL)
}
}
// DoNotPoll returns true if the client should not poll, false otherwise.
func (c Client) DoNotPoll() bool {
return len(c.PollingMode) == 0 || c.PollingMode == DoNotPoll
}
// PollForAttempts returns true if the PollingMode is set to ForAttempts, false otherwise.
func (c Client) PollForAttempts() bool {
return c.PollingMode == PollUntilAttempts
}
// PollForDuration return true if the PollingMode is set to ForDuration, false otherwise.
func (c Client) PollForDuration() bool {
return c.PollingMode == PollUntilDuration
}
// Do is a convenience method that invokes the Sender of the Client. If no Sender is set, it will
// be set to the default http.Client.
func (c *Client) Do(r *http.Request) (*http.Response, error) {
if c.Sender == nil {
c.Sender = &http.Client{}
}
return c.Sender.Do(r)
}
// WithAuthorization is a convenience method that returns the WithAuthorization PrepareDecorator
// from the current Authorizer. If not Authorizer is set, it sets it to the NullAuthorizer.
func (c *Client) WithAuthorization() PrepareDecorator {
if c.Authorizer == nil {
c.Authorizer = NullAuthorizer{}
}
return c.Authorizer.WithAuthorization()
}
// WithInspection is a convenience method that passes the request to the supplied RequestInspector,
// if present, or returns the WithNothing PrepareDecorator otherwise.
func (c *Client) WithInspection() PrepareDecorator {
if c.RequestInspector == nil {
return WithNothing()
} else {
return c.RequestInspector.WithInspection()
}
}
// ByInspecting is a convenience method that passes the response to the supplied ResponseInspector,
// if present, or returns the ByIgnoring RespondDecorator otherwise.
func (c *Client) ByInspecting() RespondDecorator {
if c.ResponseInspector == nil {
return ByIgnoring()
} else {
return c.ResponseInspector.ByInspecting()
}
}<|fim▁end|>
|
"fmt"
"net/http"
"time"
|
<|file_name|>createuser.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
Create a user.
"""
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Create a user."
def add_arguments(self, parser):
parser.add_argument("username", help="account username")
parser.add_argument("password", help="account password")
parser.add_argument("email", help="account email address")
def handle(self, **options):
username = options["username"]
password = options["password"]
email = options["email"]
if User.objects.filter(username=username).exists():
self.stdout.write("User {} already exists.".format(username))
return
user = User.objects.create(username=username, email=email)
user.set_password(password)<|fim▁hole|><|fim▁end|>
|
user.save()
self.stdout.write("User {} created.".format(username))
|
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models<|fim▁hole|># Create your models here.
class TempMail(models.Model):
mailfrom = models.EmailField()
mailsubj = models.CharField(max_length=20)
mailrcvd = models.DateTimeField()
mailhdrs = models.CharField()
class SavedMail(models.Model):
mailrcvd = models.DateTimeField()
mailhdrs = models.CharField()
organization = models.ForeignKey('Organization')
class Organization(models.Model):
emailsuffix = models.CharField(max_length=255)
class Follower(models.Model):
email = models.EmailField()<|fim▁end|>
|
# from django.contrib.gis.geoip import GeoIP
#
# g = GeoIP()
|
<|file_name|>string.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! An owned, growable string that enforces that its contents are valid UTF-8.
#![stable(feature = "rust1", since = "1.0.0")]
#[cfg(stage0)]
use core::prelude::v1::*;
use core::fmt;
use core::hash;
use core::iter::FromIterator;
use core::mem;
use core::ops::{self, Deref, Add, Index};
use core::ptr;
use core::slice;
use core::str::pattern::Pattern;
use rustc_unicode::str as unicode_str;
use rustc_unicode::str::Utf16Item;
use borrow::{Cow, IntoCow};
use range::RangeArgument;
use str::{self, FromStr, Utf8Error, Chars};
use vec::Vec;
use boxed::Box;
/// A growable string stored as a UTF-8 encoded buffer.
#[derive(Clone, PartialOrd, Eq, Ord)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct String {
vec: Vec<u8>,
}
/// A possible error value from the `String::from_utf8` function.
#[stable(feature = "rust1", since = "1.0.0")]
#[derive(Debug)]
pub struct FromUtf8Error {
bytes: Vec<u8>,
error: Utf8Error,
}
/// A possible error value from the `String::from_utf16` function.
#[stable(feature = "rust1", since = "1.0.0")]
#[derive(Debug)]
pub struct FromUtf16Error(());
impl String {
/// Creates a new string buffer initialized with the empty string.
///
/// # Examples
///
/// ```
/// let mut s = String::new();
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new() -> String {
String {
vec: Vec::new(),
}
}
/// Creates a new string buffer with the given capacity.
/// The string will be able to hold exactly `capacity` bytes without
/// reallocating. If `capacity` is 0, the string will not allocate.
///
/// # Examples
///
/// ```
/// let mut s = String::with_capacity(10);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn with_capacity(capacity: usize) -> String {
String {
vec: Vec::with_capacity(capacity),
}
}
/// Creates a new string buffer from the given string.
///
/// # Examples
///
/// ```
/// #![feature(collections)]
///
/// let s = String::from("hello");
/// assert_eq!(&s[..], "hello");
/// ```
#[inline]
#[unstable(feature = "collections", reason = "use `String::from` instead")]
#[deprecated(since = "1.2.0", reason = "use `String::from` instead")]
#[cfg(not(test))]
pub fn from_str(string: &str) -> String {
String { vec: <[_]>::to_vec(string.as_bytes()) }
}
// HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
// required for this method definition, is not available. Since we don't
// require this method for testing purposes, I'll just stub it
// NB see the slice::hack module in slice.rs for more information
#[inline]
#[cfg(test)]
pub fn from_str(_: &str) -> String {
panic!("not available with cfg(test)");
}
/// Returns the vector as a string buffer, if possible, taking care not to
/// copy it.
///
/// # Failure
///
/// If the given vector is not valid UTF-8, then the original vector and the
/// corresponding error is returned.
///
/// # Examples
///
/// ```
/// let hello_vec = vec![104, 101, 108, 108, 111];
/// let s = String::from_utf8(hello_vec).unwrap();
/// assert_eq!(s, "hello");
///
/// let invalid_vec = vec![240, 144, 128];
/// let s = String::from_utf8(invalid_vec).err().unwrap();
/// let err = s.utf8_error();
/// assert_eq!(s.into_bytes(), [240, 144, 128]);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
match str::from_utf8(&vec) {
Ok(..) => Ok(String { vec: vec }),
Err(e) => Err(FromUtf8Error { bytes: vec, error: e })
}
}
/// Converts a vector of bytes to a new UTF-8 string.
/// Any invalid UTF-8 sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
///
/// # Examples
///
/// ```
/// let input = b"Hello \xF0\x90\x80World";
/// let output = String::from_utf8_lossy(input);
/// assert_eq!(output, "Hello \u{FFFD}World");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> {
let mut i;
match str::from_utf8(v) {
Ok(s) => return Cow::Borrowed(s),
Err(e) => i = e.valid_up_to(),
}
const TAG_CONT_U8: u8 = 128;
const REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
let total = v.len();
fn unsafe_get(xs: &[u8], i: usize) -> u8 {
unsafe { *xs.get_unchecked(i) }
}
fn safe_get(xs: &[u8], i: usize, total: usize) -> u8 {
if i >= total {
0
} else {
unsafe_get(xs, i)
}
}
let mut res = String::with_capacity(total);
if i > 0 {
unsafe {
res.as_mut_vec().push_all(&v[..i])
};
}
// subseqidx is the index of the first byte of the subsequence we're
// looking at. It's used to copy a bunch of contiguous good codepoints
// at once instead of copying them one by one.
let mut subseqidx = i;
while i < total {
let i_ = i;
let byte = unsafe_get(v, i);
i += 1;
macro_rules! error { () => ({
unsafe {
if subseqidx != i_ {
res.as_mut_vec().push_all(&v[subseqidx..i_]);
}
subseqidx = i;
res.as_mut_vec().push_all(REPLACEMENT);
}
})}
if byte < 128 {
// subseqidx handles this
} else {
let w = unicode_str::utf8_char_width(byte);
match w {
2 => {
if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
error!();
continue;
}
i += 1;
}
3 => {
match (byte, safe_get(v, i, total)) {
(0xE0 , 0xA0 ... 0xBF) => (),
(0xE1 ... 0xEC, 0x80 ... 0xBF) => (),
(0xED , 0x80 ... 0x9F) => (),
(0xEE ... 0xEF, 0x80 ... 0xBF) => (),
_ => {
error!();
continue;
}
}
i += 1;
if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
error!();
continue;
}
i += 1;
}
4 => {
match (byte, safe_get(v, i, total)) {
(0xF0 , 0x90 ... 0xBF) => (),
(0xF1 ... 0xF3, 0x80 ... 0xBF) => (),
(0xF4 , 0x80 ... 0x8F) => (),
_ => {
error!();
continue;
}
}
i += 1;
if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
error!();
continue;
}
i += 1;
if safe_get(v, i, total) & 192 != TAG_CONT_U8 {
error!();
continue;
}
i += 1;
}
_ => {
error!();
continue;
}
}
}
}
if subseqidx < total {
unsafe {
res.as_mut_vec().push_all(&v[subseqidx..total])
};
}
Cow::Owned(res)
}
/// Decode a UTF-16 encoded vector `v` into a `String`, returning `None`
/// if `v` contains any invalid data.
///
/// # Examples
///
/// ```
/// // 𝄞music
/// let mut v = &mut [0xD834, 0xDD1E, 0x006d, 0x0075,
/// 0x0073, 0x0069, 0x0063];
/// assert_eq!(String::from_utf16(v).unwrap(),
/// "𝄞music".to_string());
///
/// // 𝄞mu<invalid>ic
/// v[4] = 0xD800;
/// assert!(String::from_utf16(v).is_err());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
let mut s = String::with_capacity(v.len());
for c in unicode_str::utf16_items(v) {
match c {
Utf16Item::ScalarValue(c) => s.push(c),
Utf16Item::LoneSurrogate(_) => return Err(FromUtf16Error(())),
}
}
Ok(s)
}
/// Decode a UTF-16 encoded vector `v` into a string, replacing
/// invalid data with the replacement character (U+FFFD).
///
/// # Examples
///
/// ```
/// // 𝄞mus<invalid>ic<invalid>
/// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
/// 0x0073, 0xDD1E, 0x0069, 0x0063,
/// 0xD834];
///
/// assert_eq!(String::from_utf16_lossy(v),
/// "𝄞mus\u{FFFD}ic\u{FFFD}".to_string());
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_utf16_lossy(v: &[u16]) -> String {
unicode_str::utf16_items(v).map(|c| c.to_char_lossy()).collect()
}
/// Creates a new `String` from a length, capacity, and pointer.
///
/// # Unsafety
///
/// This is _very_ unsafe because:
///
/// * We call `Vec::from_raw_parts` to get a `Vec<u8>`. Therefore, this
/// function inherits all of its unsafety, see [its
/// documentation](../vec/struct.Vec.html#method.from_raw_parts)
/// for the invariants it expects, they also apply to this function.
/// * We assume that the `Vec` contains valid UTF-8.
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
String {
vec: Vec::from_raw_parts(buf, length, capacity),
}
}
/// Converts a vector of bytes to a new `String` without checking if
/// it contains valid UTF-8. This is unsafe because it assumes that
/// the UTF-8-ness of the vector has already been validated.
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
String { vec: bytes }
}
/// Returns the underlying byte buffer, encoded as UTF-8.
///
/// # Examples
///
/// ```
/// let s = String::from("hello");
/// let bytes = s.into_bytes();
/// assert_eq!(bytes, [104, 101, 108, 108, 111]);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn into_bytes(self) -> Vec<u8> {
self.vec
}
/// Extracts a string slice containing the entire string.
#[inline]
#[unstable(feature = "convert",
reason = "waiting on RFC revision")]
pub fn as_str(&self) -> &str {
self
}
/// Pushes the given string onto this string buffer.
///
/// # Examples
///
/// ```
/// let mut s = String::from("foo");
/// s.push_str("bar");
/// assert_eq!(s, "foobar");
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn push_str(&mut self, string: &str) {
self.vec.push_all(string.as_bytes())
}
/// Returns the number of bytes that this string buffer can hold without
/// reallocating.
///
/// # Examples
///
/// ```
/// let s = String::with_capacity(10);
/// assert!(s.capacity() >= 10);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn capacity(&self) -> usize {
self.vec.capacity()
}
/// Reserves capacity for at least `additional` more bytes to be inserted
/// in the given `String`. The collection may reserve more space to avoid
/// frequent reallocations.
///
/// # Panics
///
/// Panics if the new capacity overflows `usize`.
///
/// # Examples
///
/// ```
/// let mut s = String::new();
/// s.reserve(10);
/// assert!(s.capacity() >= 10);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn reserve(&mut self, additional: usize) {
self.vec.reserve(additional)
}
/// Reserves the minimum capacity for exactly `additional` more bytes to be
/// inserted in the given `String`. Does nothing if the capacity is already
/// sufficient.
///
/// Note that the allocator may give the collection more space than it
/// requests. Therefore capacity can not be relied upon to be precisely
/// minimal. Prefer `reserve` if future insertions are expected.
///
/// # Panics
///
/// Panics if the new capacity overflows `usize`.
///
/// # Examples
///
/// ```
/// let mut s = String::new();
/// s.reserve_exact(10);
/// assert!(s.capacity() >= 10);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn reserve_exact(&mut self, additional: usize) {
self.vec.reserve_exact(additional)
}
/// Shrinks the capacity of this string buffer to match its length.
///
/// # Examples
///
/// ```
/// let mut s = String::from("foo");
/// s.reserve(100);
/// assert!(s.capacity() >= 100);
/// s.shrink_to_fit();
/// assert_eq!(s.capacity(), 3);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn shrink_to_fit(&mut self) {
self.vec.shrink_to_fit()
}
/// Adds the given character to the end of the string.
///
/// # Examples
///
/// ```
/// let mut s = String::from("abc");
/// s.push('1');
/// s.push('2');
/// s.push('3');
/// assert_eq!(s, "abc123");
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn push(&mut self, ch: char) {
match ch.len_utf8() {
1 => self.vec.push(ch as u8),
ch_len => {
let cur_len = self.len();
// This may use up to 4 bytes.
self.vec.reserve(ch_len);
unsafe {
// Attempt to not use an intermediate buffer by just pushing bytes
// directly onto this string.
let slice = slice::from_raw_parts_mut (
self.vec.as_mut_ptr().offset(cur_len as isize),
ch_len
);
let used = ch.encode_utf8(slice).unwrap_or(0);
self.vec.set_len(cur_len + used);
}
}
}
}
/// Works with the underlying buffer as a byte slice.
///
/// # Examples
///
/// ```
/// let s = String::from("hello");
/// assert_eq!(s.as_bytes(), [104, 101, 108, 108, 111]);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn as_bytes(&self) -> &[u8] {
&self.vec
}
/// Shortens a string to the specified length.
///
/// # Panics
///
/// Panics if `new_len` > current length,
/// or if `new_len` is not a character boundary.
///
/// # Examples
///
/// ```
/// let mut s = String::from("hello");
/// s.truncate(2);
/// assert_eq!(s, "he");
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn truncate(&mut self, new_len: usize) {
assert!(self.is_char_boundary(new_len));
self.vec.truncate(new_len)
}
/// Removes the last character from the string buffer and returns it.
/// Returns `None` if this string buffer is empty.
///
/// # Examples
///
/// ```
/// let mut s = String::from("foo");
/// assert_eq!(s.pop(), Some('o'));
/// assert_eq!(s.pop(), Some('o'));
/// assert_eq!(s.pop(), Some('f'));
/// assert_eq!(s.pop(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn pop(&mut self) -> Option<char> {
let len = self.len();
if len == 0 {
return None
}
let ch = self.char_at_reverse(len);
unsafe {
self.vec.set_len(len - ch.len_utf8());
}
Some(ch)
}
/// Removes the character from the string buffer at byte position `idx` and
/// returns it.
///
/// # Warning
///
/// This is an O(n) operation as it requires copying every element in the
/// buffer.
///
/// # Panics
///
/// If `idx` does not lie on a character boundary, or if it is out of
/// bounds, then this function will panic.
///
/// # Examples
///
/// ```
/// let mut s = String::from("foo");
/// assert_eq!(s.remove(0), 'f');
/// assert_eq!(s.remove(1), 'o');
/// assert_eq!(s.remove(0), 'o');
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn remove(&mut self, idx: usize) -> char {
let len = self.len();
assert!(idx <= len);
let ch = self.char_at(idx);
let next = idx + ch.len_utf8();
unsafe {
ptr::copy(self.vec.as_ptr().offset(next as isize),
self.vec.as_mut_ptr().offset(idx as isize),
len - next);
self.vec.set_len(len - (next - idx));
}
ch
}
/// Inserts a character into the string buffer at byte position `idx`.
///
/// # Warning
///
/// This is an O(n) operation as it requires copying every element in the
/// buffer.
///
/// # Panics
///
/// If `idx` does not lie on a character boundary or is out of bounds, then
/// this function will panic.
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn insert(&mut self, idx: usize, ch: char) {
let len = self.len();
assert!(idx <= len);
assert!(self.is_char_boundary(idx));
self.vec.reserve(4);
let mut bits = [0; 4];
let amt = ch.encode_utf8(&mut bits).unwrap();
unsafe {
ptr::copy(self.vec.as_ptr().offset(idx as isize),
self.vec.as_mut_ptr().offset((idx + amt) as isize),
len - idx);
ptr::copy(bits.as_ptr(),
self.vec.as_mut_ptr().offset(idx as isize),
amt);
self.vec.set_len(len + amt);
}
}
/// Views the string buffer as a mutable sequence of bytes.
///
/// This is unsafe because it does not check
/// to ensure that the resulting string will be valid UTF-8.
///
/// # Examples
///
/// ```
/// let mut s = String::from("hello");
/// unsafe {
/// let vec = s.as_mut_vec();
/// assert!(vec == &[104, 101, 108, 108, 111]);
/// vec.reverse();
/// }
/// assert_eq!(s, "olleh");
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
&mut self.vec
}
/// Returns the number of bytes in this string.
///
/// # Examples
///
/// ```
/// let a = "foo".to_string();
/// assert_eq!(a.len(), 3);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn len(&self) -> usize { self.vec.len() }
/// Returns true if the string contains no bytes
///
/// # Examples
///
/// ```
/// let mut v = String::new();
/// assert!(v.is_empty());
/// v.push('a');
/// assert!(!v.is_empty());
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn is_empty(&self) -> bool { self.len() == 0 }
/// Truncates the string, returning it to 0 length.
///
/// # Examples
///
/// ```
/// let mut s = "foo".to_string();
/// s.clear();
/// assert!(s.is_empty());
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn clear(&mut self) {
self.vec.clear()
}
/// Create a draining iterator that removes the specified range in the string
/// and yields the removed chars from start to end. The element range is
/// removed even if the iterator is not consumed until the end.
///
/// # Panics
///
/// Panics if the starting point or end point are not on character boundaries,
/// or if they are out of bounds.
///
/// # Examples
///
/// ```
/// #![feature(drain)]
///
/// let mut s = String::from("α is alpha, β is beta");
/// let beta_offset = s.find('β').unwrap_or(s.len());
///
/// // Remove the range up until the β from the string
/// let t: String = s.drain(..beta_offset).collect();
/// assert_eq!(t, "α is alpha, ");
/// assert_eq!(s, "β is beta");
///
/// // A full range clears the string
/// s.drain(..);
/// assert_eq!(s, "");
/// ```
#[unstable(feature = "drain",
reason = "recently added, matches RFC")]
pub fn drain<R>(&mut self, range: R) -> Drain where R: RangeArgument<usize> {
// Memory safety
//
// The String version of Drain does not have the memory safety issues
// of the vector version. The data is just plain bytes.
// Because the range removal happens in Drop, if the Drain iterator is leaked,
// the removal will not happen.
let len = self.len();
let start = *range.start().unwrap_or(&0);
let end = *range.end().unwrap_or(&len);
// Take out two simultaneous borrows. The &mut String won't be accessed
// until iteration is over, in Drop.
let self_ptr = self as *mut _;
// slicing does the appropriate bounds checks
let chars_iter = self[start..end].chars();
Drain {
start: start,
end: end,
iter: chars_iter,
string: self_ptr,
}
}
/// Converts the string into `Box<str>`.
///
/// Note that this will drop any excess capacity.
#[unstable(feature = "box_str",
reason = "recently added, matches RFC")]
pub fn into_boxed_slice(self) -> Box<str> {
let slice = self.vec.into_boxed_slice();
unsafe { mem::transmute::<Box<[u8]>, Box<str>>(slice) }
}
}
impl FromUtf8Error {
/// Consumes this error, returning the bytes that were attempted to make a
/// `String` with.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn into_bytes(self) -> Vec<u8> { self.bytes }
/// Access the underlying UTF8-error that was the cause of this error.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn utf8_error(&self) -> Utf8Error { self.error }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Display for FromUtf8Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.error, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Display for FromUtf16Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl FromIterator<char> for String {
fn from_iter<I: IntoIterator<Item=char>>(iter: I) -> String {
let mut buf = String::new();
buf.extend(iter);
buf
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> FromIterator<&'a str> for String {
fn from_iter<I: IntoIterator<Item=&'a str>>(iter: I) -> String {
let mut buf = String::new();
buf.extend(iter);
buf
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Extend<char> for String {
fn extend<I: IntoIterator<Item=char>>(&mut self, iterable: I) {
let iterator = iterable.into_iter();
let (lower_bound, _) = iterator.size_hint();
self.reserve(lower_bound);
for ch in iterator {
self.push(ch)
}
}
}
#[stable(feature = "extend_ref", since = "1.2.0")]
impl<'a> Extend<&'a char> for String {
fn extend<I: IntoIterator<Item=&'a char>>(&mut self, iter: I) {
self.extend(iter.into_iter().cloned());
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> Extend<&'a str> for String {
fn extend<I: IntoIterator<Item=&'a str>>(&mut self, iterable: I) {
let iterator = iterable.into_iter();
// A guess that at least one byte per iterator element will be needed.
let (lower_bound, _) = iterator.size_hint();
self.reserve(lower_bound);
for s in iterator {
self.push_str(s)
}
}
}
/// A convenience impl that delegates to the impl for `&str`
impl<'a, 'b> Pattern<'a> for &'b String {
type Searcher = <&'b str as Pattern<'a>>::Searcher;
fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
self[..].into_searcher(haystack)
}
#[inline]
fn is_contained_in(self, haystack: &'a str) -> bool {
self[..].is_contained_in(haystack)
}
#[inline]
fn is_prefix_of(self, haystack: &'a str) -> bool {
self[..].is_prefix_of(haystack)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq for String {
#[inline]
fn eq(&self, other: &String) -> bool { PartialEq::eq(&self[..], &other[..]) }
#[inline]
fn ne(&self, other: &String) -> bool { PartialEq::ne(&self[..], &other[..]) }
}
macro_rules! impl_eq {
($lhs:ty, $rhs: ty) => {
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> PartialEq<$rhs> for $lhs {
#[inline]
fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
#[inline]
fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> PartialEq<$lhs> for $rhs {
#[inline]
fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&self[..], &other[..]) }
#[inline]
fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&self[..], &other[..]) }
}
}
}
impl_eq! { String, str }
impl_eq! { String, &'a str }
impl_eq! { Cow<'a, str>, str }
impl_eq! { Cow<'a, str>, String }
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, 'b> PartialEq<&'b str> for Cow<'a, str> {
#[inline]<|fim▁hole|> fn ne(&self, other: &&'b str) -> bool { PartialEq::ne(&self[..], &other[..]) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, 'b> PartialEq<Cow<'a, str>> for &'b str {
#[inline]
fn eq(&self, other: &Cow<'a, str>) -> bool { PartialEq::eq(&self[..], &other[..]) }
#[inline]
fn ne(&self, other: &Cow<'a, str>) -> bool { PartialEq::ne(&self[..], &other[..]) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Default for String {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> String {
String::new()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Display for String {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for String {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl hash::Hash for String {
#[inline]
fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
(**self).hash(hasher)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> Add<&'a str> for String {
type Output = String;
#[inline]
fn add(mut self, other: &str) -> String {
self.push_str(other);
self
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Index<ops::Range<usize>> for String {
type Output = str;
#[inline]
fn index(&self, index: ops::Range<usize>) -> &str {
&self[..][index]
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Index<ops::RangeTo<usize>> for String {
type Output = str;
#[inline]
fn index(&self, index: ops::RangeTo<usize>) -> &str {
&self[..][index]
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Index<ops::RangeFrom<usize>> for String {
type Output = str;
#[inline]
fn index(&self, index: ops::RangeFrom<usize>) -> &str {
&self[..][index]
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Index<ops::RangeFull> for String {
type Output = str;
#[inline]
fn index(&self, _index: ops::RangeFull) -> &str {
unsafe { str::from_utf8_unchecked(&self.vec) }
}
}
#[stable(feature = "derefmut_for_string", since = "1.2.0")]
impl ops::IndexMut<ops::Range<usize>> for String {
#[inline]
fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
&mut self[..][index]
}
}
#[stable(feature = "derefmut_for_string", since = "1.2.0")]
impl ops::IndexMut<ops::RangeTo<usize>> for String {
#[inline]
fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
&mut self[..][index]
}
}
#[stable(feature = "derefmut_for_string", since = "1.2.0")]
impl ops::IndexMut<ops::RangeFrom<usize>> for String {
#[inline]
fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
&mut self[..][index]
}
}
#[stable(feature = "derefmut_for_string", since = "1.2.0")]
impl ops::IndexMut<ops::RangeFull> for String {
#[inline]
fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
unsafe { mem::transmute(&mut *self.vec) }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Deref for String {
type Target = str;
#[inline]
fn deref(&self) -> &str {
unsafe { str::from_utf8_unchecked(&self.vec) }
}
}
#[stable(feature = "derefmut_for_string", since = "1.2.0")]
impl ops::DerefMut for String {
#[inline]
fn deref_mut(&mut self) -> &mut str {
unsafe { mem::transmute(&mut *self.vec) }
}
}
/// Error returned from `String::from`
#[unstable(feature = "str_parse_error", reason = "may want to be replaced with \
Void if it ever exists")]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct ParseError(());
#[stable(feature = "rust1", since = "1.0.0")]
impl FromStr for String {
type Err = ParseError;
#[inline]
fn from_str(s: &str) -> Result<String, ParseError> {
Ok(String::from(s))
}
}
/// A generic trait for converting a value to a string
#[stable(feature = "rust1", since = "1.0.0")]
pub trait ToString {
/// Converts the value of `self` to an owned string
#[stable(feature = "rust1", since = "1.0.0")]
fn to_string(&self) -> String;
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Display + ?Sized> ToString for T {
#[inline]
fn to_string(&self) -> String {
use core::fmt::Write;
let mut buf = String::new();
let _ = buf.write_fmt(format_args!("{}", self));
buf.shrink_to_fit();
buf
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRef<str> for String {
#[inline]
fn as_ref(&self) -> &str {
self
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRef<[u8]> for String {
#[inline]
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> From<&'a str> for String {
#[cfg(not(test))]
#[inline]
fn from(s: &'a str) -> String {
String { vec: <[_]>::to_vec(s.as_bytes()) }
}
// HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
// required for this method definition, is not available. Since we don't
// require this method for testing purposes, I'll just stub it
// NB see the slice::hack module in slice.rs for more information
#[inline]
#[cfg(test)]
fn from(_: &str) -> String {
panic!("not available with cfg(test)");
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> From<&'a str> for Cow<'a, str> {
#[inline]
fn from(s: &'a str) -> Cow<'a, str> {
Cow::Borrowed(s)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> From<String> for Cow<'a, str> {
#[inline]
fn from(s: String) -> Cow<'a, str> {
Cow::Owned(s)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Into<Vec<u8>> for String {
fn into(self) -> Vec<u8> {
self.into_bytes()
}
}
#[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`")]
impl IntoCow<'static, str> for String {
#[inline]
fn into_cow(self) -> Cow<'static, str> {
Cow::Owned(self)
}
}
#[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`")]
impl<'a> IntoCow<'a, str> for &'a str {
#[inline]
fn into_cow(self) -> Cow<'a, str> {
Cow::Borrowed(self)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Write for String {
#[inline]
fn write_str(&mut self, s: &str) -> fmt::Result {
self.push_str(s);
Ok(())
}
#[inline]
fn write_char(&mut self, c: char) -> fmt::Result {
self.push(c);
Ok(())
}
}
/// A draining iterator for `String`.
#[unstable(feature = "drain", reason = "recently added")]
pub struct Drain<'a> {
/// Will be used as &'a mut String in the destructor
string: *mut String,
/// Start of part to remove
start: usize,
/// End of part to remove
end: usize,
/// Current remaining range to remove
iter: Chars<'a>,
}
unsafe impl<'a> Sync for Drain<'a> {}
unsafe impl<'a> Send for Drain<'a> {}
#[unstable(feature = "drain", reason = "recently added")]
impl<'a> Drop for Drain<'a> {
fn drop(&mut self) {
unsafe {
// Use Vec::drain. "Reaffirm" the bounds checks to avoid
// panic code being inserted again.
let self_vec = (*self.string).as_mut_vec();
if self.start <= self.end && self.end <= self_vec.len() {
self_vec.drain(self.start..self.end);
}
}
}
}
#[unstable(feature = "drain", reason = "recently added")]
impl<'a> Iterator for Drain<'a> {
type Item = char;
#[inline]
fn next(&mut self) -> Option<char> {
self.iter.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
#[unstable(feature = "drain", reason = "recently added")]
impl<'a> DoubleEndedIterator for Drain<'a> {
#[inline]
fn next_back(&mut self) -> Option<char> {
self.iter.next_back()
}
}<|fim▁end|>
|
fn eq(&self, other: &&'b str) -> bool { PartialEq::eq(&self[..], &other[..]) }
#[inline]
|
<|file_name|>test_rjust.py<|end_file_name|><|fim▁begin|>from django.template.defaultfilters import rjust
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe
from ..utils import setup
class RjustTests(SimpleTestCase):
@setup({'rjust01': '{% autoescape off %}.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.{% endautoescape %}'})
def test_rjust01(self):
output = self.engine.render_to_string('rjust01', {"a": "a&b", "b": mark_safe("a&b")})
self.assertEqual(output, ". a&b. . a&b.")
@setup({'rjust02': '.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.'})
def test_rjust02(self):
output = self.engine.render_to_string('rjust02', {"a": "a&b", "b": mark_safe("a&b")})
self.assertEqual(output, ". a&b. . a&b.")
<|fim▁hole|>class FunctionTests(SimpleTestCase):
def test_rjust(self):
self.assertEqual(rjust('test', 10), ' test')
def test_less_than_string_length(self):
self.assertEqual(rjust('test', 3), 'test')
def test_non_string_input(self):
self.assertEqual(rjust(123, 4), ' 123')<|fim▁end|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.