code stringlengths 2 1.05M |
|---|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M20 18l1.99-2L22 3H2v13l2 2H0v2h24v-2h-4zM4 5h16v11H4V5zm8 14c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z" />
, 'LaptopMacSharp');
|
/*!
* .______ _______ ___ .______ ______ ___ .__________.
* ( _ ) ( ____) / \ ( _ ) ( ) / \ ( )
* | |_) ) | |__ / ^ \ | |_) ) | ,----' / ^ \ `---| |---`
* | _ < | __) / /_\ \ | ) | | / /_\ \ | |
* | |_) ) | |____ / _____ \ | |) ----.| `----./ _____ \ | |
* (______) (_______/__/ \__\ ( _| `.____) (______)__/ \__\ |__|
*
* Bearcat-dao MysqlConnectionManager
* Copyright(c) 2014 fantasyni <fantasyni@163.com>
* MIT Licensed
*/
var EventEmitter = require('events').EventEmitter;
var Constant = require('../../util/constant');
var utils = require('../../util/utils');
var mysql = require('mysql');
var util = require('util');
/**
* MysqlConnectionManager constructor function.
*
* @api public
*/
var MysqlConnectionManager = function() {
this.pool = null;
this.user = null;
this.options = {};
this.password = null;
this.database = null;
this.port = Constant.DEFAULT_MYSQL_PORT;
this.host = Constant.DEFAULT_MYSQL_HOST;
this.usePool = Constant.DEFAULT_MYSQL_USE_POOL;
this.connectionCb = Constant.DEFAULT_MYSQL_CONNECT_CB;
}
util.inherits(MysqlConnectionManager, EventEmitter);
module.exports = MysqlConnectionManager;
/**
* MysqlConnectionManager get connection.
*
* @param {Function} cb callback function
* @api public
*/
MysqlConnectionManager.prototype.getConnection = function(cb) {
var self = this;
this.fetchConnector(function(err, connection) {
if (err) {
cb(err);
return;
}
self.bindEvents(connection);
cb(err, connection);
});
}
MysqlConnectionManager.prototype.genId = function(connection, tableName) {
}
/**
* MysqlConnectionManager release connection.
*
* @param {Object} connection
* @api public
*/
MysqlConnectionManager.prototype.release = function(connection) {
if (this.usePool) {
connection.release();
} else {
connection.end();
}
}
/**
* MysqlConnectionManager end connection.
*
* @param {Object} connection
* @api public
*/
MysqlConnectionManager.prototype.end = function(connection) {
connection.end();
}
/**
* MysqlConnectionManager destroy connection.
*
* @param {Object} connection
* @api public
*/
MysqlConnectionManager.prototype.destroy = function(connection) {
connection.destroy();
}
/**
* MysqlConnectionManager fetch connection.
*
* @param {Function} cb callback function
* @api public
*/
MysqlConnectionManager.prototype.fetchConnector = function(cb) {
if (!utils.checkFunction(cb)) {
cb = this.connectionCb;
}
if (this.usePool) {
if (!this.pool) {
this.setPool(this.createPool());
}
this.pool.getConnection(function(err, connection) {
// connected! (unless `err` is set)
cb(err, connection);
});
} else {
var connection = this.createConnection();
cb(null, connection);
}
}
MysqlConnectionManager.prototype.bindEvents = function(connection) {
}
/**
* MysqlConnectionManager create connection pool.
*
* @api public
*/
MysqlConnectionManager.prototype.createPool = function() {
var options = this.getConnectionOptions();
var pool = mysql.createPool(options);
return pool;
}
/**
* MysqlConnectionManager create connection.
*
* @api public
*/
MysqlConnectionManager.prototype.createConnection = function() {
var options = this.getConnectionOptions();
var connection = mysql.createConnection(options);
return this.postProcessConnection(connection);
}
/**
* MysqlConnectionManager get connection options.
*
* @return {Object} connection options
* @api public
*/
MysqlConnectionManager.prototype.getConnectionOptions = function() {
var options = this.options || {};
options['host'] = this.host;
options['port'] = this.port;
options['user'] = this.user;
options['password'] = this.password;
options['database'] = this.database;
return options
}
/**
* MysqlConnectionManager post process connection.
*
* @param {Object} connection
* @api public
*/
MysqlConnectionManager.prototype.postProcessConnection = function(connection) {
return connection;
}
/**
* MysqlConnectionManager set port.
*
* @param {Number} port
* @api public
*/
MysqlConnectionManager.prototype.setPort = function(port) {
this.port = port;
}
/**
* MysqlConnectionManager get port.
*
* @return {Number} port
* @api public
*/
MysqlConnectionManager.prototype.getPort = function() {
return this.port;
}
/**
* MysqlConnectionManager set host.
*
* @param {String} host
* @api public
*/
MysqlConnectionManager.prototype.setHost = function(host) {
this.host = host;
}
/**
* MysqlConnectionManager get host.
*
* @return {String} host
* @api public
*/
MysqlConnectionManager.prototype.getHost = function() {
return this.host;
}
/**
* MysqlConnectionManager set user.
*
* @param {String} user username
* @api public
*/
MysqlConnectionManager.prototype.setUser = function(user) {
this.user = user;
}
/**
* MysqlConnectionManager get user.
*
* @return {String} username
* @api public
*/
MysqlConnectionManager.prototype.getUser = function() {
return this.user;
}
/**
* MysqlConnectionManager set password.
*
* @param {String} password
* @api public
*/
MysqlConnectionManager.prototype.setPassword = function(password) {
this.password = password;
}
/**
* MysqlConnectionManager get password.
*
* @return {String} password
* @api public
*/
MysqlConnectionManager.prototype.getPassword = function() {
return this.password;
}
/**
* MysqlConnectionManager set database.
*
* @param {String} database
* @api public
*/
MysqlConnectionManager.prototype.setDatabase = function(database) {
this.database = database;
}
/**
* MysqlConnectionManager get database.
*
* @return {String} database
* @api public
*/
MysqlConnectionManager.prototype.getDatabase = function() {
return this.database;
}
/**
* MysqlConnectionManager set options.
*
* @param {Object} options
* @api public
*/
MysqlConnectionManager.prototype.setOptions = function(options) {
this.options = options;
}
/**
* MysqlConnectionManager get options.
*
* @return {Object} options
* @api public
*/
MysqlConnectionManager.prototype.getOptions = function() {
return this.options;
}
/**
* MysqlConnectionManager set usePool.
*
* @param {Boolean} usePool
* @api public
*/
MysqlConnectionManager.prototype.setUsePool = function(usePool) {
this.usePool = usePool;
}
/**
* MysqlConnectionManager get usePool.
*
* @return {Boolean} usePool
* @api public
*/
MysqlConnectionManager.prototype.getUsePool = function() {
return this.usePool;
}
/**
* MysqlConnectionManager set pool.
*
* @return {Object} pool
* @api public
*/
MysqlConnectionManager.prototype.setPool = function(pool) {
this.pool = pool;
}
/**
* MysqlConnectionManager get pool.
*
* @return {Object} pool
* @api public
*/
MysqlConnectionManager.prototype.getPool = function() {
return this.pool;
} |
'use strict';
var shell = require('shelljs'),
prompt = require('prompt'),
querystring = require('querystring'),
request = require('request'),
chalk = require('chalk'),
fs = require('fs');
function getUserHome() {
return process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'];
}
function readToken() {
var file = (process.platform === 'win32') ? '_mean' : '.mean';
var path = getUserHome() + '/' + file;
if (!shell.test('-e', path)) return null;
return shell.cat(path);
}
var whoami = exports.whoami = function(callback) {
var token = readToken();
if (token) {
var options = {
uri: 'https://network.mean.io/api/v0.1/whoami',
method: 'GET',
headers: {
'authorization': token
}
};
request(options, function(error, response, body) {
if (!error && (response.statusCode === 200 || response.statusCode === 201)) {
if (callback) return callback(body);
console.log(body);
} else {
console.log('Client is NOT Authorized. Invalid token.');
}
});
} else {
console.log('Client is NOT Authorized.');
}
};
var authorize = exports.authorize = function(token, callback) {
var file = (process.platform === 'win32') ? '_mean' : '.mean';
var path = getUserHome() + '/' + file;
if (token) {
fs.writeFile(path, token, function(err) {
if (err) console.log(err);
whoami();
});
} else {
prompt.start();
prompt.get({
properties: {
token: {
hidden: true,
required: true
}
}
},
function(err, result) {
fs.writeFile(path, result.token, function(err) {
if (err) console.log(err);
whoami(callback);
});
});
}
};
exports.login = function() {
prompt.start();
prompt.get({
properties: {
email: {
format: 'email',
required: true
},
password: {
minLength: 8,
maxLength: 15,
pattern: /^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$/,
message: 'Password must be only letters, spaces, or dashes 8-15 characters long',
hidden: true,
required: true
}
}
},
function(err, result) {
if (err) throw err;
var options = {
uri: 'https://network.mean.io/api/v0.1/user/login',
method: 'POST',
form: result,
headers: {
'Content-Type': 'multipart/form-data',
'Content-Length': querystring.stringify(result).length
}
};
request(options, function(err, response, body) {
if (!err && (response.statusCode === 200 || response.statusCode === 201)) {
console.log('Login Successful! \n Authorizing the mean client.');
body = JSON.parse(body);
authorize(body.token.api, function() {
console.log('Run `mean whoami` to see authorized credentials');
});
} else {
console.log(chalk.red('Error: Login Failed!'));
if (err) {
return console.error(err);
}
}
});
});
};
exports.logout = function() {
var file = (process.platform === 'win32') ? '_mean' : '.mean';
var path = getUserHome() + '/' + file;
shell.rm(path);
};
exports.register = function() {
prompt.start();
prompt.get({
properties: {
name: {
pattern: /^[a-zA-Z\s\-]+$/,
minLength: 4,
maxLength: 15,
message: 'Name must be only letters, spaces, or dashes (min length of 4)',
required: true
},
username: {
minLength: 4,
maxLength: 15,
pattern: /^[a-zA-Z\s\-]+$/,
message: 'Username must be only letters, spaces, or dashes (min length of 4)',
required: true
},
email: {
format: 'email',
required: true
},
password: {
minLength: 8,
maxLength: 15,
pattern: /^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$/,
message: 'Password must be only letters, spaces, or dashes 8-15 characters long',
hidden: true,
required: true
}
}
},
function(err, result) {
if (err) throw err;
var options = {
uri: 'https://network.mean.io/api/v0.1/user',
method: 'POST',
form: result,
headers: {
'Content-Type': 'multipart/form-data',
'Content-Length': querystring.stringify(result).length
}
};
request(options, function(err, response, body) {
if (!err && (response.statusCode === 200 || response.statusCode === 201)) {
console.log('Registration Successful! \n Authorizing the mean client.');
body = JSON.parse(body);
authorize(body.token, function() {
console.log('Run `mean whoami` to see authorized credentials');
});
} else {
console.log(chalk.red('Error: Registration Failed!'));
if (err) {
return console.error(err);
}
}
});
});
}; |
var uniqueObjectId = require("../../webgl/base/utils.js").getUniqueCounter();
/**
* Connects a material model with a set of default parameters defined by
* an Xflow DataNode. The MaterialConfiguration is immutable
*
* @param model The material model
* @param {Xflow.DataNode} dataNode The material parameters of this node
* @param {{}} opt
* @constructor
*/
var MaterialConfiguration = function(model, dataNode, opt) {
opt = opt || {};
this.id = uniqueObjectId();
/**
* @type {{type: string}}
*/
this.model = model;
/**
* Data Node of the renderObject
* @type {Xflow.DataNode}
*/
this.dataNode = dataNode;
/**
* A name for debug purposes
* @type {string|null}
*/
this.name = opt.name || null;
};
module.exports = MaterialConfiguration;
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M20 8h-3V6.22c0-2.61-1.91-4.94-4.51-5.19C9.51.74 7 3.08 7 6v2H4v14h16V8zM8.9 6c0-1.71 1.39-3.1 3.1-3.1s3.1 1.39 3.1 3.1v2H8.9V6zM16 16h-3v3h-2v-3H8v-2h3v-3h2v3h3v2z"
}), 'EnhancedEncryptionSharp');
exports.default = _default; |
export default function getTransform ( isSvg, cx, cy, dx, dy, dsx, dsy, t, t_scale ) {
const transform = isSvg ?
`translate(${cx} ${cy}) scale(${( 1 + ( t_scale * dsx ) )} ${( 1 + ( t_scale * dsy ) )}) translate(${-cx} ${-cy}) translate(${( t * dx )} ${( t * dy )})` :
`translate(${( t * dx )}px,${( t * dy )}px) scale(${( 1 + ( t_scale * dsx ) )},${( 1 + ( t_scale * dsy ) )})`;
return transform;
}
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M21 23c-1.03 0-2.06-.25-3-.75-1.89 1-4.11 1-6 0-1.89 1-4.11 1-6 0-.95.5-1.97.75-3 .75H2v-2h1c1.04 0 2.08-.35 3-1 1.83 1.3 4.17 1.3 6 0 1.83 1.3 4.17 1.3 6 0 .91.65 1.96 1 3 1h1v2h-1zM12 5.5c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12 12s-1.52.71-3.93 1.37c-.82-.23-1.53-.75-2.07-1.37-.73.84-1.8 1.5-3 1.5s-2.27-.66-3-1.5c-.73.84-1.8 1.5-3 1.5s-2.27-.66-3-1.5c-.54.61-1.25 1.13-2.07 1.37C1.52 18.21 0 17.5 0 17.5s2.93-1.36 7.13-2.08l1.35-4.17c.31-.95 1.32-1.47 2.27-1.16.09.03.19.07.27.11l2.47 1.3 2.84-1.5 1.65-3.71-.51-1.32L18.8 2 22 3.43 20.67 6.4l-1.31.5-3.72 8.34c4.85.63 8.36 2.26 8.36 2.26zm-8.98-4.54-1.52.8-1.75-.92-.71 2.17c.32 0 .64-.01.96-.01.71 0 1.4.03 2.07.08l.95-2.12z"
}), 'KayakingTwoTone'); |
version https://git-lfs.github.com/spec/v1
oid sha256:14d75d38aa659f6e50ce78a03f82983c6b82fe2e71b292b1b2128870d6893962
size 42517
|
//>>built
define("dojo/_base/array dojo/_base/declare dojo/_base/event dojo/_base/lang dojo/_base/window dojo/dom-class dojo/dom-construct dojo/dom-attr dojo/touch dijit/_WidgetBase ./iconUtils dojo/has dojo/has!dojo-bidi?dojox/mobile/bidi/ValuePickerSlot".split(" "),function(f,l,r,m,n,k,c,d,g,h,p,q,t){h=l(q("dojo-bidi")?"dojox.mobile.NonBidiValuePickerSlot":"dojox.mobile.ValuePickerSlot",h,{items:[],labels:[],labelFrom:0,labelTo:0,zeroPad:0,value:"",step:1,readOnly:!1,tabIndex:"0",plusBtnLabel:"",plusBtnLabelRef:"",
minusBtnLabel:"",minusBtnLabelRef:"",baseClass:"mblValuePickerSlot",buildRendering:function(){this.inherited(arguments);this.initLabels();if(0<this.labels.length){this.items=[];for(var a=0;a<this.labels.length;a++)this.items.push([a,this.labels[a]])}this.plusBtnNode=c.create("div",{className:"mblValuePickerSlotPlusButton mblValuePickerSlotButton",title:"+"},this.domNode);this.plusIconNode=c.create("div",{className:"mblValuePickerSlotIcon"},this.plusBtnNode);p.createIcon("mblDomButtonGrayPlus",null,
this.plusIconNode);this.inputAreaNode=c.create("div",{className:"mblValuePickerSlotInputArea"},this.domNode);this.inputNode=c.create("input",{className:"mblValuePickerSlotInput",readonly:this.readOnly},this.inputAreaNode);this.minusBtnNode=c.create("div",{className:"mblValuePickerSlotMinusButton mblValuePickerSlotButton",title:"-"},this.domNode);this.minusIconNode=c.create("div",{className:"mblValuePickerSlotIcon"},this.minusBtnNode);p.createIcon("mblDomButtonGrayMinus",null,this.minusIconNode);d.set(this.plusBtnNode,
"role","button");this._setPlusBtnLabelAttr(this.plusBtnLabel);this._setPlusBtnLabelRefAttr(this.plusBtnLabelRef);d.set(this.inputNode,"role","textbox");a=require("dijit/registry").getUniqueId("dojo_mobile__mblValuePickerSlotInput");d.set(this.inputNode,"id",a);d.set(this.plusBtnNode,"aria-controls",a);d.set(this.minusBtnNode,"role","button");d.set(this.minusBtnNode,"aria-controls",a);this._setMinusBtnLabelAttr(this.minusBtnLabel);this._setMinusBtnLabelRefAttr(this.minusBtnLabelRef);""===this.value&&
0<this.items.length&&(this.value=this.items[0][1]);this._initialValue=this.value},startup:function(){this._started||(this._handlers=[this.connect(this.plusBtnNode,g.press,"_onTouchStart"),this.connect(this.minusBtnNode,g.press,"_onTouchStart"),this.connect(this.plusBtnNode,"onkeydown","_onClick"),this.connect(this.minusBtnNode,"onkeydown","_onClick"),this.connect(this.inputNode,"onchange",m.hitch(this,function(a){this._onChange(a)}))],this.inherited(arguments),this._set(this.plusBtnLabel))},initLabels:function(){if(this.labelFrom!==
this.labelTo)for(var a=this.labels=[],b=this.zeroPad&&Array(this.zeroPad).join("0"),e=this.labelFrom;e<=this.labelTo;e+=this.step)a.push(this.zeroPad?(b+e).slice(-this.zeroPad):e+"")},spin:function(a){for(var b=-1,e=this.get("value"),d=this.items.length,c=0;c<d;c++)if(this.items[c][1]===e){b=c;break}-1!=e&&(b+=a,0>b&&(b+=(Math.abs(Math.ceil(b/d))+1)*d),this.set("value",this.items[b%d][1]))},setInitialValue:function(){this.set("value",this._initialValue)},_onClick:function(a){if((!a||"keydown"!==a.type||
13===a.keyCode)&&!1!==this.onClick(a)){a=a.currentTarget;if(a===this.plusBtnNode||a===this.minusBtnNode)this._btn=a;this.spin(this._btn===this.plusBtnNode?1:-1)}},onClick:function(){},_onChange:function(a){!1!==this.onChange(a)&&(a=this.get("value"),a=this.validate(a),this.set("value",a.length?a[0][1]:this.value))},onChange:function(){},validate:function(a){return f.filter(this.items,function(b){return(b[1]+"").toLowerCase()==(a+"").toLowerCase()})},_onTouchStart:function(a){this._conn=[this.connect(n.body(),
g.move,"_onTouchMove"),this.connect(n.body(),g.release,"_onTouchEnd")];this.touchStartX=a.touches?a.touches[0].pageX:a.clientX;this.touchStartY=a.touches?a.touches[0].pageY:a.clientY;k.add(a.currentTarget,"mblValuePickerSlotButtonSelected");this._btn=a.currentTarget;this._timer&&(this._timer.remove(),this._timer=null);this._interval&&(clearInterval(this._interval),this._interval=null);this._timer=this.defer(function(){this._interval=setInterval(m.hitch(this,function(){this.spin(this._btn===this.plusBtnNode?
1:-1)}),60);this._timer=null},1E3);r.stop(a)},_onTouchMove:function(a){var b=a.touches?a.touches[0].pageY:a.clientY;if(4<=Math.abs((a.touches?a.touches[0].pageX:a.clientX)-this.touchStartX)||4<=Math.abs(b-this.touchStartY))this._timer&&(this._timer.remove(),this._timer=null),this._interval&&(clearInterval(this._interval),this._interval=null),f.forEach(this._conn,this.disconnect,this),k.remove(this._btn,"mblValuePickerSlotButtonSelected")},_onTouchEnd:function(a){this._timer&&(this._timer.remove(),
this._timer=null);f.forEach(this._conn,this.disconnect,this);k.remove(this._btn,"mblValuePickerSlotButtonSelected");this._interval?(clearInterval(this._interval),this._interval=null):this._onClick(a)},_getKeyAttr:function(){var a=this.get("value"),b=f.filter(this.items,function(b){return b[1]===a})[0];return b?b[0]:null},_getValueAttr:function(){return this.inputNode.value},_setValueAttr:function(a){this._spinToValue(a,!0)},_spinToValue:function(a,b){if(this.get("value")!=a&&(this.inputNode.value=
a,b&&this._set("value",a),(a=this.getParent())&&a.onValueChanged))a.onValueChanged(this)},_setTabIndexAttr:function(a){this.plusBtnNode.setAttribute("tabIndex",a);this.minusBtnNode.setAttribute("tabIndex",a)},_setAria:function(a,b,c){c?d.set(a,b,c):d.remove(a,b)},_setPlusBtnLabelAttr:function(a){this._setAria(this.plusBtnNode,"aria-label",a)},_setPlusBtnLabelRefAttr:function(a){this._setAria(this.plusBtnNode,"aria-labelledby",a)},_setMinusBtnLabelAttr:function(a){this._setAria(this.minusBtnNode,"aria-label",
a)},_setMinusBtnLabelRefAttr:function(a){this._setAria(this.minusBtnNode,"aria-labelledby",a)}});return q("dojo-bidi")?l("dojox.mobile.ValuePickerSlot",[h,t]):h}); |
import React, { Component } from 'react';
import {
Text,
View,
TouchableOpacity
} from 'react-native';
export default class OverviewContent extends Component {
constructor(props){
super(props);
}
getFormattedMessage(){
var message = this.props.messageData.message;
var text = message.split('---');
if(text.length === 1){
return (
<Text>{message}</Text>
)
}
else{
return (
<Text>
<Text>{text[0]}</Text>
<Text style={{color: '#0076FF'}}>{text[1]}</Text>
<Text>{text[2]}</Text>
</Text>
)
}
}
render(){
var txt = this.getFormattedMessage();
return(
<View>
<Text style={styles.messageText} numberOfLines={2}>{this.getFormattedMessage()}</Text>
<TouchableOpacity style={{alignItems: 'flex-end'}} onPress={this.props.toggleItem}>
<Text style={styles.pressableText}>more</Text>
</TouchableOpacity>
</View>
)
}
} |
'use strict';
var _ = require('lodash');
var Random = require('./random.model');
// Get list of randoms
exports.index = function(req, res) {
Random.find(function (err, randoms) {
if(err) { return handleError(res, err); }
return res.json(200, randoms);
});
};
// Get a single random
exports.show = function(req, res) {
Random.findById(req.params.id, function (err, random) {
if(err) { return handleError(res, err); }
if(!random) { return res.send(404); }
return res.json(random);
});
};
// Creates a new random in the DB.
exports.create = function(req, res) {
Random.create(req.body, function(err, random) {
if(err) { return handleError(res, err); }
return res.json(201, random);
});
};
// Updates an existing random in the DB.
exports.update = function(req, res) {
if(req.body._id) { delete req.body._id; }
Random.findById(req.params.id, function (err, random) {
if (err) { return handleError(res, err); }
if(!random) { return res.send(404); }
var updated = _.merge(random, req.body);
updated.save(function (err) {
if (err) { return handleError(res, err); }
return res.json(200, random);
});
});
};
// Deletes a random from the DB.
exports.destroy = function(req, res) {
Random.findById(req.params.id, function (err, random) {
if(err) { return handleError(res, err); }
if(!random) { return res.send(404); }
random.remove(function(err) {
if(err) { return handleError(res, err); }
return res.send(204);
});
});
};
function handleError(res, err) {
return res.send(500, err);
} |
module.exports = function (karma) {
karma.set({
/**
* From where to look for files, starting with the location of this file.
*/
basePath: './',
/**
* This is the list of file patterns to load into the browser during testing.
*/
files: [
'js/**/*.js',
'test/fixtures/*.js',
'test/unit/*.js',
'test/integration/*.js',
],
colors: true,
exclude: [],
frameworks: ['mocha', 'chai-sinon', 'browserify', 'source-map-support'],
plugins: ['karma-*'],
preprocessors: {
'js/**/*.js': ['browserify'],
'test/**/*.js': ['browserify']
},
browserify: {
debug: true,
},
logLevel: 'ERROR',
/**
* How to report, by default.
*/
reporters: ['spec'],
/**
* On which port should the browser connect, on which port is the test runner
* operating, and what is the URL path for the browser to use.
*/
port: 9018,
runnerPort: 9019,
urlRoot: '/',
singleRun: true,
autoWatch: false,
/**
* The list of browsers to launch to test on. This includes only "Firefox" by
* default, but other browser names include:
* Chrome, ChromeCanary, Firefox, Opera, Safari, PhantomJS
*
* Note that you can also use the executable name of the browser, like "chromium"
* or "firefox", but that these vary based on your operating system.
*
* You may also leave this blank and manually navigate your browser to
* http://localhost:9018/ when you're running tests. The window/tab can be left
* open and the tests will automatically occur there during the build. This has
* the aesthetic advantage of not launching a browser every time you save.
*/
browsers: [
//'Safari',
//'Firefox',
'Chrome'
]
});
};
|
import Ember from 'ember';
export default Ember.Controller.extend({
queryParams: ["page","perPage","sortByField"],
page: 1,
updatePaged: Ember.observer("sortByField", function() {
var field = this.get('sortByField');
var paged = this.get('model');
if (paged && paged.setOtherParam) {
paged.setOtherParam('sortByField',field);
}
})
});
|
define(function () {
// Hebrew
return {
errorLoading: function () {
return 'התוצאות לא נטענו בהלכה';
},
inputTooLong: function (args) {
var overChars = args.input.length - args.maximum;
var message = 'נא למחוק ' + overChars + ' תווים';
if (overChars != 1) {
message += 's';
}
return message;
},
inputTooShort: function (args) {
var remainingChars = args.minimum - args.input.length;
var message = 'נא להכניס ' + remainingChars + ' תווים או יותר';
return message;
},
loadingMore: function () {
return 'טען תוצאות נוספות…';
},
maximumSelected: function (args) {
var message = 'באפשרותך לבחור רק ' + args.maximum + ' פריטים';
if (args.maximum != 1) {
message += 's';
}
return message;
},
noResults: function () {
return 'לא נמצאו תוצאות';
},
searching: function () {
return 'מחפש…';
}
};
});
|
(function($) {
$(document).ready(function() {
// Toggle the menu on mobile
var menuToggle = $('#js-topbar-toggle').unbind();
$('#primary-menu').removeClass("menu-show");
menuToggle.on('click', function(e) {
e.preventDefault();
$('.main-menu').slideToggle(function(){
if($('.main-menu').is(':hidden')) {
$('.main-menu').removeAttr('style');
}
});
});
// Remove links to let submenu work on mobile device
$(".menu-item-has-children > a").attr("href", "#").each();
});
})(jQuery); |
/*globals describe, before, beforeEach, afterEach, it */
var testUtils = require('../../utils'),
should = require('should'),
_ = require('underscore'),
request = require('request');
request = request.defaults({jar:true})
describe('Tag API', function () {
var user = testUtils.DataGenerator.forModel.users[0],
csrfToken = '';
before(function (done) {
testUtils.clearData()
.then(function () {
done();
}, done);
});
beforeEach(function (done) {
testUtils.initData()
.then(function () {
return testUtils.insertDefaultFixtures();
})
.then(function () {
// do a get request to get the CSRF token first
request.get(testUtils.API.getSigninURL(), function (error, response, body) {
response.should.have.status(200);
var pattern_meta = /<meta.*?name="csrf-param".*?content="(.*?)".*?>/i;
pattern_meta.should.exist;
csrfToken = body.match(pattern_meta)[1];
setTimeout((function () {
request.post({uri: testUtils.API.getSigninURL(),
headers: {'X-CSRF-Token': csrfToken}}, function (error, response, body) {
response.should.have.status(200);
done();
}).form({email: user.email, password: user.password});
}), 2000);
});
}, done);
});
afterEach(function (done) {
testUtils.clearData().then(function () {
done();
}, done);
});
it('can retrieve all tags', function (done) {
request.get(testUtils.API.getApiURL('tags/'), function (error, response, body) {
response.should.have.status(200);
should.not.exist(response.headers['x-cache-invalidate']);
response.should.be.json;
var jsonResponse = JSON.parse(body);
jsonResponse.should.exist;
jsonResponse.should.have.length(5);
testUtils.API.checkResponse(jsonResponse[0], 'tag');
done();
});
});
});
|
/**
Inspired by [simple counter](http://baconjs.github.io/)
Implemented in *menrva*, [Bacon.js](https://github.com/baconjs/bacon.js) and [RxJS](https://github.com/Reactive-Extensions/RxJS).
Bacon.js and RxJS variants, come in two flavours, *direct* and *data-flowish*.
*/
$(function () {
"use strict";
var MIN_VALUE = 0;
var $value = menrva.source(0);
$value.onValue(function (x) {
$("#counter").text(x);
});
$value.onValue(function (x) {
var down = $("#down");
if (x <= MIN_VALUE) {
down.attr("disabled", "disabled");
} else {
down.removeAttr("disabled");
}
});
function inc(x) {
return x + 1;
}
function dec(x) {
return Math.max(MIN_VALUE, x - 1);
}
$("#up").click(function () {
var tx = menrva.transaction();
$value.modify(tx, inc);
tx.commit();
});
$("#down").click(function () {
var tx = menrva.transaction();
$value.modify(tx, dec);
tx.commit();
});
});
|
'use strict';
var elementHelper = require('../helper/ElementHelper');
/**
* A handler capable of creating a new element under a provided parent
* and updating / creating a reference to it in one atomic action.
*
* @class
* @constructor
*/
function CreateAndReferenceElementHandler(elementRegistry, bpmnFactory) {
this._elementRegistry = elementRegistry;
this._bpmnFactory = bpmnFactory;
}
CreateAndReferenceElementHandler.$inject = [ 'elementRegistry', 'bpmnFactory' ];
module.exports = CreateAndReferenceElementHandler;
function ensureNotNull(prop, name) {
if (!prop) {
throw new Error(name + ' required');
}
return prop;
}
////// api /////////////////////////////////////////////
/**
* Creates a new element under a provided parent and updates / creates a reference to it in
* one atomic action.
*
* @method CreateAndReferenceElementHandler#execute
*
* @param {Object} context
* @param {djs.model.Base} context.element which is the context for the reference
* @param {moddle.referencingObject} context.referencingObject the object which creates the reference
* @param {String} context.referenceProperty the property of the referencingObject which makes the reference
* @param {moddle.newObject} context.newObject the new object to add
* @param {moddle.newObjectContainer} context.newObjectContainer the container for the new object
*
* @returns {Array<djs.mode.Base>} the updated element
*/
CreateAndReferenceElementHandler.prototype.execute = function(context) {
var referencingObject = ensureNotNull(context.referencingObject, 'referencingObject'),
referenceProperty = ensureNotNull(context.referenceProperty, 'referenceProperty'),
newObject = ensureNotNull(context.newObject, 'newObject'),
newObjectContainer = ensureNotNull(context.newObjectContainer, 'newObjectContainer'),
newObjectParent = ensureNotNull(context.newObjectParent, 'newObjectParent'),
changed = [ context.element ]; // this will not change any diagram-js elements
// create new object
var referencedObject = elementHelper
.createElement(newObject.type, newObject.properties, newObjectParent, this._bpmnFactory);
context.referencedObject = referencedObject;
// add to containing list
newObjectContainer.push(referencedObject);
// adjust reference attribute
context.previousReference = referencingObject[referenceProperty];
referencingObject[referenceProperty] = referencedObject;
context.changed = changed;
// indicate changed on objects affected by the update
return changed;
};
/**
* Reverts the update
*
* @method CreateAndReferenceElementHandler#revert
*
* @param {Object} context
*
* @returns {djs.mode.Base} the updated element
*/
CreateAndReferenceElementHandler.prototype.revert = function(context) {
var referencingObject = context.referencingObject,
referenceProperty = context.referenceProperty,
previousReference = context.previousReference,
referencedObject = context.referencedObject,
newObjectContainer = context.newObjectContainer;
// reset reference
referencingObject.set(referenceProperty, previousReference);
// remove new element
newObjectContainer.splice(newObjectContainer.indexOf(referencedObject), 1);
return context.changed;
};
|
#!/usr/bin/env node
/* Based on webpack/bin/webpack.js */
/* eslint-disable no-console */
"use strict";
/**
* @param {string} command process to run
* @param {string[]} args command line arguments
* @returns {Promise<void>} promise
*/
const runCommand = (command, args) => {
const cp = require("child_process");
return new Promise((resolve, reject) => {
const executedCommand = cp.spawn(command, args, {
stdio: "inherit",
shell: true,
});
executedCommand.on("error", (error) => {
reject(error);
});
executedCommand.on("exit", (code) => {
if (code === 0) {
resolve();
} else {
reject();
}
});
});
};
/**
* @param {string} packageName name of the package
* @returns {boolean} is the package installed?
*/
const isInstalled = (packageName) => {
if (process.versions.pnp) {
return true;
}
const path = require("path");
const fs = require("graceful-fs");
let dir = __dirname;
do {
try {
if (
fs.statSync(path.join(dir, "node_modules", packageName)).isDirectory()
) {
return true;
}
} catch (_error) {
// Nothing
}
// eslint-disable-next-line no-cond-assign
} while (dir !== (dir = path.dirname(dir)));
return false;
};
/**
* @param {CliOption} cli options
* @returns {void}
*/
const runCli = (cli) => {
if (cli.preprocess) {
cli.preprocess();
}
const path = require("path");
const pkgPath = require.resolve(`${cli.package}/package.json`);
// eslint-disable-next-line import/no-dynamic-require
const pkg = require(pkgPath);
// eslint-disable-next-line import/no-dynamic-require
require(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName]));
};
/**
* @typedef {Object} CliOption
* @property {string} name display name
* @property {string} package npm package name
* @property {string} binName name of the executable file
* @property {boolean} installed currently installed?
* @property {string} url homepage
* @property {function} preprocess preprocessor
*/
/** @type {CliOption} */
const cli = {
name: "webpack-cli",
package: "webpack-cli",
binName: "webpack-cli",
installed: isInstalled("webpack-cli"),
url: "https://github.com/webpack/webpack-cli",
preprocess() {
process.argv.splice(2, 0, "serve");
},
};
if (!cli.installed) {
const path = require("path");
const fs = require("graceful-fs");
const readLine = require("readline");
const notify = `CLI for webpack must be installed.\n ${cli.name} (${cli.url})\n`;
console.error(notify);
/**
* @type {string}
*/
let packageManager;
if (fs.existsSync(path.resolve(process.cwd(), "yarn.lock"))) {
packageManager = "yarn";
} else if (fs.existsSync(path.resolve(process.cwd(), "pnpm-lock.yaml"))) {
packageManager = "pnpm";
} else {
packageManager = "npm";
}
const installOptions = [packageManager === "yarn" ? "add" : "install", "-D"];
console.error(
`We will use "${packageManager}" to install the CLI via "${packageManager} ${installOptions.join(
" "
)} ${cli.package}".`
);
const question = `Do you want to install 'webpack-cli' (yes/no): `;
const questionInterface = readLine.createInterface({
input: process.stdin,
output: process.stderr,
});
// In certain scenarios (e.g. when STDIN is not in terminal mode), the callback function will not be
// executed. Setting the exit code here to ensure the script exits correctly in those cases. The callback
// function is responsible for clearing the exit code if the user wishes to install webpack-cli.
process.exitCode = 1;
questionInterface.question(question, (answer) => {
questionInterface.close();
const normalizedAnswer = answer.toLowerCase().startsWith("y");
if (!normalizedAnswer) {
console.error(
"You need to install 'webpack-cli' to use webpack via CLI.\n" +
"You can also install the CLI manually."
);
return;
}
process.exitCode = 0;
console.log(
`Installing '${
cli.package
}' (running '${packageManager} ${installOptions.join(" ")} ${
cli.package
}')...`
);
runCommand(packageManager, installOptions.concat(cli.package))
.then(() => {
runCli(cli);
})
.catch((error) => {
console.error(error);
process.exitCode = 1;
});
});
} else {
runCli(cli);
}
|
define(['./forEach', '../function/makeIterator_'], function (forEach, makeIterator) {
/**
* Return minimum value inside array
*/
function min(arr, iterator, thisObj){
if (arr == null || !arr.length) {
return -Infinity;
} else if (arr.length && !iterator) {
return Math.min.apply(Math, arr);
} else {
iterator = makeIterator(iterator, thisObj);
var result,
compare = Infinity,
value,
temp;
var i = -1, len = arr.length;
while (++i < len) {
value = arr[i];
temp = iterator(value, i, arr);
if (temp < compare) {
compare = temp;
result = value;
}
}
return result;
}
}
return min;
});
|
'use strict';
const Bluebird = require('bluebird');
const find = require('lodash.find');
const tmp = require('tmp');
const path = require('path');
const os = require('os');
const tmpDirAsync = Bluebird.promisify(tmp.dir);
const expect = require('chai').expect;
const file = require('chai-files').file;
const knownBrowsers = require('../../lib/utils/known-browsers');
function addBrowserArgsToConfig(config, browserName) {
config.get = function(name) {
let args = {};
if (name === 'browser_args') {
args[browserName] = '--testem';
return args;
}
};
}
function createConfig() {
return {
getHomeDir: function() {
return 'home/dir';
},
get: function() {
return;
}
};
}
function findBrowser(browsers, browserName) {
return find(browsers, function(browser) {
return browser.name === browserName;
});
}
describe('knownBrowsers', function() {
let browserTmpDir;
let url = 'http://localhost:7357';
let launcher = {
browserTmpDir: function() {
return browserTmpDir;
},
getUrl: function() {
return url;
}
};
let config;
beforeEach(function() {
config = createConfig();
return tmpDirAsync().then(function(path) {
browserTmpDir = path;
});
});
describe('Any platform', function() {
describe('Firefox', function() {
let browsers;
let firefox;
function setup(browserName) {
if (browserName) {
addBrowserArgsToConfig(config, browserName);
} else {
config = createConfig();
}
browsers = knownBrowsers('any', config);
firefox = findBrowser(browsers, browserName || 'Firefox');
}
beforeEach(function() {
setup();
});
it('exists', function() {
expect(firefox).to.exist();
});
it('constructs correct args', function() {
expect(firefox.args.call(launcher, config, url)).to.deep.eq([
'-profile', browserTmpDir, url
]);
});
it('creates a config file on setup', function(done) {
firefox.setup.call(launcher, config, function(err) {
expect(err).to.be.null();
expect(file(path.join(browserTmpDir, 'user.js'))).to.equal([
'user_pref("browser.shell.checkDefaultBrowser", false);',
'user_pref("browser.cache.disk.smart_size.first_run", false);',
'user_pref("datareporting.policy.dataSubmissionEnabled", false);',
'user_pref("datareporting.policy.dataSubmissionPolicyNotifiedTime", "1481830156314");'
].join(os.EOL));
done();
});
});
it('allows to provide a custom user.js', function(done) {
let customPrefsJSPath = path.join(__dirname, '../fixtures/firefox/custom_user.js');
config.get = function(name) {
if (name === 'firefox_user_js') {
return customPrefsJSPath;
}
};
firefox.setup.call(launcher, config, function(err) {
expect(err).to.be.null();
expect(file(path.join(browserTmpDir, 'user.js'))).to.equal([
'user_pref("browser.shell.checkDefaultBrowser", false);',
'user_pref("browser.cache.disk.smart_size.first_run", false);',
'user_pref("dom.max_script_run_time", 0);'
].join(os.EOL) + os.EOL);
done();
});
});
it('allows a custom path to be used as the possiblePath for firefox ', function() {
let customPath = '/my/custom/path/to/firefox';
config.get = function(name) {
if (name === 'browser_paths') {
return {
Firefox: customPath
};
}
};
browsers = knownBrowsers('any', config);
firefox = findBrowser(browsers, 'Firefox');
expect(firefox.possiblePath).to.be.a('string');
expect(firefox.possiblePath).to.equal(customPath);
});
it('allows a custom exe to be used as the possibleExe for firefox ', function() {
let customExe = 'firefox-custom';
config.get = function(name) {
if (name === 'browser_exes') {
return {
Firefox: customExe
};
}
};
browsers = knownBrowsers('any', config);
firefox = findBrowser(browsers, 'Firefox');
expect(firefox.possibleExe).to.be.a('string');
expect(firefox.possibleExe).to.equal(customExe);
});
describe('browser_args', function() {
beforeEach(function() {
setup('Firefox');
});
afterEach(function() {
setup();
});
it('constructs correct args with browser_args', function() {
expect(firefox.args.call(launcher, config, url)).to.deep.eq([
'--testem', '-profile', browserTmpDir, url
]);
});
});
describe('headless browser_args', function() {
beforeEach(function() {
setup('Headless Firefox');
});
afterEach(function() {
setup();
});
it('constructs correct args with browser_args', function() {
expect(firefox.args.call(launcher, config, url)).to.deep.eq([
'--testem', '-profile', '--headless', browserTmpDir, url
]);
});
});
});
describe('Chrome', function() {
let browsers;
let chrome;
function setup(browserName) {
if (browserName) {
addBrowserArgsToConfig(config, browserName);
} else {
config = createConfig();
}
browsers = knownBrowsers('any', config);
chrome = findBrowser(browsers, browserName || 'Chrome');
}
beforeEach(function() {
setup();
});
it('exists', function() {
expect(chrome).to.exist();
});
it('constructs correct args', function() {
expect(chrome.args.call(launcher, config, url)).to.deep.eq([
'--user-data-dir=' + browserTmpDir,
'--no-default-browser-check',
'--no-first-run',
'--ignore-certificate-errors',
'--test-type',
'--disable-renderer-backgrounding',
'--disable-background-timer-throttling',
url
]);
});
it('checks correct paths', function() {
expect(chrome.possiblePath).to.deep.eq([
'home/dir\\Local Settings\\Application Data\\Google\\Chrome\\Application\\chrome.exe',
'home/dir\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe',
'C:\\Program Files\\Google\\Chrome\\Application\\Chrome.exe',
'C:\\Program Files (x86)\\Google\\Chrome\\Application\\Chrome.exe',
process.env.HOME + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
]);
});
it('allows a custom path to be used as the possiblePath for chrome ', function() {
let customPath = '/my/custom/path/to/chrome';
config.get = function(name) {
if (name === 'browser_paths') {
return {
Chrome: customPath
};
}
};
browsers = knownBrowsers('any', config);
chrome = findBrowser(browsers, 'Chrome');
expect(chrome.possiblePath).to.be.a('string');
expect(chrome.possiblePath).to.equal(customPath);
});
it('allows a custom exe to be used as the possibleExe for chrome ', function() {
let customExe = 'chrome-custom';
config.get = function(name) {
if (name === 'browser_exes') {
return {
Chrome: customExe
};
}
};
browsers = knownBrowsers('any', config);
chrome = findBrowser(browsers, 'Chrome');
expect(chrome.possibleExe).to.be.a('string');
expect(chrome.possibleExe).to.equal(customExe);
});
describe('browser_args', function() {
beforeEach(function() {
setup('Chrome');
});
afterEach(function() {
setup();
});
it('constructs correct args with browser_args', function() {
expect(chrome.args.call(launcher, config, url)).to.deep.eq([
'--testem',
'--user-data-dir=' + browserTmpDir,
'--no-default-browser-check',
'--no-first-run',
'--ignore-certificate-errors',
'--test-type',
'--disable-renderer-backgrounding',
'--disable-background-timer-throttling',
url
]);
});
});
describe('headless browser_args', function() {
beforeEach(function() {
setup('Headless Chrome');
});
afterEach(function() {
setup();
});
it('constructs correct args with browser_args', function() {
expect(chrome.args.call(launcher, config, url)).to.deep.eq([
'--testem',
'--headless',
'--disable-gpu',
'--disable-software-rasterizer',
'--mute-audio',
'--remote-debugging-port=0',
'--window-size=1440,900',
'--user-data-dir=' + browserTmpDir,
'--no-default-browser-check',
'--no-first-run',
'--ignore-certificate-errors',
'--test-type',
'--disable-renderer-backgrounding',
'--disable-background-timer-throttling',
url
]);
});
});
});
describe('Safari', function() {
let browsers;
let safari;
function setup(browserName) {
if (browserName) {
addBrowserArgsToConfig(config, browserName);
} else {
config = createConfig();
}
browsers = knownBrowsers('any', config);
safari = findBrowser(browsers, 'Safari');
}
beforeEach(function() {
setup();
});
it('exists', function() {
expect(safari).to.exist();
});
it('constructs correct args', function() {
expect(safari.args.call(launcher, config, url)).to.deep.eq([
path.join(browserTmpDir, 'start.html')
]);
});
it('creates a config file on setup', function(done) {
safari.setup.call(launcher, config, function(err) {
expect(err).to.be.null();
expect(file(path.join(browserTmpDir, 'start.html'))).to.equal(
'<script>window.location = \'http://localhost:7357\'</script>'
);
done();
});
});
it('allows a custom path to be used as the possiblePath for safari ', function() {
let customPath = '/my/custom/path/to/safari';
config.get = function(name) {
if (name === 'browser_paths') {
return {
Safari: customPath
};
}
};
browsers = knownBrowsers('any', config);
safari = findBrowser(browsers, 'Safari');
expect(safari.possiblePath).to.be.a('string');
expect(safari.possiblePath).to.equal(customPath);
});
it('allows a custom exe to be used as the possibleExe for safari ', function() {
let customExe = 'safari-custom';
config.get = function(name) {
if (name === 'browser_exes') {
return {
Safari: customExe
};
}
};
browsers = knownBrowsers('any', config);
safari = findBrowser(browsers, 'Safari');
expect(safari.possibleExe).to.be.a('string');
expect(safari.possibleExe).to.equal(customExe);
});
describe('browser_args', function() {
beforeEach(function() {
setup('Safari');
});
afterEach(function() {
setup();
});
it('constructs correct args with browser_args', function() {
expect(safari.args.call(launcher, config, url)).to.deep.eq([
'--testem', path.join(browserTmpDir, 'start.html')
]);
});
});
});
describe('Safari Technology Preview', function() {
let browsers;
let safariTP;
function setup(browserName) {
if (browserName) {
addBrowserArgsToConfig(config, browserName);
} else {
config = createConfig();
}
browsers = knownBrowsers('any', config);
safariTP = findBrowser(browsers, 'Safari Technology Preview');
}
beforeEach(function() {
setup();
});
it('exists', function() {
expect(safariTP).to.exist();
});
it('constructs correct args', function() {
expect(safariTP.args.call(launcher, config, url)).to.deep.eq([
path.join(browserTmpDir, 'start.html')
]);
});
it('creates a config file on setup', function(done) {
safariTP.setup.call(launcher, config, function(err) {
expect(err).to.be.null();
expect(file(path.join(browserTmpDir, 'start.html'))).to.equal(
'<script>window.location = \'http://localhost:7357\'</script>'
);
done();
});
});
it('allows a custom path to be used as the possiblePath for Safari Technology Preview ', function() {
let customPath = '/my/custom/path/to/safari-technology-preview';
config.get = function(name) {
if (name === 'browser_paths') {
return {
'Safari Technology Preview': customPath
};
}
};
browsers = knownBrowsers('any', config);
safariTP = findBrowser(browsers, 'Safari Technology Preview');
expect(safariTP.possiblePath).to.be.a('string');
expect(safariTP.possiblePath).to.equal(customPath);
});
it('allows a custom exe to be used as the possibleExe for Safari Technology Preview ', function() {
let customExe = 'safari-technology-preview-custom';
config.get = function(name) {
if (name === 'browser_exes') {
return {
'Safari Technology Preview': customExe
};
}
};
browsers = knownBrowsers('any', config);
safariTP = findBrowser(browsers, 'Safari Technology Preview');
expect(safariTP.possibleExe).to.be.a('string');
expect(safariTP.possibleExe).to.equal(customExe);
});
describe('browser_args', function() {
beforeEach(function() {
setup('Safari Technology Preview');
});
afterEach(function() {
setup();
});
it('constructs correct args with browser_args', function() {
expect(safariTP.args.call(launcher, config, url)).to.deep.eq([
'--testem', path.join(browserTmpDir, 'start.html')
]);
});
});
});
describe('Opera', function() {
let browsers;
let opera;
function setup(browserName) {
if (browserName) {
addBrowserArgsToConfig(config, browserName);
} else {
config = createConfig();
}
browsers = knownBrowsers('any', config);
opera = findBrowser(browsers, 'Opera');
}
beforeEach(function() {
setup();
});
it('exists', function() {
expect(opera).to.exist();
});
it('constructs correct args', function() {
expect(opera.args.call(launcher, config, url)).to.deep.eq([
'--user-data-dir=' + browserTmpDir, '-pd', browserTmpDir, url
]);
});
it('allows a custom path to be used as the possiblePath for opera ', function() {
let customPath = '/my/custom/path/to/opera';
config.get = function(name) {
if (name === 'browser_paths') {
return {
Opera: customPath
};
}
};
browsers = knownBrowsers('any', config);
opera = findBrowser(browsers, 'Opera');
expect(opera.possiblePath).to.be.a('string');
expect(opera.possiblePath).to.equal(customPath);
});
it('allows a custom exe to be used as the possibleExe for opera ', function() {
let customExe = 'opera-custom';
config.get = function(name) {
if (name === 'browser_exes') {
return {
Opera: customExe
};
}
};
browsers = knownBrowsers('any', config);
opera = findBrowser(browsers, 'Opera');
expect(opera.possibleExe).to.be.a('string');
expect(opera.possibleExe).to.equal(customExe);
});
describe('browser_args', function() {
beforeEach(function() {
setup('Opera');
});
afterEach(function() {
setup();
});
it('constructs correct args with browser_args', function() {
expect(opera.args.call(launcher, config, url)).to.deep.eq([
'--testem', '--user-data-dir=' + browserTmpDir, '-pd', browserTmpDir, url
]);
});
});
});
describe('PhantomJS', function() {
let browsers;
let phantomJS;
let scriptPath;
function setup(browserName) {
if (browserName) {
addBrowserArgsToConfig(config, browserName);
} else {
config = createConfig();
}
browsers = knownBrowsers('any', config);
phantomJS = findBrowser(browsers, 'PhantomJS');
}
beforeEach(function() {
setup();
scriptPath = path.resolve(__dirname, '../../assets/phantom.js');
});
it('exists', function() {
expect(phantomJS).to.exist();
});
it('constructs correct args', function() {
expect(phantomJS.args.call(launcher, config, url)).to.deep.eq([
scriptPath, url
]);
});
it('constructs correct args with phantomjs_debug_port', function() {
config.get = function(name) {
if (name === 'phantomjs_debug_port') {
return '1234';
}
};
expect(phantomJS.args.call(launcher, config, url)).to.deep.eq([
'--remote-debugger-port=1234',
'--remote-debugger-autorun=true',
scriptPath,
url
]);
});
it('constructs correct args with phantomjs_args', function() {
config.get = function(name) {
if (name === 'phantomjs_args') {
return ['arg1', 'arg2'];
}
};
expect(phantomJS.args.call(launcher, config, url)).to.deep.eq([
'arg1', 'arg2', scriptPath, url
]);
});
it('allows a custom path to be used as the possiblePath for phantomjs ', function() {
let customPath = '/my/custom/path/to/phantomjs';
config.get = function(name) {
if (name === 'browser_paths') {
return {
PhantomJS: customPath
};
}
};
browsers = knownBrowsers('any', config);
phantomJS = findBrowser(browsers, 'PhantomJS');
expect(phantomJS.possiblePath).to.be.a('string');
expect(phantomJS.possiblePath).to.equal(customPath);
});
it('allows a custom exe to be used as the possibleExe for phantomjs ', function() {
let customExe = 'phantomjs-custom';
config.get = function(name) {
if (name === 'browser_exes') {
return {
PhantomJS: customExe
};
}
};
browsers = knownBrowsers('any', config);
phantomJS = findBrowser(browsers, 'PhantomJS');
expect(phantomJS.possibleExe).to.be.a('string');
expect(phantomJS.possibleExe).to.equal(customExe);
});
describe('browser_args', function() {
beforeEach(function() {
setup('PhantomJS');
scriptPath = path.resolve(__dirname, '../../assets/phantom.js');
});
afterEach(function() {
setup();
});
it('constructs correct args and browser_args', function() {
expect(phantomJS.args.call(launcher, config, url)).to.deep.eq([
'--testem', scriptPath, url
]);
});
it('constructs correct args with phantomjs_debug_port and browser_args', function() {
config.get = function(name) {
if (name === 'phantomjs_debug_port') {
return '1234';
} else if (name === 'browser_args') {
return {
PhantomJS: '--testem'
};
}
};
expect(phantomJS.args.call(launcher, config, url)).to.deep.eq([
'--testem',
'--remote-debugger-port=1234',
'--remote-debugger-autorun=true',
scriptPath,
url
]);
});
it('constructs correct args with phantomjs_args and browser_args', function() {
config.get = function(name) {
if (name === 'phantomjs_args') {
return ['arg1', 'arg2'];
} else if (name === 'browser_args') {
return {
PhantomJS: '--testem'
};
}
};
expect(phantomJS.args.call(launcher, config, url)).to.deep.eq([
'--testem', 'arg1', 'arg2', scriptPath, url
]);
});
it('constructs correct args with custom launch script', function() {
let customScriptPath = './custom_phantom.js';
config.get = function(name) {
if (name === 'phantomjs_launch_script') {
return customScriptPath;
}
};
expect(phantomJS.args.call(launcher, config, url)).to.deep.eq([
'--testem', customScriptPath, url
]);
});
});
});
});
describe('Windows', function() {
describe('Internet Explorer', function() {
let browsers;
let internetExplorer;
function setup(browserName) {
if (browserName) {
addBrowserArgsToConfig(config, browserName);
} else {
config = createConfig();
}
browsers = knownBrowsers('win32', config);
internetExplorer = findBrowser(browsers, 'IE');
}
beforeEach(function() {
setup();
});
it('exists', function() {
expect(internetExplorer).to.exist();
});
it('allows a custom path to be used as the possiblePath for IE ', function() {
let customPath = 'c:\\my\\custom\\path\\to\\IE';
config.get = function(name) {
if (name === 'browser_paths') {
return {
IE: customPath
};
}
};
browsers = knownBrowsers('win32', config);
internetExplorer = findBrowser(browsers, 'IE');
expect(internetExplorer.possiblePath).to.be.a('string');
expect(internetExplorer.possiblePath).to.equal(customPath);
});
it('allows a custom exe to be used as the possibleExe for IE ', function() {
let customExe = 'iexplore-custom.exe';
config.get = function(name) {
if (name === 'browser_exes') {
return {
IE: customExe
};
}
};
browsers = knownBrowsers('win32', config);
internetExplorer = findBrowser(browsers, 'IE');
expect(internetExplorer.possibleExe).to.be.a('string');
expect(internetExplorer.possibleExe).to.equal(customExe);
});
describe('browser_args', function() {
beforeEach(function() {
setup('IE');
});
afterEach(function() {
setup();
});
it('constructs correct args with browser_args', function() {
expect(internetExplorer.args.call(launcher, config, url)).to.deep.eq([
'--testem'
]);
});
});
});
});
});
|
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// This file is not used to build this module. It is only used during editing
// by the TypeScript language service and during build for verification. `ngc`
// replaces this file with production index.ts when it rewrites private symbol
// names.
export { BrowserXhr, JSONPBackend, JSONPConnection, CookieXSRFStrategy, XHRBackend, XHRConnection, BaseRequestOptions, RequestOptions, BaseResponseOptions, ResponseOptions, ReadyState, RequestMethod, ResponseContentType, ResponseType, Headers, Http, Jsonp, HttpModule, JsonpModule, Connection, ConnectionBackend, XSRFStrategy, Request, Response, QueryEncoder, URLSearchParams, VERSION } from './public_api';
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9wYWNrYWdlcy9odHRwL2luZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7OztBQWFBLHdZQUFjLGNBQWMsQ0FBQyIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogQGxpY2Vuc2VcbiAqIENvcHlyaWdodCBHb29nbGUgSW5jLiBBbGwgUmlnaHRzIFJlc2VydmVkLlxuICpcbiAqIFVzZSBvZiB0aGlzIHNvdXJjZSBjb2RlIGlzIGdvdmVybmVkIGJ5IGFuIE1JVC1zdHlsZSBsaWNlbnNlIHRoYXQgY2FuIGJlXG4gKiBmb3VuZCBpbiB0aGUgTElDRU5TRSBmaWxlIGF0IGh0dHBzOi8vYW5ndWxhci5pby9saWNlbnNlXG4gKi9cblxuLy8gVGhpcyBmaWxlIGlzIG5vdCB1c2VkIHRvIGJ1aWxkIHRoaXMgbW9kdWxlLiBJdCBpcyBvbmx5IHVzZWQgZHVyaW5nIGVkaXRpbmdcbi8vIGJ5IHRoZSBUeXBlU2NyaXB0IGxhbmd1YWdlIHNlcnZpY2UgYW5kIGR1cmluZyBidWlsZCBmb3IgdmVyaWZpY2F0aW9uLiBgbmdjYFxuLy8gcmVwbGFjZXMgdGhpcyBmaWxlIHdpdGggcHJvZHVjdGlvbiBpbmRleC50cyB3aGVuIGl0IHJld3JpdGVzIHByaXZhdGUgc3ltYm9sXG4vLyBuYW1lcy5cblxuZXhwb3J0ICogZnJvbSAnLi9wdWJsaWNfYXBpJztcbiJdfQ== |
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ 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;
/******/ }
/******/ // 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__) {
'use strict';
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(35);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _RadioGroup = __webpack_require__(175);
var _RadioGroup2 = _interopRequireDefault(_RadioGroup);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DATA = [{ label: '苹果', value: 'Apple', checked: false }, { label: '梨', value: 'Pear', checked: false }, { label: '橘', value: 'Orange', checked: false }];
_reactDom2.default.render(_react2.default.createElement(
'div',
null,
_react2.default.createElement(_RadioGroup2.default, {
options: DATA,
name: 'fruit'
})
), document.getElementById('haha'));
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
module.exports = __webpack_require__(2);
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 _assign = __webpack_require__(4);
var ReactChildren = __webpack_require__(5);
var ReactComponent = __webpack_require__(17);
var ReactPureComponent = __webpack_require__(20);
var ReactClass = __webpack_require__(21);
var ReactDOMFactories = __webpack_require__(26);
var ReactElement = __webpack_require__(9);
var ReactPropTypes = __webpack_require__(32);
var ReactVersion = __webpack_require__(33);
var onlyChild = __webpack_require__(34);
var warning = __webpack_require__(11);
var createElement = ReactElement.createElement;
var createFactory = ReactElement.createFactory;
var cloneElement = ReactElement.cloneElement;
if (process.env.NODE_ENV !== 'production') {
var ReactElementValidator = __webpack_require__(28);
createElement = ReactElementValidator.createElement;
createFactory = ReactElementValidator.createFactory;
cloneElement = ReactElementValidator.cloneElement;
}
var __spread = _assign;
if (process.env.NODE_ENV !== 'production') {
var warned = false;
__spread = function () {
process.env.NODE_ENV !== 'production' ? warning(warned, 'React.__spread is deprecated and should not be used. Use ' + 'Object.assign directly or another helper function with similar ' + 'semantics. You may be seeing this warning due to your compiler. ' + 'See https://fb.me/react-spread-deprecation for more details.') : void 0;
warned = true;
return _assign.apply(null, arguments);
};
}
var React = {
// Modern
Children: {
map: ReactChildren.map,
forEach: ReactChildren.forEach,
count: ReactChildren.count,
toArray: ReactChildren.toArray,
only: onlyChild
},
Component: ReactComponent,
PureComponent: ReactPureComponent,
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,
// Deprecated hook for JSX spread, don't use this for anything.
__spread: __spread
};
module.exports = React;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 3 */
/***/ function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
(function () {
try {
cachedSetTimeout = setTimeout;
} catch (e) {
cachedSetTimeout = function () {
throw new Error('setTimeout is not defined');
}
}
try {
cachedClearTimeout = clearTimeout;
} catch (e) {
cachedClearTimeout = function () {
throw new Error('clearTimeout is not defined');
}
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ },
/* 4 */
/***/ function(module, exports) {
'use strict';
/* eslint-disable no-unused-vars */
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (e) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
module.exports = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (Object.getOwnPropertySymbols) {
symbols = Object.getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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__(6);
var ReactElement = __webpack_require__(9);
var emptyFunction = __webpack_require__(12);
var traverseAllChildren = __webpack_require__(14);
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`.
*
* See https://facebook.github.io/react/docs/top-level-api.html#react.children.foreach
*
* 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.key && (!child || child.key !== mappedChild.key) ? 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`.
*
* See https://facebook.github.io/react/docs/top-level-api.html#react.children.map
*
* 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`.
*
* See https://facebook.github.io/react/docs/top-level-api.html#react.children.count
*
* @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.
*
* See https://facebook.github.io/react/docs/top-level-api.html#react.children.toarray
*/
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;
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 _prodInvariant = __webpack_require__(7);
var invariant = __webpack_require__(8);
/**
* 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.') : _prodInvariant('25') : void 0;
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.
*
* @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__(3)))
/***/ },
/* 7 */
/***/ function(module, exports) {
/**
* Copyright (c) 2013-present, 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 reactProdInvariant
*
*/
'use strict';
/**
* WARNING: DO NOT manually require this module.
* This is a replacement for `invariant(...)` used by the error code system
* and will _only_ be required by the corresponding babel pass.
* It always throws.
*/
function reactProdInvariant(code) {
var argCount = arguments.length - 1;
var message = 'Minified React error #' + code + '; visit ' + 'http://facebook.github.io/react/docs/error-decoder.html?invariant=' + code;
for (var argIdx = 0; argIdx < argCount; argIdx++) {
message += '&args[]=' + encodeURIComponent(arguments[argIdx + 1]);
}
message += ' for the full message or use the non-minified dev environment' + ' for full errors and additional helpful warnings.';
var error = new Error(message);
error.name = 'Invariant Violation';
error.framesToPop = 1; // we don't care about reactProdInvariant's own frame
throw error;
}
module.exports = reactProdInvariant;
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright (c) 2013-present, 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.
*
*/
'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__(3)))
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2014-present, 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 _assign = __webpack_require__(4);
var ReactCurrentOwner = __webpack_require__(10);
var warning = __webpack_require__(11);
var canDefineProperty = __webpack_require__(13);
var hasOwnProperty = Object.prototype.hasOwnProperty;
// 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
};
var specialPropKeyWarningShown, specialPropRefWarningShown;
function hasValidRef(config) {
if (process.env.NODE_ENV !== 'production') {
if (hasOwnProperty.call(config, 'ref')) {
var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.ref !== undefined;
}
function hasValidKey(config) {
if (process.env.NODE_ENV !== 'production') {
if (hasOwnProperty.call(config, 'key')) {
var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.key !== undefined;
}
/**
* Factory method to create a new React element. This no longer adheres to
* the class pattern, so do not use new to call it. Also, no instanceof check
* will work. Instead test $$typeof field against Symbol.for('react.element') to check
* if something is a React Element.
*
* @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 = {};
var shadowChildren = Array.isArray(props.children) ? props.children.slice(0) : props.children;
// 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
});
Object.defineProperty(element, '_shadowChildren', {
configurable: false,
enumerable: false,
writable: false,
value: shadowChildren
});
// 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._shadowChildren = shadowChildren;
element._source = source;
}
if (Object.freeze) {
Object.freeze(element.props);
Object.freeze(element);
}
}
return element;
};
/**
* Create and return a new ReactElement of the given type.
* See https://facebook.github.io/react/docs/top-level-api.html#react.createelement
*/
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) {
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(
/* eslint-disable no-proto */
config.__proto__ == null || config.__proto__ === Object.prototype,
/* eslint-enable no-proto */
'React.createElement(...): Expected props argument to be a plain object. ' + 'Properties defined in its prototype chain will be ignored.') : void 0;
}
if (hasValidRef(config)) {
ref = config.ref;
}
if (hasValidKey(config)) {
key = '' + 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 (hasOwnProperty.call(config, 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 (props[propName] === undefined) {
props[propName] = defaultProps[propName];
}
}
}
if (process.env.NODE_ENV !== 'production') {
var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
// Create dummy `key` and `ref` property to `props` to warn users against its use
var warnAboutAccessingKey = function () {
if (!specialPropKeyWarningShown) {
specialPropKeyWarningShown = true;
process.env.NODE_ENV !== 'production' ? warning(false, '%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName) : void 0;
}
return undefined;
};
warnAboutAccessingKey.isReactWarning = true;
var warnAboutAccessingRef = function () {
if (!specialPropRefWarningShown) {
specialPropRefWarningShown = true;
process.env.NODE_ENV !== 'production' ? warning(false, '%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName) : void 0;
}
return undefined;
};
warnAboutAccessingRef.isReactWarning = true;
if (typeof props.$$typeof === 'undefined' || props.$$typeof !== REACT_ELEMENT_TYPE) {
if (!props.hasOwnProperty('key')) {
Object.defineProperty(props, 'key', {
get: warnAboutAccessingKey,
configurable: true
});
}
if (!props.hasOwnProperty('ref')) {
Object.defineProperty(props, 'ref', {
get: warnAboutAccessingRef,
configurable: true
});
}
}
}
return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
};
/**
* Return a function that produces ReactElements of a given type.
* See https://facebook.github.io/react/docs/top-level-api.html#react.createfactory
*/
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;
};
/**
* Clone and return a new ReactElement using element as the starting point.
* See https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement
*/
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 (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(
/* eslint-disable no-proto */
config.__proto__ == null || config.__proto__ === Object.prototype,
/* eslint-enable no-proto */
'React.cloneElement(...): Expected props argument to be a plain object. ' + 'Properties defined in its prototype chain will be ignored.') : void 0;
}
if (hasValidRef(config)) {
// Silently steal the ref from the parent.
ref = config.ref;
owner = ReactCurrentOwner.current;
}
if (hasValidKey(config)) {
key = '' + config.key;
}
// Remaining properties override existing props
var defaultProps;
if (element.type && element.type.defaultProps) {
defaultProps = element.type.defaultProps;
}
for (propName in config) {
if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
if (config[propName] === undefined && defaultProps !== undefined) {
// Resolve default props
props[propName] = defaultProps[propName];
} else {
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);
};
/**
* Verifies the object is a ReactElement.
* See https://facebook.github.io/react/docs/top-level-api.html#react.isvalidelement
* @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;
};
ReactElement.REACT_ELEMENT_TYPE = REACT_ELEMENT_TYPE;
module.exports = ReactElement;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 10 */
/***/ function(module, exports) {
/**
* Copyright 2013-present, 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;
/***/ },
/* 11 */
/***/ 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.
*
*/
'use strict';
var emptyFunction = __webpack_require__(12);
/**
* 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 warning(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__(3)))
/***/ },
/* 12 */
/***/ function(module, exports) {
"use strict";
/**
* Copyright (c) 2013-present, 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.
*
*
*/
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.
*/
var emptyFunction = 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;
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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__(3)))
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 _prodInvariant = __webpack_require__(7);
var ReactCurrentOwner = __webpack_require__(10);
var ReactElement = __webpack_require__(9);
var getIteratorFn = __webpack_require__(15);
var invariant = __webpack_require__(8);
var KeyEscapeUtils = __webpack_require__(16);
var warning = __webpack_require__(11);
var SEPARATOR = '.';
var SUBSEPARATOR = ':';
/**
* TODO: Test that a single child and an array with one item have the same key
* pattern.
*/
var didWarnAboutMaps = false;
/**
* 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) {
// Do some typechecking here since we call this blindly. We want to ensure
// that we don't block potential future ES APIs.
if (component && typeof component === 'object' && component.key != null) {
// Explicit key
return KeyEscapeUtils.escape(component.key);
}
// Implicit key determined by the index in the set
return index.toString(36);
}
/**
* @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') {
var mapsAsChildrenAddendum = '';
if (ReactCurrentOwner.current) {
var mapsAsChildrenOwnerName = ReactCurrentOwner.current.getName();
if (mapsAsChildrenOwnerName) {
mapsAsChildrenAddendum = ' Check the render method of `' + mapsAsChildrenOwnerName + '`.';
}
}
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.%s', mapsAsChildrenAddendum) : void 0;
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 + KeyEscapeUtils.escape(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) : _prodInvariant('31', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : void 0;
}
}
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__(3)))
/***/ },
/* 15 */
/***/ function(module, exports) {
/**
* Copyright 2013-present, 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
*
*/
'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;
/***/ },
/* 16 */
/***/ function(module, exports) {
/**
* Copyright 2013-present, 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 KeyEscapeUtils
*
*/
'use strict';
/**
* Escape and wrap key so it is safe to use as a reactid
*
* @param {string} key to be escaped.
* @return {string} the escaped key.
*/
function escape(key) {
var escapeRegex = /[=:]/g;
var escaperLookup = {
'=': '=0',
':': '=2'
};
var escapedString = ('' + key).replace(escapeRegex, function (match) {
return escaperLookup[match];
});
return '$' + escapedString;
}
/**
* Unescape and unwrap key for human-readable display
*
* @param {string} key to unescape.
* @return {string} the unescaped key.
*/
function unescape(key) {
var unescapeRegex = /(=0|=2)/g;
var unescaperLookup = {
'=0': '=',
'=2': ':'
};
var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1);
return ('' + keySubstring).replace(unescapeRegex, function (match) {
return unescaperLookup[match];
});
}
var KeyEscapeUtils = {
escape: escape,
unescape: unescape
};
module.exports = KeyEscapeUtils;
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 _prodInvariant = __webpack_require__(7);
var ReactNoopUpdateQueue = __webpack_require__(18);
var canDefineProperty = __webpack_require__(13);
var emptyObject = __webpack_require__(19);
var invariant = __webpack_require__(8);
var warning = __webpack_require__(11);
/**
* 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.') : _prodInvariant('85') : void 0;
this.updater.enqueueSetState(this, partialState);
if (callback) {
this.updater.enqueueCallback(this, callback, 'setState');
}
};
/**
* 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, 'forceUpdate');
}
};
/**
* 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 = {
isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],
replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).']
};
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]) : void 0;
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__(3)))
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2015-present, 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__(11);
function warnNoop(publicInstance, callerName) {
if (process.env.NODE_ENV !== 'production') {
var constructor = publicInstance.constructor;
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, constructor && (constructor.displayName || constructor.name) || 'ReactClass') : void 0;
}
}
/**
* 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) {
warnNoop(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) {
warnNoop(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) {
warnNoop(publicInstance, 'setState');
}
};
module.exports = ReactNoopUpdateQueue;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright (c) 2013-present, 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.
*
*/
'use strict';
var emptyObject = {};
if (process.env.NODE_ENV !== 'production') {
Object.freeze(emptyObject);
}
module.exports = emptyObject;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 20 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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 ReactPureComponent
*/
'use strict';
var _assign = __webpack_require__(4);
var ReactComponent = __webpack_require__(17);
var ReactNoopUpdateQueue = __webpack_require__(18);
var emptyObject = __webpack_require__(19);
/**
* Base class helpers for the updating state of a component.
*/
function ReactPureComponent(props, context, updater) {
// Duplicated from ReactComponent.
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;
}
function ComponentDummy() {}
ComponentDummy.prototype = ReactComponent.prototype;
ReactPureComponent.prototype = new ComponentDummy();
ReactPureComponent.prototype.constructor = ReactPureComponent;
// Avoid an extra prototype jump for these methods.
_assign(ReactPureComponent.prototype, ReactComponent.prototype);
ReactPureComponent.prototype.isPureReactComponent = true;
module.exports = ReactPureComponent;
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 _prodInvariant = __webpack_require__(7),
_assign = __webpack_require__(4);
var ReactComponent = __webpack_require__(17);
var ReactElement = __webpack_require__(9);
var ReactPropTypeLocations = __webpack_require__(22);
var ReactPropTypeLocationNames = __webpack_require__(24);
var ReactNoopUpdateQueue = __webpack_require__(18);
var emptyObject = __webpack_require__(19);
var invariant = __webpack_require__(8);
var keyMirror = __webpack_require__(23);
var keyOf = __webpack_require__(25);
var warning = __webpack_require__(11);
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 = [];
/**
* Composite components are higher-level components that compose other composite
* or host 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 only 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) : void 0;
}
}
}
function validateMethodOverride(isAlreadyDefined, 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) : _prodInvariant('73', name) : void 0;
}
// Disallow defining methods more than once unless explicitly allowed.
if (isAlreadyDefined) {
!(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) : _prodInvariant('74', name) : void 0;
}
}
/**
* Mixin helper which handles policy validation and reserved
* specification keys when building React classes.
*/
function mixSpecIntoComponent(Constructor, spec) {
if (!spec) {
if (process.env.NODE_ENV !== 'production') {
var typeofSpec = typeof spec;
var isMixinValid = typeofSpec === 'object' && spec !== null;
process.env.NODE_ENV !== 'production' ? warning(isMixinValid, '%s: You\'re attempting to include a mixin that is either null ' + 'or not an object. Check the mixins included by the component, ' + 'as well as any mixins they include themselves. ' + 'Expected object but got %s.', Constructor.displayName || 'ReactClass', spec === null ? null : typeofSpec) : void 0;
}
return;
}
!(typeof spec !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to use a component class or function as a mixin. Instead, just use a regular object.') : _prodInvariant('75') : void 0;
!!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.') : _prodInvariant('76') : void 0;
var proto = Constructor.prototype;
var autoBindPairs = proto.__reactAutoBindPairs;
// 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];
var isAlreadyDefined = proto.hasOwnProperty(name);
validateMethodOverride(isAlreadyDefined, 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 isFunction = typeof property === 'function';
var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false;
if (shouldAutoBind) {
autoBindPairs.push(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) : _prodInvariant('77', specPolicy, name) : void 0;
// 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) : _prodInvariant('78', name) : void 0;
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) : _prodInvariant('79', name) : void 0;
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.') : _prodInvariant('80') : void 0;
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) : _prodInvariant('81', key) : void 0;
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;
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) : void 0;
} 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) : void 0;
return boundMethod;
}
var reboundMethod = _bind.apply(boundMethod, arguments);
reboundMethod.__reactBoundContext = component;
reboundMethod.__reactBoundMethod = method;
reboundMethod.__reactBoundArguments = args;
return reboundMethod;
};
}
return boundMethod;
}
/**
* Binds all auto-bound methods in a component.
*
* @param {object} component Component whose method is going to be bound.
*/
function bindAutoBindMethods(component) {
var pairs = component.__reactAutoBindPairs;
for (var i = 0; i < pairs.length; i += 2) {
var autoBindKey = pairs[i];
var method = pairs[i + 1];
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, 'replaceState');
}
},
/**
* 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);
}
};
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.
* See https://facebook.github.io/react/docs/top-level-api.html#react.createclass
*
* @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 gets 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') : void 0;
}
// Wire up auto-binding
if (this.__reactAutoBindPairs.length) {
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 (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') : _prodInvariant('82', Constructor.displayName || 'ReactCompositeComponent') : void 0;
this.state = initialState;
};
Constructor.prototype = new ReactClassComponent();
Constructor.prototype.constructor = Constructor;
Constructor.prototype.__reactAutoBindPairs = [];
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.') : _prodInvariant('83') : void 0;
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') : void 0;
process.env.NODE_ENV !== 'production' ? warning(!Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component') : void 0;
}
// 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__(3)))
/***/ },
/* 22 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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__(23);
var ReactPropTypeLocations = keyMirror({
prop: null,
context: null,
childContext: null
});
module.exports = ReactPropTypeLocations;
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright (c) 2013-present, 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
*/
'use strict';
var invariant = __webpack_require__(8);
/**
* 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 keyMirror(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) : void 0;
for (key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
ret[key] = key;
}
return ret;
};
module.exports = keyMirror;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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__(3)))
/***/ },
/* 25 */
/***/ function(module, exports) {
"use strict";
/**
* Copyright (c) 2013-present, 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.
*
*/
/**
* 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.
*/
var keyOf = function keyOf(oneKeyObj) {
var key;
for (key in oneKeyObj) {
if (!oneKeyObj.hasOwnProperty(key)) {
continue;
}
return key;
}
return null;
};
module.exports = keyOf;
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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
*/
'use strict';
var ReactElement = __webpack_require__(9);
var mapObject = __webpack_require__(27);
/**
* 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') {
var ReactElementValidator = __webpack_require__(28);
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__(3)))
/***/ },
/* 27 */
/***/ function(module, exports) {
/**
* Copyright (c) 2013-present, 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.
*
*/
'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;
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2014-present, 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 ReactCurrentOwner = __webpack_require__(10);
var ReactComponentTreeDevtool = __webpack_require__(29);
var ReactElement = __webpack_require__(9);
var ReactPropTypeLocations = __webpack_require__(22);
var checkReactTypeSpec = __webpack_require__(30);
var canDefineProperty = __webpack_require__(13);
var getIteratorFn = __webpack_require__(15);
var warning = __webpack_require__(11);
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 = {};
function getCurrentComponentErrorInfo(parentType) {
var info = getDeclarationErrorAddendum();
if (!info) {
var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
if (parentName) {
info = ' Check the top-level render call using <' + parentName + '>.';
}
}
return info;
}
/**
* 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. Error statuses are cached so a warning
* will only be shown once.
*
* @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 memoizer = ownerHasKeyUseWarning.uniqueKey || (ownerHasKeyUseWarning.uniqueKey = {});
var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
if (memoizer[currentComponentErrorInfo]) {
return;
}
memoizer[currentComponentErrorInfo] = true;
// 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.
var childOwner = '';
if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
// Give the component that originally created this child.
childOwner = ' It was passed a child from ' + element._owner.getName() + '.';
}
process.env.NODE_ENV !== 'production' ? warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s See https://fb.me/react-warning-keys for more information.%s', currentComponentErrorInfo, childOwner, ReactComponentTreeDevtool.getCurrentStackAddendum(element)) : void 0;
}
/**
* 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);
}
}
}
}
}
}
/**
* 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) {
checkReactTypeSpec(componentClass.propTypes, element.props, ReactPropTypeLocations.prop, name, element, null);
}
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.') : void 0;
}
}
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()) : void 0;
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.') : void 0;
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__(3)))
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2016-present, 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 ReactComponentTreeDevtool
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var ReactCurrentOwner = __webpack_require__(10);
var invariant = __webpack_require__(8);
var warning = __webpack_require__(11);
var tree = {};
var unmountedIDs = {};
var rootIDs = {};
function updateTree(id, update) {
if (!tree[id]) {
tree[id] = {
element: null,
parentID: null,
ownerID: null,
text: null,
childIDs: [],
displayName: 'Unknown',
isMounted: false,
updateCount: 0
};
}
update(tree[id]);
}
function purgeDeep(id) {
var item = tree[id];
if (item) {
var childIDs = item.childIDs;
delete tree[id];
childIDs.forEach(purgeDeep);
}
}
function describeComponentFrame(name, source, ownerName) {
return '\n in ' + name + (source ? ' (at ' + source.fileName.replace(/^.*[\\\/]/, '') + ':' + source.lineNumber + ')' : ownerName ? ' (created by ' + ownerName + ')' : '');
}
function describeID(id) {
var name = ReactComponentTreeDevtool.getDisplayName(id);
var element = ReactComponentTreeDevtool.getElement(id);
var ownerID = ReactComponentTreeDevtool.getOwnerID(id);
var ownerName;
if (ownerID) {
ownerName = ReactComponentTreeDevtool.getDisplayName(ownerID);
}
process.env.NODE_ENV !== 'production' ? warning(element, 'ReactComponentTreeDevtool: Missing React element for debugID %s when ' + 'building stack', id) : void 0;
return describeComponentFrame(name, element && element._source, ownerName);
}
var ReactComponentTreeDevtool = {
onSetDisplayName: function (id, displayName) {
updateTree(id, function (item) {
return item.displayName = displayName;
});
},
onSetChildren: function (id, nextChildIDs) {
updateTree(id, function (item) {
item.childIDs = nextChildIDs;
nextChildIDs.forEach(function (nextChildID) {
var nextChild = tree[nextChildID];
!nextChild ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected devtool events to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('68') : void 0;
!(nextChild.displayName != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected onSetDisplayName() to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('69') : void 0;
!(nextChild.childIDs != null || nextChild.text != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected onSetChildren() or onSetText() to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('70') : void 0;
!nextChild.isMounted ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected onMountComponent() to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('71') : void 0;
if (nextChild.parentID == null) {
nextChild.parentID = id;
// TODO: This shouldn't be necessary but mounting a new root during in
// componentWillMount currently causes not-yet-mounted components to
// be purged from our tree data so their parent ID is missing.
}
!(nextChild.parentID === id) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected onSetParent() and onSetChildren() to be consistent (%s has parents %s and %s).', nextChildID, nextChild.parentID, id) : _prodInvariant('72', nextChildID, nextChild.parentID, id) : void 0;
});
});
},
onSetOwner: function (id, ownerID) {
updateTree(id, function (item) {
return item.ownerID = ownerID;
});
},
onSetParent: function (id, parentID) {
updateTree(id, function (item) {
return item.parentID = parentID;
});
},
onSetText: function (id, text) {
updateTree(id, function (item) {
return item.text = text;
});
},
onBeforeMountComponent: function (id, element) {
updateTree(id, function (item) {
return item.element = element;
});
},
onBeforeUpdateComponent: function (id, element) {
updateTree(id, function (item) {
return item.element = element;
});
},
onMountComponent: function (id) {
updateTree(id, function (item) {
return item.isMounted = true;
});
},
onMountRootComponent: function (id) {
rootIDs[id] = true;
},
onUpdateComponent: function (id) {
updateTree(id, function (item) {
return item.updateCount++;
});
},
onUnmountComponent: function (id) {
updateTree(id, function (item) {
return item.isMounted = false;
});
unmountedIDs[id] = true;
delete rootIDs[id];
},
purgeUnmountedComponents: function () {
if (ReactComponentTreeDevtool._preventPurging) {
// Should only be used for testing.
return;
}
for (var id in unmountedIDs) {
purgeDeep(id);
}
unmountedIDs = {};
},
isMounted: function (id) {
var item = tree[id];
return item ? item.isMounted : false;
},
getCurrentStackAddendum: function (topElement) {
var info = '';
if (topElement) {
var type = topElement.type;
var name = typeof type === 'function' ? type.displayName || type.name : type;
var owner = topElement._owner;
info += describeComponentFrame(name || 'Unknown', topElement._source, owner && owner.getName());
}
var currentOwner = ReactCurrentOwner.current;
var id = currentOwner && currentOwner._debugID;
info += ReactComponentTreeDevtool.getStackAddendumByID(id);
return info;
},
getStackAddendumByID: function (id) {
var info = '';
while (id) {
info += describeID(id);
id = ReactComponentTreeDevtool.getParentID(id);
}
return info;
},
getChildIDs: function (id) {
var item = tree[id];
return item ? item.childIDs : [];
},
getDisplayName: function (id) {
var item = tree[id];
return item ? item.displayName : 'Unknown';
},
getElement: function (id) {
var item = tree[id];
return item ? item.element : null;
},
getOwnerID: function (id) {
var item = tree[id];
return item ? item.ownerID : null;
},
getParentID: function (id) {
var item = tree[id];
return item ? item.parentID : null;
},
getSource: function (id) {
var item = tree[id];
var element = item ? item.element : null;
var source = element != null ? element._source : null;
return source;
},
getText: function (id) {
var item = tree[id];
return item ? item.text : null;
},
getUpdateCount: function (id) {
var item = tree[id];
return item ? item.updateCount : 0;
},
getRootIDs: function () {
return Object.keys(rootIDs);
},
getRegisteredIDs: function () {
return Object.keys(tree);
}
};
module.exports = ReactComponentTreeDevtool;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 30 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 checkReactTypeSpec
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var ReactPropTypeLocationNames = __webpack_require__(24);
var ReactPropTypesSecret = __webpack_require__(31);
var invariant = __webpack_require__(8);
var warning = __webpack_require__(11);
var ReactComponentTreeDevtool;
if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test') {
// Temporary hack.
// Inline requires don't work well with Jest:
// https://github.com/facebook/react/issues/7240
// Remove the inline requires when we don't need them anymore:
// https://github.com/facebook/react/pull/7178
ReactComponentTreeDevtool = __webpack_require__(29);
}
var loggedTypeFailures = {};
/**
* Assert that the values match with the type specs.
* Error messages are memorized and will only be shown once.
*
* @param {object} typeSpecs Map of name to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @param {string} componentName Name of the component for error messages.
* @param {?object} element The React element that is being type-checked
* @param {?number} debugID The React component instance that is being type-checked
* @private
*/
function checkReactTypeSpec(typeSpecs, values, location, componentName, element, debugID) {
for (var typeSpecName in typeSpecs) {
if (typeSpecs.hasOwnProperty(typeSpecName)) {
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 typeSpecs[typeSpecName] === '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], typeSpecName) : _prodInvariant('84', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : void 0;
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
} 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], typeSpecName, typeof error) : void 0;
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 componentStackInfo = '';
if (process.env.NODE_ENV !== 'production') {
if (!ReactComponentTreeDevtool) {
ReactComponentTreeDevtool = __webpack_require__(29);
}
if (debugID !== null) {
componentStackInfo = ReactComponentTreeDevtool.getStackAddendumByID(debugID);
} else if (element !== null) {
componentStackInfo = ReactComponentTreeDevtool.getCurrentStackAddendum(element);
}
}
process.env.NODE_ENV !== 'production' ? warning(false, 'Failed %s type: %s%s', location, error.message, componentStackInfo) : void 0;
}
}
}
}
module.exports = checkReactTypeSpec;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 31 */
/***/ function(module, exports) {
/**
* Copyright 2013-present, 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 ReactPropTypesSecret
*/
'use strict';
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
module.exports = ReactPropTypesSecret;
/***/ },
/* 32 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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__(9);
var ReactPropTypeLocationNames = __webpack_require__(24);
var ReactPropTypesSecret = __webpack_require__(31);
var emptyFunction = __webpack_require__(12);
var getIteratorFn = __webpack_require__(15);
var warning = __webpack_require__(11);
/**
* 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'),
symbol: createPrimitiveTypeChecker('symbol'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker
};
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
/*eslint-disable no-self-compare*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/*eslint-enable no-self-compare*/
function createChainableTypeChecker(validate) {
if (process.env.NODE_ENV !== 'production') {
var manualPropTypeCallCache = {};
}
function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (process.env.NODE_ENV !== 'production') {
if (secret !== ReactPropTypesSecret && typeof console !== 'undefined') {
var cacheKey = componentName + ':' + propName;
if (!manualPropTypeCallCache[cacheKey]) {
process.env.NODE_ENV !== 'production' ? warning(false, 'You are manually calling a React.PropTypes validation ' + 'function for the `%s` prop on `%s`. This is deprecated ' + 'and will not work in the next major version. You may be ' + 'seeing this warning due to a third-party PropTypes library. ' + 'See https://fb.me/react-warning-dont-call-proptypes for details.', propFullName, componentName) : void 0;
manualPropTypeCallCache[cacheKey] = true;
}
}
}
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, secret) {
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) {
if (typeof typeChecker !== 'function') {
return new Error('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
}
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 + ']', ReactPropTypesSecret);
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!ReactElement.isValidElement(propValue)) {
var locationName = ReactPropTypeLocationNames[location];
var propType = getPropType(propValue);
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` 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)) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0;
return emptyFunction.thatReturnsNull;
}
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (is(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) {
if (typeof typeChecker !== 'function') {
return new Error('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
}
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, ReactPropTypesSecret);
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0;
return emptyFunction.thatReturnsNull;
}
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, ReactPropTypesSecret) == 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, ReactPropTypesSecret);
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;
}
}
function isSymbol(propType, propValue) {
// Native Symbol.
if (propType === 'symbol') {
return true;
}
// 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
if (propValue['@@toStringTag'] === 'Symbol') {
return true;
}
// Fallback for non-spec compliant Symbols which are polyfilled.
if (typeof Symbol === 'function' && propValue instanceof Symbol) {
return true;
}
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';
}
if (isSymbol(propType, propValue)) {
return 'symbol';
}
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;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 33 */
/***/ function(module, exports) {
/**
* Copyright 2013-present, 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 = '15.3.0';
/***/ },
/* 34 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 _prodInvariant = __webpack_require__(7);
var ReactElement = __webpack_require__(9);
var invariant = __webpack_require__(8);
/**
* Returns the first child in a collection of children and verifies that there
* is only one child in the collection.
*
* See https://facebook.github.io/react/docs/top-level-api.html#react.children.only
*
* 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 {ReactElement} The first and only `ReactElement` 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.') : _prodInvariant('23') : void 0;
return children;
}
module.exports = onlyChild;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
module.exports = __webpack_require__(36);
/***/ },
/* 36 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 ReactDOMComponentTree = __webpack_require__(37);
var ReactDefaultInjection = __webpack_require__(40);
var ReactMount = __webpack_require__(167);
var ReactReconciler = __webpack_require__(60);
var ReactUpdates = __webpack_require__(57);
var ReactVersion = __webpack_require__(33);
var findDOMNode = __webpack_require__(172);
var getHostComponentFromComposite = __webpack_require__(173);
var renderSubtreeIntoContainer = __webpack_require__(174);
var warning = __webpack_require__(11);
ReactDefaultInjection.inject();
var ReactDOM = {
findDOMNode: findDOMNode,
render: ReactMount.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({
ComponentTree: {
getClosestInstanceFromNode: ReactDOMComponentTree.getClosestInstanceFromNode,
getNodeFromInstance: function (inst) {
// inst is an internal instance (but could be a composite)
if (inst._renderedComponent) {
inst = getHostComponentFromComposite(inst);
}
if (inst) {
return ReactDOMComponentTree.getNodeFromInstance(inst);
} else {
return null;
}
}
},
Mount: ReactMount,
Reconciler: ReactReconciler
});
}
if (process.env.NODE_ENV !== 'production') {
var ExecutionEnvironment = __webpack_require__(50);
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) {
// Firefox does not have the issue with devtools loaded over file://
var showFileUrlMessage = window.location.protocol.indexOf('http') === -1 && navigator.userAgent.indexOf('Firefox') === -1;
console.debug('Download the React DevTools ' + (showFileUrlMessage ? 'and use an HTTP server (instead of a file: URL) ' : '') + 'for a better development experience: ' + 'https://fb.me/react-devtools');
}
}
var testFunc = function testFn() {};
process.env.NODE_ENV !== 'production' ? warning((testFunc.name || testFunc.toString()).indexOf('testFn') !== -1, 'It looks like you\'re using a minified copy of the development build ' + 'of React. When deploying React apps to production, make sure to use ' + 'the production build which skips development warnings and is faster. ' + 'See https://fb.me/react-minification for more details.') : void 0;
// 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" />') : void 0;
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];
for (var i = 0; i < expectedFeatures.length; i++) {
if (!expectedFeatures[i]) {
process.env.NODE_ENV !== 'production' ? warning(false, 'One or more ES5 shims expected by React are not available: ' + 'https://fb.me/react-warning-polyfills') : void 0;
break;
}
}
}
}
module.exports = ReactDOM;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 37 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 ReactDOMComponentTree
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var DOMProperty = __webpack_require__(38);
var ReactDOMComponentFlags = __webpack_require__(39);
var invariant = __webpack_require__(8);
var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME;
var Flags = ReactDOMComponentFlags;
var internalInstanceKey = '__reactInternalInstance$' + Math.random().toString(36).slice(2);
/**
* Drill down (through composites and empty components) until we get a host or
* host text component.
*
* This is pretty polymorphic but unavoidable with the current structure we have
* for `_renderedChildren`.
*/
function getRenderedHostOrTextFromComponent(component) {
var rendered;
while (rendered = component._renderedComponent) {
component = rendered;
}
return component;
}
/**
* Populate `_hostNode` on the rendered host/text component with the given
* DOM node. The passed `inst` can be a composite.
*/
function precacheNode(inst, node) {
var hostInst = getRenderedHostOrTextFromComponent(inst);
hostInst._hostNode = node;
node[internalInstanceKey] = hostInst;
}
function uncacheNode(inst) {
var node = inst._hostNode;
if (node) {
delete node[internalInstanceKey];
inst._hostNode = null;
}
}
/**
* Populate `_hostNode` on each child of `inst`, assuming that the children
* match up with the DOM (element) children of `node`.
*
* We cache entire levels at once to avoid an n^2 problem where we access the
* children of a node sequentially and have to walk from the start to our target
* node every time.
*
* Since we update `_renderedChildren` and the actual DOM at (slightly)
* different times, we could race here and see a newer `_renderedChildren` than
* the DOM nodes we see. To avoid this, ReactMultiChild calls
* `prepareToManageChildren` before we change `_renderedChildren`, at which
* time the container's child nodes are always cached (until it unmounts).
*/
function precacheChildNodes(inst, node) {
if (inst._flags & Flags.hasCachedChildNodes) {
return;
}
var children = inst._renderedChildren;
var childNode = node.firstChild;
outer: for (var name in children) {
if (!children.hasOwnProperty(name)) {
continue;
}
var childInst = children[name];
var childID = getRenderedHostOrTextFromComponent(childInst)._domID;
if (childID == null) {
// We're currently unmounting this child in ReactMultiChild; skip it.
continue;
}
// We assume the child nodes are in the same order as the child instances.
for (; childNode !== null; childNode = childNode.nextSibling) {
if (childNode.nodeType === 1 && childNode.getAttribute(ATTR_NAME) === String(childID) || childNode.nodeType === 8 && childNode.nodeValue === ' react-text: ' + childID + ' ' || childNode.nodeType === 8 && childNode.nodeValue === ' react-empty: ' + childID + ' ') {
precacheNode(childInst, childNode);
continue outer;
}
}
// We reached the end of the DOM children without finding an ID match.
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Unable to find element with ID %s.', childID) : _prodInvariant('32', childID) : void 0;
}
inst._flags |= Flags.hasCachedChildNodes;
}
/**
* Given a DOM node, return the closest ReactDOMComponent or
* ReactDOMTextComponent instance ancestor.
*/
function getClosestInstanceFromNode(node) {
if (node[internalInstanceKey]) {
return node[internalInstanceKey];
}
// Walk up the tree until we find an ancestor whose instance we have cached.
var parents = [];
while (!node[internalInstanceKey]) {
parents.push(node);
if (node.parentNode) {
node = node.parentNode;
} else {
// Top of the tree. This node must not be part of a React tree (or is
// unmounted, potentially).
return null;
}
}
var closest;
var inst;
for (; node && (inst = node[internalInstanceKey]); node = parents.pop()) {
closest = inst;
if (parents.length) {
precacheChildNodes(inst, node);
}
}
return closest;
}
/**
* Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent
* instance, or null if the node was not rendered by this React.
*/
function getInstanceFromNode(node) {
var inst = getClosestInstanceFromNode(node);
if (inst != null && inst._hostNode === node) {
return inst;
} else {
return null;
}
}
/**
* Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding
* DOM node.
*/
function getNodeFromInstance(inst) {
// Without this first invariant, passing a non-DOM-component triggers the next
// invariant for a missing parent, which is super confusing.
!(inst._hostNode !== undefined) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0;
if (inst._hostNode) {
return inst._hostNode;
}
// Walk up the tree until we find an ancestor whose DOM node we have cached.
var parents = [];
while (!inst._hostNode) {
parents.push(inst);
!inst._hostParent ? process.env.NODE_ENV !== 'production' ? invariant(false, 'React DOM tree root should always have a node reference.') : _prodInvariant('34') : void 0;
inst = inst._hostParent;
}
// Now parents contains each ancestor that does *not* have a cached native
// node, and `inst` is the deepest ancestor that does.
for (; parents.length; inst = parents.pop()) {
precacheChildNodes(inst, inst._hostNode);
}
return inst._hostNode;
}
var ReactDOMComponentTree = {
getClosestInstanceFromNode: getClosestInstanceFromNode,
getInstanceFromNode: getInstanceFromNode,
getNodeFromInstance: getNodeFromInstance,
precacheChildNodes: precacheChildNodes,
precacheNode: precacheNode,
uncacheNode: uncacheNode
};
module.exports = ReactDOMComponentTree;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 38 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var invariant = __webpack_require__(8);
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_PROPERTY: 0x1,
HAS_BOOLEAN_VALUE: 0x4,
HAS_NUMERIC_VALUE: 0x8,
HAS_POSITIVE_NUMERIC_VALUE: 0x10 | 0x8,
HAS_OVERLOADED_BOOLEAN_VALUE: 0x20,
/**
* 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) : _prodInvariant('48', propName) : void 0;
var lowerCased = propName.toLowerCase();
var propConfig = Properties[propName];
var propertyInfo = {
attributeName: lowerCased,
attributeNamespace: null,
propertyName: propName,
mutationMethod: null,
mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY),
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.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) : _prodInvariant('50', propName) : void 0;
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;
}
}
};
/* eslint-disable max-len */
var ATTRIBUTE_NAME_START_CHAR = ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD';
/* eslint-enable max-len */
/**
* 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',
ROOT_ATTRIBUTE_NAME: 'data-reactroot',
ATTRIBUTE_NAME_START_CHAR: ATTRIBUTE_NAME_START_CHAR,
ATTRIBUTE_NAME_CHAR: ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040',
/**
* 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.
* mustUseProperty:
* Whether the property must be accessed and mutated as an object property.
* 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;
},
injection: DOMPropertyInjection
};
module.exports = DOMProperty;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 39 */
/***/ function(module, exports) {
/**
* Copyright 2015-present, 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 ReactDOMComponentFlags
*/
'use strict';
var ReactDOMComponentFlags = {
hasCachedChildNodes: 1 << 0
};
module.exports = ReactDOMComponentFlags;
/***/ },
/* 40 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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__(41);
var ChangeEventPlugin = __webpack_require__(56);
var DefaultEventPluginOrder = __webpack_require__(74);
var EnterLeaveEventPlugin = __webpack_require__(75);
var HTMLDOMPropertyConfig = __webpack_require__(80);
var ReactComponentBrowserEnvironment = __webpack_require__(81);
var ReactDOMComponent = __webpack_require__(95);
var ReactDOMComponentTree = __webpack_require__(37);
var ReactDOMEmptyComponent = __webpack_require__(138);
var ReactDOMTreeTraversal = __webpack_require__(139);
var ReactDOMTextComponent = __webpack_require__(140);
var ReactDefaultBatchingStrategy = __webpack_require__(141);
var ReactEventListener = __webpack_require__(142);
var ReactInjection = __webpack_require__(145);
var ReactReconcileTransaction = __webpack_require__(146);
var SVGDOMPropertyConfig = __webpack_require__(154);
var SelectEventPlugin = __webpack_require__(155);
var SimpleEventPlugin = __webpack_require__(156);
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.EventPluginUtils.injectComponentTree(ReactDOMComponentTree);
ReactInjection.EventPluginUtils.injectTreeTraversal(ReactDOMTreeTraversal);
/**
* 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.HostComponent.injectGenericComponentClass(ReactDOMComponent);
ReactInjection.HostComponent.injectTextComponentClass(ReactDOMTextComponent);
ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig);
ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig);
ReactInjection.EmptyComponent.injectEmptyComponentFactory(function (instantiate) {
return new ReactDOMEmptyComponent(instantiate);
});
ReactInjection.Updates.injectReconcileTransaction(ReactReconcileTransaction);
ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy);
ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment);
}
module.exports = {
inject: inject
};
/***/ },
/* 41 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present 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
*/
'use strict';
var EventConstants = __webpack_require__(42);
var EventPropagators = __webpack_require__(43);
var ExecutionEnvironment = __webpack_require__(50);
var FallbackCompositionState = __webpack_require__(51);
var SyntheticCompositionEvent = __webpack_require__(53);
var SyntheticInputEvent = __webpack_require__(55);
var keyOf = __webpack_require__(25);
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;
/**
* @return {?object} A SyntheticCompositionEvent.
*/
function extractCompositionEvent(topLevelType, targetInst, 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(nativeEventTarget);
} else if (eventType === eventTypes.compositionEnd) {
if (currentComposition) {
fallbackData = currentComposition.getData();
}
}
}
var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, 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.
*
* @return {?object} A SyntheticInputEvent.
*/
function extractBeforeInputEvent(topLevelType, targetInst, 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, targetInst, 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,
extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
return [extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget), extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget)];
}
};
module.exports = BeforeInputEventPlugin;
/***/ },
/* 42 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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__(23);
var PropagationPhases = keyMirror({ bubbled: null, captured: null });
/**
* Types of raw signals from the browser caught at the top level.
*/
var topLevelTypes = keyMirror({
topAbort: null,
topAnimationEnd: null,
topAnimationIteration: null,
topAnimationStart: 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,
topInvalid: 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,
topTransitionEnd: null,
topVolumeChange: null,
topWaiting: null,
topWheel: null
});
var EventConstants = {
topLevelTypes: topLevelTypes,
PropagationPhases: PropagationPhases
};
module.exports = EventConstants;
/***/ },
/* 43 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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__(42);
var EventPluginHub = __webpack_require__(44);
var EventPluginUtils = __webpack_require__(46);
var accumulateInto = __webpack_require__(48);
var forEachAccumulated = __webpack_require__(49);
var warning = __webpack_require__(11);
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(inst, event, propagationPhase) {
var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];
return getListener(inst, 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(inst, upwards, event) {
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(inst, 'Dispatching inst must not be null') : void 0;
}
var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured;
var listener = listenerAtPhase(inst, event, phase);
if (listener) {
event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
}
}
/**
* 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) {
EventPluginUtils.traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
}
}
/**
* Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID.
*/
function accumulateTwoPhaseDispatchesSingleSkipTarget(event) {
if (event && event.dispatchConfig.phasedRegistrationNames) {
var targetInst = event._targetInst;
var parentInst = targetInst ? EventPluginUtils.getParentInstance(targetInst) : null;
EventPluginUtils.traverseTwoPhase(parentInst, 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(inst, ignoredDirection, event) {
if (event && event.dispatchConfig.registrationName) {
var registrationName = event.dispatchConfig.registrationName;
var listener = getListener(inst, registrationName);
if (listener) {
event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
}
}
}
/**
* Accumulates dispatches on an `SyntheticEvent`, but only for the
* `dispatchMarker`.
* @param {SyntheticEvent} event
*/
function accumulateDirectDispatchesSingle(event) {
if (event && event.dispatchConfig.registrationName) {
accumulateDispatches(event._targetInst, null, event);
}
}
function accumulateTwoPhaseDispatches(events) {
forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
}
function accumulateTwoPhaseDispatchesSkipTarget(events) {
forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget);
}
function accumulateEnterLeaveDispatches(leave, enter, from, to) {
EventPluginUtils.traverseEnterLeave(from, to, 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__(3)))
/***/ },
/* 44 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 _prodInvariant = __webpack_require__(7);
var EventPluginRegistry = __webpack_require__(45);
var EventPluginUtils = __webpack_require__(46);
var ReactErrorUtils = __webpack_require__(47);
var accumulateInto = __webpack_require__(48);
var forEachAccumulated = __webpack_require__(49);
var invariant = __webpack_require__(8);
/**
* 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);
};
var getDictionaryKey = function (inst) {
return '.' + inst._rootNodeID;
};
/**
* 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 {array} InjectedEventPluginOrder
* @public
*/
injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder,
/**
* @param {object} injectedNamesToPlugins Map from names to plugin modules.
*/
injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName
},
/**
* Stores `listener` at `listenerBank[registrationName][key]`. Is idempotent.
*
* @param {object} inst The instance, which is the source of events.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @param {function} listener The callback to store.
*/
putListener: function (inst, 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) : _prodInvariant('94', registrationName, typeof listener) : void 0;
var key = getDictionaryKey(inst);
var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {});
bankForRegistrationName[key] = listener;
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
if (PluginModule && PluginModule.didPutListener) {
PluginModule.didPutListener(inst, registrationName, listener);
}
},
/**
* @param {object} inst The instance, which is the source of events.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @return {?function} The stored callback.
*/
getListener: function (inst, registrationName) {
var bankForRegistrationName = listenerBank[registrationName];
var key = getDictionaryKey(inst);
return bankForRegistrationName && bankForRegistrationName[key];
},
/**
* Deletes a listener from the registration bank.
*
* @param {object} inst The instance, which is the source of events.
* @param {string} registrationName Name of listener (e.g. `onClick`).
*/
deleteListener: function (inst, registrationName) {
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
if (PluginModule && PluginModule.willDeleteListener) {
PluginModule.willDeleteListener(inst, registrationName);
}
var bankForRegistrationName = listenerBank[registrationName];
// TODO: This should never be null -- when is it?
if (bankForRegistrationName) {
var key = getDictionaryKey(inst);
delete bankForRegistrationName[key];
}
},
/**
* Deletes all listeners for the DOM element with the supplied ID.
*
* @param {object} inst The instance, which is the source of events.
*/
deleteAllListeners: function (inst) {
var key = getDictionaryKey(inst);
for (var registrationName in listenerBank) {
if (!listenerBank.hasOwnProperty(registrationName)) {
continue;
}
if (!listenerBank[registrationName][key]) {
continue;
}
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
if (PluginModule && PluginModule.willDeleteListener) {
PluginModule.willDeleteListener(inst, registrationName);
}
delete listenerBank[registrationName][key];
}
},
/**
* Allows registered plugins an opportunity to extract events from top-level
* native browser events.
*
* @return {*} An accumulation of synthetic events.
* @internal
*/
extractEvents: function (topLevelType, targetInst, 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, targetInst, 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.') : _prodInvariant('95') : void 0;
// 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__(3)))
/***/ },
/* 45 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var invariant = __webpack_require__(8);
/**
* 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) : _prodInvariant('96', pluginName) : void 0;
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) : _prodInvariant('97', pluginName) : void 0;
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) : _prodInvariant('98', eventName, pluginName) : void 0;
}
}
}
/**
* 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) : _prodInvariant('99', eventName) : void 0;
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) : _prodInvariant('100', registrationName) : void 0;
EventPluginRegistry.registrationNameModules[registrationName] = PluginModule;
EventPluginRegistry.registrationNameDependencies[registrationName] = PluginModule.eventTypes[eventName].dependencies;
if (process.env.NODE_ENV !== 'production') {
var lowerCasedName = registrationName.toLowerCase();
EventPluginRegistry.possibleRegistrationNames[lowerCasedName] = registrationName;
if (registrationName === 'onDoubleClick') {
EventPluginRegistry.possibleRegistrationNames.ondblclick = registrationName;
}
}
}
/**
* 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: {},
/**
* Mapping from lowercase registration names to the properly cased version,
* used to warn in the case of missing event handlers. Available
* only in __DEV__.
* @type {Object}
*/
possibleRegistrationNames: process.env.NODE_ENV !== 'production' ? {} : null,
/**
* 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.') : _prodInvariant('101') : void 0;
// 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) : _prodInvariant('102', pluginName) : void 0;
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];
}
}
if (process.env.NODE_ENV !== 'production') {
var possibleRegistrationNames = EventPluginRegistry.possibleRegistrationNames;
for (var lowerCasedName in possibleRegistrationNames) {
if (possibleRegistrationNames.hasOwnProperty(lowerCasedName)) {
delete possibleRegistrationNames[lowerCasedName];
}
}
}
}
};
module.exports = EventPluginRegistry;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 46 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 _prodInvariant = __webpack_require__(7);
var EventConstants = __webpack_require__(42);
var ReactErrorUtils = __webpack_require__(47);
var invariant = __webpack_require__(8);
var warning = __webpack_require__(11);
/**
* Injected dependencies:
*/
/**
* - `ComponentTree`: [required] Module that can convert between React instances
* and actual node references.
*/
var ComponentTree;
var TreeTraversal;
var injection = {
injectComponentTree: function (Injected) {
ComponentTree = Injected;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(Injected && Injected.getNodeFromInstance && Injected.getInstanceFromNode, 'EventPluginUtils.injection.injectComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : void 0;
}
},
injectTreeTraversal: function (Injected) {
TreeTraversal = Injected;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(Injected && Injected.isAncestor && Injected.getLowestCommonAncestor, 'EventPluginUtils.injection.injectTreeTraversal(...): Injected ' + 'module is missing isAncestor or getLowestCommonAncestor.') : void 0;
}
}
};
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 dispatchInstances = event._dispatchInstances;
var listenersIsArr = Array.isArray(dispatchListeners);
var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0;
var instancesIsArr = Array.isArray(dispatchInstances);
var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0;
process.env.NODE_ENV !== 'production' ? warning(instancesIsArr === listenersIsArr && instancesLen === listenersLen, 'EventPluginUtils: Invalid `event`.') : void 0;
};
}
/**
* 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 {*} inst Internal component instance
*/
function executeDispatch(event, simulated, listener, inst) {
var type = event.type || 'unknown-event';
event.currentTarget = EventPluginUtils.getNodeFromInstance(inst);
if (simulated) {
ReactErrorUtils.invokeGuardedCallbackWithCatch(type, listener, event);
} else {
ReactErrorUtils.invokeGuardedCallback(type, listener, event);
}
event.currentTarget = null;
}
/**
* Standard/simple iteration through an event's collected dispatches.
*/
function executeDispatchesInOrder(event, simulated) {
var dispatchListeners = event._dispatchListeners;
var dispatchInstances = event._dispatchInstances;
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 Instances are two parallel arrays that are always in sync.
executeDispatch(event, simulated, dispatchListeners[i], dispatchInstances[i]);
}
} else if (dispatchListeners) {
executeDispatch(event, simulated, dispatchListeners, dispatchInstances);
}
event._dispatchListeners = null;
event._dispatchInstances = 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 dispatchInstances = event._dispatchInstances;
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 Instances are two parallel arrays that are always in sync.
if (dispatchListeners[i](event, dispatchInstances[i])) {
return dispatchInstances[i];
}
}
} else if (dispatchListeners) {
if (dispatchListeners(event, dispatchInstances)) {
return dispatchInstances;
}
}
return null;
}
/**
* @see executeDispatchesInOrderStopAtTrueImpl
*/
function executeDispatchesInOrderStopAtTrue(event) {
var ret = executeDispatchesInOrderStopAtTrueImpl(event);
event._dispatchInstances = 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 dispatchInstance = event._dispatchInstances;
!!Array.isArray(dispatchListener) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'executeDirectDispatch(...): Invalid `event`.') : _prodInvariant('103') : void 0;
event.currentTarget = dispatchListener ? EventPluginUtils.getNodeFromInstance(dispatchInstance) : null;
var res = dispatchListener ? dispatchListener(event) : null;
event.currentTarget = null;
event._dispatchListeners = null;
event._dispatchInstances = 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,
getInstanceFromNode: function (node) {
return ComponentTree.getInstanceFromNode(node);
},
getNodeFromInstance: function (node) {
return ComponentTree.getNodeFromInstance(node);
},
isAncestor: function (a, b) {
return TreeTraversal.isAncestor(a, b);
},
getLowestCommonAncestor: function (a, b) {
return TreeTraversal.getLowestCommonAncestor(a, b);
},
getParentInstance: function (inst) {
return TreeTraversal.getParentInstance(inst);
},
traverseTwoPhase: function (target, fn, arg) {
return TreeTraversal.traverseTwoPhase(target, fn, arg);
},
traverseEnterLeave: function (from, to, fn, argFrom, argTo) {
return TreeTraversal.traverseEnterLeave(from, to, fn, argFrom, argTo);
},
injection: injection
};
module.exports = EventPluginUtils;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 47 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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
*/
'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__(3)))
/***/ },
/* 48 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2014-present, 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 _prodInvariant = __webpack_require__(7);
var invariant = __webpack_require__(8);
/**
* 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.') : _prodInvariant('30') : void 0;
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).
if (Array.isArray(current)) {
if (Array.isArray(next)) {
current.push.apply(current, next);
return current;
}
current.push(next);
return current;
}
if (Array.isArray(next)) {
// A bit too dangerous to mutate `next`.
return [current].concat(next);
}
return [current, next];
}
module.exports = accumulateInto;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 49 */
/***/ function(module, exports) {
/**
* Copyright 2013-present, 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).
*/
function forEachAccumulated(arr, cb, scope) {
if (Array.isArray(arr)) {
arr.forEach(cb, scope);
} else if (arr) {
cb.call(scope, arr);
}
}
module.exports = forEachAccumulated;
/***/ },
/* 50 */
/***/ function(module, exports) {
/**
* Copyright (c) 2013-present, 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.
*
*/
'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;
/***/ },
/* 51 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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
*/
'use strict';
var _assign = __webpack_require__(4);
var PooledClass = __webpack_require__(6);
var getTextContentAccessor = __webpack_require__(52);
/**
* 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;
/***/ },
/* 52 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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__(50);
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;
/***/ },
/* 53 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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
*/
'use strict';
var SyntheticEvent = __webpack_require__(54);
/**
* @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) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticCompositionEvent, CompositionEventInterface);
module.exports = SyntheticCompositionEvent;
/***/ },
/* 54 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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
*/
'use strict';
var _assign = __webpack_require__(4);
var PooledClass = __webpack_require__(6);
var emptyFunction = __webpack_require__(12);
var warning = __webpack_require__(11);
var didWarnForAddedNewProperty = false;
var isProxySupported = typeof Proxy === 'function';
var shouldBeReleasedProperties = ['dispatchConfig', '_targetInst', 'nativeEvent', 'isDefaultPrevented', 'isPropagationStopped', '_dispatchListeners', '_dispatchInstances'];
/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var EventInterface = {
type: null,
target: 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 {*} targetInst Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @param {DOMEventTarget} nativeEventTarget Target node.
*/
function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {
if (process.env.NODE_ENV !== 'production') {
// these have a getter/setter for warnings
delete this.nativeEvent;
delete this.preventDefault;
delete this.stopPropagation;
}
this.dispatchConfig = dispatchConfig;
this._targetInst = targetInst;
this.nativeEvent = nativeEvent;
var Interface = this.constructor.Interface;
for (var propName in Interface) {
if (!Interface.hasOwnProperty(propName)) {
continue;
}
if (process.env.NODE_ENV !== 'production') {
delete this[propName]; // this has a getter/setter for warnings
}
var normalize = Interface[propName];
if (normalize) {
this[propName] = normalize(nativeEvent);
} else {
if (propName === 'target') {
this.target = nativeEventTarget;
} 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;
return this;
}
_assign(SyntheticEvent.prototype, {
preventDefault: function () {
this.defaultPrevented = true;
var event = this.nativeEvent;
if (!event) {
return;
}
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
},
stopPropagation: function () {
var event = this.nativeEvent;
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) {
if (process.env.NODE_ENV !== 'production') {
Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));
} else {
this[propName] = null;
}
}
for (var i = 0; i < shouldBeReleasedProperties.length; i++) {
this[shouldBeReleasedProperties[i]] = null;
}
if (process.env.NODE_ENV !== 'production') {
Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));
Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', emptyFunction));
Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', emptyFunction));
}
}
});
SyntheticEvent.Interface = EventInterface;
if (process.env.NODE_ENV !== 'production') {
if (isProxySupported) {
/*eslint-disable no-func-assign */
SyntheticEvent = new Proxy(SyntheticEvent, {
construct: function (target, args) {
return this.apply(target, Object.create(target.prototype), args);
},
apply: function (constructor, that, args) {
return new Proxy(constructor.apply(that, args), {
set: function (target, prop, value) {
if (prop !== 'isPersistent' && !target.constructor.Interface.hasOwnProperty(prop) && shouldBeReleasedProperties.indexOf(prop) === -1) {
process.env.NODE_ENV !== 'production' ? warning(didWarnForAddedNewProperty || target.isPersistent(), 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re adding a new property in the synthetic event object. ' + 'The property is never released. See ' + 'https://fb.me/react-event-pooling for more information.') : void 0;
didWarnForAddedNewProperty = true;
}
target[prop] = value;
return true;
}
});
}
});
/*eslint-enable no-func-assign */
}
}
/**
* Helper to reduce boilerplate when creating subclasses.
*
* @param {function} Class
* @param {?object} Interface
*/
SyntheticEvent.augmentClass = function (Class, Interface) {
var Super = this;
var E = function () {};
E.prototype = Super.prototype;
var prototype = new E();
_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;
/**
* Helper to nullify syntheticEvent instance properties when destructing
*
* @param {object} SyntheticEvent
* @param {String} propName
* @return {object} defineProperty object
*/
function getPooledWarningPropertyDefinition(propName, getVal) {
var isFunction = typeof getVal === 'function';
return {
configurable: true,
set: set,
get: get
};
function set(val) {
var action = isFunction ? 'setting the method' : 'setting the property';
warn(action, 'This is effectively a no-op');
return val;
}
function get() {
var action = isFunction ? 'accessing the method' : 'accessing the property';
var result = isFunction ? 'This is a no-op function' : 'This is set to null';
warn(action, result);
return getVal;
}
function warn(action, result) {
var warningCondition = false;
process.env.NODE_ENV !== 'production' ? warning(warningCondition, 'This synthetic event is reused for performance reasons. If you\'re seeing this, ' + 'you\'re %s `%s` on a released/nullified synthetic event. %s. ' + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result) : void 0;
}
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 55 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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
*/
'use strict';
var SyntheticEvent = __webpack_require__(54);
/**
* @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) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface);
module.exports = SyntheticInputEvent;
/***/ },
/* 56 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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__(42);
var EventPluginHub = __webpack_require__(44);
var EventPropagators = __webpack_require__(43);
var ExecutionEnvironment = __webpack_require__(50);
var ReactDOMComponentTree = __webpack_require__(37);
var ReactUpdates = __webpack_require__(57);
var SyntheticEvent = __webpack_require__(54);
var getEventTarget = __webpack_require__(71);
var isEventSupported = __webpack_require__(72);
var isTextInputElement = __webpack_require__(73);
var keyOf = __webpack_require__(25);
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 activeElementInst = 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, activeElementInst, 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, targetInst) {
activeElement = target;
activeElementInst = targetInst;
activeElement.attachEvent('onchange', manualDispatchChangeEvent);
}
function stopWatchingForChangeEventIE8() {
if (!activeElement) {
return;
}
activeElement.detachEvent('onchange', manualDispatchChangeEvent);
activeElement = null;
activeElementInst = null;
}
function getTargetInstForChangeEvent(topLevelType, targetInst) {
if (topLevelType === topLevelTypes.topChange) {
return targetInst;
}
}
function handleEventsForChangeEventIE8(topLevelType, target, targetInst) {
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(target, targetInst);
} 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.
// IE10+ fire input events to often, such when a placeholder
// changes or when an input with a placeholder is focused.
isInputEventSupported = isEventSupported('input') && (!('documentMode' in document) || document.documentMode > 11);
}
/**
* (For IE <=11) 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 IE <=11) 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, targetInst) {
activeElement = target;
activeElementInst = targetInst;
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);
if (activeElement.attachEvent) {
activeElement.attachEvent('onpropertychange', handlePropertyChange);
} else {
activeElement.addEventListener('propertychange', handlePropertyChange, false);
}
}
/**
* (For IE <=11) 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;
if (activeElement.detachEvent) {
activeElement.detachEvent('onpropertychange', handlePropertyChange);
} else {
activeElement.removeEventListener('propertychange', handlePropertyChange, false);
}
activeElement = null;
activeElementInst = null;
activeElementValue = null;
activeElementValueProp = null;
}
/**
* (For IE <=11) 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 getTargetInstForInputEvent(topLevelType, targetInst) {
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 targetInst;
}
}
function handleEventsForInputEventIE(topLevelType, target, targetInst) {
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-11, 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(target, targetInst);
} else if (topLevelType === topLevelTypes.topBlur) {
stopWatchingForValueChange();
}
}
// For IE8 and IE9.
function getTargetInstForInputEventIE(topLevelType, targetInst) {
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 activeElementInst;
}
}
}
/**
* 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 getTargetInstForClickEvent(topLevelType, targetInst) {
if (topLevelType === topLevelTypes.topClick) {
return targetInst;
}
}
/**
* 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,
extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window;
var getTargetInstFunc, handleEventFunc;
if (shouldUseChangeEvent(targetNode)) {
if (doesChangeEventBubble) {
getTargetInstFunc = getTargetInstForChangeEvent;
} else {
handleEventFunc = handleEventsForChangeEventIE8;
}
} else if (isTextInputElement(targetNode)) {
if (isInputEventSupported) {
getTargetInstFunc = getTargetInstForInputEvent;
} else {
getTargetInstFunc = getTargetInstForInputEventIE;
handleEventFunc = handleEventsForInputEventIE;
}
} else if (shouldUseClickEvent(targetNode)) {
getTargetInstFunc = getTargetInstForClickEvent;
}
if (getTargetInstFunc) {
var inst = getTargetInstFunc(topLevelType, targetInst);
if (inst) {
var event = SyntheticEvent.getPooled(eventTypes.change, inst, nativeEvent, nativeEventTarget);
event.type = 'change';
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
}
if (handleEventFunc) {
handleEventFunc(topLevelType, targetNode, targetInst);
}
}
};
module.exports = ChangeEventPlugin;
/***/ },
/* 57 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 _prodInvariant = __webpack_require__(7),
_assign = __webpack_require__(4);
var CallbackQueue = __webpack_require__(58);
var PooledClass = __webpack_require__(6);
var ReactFeatureFlags = __webpack_require__(59);
var ReactReconciler = __webpack_require__(60);
var Transaction = __webpack_require__(70);
var invariant = __webpack_require__(8);
var dirtyComponents = [];
var updateBatchNumber = 0;
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') : _prodInvariant('123') : void 0;
}
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(
/* useCreateElement */true);
}
_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) : _prodInvariant('124', len, dirtyComponents.length) : void 0;
// 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);
// Any updates enqueued while reconciling must be performed after this entire
// batch. Otherwise, if dirtyComponents is [A, B] where A has children B and
// C, B could update twice in a single batch if C's render enqueues an update
// to B (since B would have already updated, we should skip it, and the only
// way we can know to do so is by checking the batch counter).
updateBatchNumber++;
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;
var markerName;
if (ReactFeatureFlags.logTopLevelRenders) {
var namedComponent = component;
// Duck type TopLevelWrapper. This is probably always true.
if (component._currentElement.props === component._renderedComponent._currentElement) {
namedComponent = component._renderedComponent;
}
markerName = 'React update: ' + namedComponent.getName();
console.time(markerName);
}
ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction, updateBatchNumber);
if (markerName) {
console.timeEnd(markerName);
}
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);
}
}
};
/**
* 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 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);
if (component._updateBatchNumber == null) {
component._updateBatchNumber = updateBatchNumber + 1;
}
}
/**
* 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 whereupdates are not being batched.') : _prodInvariant('125') : void 0;
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') : _prodInvariant('126') : void 0;
ReactUpdates.ReactReconcileTransaction = ReconcileTransaction;
},
injectBatchingStrategy: function (_batchingStrategy) {
!_batchingStrategy ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batching strategy') : _prodInvariant('127') : void 0;
!(typeof _batchingStrategy.batchedUpdates === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batchedUpdates() function') : _prodInvariant('128') : void 0;
!(typeof _batchingStrategy.isBatchingUpdates === 'boolean') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide an isBatchingUpdates boolean attribute') : _prodInvariant('129') : void 0;
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__(3)))
/***/ },
/* 58 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 _prodInvariant = __webpack_require__(7),
_assign = __webpack_require__(4);
var PooledClass = __webpack_require__(6);
var invariant = __webpack_require__(8);
/**
* 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') : _prodInvariant('24') : void 0;
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;
}
},
checkpoint: function () {
return this._callbacks ? this._callbacks.length : 0;
},
rollback: function (len) {
if (this._callbacks) {
this._callbacks.length = len;
this._contexts.length = len;
}
},
/**
* 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__(3)))
/***/ },
/* 59 */
/***/ function(module, exports) {
/**
* Copyright 2013-present, 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 ReactFeatureFlags
*
*/
'use strict';
var ReactFeatureFlags = {
// When true, call console.time() before and .timeEnd() after each top-level
// render (both initial renders and updates). Useful when looking at prod-mode
// timeline profiles in Chrome, for example.
logTopLevelRenders: false
};
module.exports = ReactFeatureFlags;
/***/ },
/* 60 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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__(61);
var ReactInstrumentation = __webpack_require__(63);
var warning = __webpack_require__(11);
/**
* 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 {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {?object} the containing host component instance
* @param {?object} info about the host container
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: function (internalInstance, transaction, hostParent, hostContainerInfo, context) {
if (process.env.NODE_ENV !== 'production') {
if (internalInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onBeforeMountComponent(internalInstance._debugID, internalInstance._currentElement);
ReactInstrumentation.debugTool.onBeginReconcilerTimer(internalInstance._debugID, 'mountComponent');
}
}
var markup = internalInstance.mountComponent(transaction, hostParent, hostContainerInfo, context);
if (internalInstance._currentElement && internalInstance._currentElement.ref != null) {
transaction.getReactMountReady().enqueue(attachRefs, internalInstance);
}
if (process.env.NODE_ENV !== 'production') {
if (internalInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onEndReconcilerTimer(internalInstance._debugID, 'mountComponent');
ReactInstrumentation.debugTool.onMountComponent(internalInstance._debugID);
}
}
return markup;
},
/**
* Returns a value that can be passed to
* ReactComponentEnvironment.replaceNodeWithMarkup.
*/
getHostNode: function (internalInstance) {
return internalInstance.getHostNode();
},
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function (internalInstance, safely) {
if (process.env.NODE_ENV !== 'production') {
if (internalInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginReconcilerTimer(internalInstance._debugID, 'unmountComponent');
}
}
ReactRef.detachRefs(internalInstance, internalInstance._currentElement);
internalInstance.unmountComponent(safely);
if (process.env.NODE_ENV !== 'production') {
if (internalInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onEndReconcilerTimer(internalInstance._debugID, 'unmountComponent');
ReactInstrumentation.debugTool.onUnmountComponent(internalInstance._debugID);
}
}
},
/**
* 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;
}
if (process.env.NODE_ENV !== 'production') {
if (internalInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, nextElement);
ReactInstrumentation.debugTool.onBeginReconcilerTimer(internalInstance._debugID, 'receiveComponent');
}
}
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);
}
if (process.env.NODE_ENV !== 'production') {
if (internalInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onEndReconcilerTimer(internalInstance._debugID, 'receiveComponent');
ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID);
}
}
},
/**
* Flush any dirty changes in a component.
*
* @param {ReactComponent} internalInstance
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function (internalInstance, transaction, updateBatchNumber) {
if (internalInstance._updateBatchNumber !== updateBatchNumber) {
// The component's enqueued batch number should always be the current
// batch or the following one.
process.env.NODE_ENV !== 'production' ? warning(internalInstance._updateBatchNumber == null || internalInstance._updateBatchNumber === updateBatchNumber + 1, 'performUpdateIfNecessary: Unexpected batch number (current %s, ' + 'pending %s)', updateBatchNumber, internalInstance._updateBatchNumber) : void 0;
return;
}
if (process.env.NODE_ENV !== 'production') {
if (internalInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginReconcilerTimer(internalInstance._debugID, 'performUpdateIfNecessary');
ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, internalInstance._currentElement);
}
}
internalInstance.performUpdateIfNecessary(transaction);
if (process.env.NODE_ENV !== 'production') {
if (internalInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onEndReconcilerTimer(internalInstance._debugID, 'performUpdateIfNecessary');
ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID);
}
}
}
};
module.exports = ReactReconciler;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 61 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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__(62);
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.ref !== prevElement.ref ||
// If owner changes but we have an unchanged function ref, don't update refs
typeof nextElement.ref === 'string' && nextElement._owner !== prevElement._owner
);
};
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;
/***/ },
/* 62 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 _prodInvariant = __webpack_require__(7);
var invariant = __webpack_require__(8);
/**
* 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).') : _prodInvariant('119') : void 0;
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).') : _prodInvariant('120') : void 0;
var ownerPublicInstance = owner.getPublicInstance();
// Check that `component`'s owner is still alive and that `component` is still the current ref
// because we do not want to detach the ref if another component stole it.
if (ownerPublicInstance && ownerPublicInstance.refs[ref] === component.getPublicInstance()) {
owner.detachRef(ref);
}
}
};
module.exports = ReactOwner;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 63 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2016-present, 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 ReactInstrumentation
*/
'use strict';
var debugTool = null;
if (process.env.NODE_ENV !== 'production') {
var ReactDebugTool = __webpack_require__(64);
debugTool = ReactDebugTool;
}
module.exports = { debugTool: debugTool };
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 64 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2016-present, 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 ReactDebugTool
*/
'use strict';
var ReactInvalidSetStateWarningDevTool = __webpack_require__(65);
var ReactHostOperationHistoryDevtool = __webpack_require__(66);
var ReactComponentTreeDevtool = __webpack_require__(29);
var ReactChildrenMutationWarningDevtool = __webpack_require__(67);
var ExecutionEnvironment = __webpack_require__(50);
var performanceNow = __webpack_require__(68);
var warning = __webpack_require__(11);
var eventHandlers = [];
var handlerDoesThrowForEvent = {};
function emitEvent(handlerFunctionName, arg1, arg2, arg3, arg4, arg5) {
eventHandlers.forEach(function (handler) {
try {
if (handler[handlerFunctionName]) {
handler[handlerFunctionName](arg1, arg2, arg3, arg4, arg5);
}
} catch (e) {
process.env.NODE_ENV !== 'production' ? warning(handlerDoesThrowForEvent[handlerFunctionName], 'exception thrown by devtool while handling %s: %s', handlerFunctionName, e + '\n' + e.stack) : void 0;
handlerDoesThrowForEvent[handlerFunctionName] = true;
}
});
}
var isProfiling = false;
var flushHistory = [];
var lifeCycleTimerStack = [];
var currentFlushNesting = 0;
var currentFlushMeasurements = null;
var currentFlushStartTime = null;
var currentTimerDebugID = null;
var currentTimerStartTime = null;
var currentTimerNestedFlushDuration = null;
var currentTimerType = null;
var lifeCycleTimerHasWarned = false;
function clearHistory() {
ReactComponentTreeDevtool.purgeUnmountedComponents();
ReactHostOperationHistoryDevtool.clearHistory();
}
function getTreeSnapshot(registeredIDs) {
return registeredIDs.reduce(function (tree, id) {
var ownerID = ReactComponentTreeDevtool.getOwnerID(id);
var parentID = ReactComponentTreeDevtool.getParentID(id);
tree[id] = {
displayName: ReactComponentTreeDevtool.getDisplayName(id),
text: ReactComponentTreeDevtool.getText(id),
updateCount: ReactComponentTreeDevtool.getUpdateCount(id),
childIDs: ReactComponentTreeDevtool.getChildIDs(id),
// Text nodes don't have owners but this is close enough.
ownerID: ownerID || ReactComponentTreeDevtool.getOwnerID(parentID),
parentID: parentID
};
return tree;
}, {});
}
function resetMeasurements() {
var previousStartTime = currentFlushStartTime;
var previousMeasurements = currentFlushMeasurements || [];
var previousOperations = ReactHostOperationHistoryDevtool.getHistory();
if (currentFlushNesting === 0) {
currentFlushStartTime = null;
currentFlushMeasurements = null;
clearHistory();
return;
}
if (previousMeasurements.length || previousOperations.length) {
var registeredIDs = ReactComponentTreeDevtool.getRegisteredIDs();
flushHistory.push({
duration: performanceNow() - previousStartTime,
measurements: previousMeasurements || [],
operations: previousOperations || [],
treeSnapshot: getTreeSnapshot(registeredIDs)
});
}
clearHistory();
currentFlushStartTime = performanceNow();
currentFlushMeasurements = [];
}
function checkDebugID(debugID) {
process.env.NODE_ENV !== 'production' ? warning(debugID, 'ReactDebugTool: debugID may not be empty.') : void 0;
}
function beginLifeCycleTimer(debugID, timerType) {
if (currentFlushNesting === 0) {
return;
}
if (currentTimerType && !lifeCycleTimerHasWarned) {
process.env.NODE_ENV !== 'production' ? warning(false, 'There is an internal error in the React performance measurement code. ' + 'Did not expect %s timer to start while %s timer is still in ' + 'progress for %s instance.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another') : void 0;
lifeCycleTimerHasWarned = true;
}
currentTimerStartTime = performanceNow();
currentTimerNestedFlushDuration = 0;
currentTimerDebugID = debugID;
currentTimerType = timerType;
}
function endLifeCycleTimer(debugID, timerType) {
if (currentFlushNesting === 0) {
return;
}
if (currentTimerType !== timerType && !lifeCycleTimerHasWarned) {
process.env.NODE_ENV !== 'production' ? warning(false, 'There is an internal error in the React performance measurement code. ' + 'We did not expect %s timer to stop while %s timer is still in ' + 'progress for %s instance. Please report this as a bug in React.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another') : void 0;
lifeCycleTimerHasWarned = true;
}
if (isProfiling) {
currentFlushMeasurements.push({
timerType: timerType,
instanceID: debugID,
duration: performanceNow() - currentTimerStartTime - currentTimerNestedFlushDuration
});
}
currentTimerStartTime = null;
currentTimerNestedFlushDuration = null;
currentTimerDebugID = null;
currentTimerType = null;
}
function pauseCurrentLifeCycleTimer() {
var currentTimer = {
startTime: currentTimerStartTime,
nestedFlushStartTime: performanceNow(),
debugID: currentTimerDebugID,
timerType: currentTimerType
};
lifeCycleTimerStack.push(currentTimer);
currentTimerStartTime = null;
currentTimerNestedFlushDuration = null;
currentTimerDebugID = null;
currentTimerType = null;
}
function resumeCurrentLifeCycleTimer() {
var _lifeCycleTimerStack$ = lifeCycleTimerStack.pop();
var startTime = _lifeCycleTimerStack$.startTime;
var nestedFlushStartTime = _lifeCycleTimerStack$.nestedFlushStartTime;
var debugID = _lifeCycleTimerStack$.debugID;
var timerType = _lifeCycleTimerStack$.timerType;
var nestedFlushDuration = performanceNow() - nestedFlushStartTime;
currentTimerStartTime = startTime;
currentTimerNestedFlushDuration += nestedFlushDuration;
currentTimerDebugID = debugID;
currentTimerType = timerType;
}
var ReactDebugTool = {
addDevtool: function (devtool) {
eventHandlers.push(devtool);
},
removeDevtool: function (devtool) {
for (var i = 0; i < eventHandlers.length; i++) {
if (eventHandlers[i] === devtool) {
eventHandlers.splice(i, 1);
i--;
}
}
},
isProfiling: function () {
return isProfiling;
},
beginProfiling: function () {
if (isProfiling) {
return;
}
isProfiling = true;
flushHistory.length = 0;
resetMeasurements();
ReactDebugTool.addDevtool(ReactHostOperationHistoryDevtool);
},
endProfiling: function () {
if (!isProfiling) {
return;
}
isProfiling = false;
resetMeasurements();
ReactDebugTool.removeDevtool(ReactHostOperationHistoryDevtool);
},
getFlushHistory: function () {
return flushHistory;
},
onBeginFlush: function () {
currentFlushNesting++;
resetMeasurements();
pauseCurrentLifeCycleTimer();
emitEvent('onBeginFlush');
},
onEndFlush: function () {
resetMeasurements();
currentFlushNesting--;
resumeCurrentLifeCycleTimer();
emitEvent('onEndFlush');
},
onBeginLifeCycleTimer: function (debugID, timerType) {
checkDebugID(debugID);
emitEvent('onBeginLifeCycleTimer', debugID, timerType);
beginLifeCycleTimer(debugID, timerType);
},
onEndLifeCycleTimer: function (debugID, timerType) {
checkDebugID(debugID);
endLifeCycleTimer(debugID, timerType);
emitEvent('onEndLifeCycleTimer', debugID, timerType);
},
onBeginReconcilerTimer: function (debugID, timerType) {
checkDebugID(debugID);
emitEvent('onBeginReconcilerTimer', debugID, timerType);
},
onEndReconcilerTimer: function (debugID, timerType) {
checkDebugID(debugID);
emitEvent('onEndReconcilerTimer', debugID, timerType);
},
onError: function (debugID) {
if (currentTimerDebugID != null) {
endLifeCycleTimer(currentTimerDebugID, currentTimerType);
}
emitEvent('onError', debugID);
},
onBeginProcessingChildContext: function () {
emitEvent('onBeginProcessingChildContext');
},
onEndProcessingChildContext: function () {
emitEvent('onEndProcessingChildContext');
},
onHostOperation: function (debugID, type, payload) {
checkDebugID(debugID);
emitEvent('onHostOperation', debugID, type, payload);
},
onComponentHasMounted: function (debugID) {
checkDebugID(debugID);
emitEvent('onComponentHasMounted', debugID);
},
onComponentHasUpdated: function (debugID) {
checkDebugID(debugID);
emitEvent('onComponentHasUpdated', debugID);
},
onSetState: function () {
emitEvent('onSetState');
},
onSetDisplayName: function (debugID, displayName) {
checkDebugID(debugID);
emitEvent('onSetDisplayName', debugID, displayName);
},
onSetChildren: function (debugID, childDebugIDs) {
checkDebugID(debugID);
childDebugIDs.forEach(checkDebugID);
emitEvent('onSetChildren', debugID, childDebugIDs);
},
onSetOwner: function (debugID, ownerDebugID) {
checkDebugID(debugID);
emitEvent('onSetOwner', debugID, ownerDebugID);
},
onSetParent: function (debugID, parentDebugID) {
checkDebugID(debugID);
emitEvent('onSetParent', debugID, parentDebugID);
},
onSetText: function (debugID, text) {
checkDebugID(debugID);
emitEvent('onSetText', debugID, text);
},
onMountRootComponent: function (debugID) {
checkDebugID(debugID);
emitEvent('onMountRootComponent', debugID);
},
onBeforeMountComponent: function (debugID, element) {
checkDebugID(debugID);
emitEvent('onBeforeMountComponent', debugID, element);
},
onMountComponent: function (debugID) {
checkDebugID(debugID);
emitEvent('onMountComponent', debugID);
},
onBeforeUpdateComponent: function (debugID, element) {
checkDebugID(debugID);
emitEvent('onBeforeUpdateComponent', debugID, element);
},
onUpdateComponent: function (debugID) {
checkDebugID(debugID);
emitEvent('onUpdateComponent', debugID);
},
onUnmountComponent: function (debugID) {
checkDebugID(debugID);
emitEvent('onUnmountComponent', debugID);
},
onTestEvent: function () {
emitEvent('onTestEvent');
}
};
ReactDebugTool.addDevtool(ReactInvalidSetStateWarningDevTool);
ReactDebugTool.addDevtool(ReactComponentTreeDevtool);
ReactDebugTool.addDevtool(ReactChildrenMutationWarningDevtool);
var url = ExecutionEnvironment.canUseDOM && window.location.href || '';
if (/[?&]react_perf\b/.test(url)) {
ReactDebugTool.beginProfiling();
}
module.exports = ReactDebugTool;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 65 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2016-present, 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 ReactInvalidSetStateWarningDevTool
*/
'use strict';
var warning = __webpack_require__(11);
if (process.env.NODE_ENV !== 'production') {
var processingChildContext = false;
var warnInvalidSetState = function () {
process.env.NODE_ENV !== 'production' ? warning(!processingChildContext, 'setState(...): Cannot call setState() inside getChildContext()') : void 0;
};
}
var ReactInvalidSetStateWarningDevTool = {
onBeginProcessingChildContext: function () {
processingChildContext = true;
},
onEndProcessingChildContext: function () {
processingChildContext = false;
},
onSetState: function () {
warnInvalidSetState();
}
};
module.exports = ReactInvalidSetStateWarningDevTool;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 66 */
/***/ function(module, exports) {
/**
* Copyright 2016-present, 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 ReactHostOperationHistoryDevtool
*/
'use strict';
var history = [];
var ReactHostOperationHistoryDevtool = {
onHostOperation: function (debugID, type, payload) {
history.push({
instanceID: debugID,
type: type,
payload: payload
});
},
clearHistory: function () {
if (ReactHostOperationHistoryDevtool._preventClearing) {
// Should only be used for tests.
return;
}
history = [];
},
getHistory: function () {
return history;
}
};
module.exports = ReactHostOperationHistoryDevtool;
/***/ },
/* 67 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 ReactChildrenMutationWarningDevtool
*/
'use strict';
var ReactComponentTreeDevtool = __webpack_require__(29);
var warning = __webpack_require__(11);
var elements = {};
function handleElement(debugID, element) {
if (element == null) {
return;
}
if (element._shadowChildren === undefined) {
return;
}
if (element._shadowChildren === element.props.children) {
return;
}
var isMutated = false;
if (Array.isArray(element._shadowChildren)) {
if (element._shadowChildren.length === element.props.children.length) {
for (var i = 0; i < element._shadowChildren.length; i++) {
if (element._shadowChildren[i] !== element.props.children[i]) {
isMutated = true;
}
}
} else {
isMutated = true;
}
}
process.env.NODE_ENV !== 'production' ? warning(Array.isArray(element._shadowChildren) && !isMutated, 'Component\'s children should not be mutated.%s', ReactComponentTreeDevtool.getStackAddendumByID(debugID)) : void 0;
}
var ReactDOMUnknownPropertyDevtool = {
onBeforeMountComponent: function (debugID, element) {
elements[debugID] = element;
},
onBeforeUpdateComponent: function (debugID, element) {
elements[debugID] = element;
},
onComponentHasMounted: function (debugID) {
handleElement(debugID, elements[debugID]);
delete elements[debugID];
},
onComponentHasUpdated: function (debugID) {
handleElement(debugID, elements[debugID]);
delete elements[debugID];
}
};
module.exports = ReactDOMUnknownPropertyDevtool;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 68 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
/**
* Copyright (c) 2013-present, 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
*/
var performance = __webpack_require__(69);
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 performanceNow() {
return performance.now();
};
} else {
performanceNow = function performanceNow() {
return Date.now();
};
}
module.exports = performanceNow;
/***/ },
/* 69 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright (c) 2013-present, 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
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(50);
var performance;
if (ExecutionEnvironment.canUseDOM) {
performance = window.performance || window.msPerformance || window.webkitPerformance;
}
module.exports = performance || {};
/***/ },
/* 70 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 _prodInvariant = __webpack_require__(7);
var invariant = __webpack_require__(8);
/**
* `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.') : _prodInvariant('27') : void 0;
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.') : _prodInvariant('28') : void 0;
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__(3)))
/***/ },
/* 71 */
/***/ function(module, exports) {
/**
* Copyright 2013-present, 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
*/
'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;
// Normalize SVG <use> element events #4963
if (target.correspondingUseElement) {
target = target.correspondingUseElement;
}
// 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;
/***/ },
/* 72 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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__(50);
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;
/***/ },
/* 73 */
/***/ function(module, exports) {
/**
* Copyright 2013-present, 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();
if (nodeName === 'input') {
return !!supportedInputTypes[elem.type];
}
if (nodeName === 'textarea') {
return true;
}
return false;
}
module.exports = isTextInputElement;
/***/ },
/* 74 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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__(25);
/**
* 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;
/***/ },
/* 75 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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
*/
'use strict';
var EventConstants = __webpack_require__(42);
var EventPropagators = __webpack_require__(43);
var ReactDOMComponentTree = __webpack_require__(37);
var SyntheticMouseEvent = __webpack_require__(76);
var keyOf = __webpack_require__(25);
var topLevelTypes = EventConstants.topLevelTypes;
var eventTypes = {
mouseEnter: {
registrationName: keyOf({ onMouseEnter: null }),
dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver]
},
mouseLeave: {
registrationName: keyOf({ onMouseLeave: null }),
dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver]
}
};
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.
*/
extractEvents: function (topLevelType, targetInst, 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 (nativeEventTarget.window === nativeEventTarget) {
// `nativeEventTarget` is probably a window object.
win = nativeEventTarget;
} else {
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
var doc = nativeEventTarget.ownerDocument;
if (doc) {
win = doc.defaultView || doc.parentWindow;
} else {
win = window;
}
}
var from;
var to;
if (topLevelType === topLevelTypes.topMouseOut) {
from = targetInst;
var related = nativeEvent.relatedTarget || nativeEvent.toElement;
to = related ? ReactDOMComponentTree.getClosestInstanceFromNode(related) : null;
} else {
// Moving to a node from outside the window.
from = null;
to = targetInst;
}
if (from === to) {
// Nothing pertains to our managed components.
return null;
}
var fromNode = from == null ? win : ReactDOMComponentTree.getNodeFromInstance(from);
var toNode = to == null ? win : ReactDOMComponentTree.getNodeFromInstance(to);
var leave = SyntheticMouseEvent.getPooled(eventTypes.mouseLeave, from, nativeEvent, nativeEventTarget);
leave.type = 'mouseleave';
leave.target = fromNode;
leave.relatedTarget = toNode;
var enter = SyntheticMouseEvent.getPooled(eventTypes.mouseEnter, to, nativeEvent, nativeEventTarget);
enter.type = 'mouseenter';
enter.target = toNode;
enter.relatedTarget = fromNode;
EventPropagators.accumulateEnterLeaveDispatches(leave, enter, from, to);
return [leave, enter];
}
};
module.exports = EnterLeaveEventPlugin;
/***/ },
/* 76 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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
*/
'use strict';
var SyntheticUIEvent = __webpack_require__(77);
var ViewportMetrics = __webpack_require__(78);
var getEventModifierState = __webpack_require__(79);
/**
* @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) {
return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface);
module.exports = SyntheticMouseEvent;
/***/ },
/* 77 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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
*/
'use strict';
var SyntheticEvent = __webpack_require__(54);
var getEventTarget = __webpack_require__(71);
/**
* @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.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) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface);
module.exports = SyntheticUIEvent;
/***/ },
/* 78 */
/***/ function(module, exports) {
/**
* Copyright 2013-present, 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;
/***/ },
/* 79 */
/***/ function(module, exports) {
/**
* Copyright 2013-present, 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
*/
'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;
/***/ },
/* 80 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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__(38);
var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY;
var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE;
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 HTMLDOMPropertyConfig = {
isCustomAttribute: RegExp.prototype.test.bind(new RegExp('^(data|aria)-[' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$')),
Properties: {
/**
* Standard Properties
*/
accept: 0,
acceptCharset: 0,
accessKey: 0,
action: 0,
allowFullScreen: HAS_BOOLEAN_VALUE,
allowTransparency: 0,
alt: 0,
async: HAS_BOOLEAN_VALUE,
autoComplete: 0,
// autoFocus is polyfilled/normalized by AutoFocusUtils
// autoFocus: HAS_BOOLEAN_VALUE,
autoPlay: HAS_BOOLEAN_VALUE,
capture: HAS_BOOLEAN_VALUE,
cellPadding: 0,
cellSpacing: 0,
charSet: 0,
challenge: 0,
checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
cite: 0,
classID: 0,
className: 0,
cols: HAS_POSITIVE_NUMERIC_VALUE,
colSpan: 0,
content: 0,
contentEditable: 0,
contextMenu: 0,
controls: HAS_BOOLEAN_VALUE,
coords: 0,
crossOrigin: 0,
data: 0, // For `<object />` acts as `src`.
dateTime: 0,
'default': HAS_BOOLEAN_VALUE,
defer: HAS_BOOLEAN_VALUE,
dir: 0,
disabled: HAS_BOOLEAN_VALUE,
download: HAS_OVERLOADED_BOOLEAN_VALUE,
draggable: 0,
encType: 0,
form: 0,
formAction: 0,
formEncType: 0,
formMethod: 0,
formNoValidate: HAS_BOOLEAN_VALUE,
formTarget: 0,
frameBorder: 0,
headers: 0,
height: 0,
hidden: HAS_BOOLEAN_VALUE,
high: 0,
href: 0,
hrefLang: 0,
htmlFor: 0,
httpEquiv: 0,
icon: 0,
id: 0,
inputMode: 0,
integrity: 0,
is: 0,
keyParams: 0,
keyType: 0,
kind: 0,
label: 0,
lang: 0,
list: 0,
loop: HAS_BOOLEAN_VALUE,
low: 0,
manifest: 0,
marginHeight: 0,
marginWidth: 0,
max: 0,
maxLength: 0,
media: 0,
mediaGroup: 0,
method: 0,
min: 0,
minLength: 0,
// Caution; `option.selected` is not updated if `select.multiple` is
// disabled with `removeAttribute`.
multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
name: 0,
nonce: 0,
noValidate: HAS_BOOLEAN_VALUE,
open: HAS_BOOLEAN_VALUE,
optimum: 0,
pattern: 0,
placeholder: 0,
poster: 0,
preload: 0,
profile: 0,
radioGroup: 0,
readOnly: HAS_BOOLEAN_VALUE,
referrerPolicy: 0,
rel: 0,
required: HAS_BOOLEAN_VALUE,
reversed: HAS_BOOLEAN_VALUE,
role: 0,
rows: HAS_POSITIVE_NUMERIC_VALUE,
rowSpan: HAS_NUMERIC_VALUE,
sandbox: 0,
scope: 0,
scoped: HAS_BOOLEAN_VALUE,
scrolling: 0,
seamless: HAS_BOOLEAN_VALUE,
selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
shape: 0,
size: HAS_POSITIVE_NUMERIC_VALUE,
sizes: 0,
span: HAS_POSITIVE_NUMERIC_VALUE,
spellCheck: 0,
src: 0,
srcDoc: 0,
srcLang: 0,
srcSet: 0,
start: HAS_NUMERIC_VALUE,
step: 0,
style: 0,
summary: 0,
tabIndex: 0,
target: 0,
title: 0,
// Setting .type throws on non-<input> tags
type: 0,
useMap: 0,
value: 0,
width: 0,
wmode: 0,
wrap: 0,
/**
* RDFa Properties
*/
about: 0,
datatype: 0,
inlist: 0,
prefix: 0,
// property is also supported for OpenGraph in meta tags.
property: 0,
resource: 0,
'typeof': 0,
vocab: 0,
/**
* Non-standard Properties
*/
// autoCapitalize and autoCorrect are supported in Mobile Safari for
// keyboard hints.
autoCapitalize: 0,
autoCorrect: 0,
// autoSave allows WebKit/Blink to persist values of input fields on page reloads
autoSave: 0,
// color is for Safari mask-icon link
color: 0,
// itemProp, itemScope, itemType are for
// Microdata support. See http://schema.org/docs/gs.html
itemProp: 0,
itemScope: HAS_BOOLEAN_VALUE,
itemType: 0,
// itemID and itemRef are for Microdata support as well but
// only specified in the WHATWG spec document. See
// https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api
itemID: 0,
itemRef: 0,
// results show looking glass icon and recent searches on input
// search fields in WebKit/Blink
results: 0,
// IE-only attribute that specifies security restrictions on an iframe
// as an alternative to the sandbox attribute on IE<10
security: 0,
// IE-only attribute that controls focus behavior
unselectable: 0
},
DOMAttributeNames: {
acceptCharset: 'accept-charset',
className: 'class',
htmlFor: 'for',
httpEquiv: 'http-equiv'
},
DOMPropertyNames: {}
};
module.exports = HTMLDOMPropertyConfig;
/***/ },
/* 81 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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 DOMChildrenOperations = __webpack_require__(82);
var ReactDOMIDOperations = __webpack_require__(94);
/**
* 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,
replaceNodeWithMarkup: DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup,
/**
* 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) {}
};
module.exports = ReactComponentBrowserEnvironment;
/***/ },
/* 82 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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
*/
'use strict';
var DOMLazyTree = __webpack_require__(83);
var Danger = __webpack_require__(89);
var ReactMultiChildUpdateTypes = __webpack_require__(93);
var ReactDOMComponentTree = __webpack_require__(37);
var ReactInstrumentation = __webpack_require__(63);
var createMicrosoftUnsafeLocalFunction = __webpack_require__(86);
var setInnerHTML = __webpack_require__(85);
var setTextContent = __webpack_require__(87);
function getNodeAfter(parentNode, node) {
// Special case for text components, which return [open, close] comments
// from getHostNode.
if (Array.isArray(node)) {
node = node[1];
}
return node ? node.nextSibling : parentNode.firstChild;
}
/**
* 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
*/
var insertChildAt = createMicrosoftUnsafeLocalFunction(function (parentNode, childNode, referenceNode) {
// We rely exclusively on `insertBefore(node, null)` instead of also using
// `appendChild(node)`. (Using `undefined` is not allowed by all browsers so
// we are careful to use `null`.)
parentNode.insertBefore(childNode, referenceNode);
});
function insertLazyTreeChildAt(parentNode, childTree, referenceNode) {
DOMLazyTree.insertTreeBefore(parentNode, childTree, referenceNode);
}
function moveChild(parentNode, childNode, referenceNode) {
if (Array.isArray(childNode)) {
moveDelimitedText(parentNode, childNode[0], childNode[1], referenceNode);
} else {
insertChildAt(parentNode, childNode, referenceNode);
}
}
function removeChild(parentNode, childNode) {
if (Array.isArray(childNode)) {
var closingComment = childNode[1];
childNode = childNode[0];
removeDelimitedText(parentNode, childNode, closingComment);
parentNode.removeChild(closingComment);
}
parentNode.removeChild(childNode);
}
function moveDelimitedText(parentNode, openingComment, closingComment, referenceNode) {
var node = openingComment;
while (true) {
var nextNode = node.nextSibling;
insertChildAt(parentNode, node, referenceNode);
if (node === closingComment) {
break;
}
node = nextNode;
}
}
function removeDelimitedText(parentNode, startNode, closingComment) {
while (true) {
var node = startNode.nextSibling;
if (node === closingComment) {
// The closing comment is removed by ReactMultiChild.
break;
} else {
parentNode.removeChild(node);
}
}
}
function replaceDelimitedText(openingComment, closingComment, stringText) {
var parentNode = openingComment.parentNode;
var nodeAfterComment = openingComment.nextSibling;
if (nodeAfterComment === closingComment) {
// There are no text nodes between the opening and closing comments; insert
// a new one if stringText isn't empty.
if (stringText) {
insertChildAt(parentNode, document.createTextNode(stringText), nodeAfterComment);
}
} else {
if (stringText) {
// Set the text content of the first node after the opening comment, and
// remove all following nodes up until the closing comment.
setTextContent(nodeAfterComment, stringText);
removeDelimitedText(parentNode, nodeAfterComment, closingComment);
} else {
removeDelimitedText(parentNode, openingComment, closingComment);
}
}
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation(ReactDOMComponentTree.getInstanceFromNode(openingComment)._debugID, 'replace text', stringText);
}
}
var dangerouslyReplaceNodeWithMarkup = Danger.dangerouslyReplaceNodeWithMarkup;
if (process.env.NODE_ENV !== 'production') {
dangerouslyReplaceNodeWithMarkup = function (oldChild, markup, prevInstance) {
Danger.dangerouslyReplaceNodeWithMarkup(oldChild, markup);
if (prevInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onHostOperation(prevInstance._debugID, 'replace with', markup.toString());
} else {
var nextInstance = ReactDOMComponentTree.getInstanceFromNode(markup.node);
if (nextInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onHostOperation(nextInstance._debugID, 'mount', markup.toString());
}
}
};
}
/**
* Operations for updating with DOM children.
*/
var DOMChildrenOperations = {
dangerouslyReplaceNodeWithMarkup: dangerouslyReplaceNodeWithMarkup,
replaceDelimitedText: replaceDelimitedText,
/**
* 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.
* @internal
*/
processUpdates: function (parentNode, updates) {
if (process.env.NODE_ENV !== 'production') {
var parentNodeDebugID = ReactDOMComponentTree.getInstanceFromNode(parentNode)._debugID;
}
for (var k = 0; k < updates.length; k++) {
var update = updates[k];
switch (update.type) {
case ReactMultiChildUpdateTypes.INSERT_MARKUP:
insertLazyTreeChildAt(parentNode, update.content, getNodeAfter(parentNode, update.afterNode));
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation(parentNodeDebugID, 'insert child', { toIndex: update.toIndex, content: update.content.toString() });
}
break;
case ReactMultiChildUpdateTypes.MOVE_EXISTING:
moveChild(parentNode, update.fromNode, getNodeAfter(parentNode, update.afterNode));
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation(parentNodeDebugID, 'move child', { fromIndex: update.fromIndex, toIndex: update.toIndex });
}
break;
case ReactMultiChildUpdateTypes.SET_MARKUP:
setInnerHTML(parentNode, update.content);
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation(parentNodeDebugID, 'replace children', update.content.toString());
}
break;
case ReactMultiChildUpdateTypes.TEXT_CONTENT:
setTextContent(parentNode, update.content);
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation(parentNodeDebugID, 'replace text', update.content.toString());
}
break;
case ReactMultiChildUpdateTypes.REMOVE_NODE:
removeChild(parentNode, update.fromNode);
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation(parentNodeDebugID, 'remove child', { fromIndex: update.fromIndex });
}
break;
}
}
}
};
module.exports = DOMChildrenOperations;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 83 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2015-present, 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 DOMLazyTree
*/
'use strict';
var DOMNamespaces = __webpack_require__(84);
var setInnerHTML = __webpack_require__(85);
var createMicrosoftUnsafeLocalFunction = __webpack_require__(86);
var setTextContent = __webpack_require__(87);
var ELEMENT_NODE_TYPE = 1;
var DOCUMENT_FRAGMENT_NODE_TYPE = 11;
/**
* In IE (8-11) and Edge, appending nodes with no children is dramatically
* faster than appending a full subtree, so we essentially queue up the
* .appendChild calls here and apply them so each node is added to its parent
* before any children are added.
*
* In other browsers, doing so is slower or neutral compared to the other order
* (in Firefox, twice as slow) so we only do this inversion in IE.
*
* See https://github.com/spicyj/innerhtml-vs-createelement-vs-clonenode.
*/
var enableLazy = typeof document !== 'undefined' && typeof document.documentMode === 'number' || typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string' && /\bEdge\/\d/.test(navigator.userAgent);
function insertTreeChildren(tree) {
if (!enableLazy) {
return;
}
var node = tree.node;
var children = tree.children;
if (children.length) {
for (var i = 0; i < children.length; i++) {
insertTreeBefore(node, children[i], null);
}
} else if (tree.html != null) {
setInnerHTML(node, tree.html);
} else if (tree.text != null) {
setTextContent(node, tree.text);
}
}
var insertTreeBefore = createMicrosoftUnsafeLocalFunction(function (parentNode, tree, referenceNode) {
// DocumentFragments aren't actually part of the DOM after insertion so
// appending children won't update the DOM. We need to ensure the fragment
// is properly populated first, breaking out of our lazy approach for just
// this level. Also, some <object> plugins (like Flash Player) will read
// <param> nodes immediately upon insertion into the DOM, so <object>
// must also be populated prior to insertion into the DOM.
if (tree.node.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE || tree.node.nodeType === ELEMENT_NODE_TYPE && tree.node.nodeName.toLowerCase() === 'object' && (tree.node.namespaceURI == null || tree.node.namespaceURI === DOMNamespaces.html)) {
insertTreeChildren(tree);
parentNode.insertBefore(tree.node, referenceNode);
} else {
parentNode.insertBefore(tree.node, referenceNode);
insertTreeChildren(tree);
}
});
function replaceChildWithTree(oldNode, newTree) {
oldNode.parentNode.replaceChild(newTree.node, oldNode);
insertTreeChildren(newTree);
}
function queueChild(parentTree, childTree) {
if (enableLazy) {
parentTree.children.push(childTree);
} else {
parentTree.node.appendChild(childTree.node);
}
}
function queueHTML(tree, html) {
if (enableLazy) {
tree.html = html;
} else {
setInnerHTML(tree.node, html);
}
}
function queueText(tree, text) {
if (enableLazy) {
tree.text = text;
} else {
setTextContent(tree.node, text);
}
}
function toString() {
return this.node.nodeName;
}
function DOMLazyTree(node) {
return {
node: node,
children: [],
html: null,
text: null,
toString: toString
};
}
DOMLazyTree.insertTreeBefore = insertTreeBefore;
DOMLazyTree.replaceChildWithTree = replaceChildWithTree;
DOMLazyTree.queueChild = queueChild;
DOMLazyTree.queueHTML = queueHTML;
DOMLazyTree.queueText = queueText;
module.exports = DOMLazyTree;
/***/ },
/* 84 */
/***/ function(module, exports) {
/**
* Copyright 2013-present, 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 DOMNamespaces
*/
'use strict';
var DOMNamespaces = {
html: 'http://www.w3.org/1999/xhtml',
mathml: 'http://www.w3.org/1998/Math/MathML',
svg: 'http://www.w3.org/2000/svg'
};
module.exports = DOMNamespaces;
/***/ },
/* 85 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(50);
var DOMNamespaces = __webpack_require__(84);
var WHITESPACE_TEST = /^[ \r\n\t\f]/;
var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/;
var createMicrosoftUnsafeLocalFunction = __webpack_require__(86);
// SVG temp container for IE lacking innerHTML
var reusableSVGContainer;
/**
* Set the innerHTML property of a node, ensuring that whitespace is preserved
* even in IE8.
*
* @param {DOMElement} node
* @param {string} html
* @internal
*/
var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) {
// IE does not have innerHTML for SVG nodes, so instead we inject the
// new markup in a temp node and then move the child nodes across into
// the target node
if (node.namespaceURI === DOMNamespaces.svg && !('innerHTML' in node)) {
reusableSVGContainer = reusableSVGContainer || document.createElement('div');
reusableSVGContainer.innerHTML = '<svg>' + html + '</svg>';
var newNodes = reusableSVGContainer.firstChild.childNodes;
for (var i = 0; i < newNodes.length; i++) {
node.appendChild(newNodes[i]);
}
} else {
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;
}
};
}
testElement = null;
}
module.exports = setInnerHTML;
/***/ },
/* 86 */
/***/ function(module, exports) {
/**
* Copyright 2013-present, 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 createMicrosoftUnsafeLocalFunction
*/
/* globals MSApp */
'use strict';
/**
* Create a function which has 'unsafe' privileges (required by windows8 apps)
*/
var createMicrosoftUnsafeLocalFunction = function (func) {
if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {
return function (arg0, arg1, arg2, arg3) {
MSApp.execUnsafeLocalFunction(function () {
return func(arg0, arg1, arg2, arg3);
});
};
} else {
return func;
}
};
module.exports = createMicrosoftUnsafeLocalFunction;
/***/ },
/* 87 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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__(50);
var escapeTextContentForBrowser = __webpack_require__(88);
var setInnerHTML = __webpack_require__(85);
/**
* 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) {
if (text) {
var firstChild = node.firstChild;
if (firstChild && firstChild === node.lastChild && firstChild.nodeType === 3) {
firstChild.nodeValue = text;
return;
}
}
node.textContent = text;
};
if (ExecutionEnvironment.canUseDOM) {
if (!('textContent' in document.documentElement)) {
setTextContent = function (node, text) {
setInnerHTML(node, escapeTextContentForBrowser(text));
};
}
}
module.exports = setTextContent;
/***/ },
/* 88 */
/***/ function(module, exports) {
/**
* Copyright 2016-present, 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.
*
* Based on the escape-html library, which is used under the MIT License below:
*
* Copyright (c) 2012-2013 TJ Holowaychuk
* Copyright (c) 2015 Andreas Lubbe
* Copyright (c) 2015 Tiancheng "Timothy" Gu
*
* 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.
*
* @providesModule escapeTextContentForBrowser
*/
'use strict';
// code copied and modified from escape-html
/**
* Module variables.
* @private
*/
var matchHtmlRegExp = /["'&<>]/;
/**
* Escape special characters in the given string of html.
*
* @param {string} string The string to escape for inserting into HTML
* @return {string}
* @public
*/
function escapeHtml(string) {
var str = '' + string;
var match = matchHtmlRegExp.exec(str);
if (!match) {
return str;
}
var escape;
var html = '';
var index = 0;
var lastIndex = 0;
for (index = match.index; index < str.length; index++) {
switch (str.charCodeAt(index)) {
case 34:
// "
escape = '"';
break;
case 38:
// &
escape = '&';
break;
case 39:
// '
escape = '''; // modified from escape-html; used to be '''
break;
case 60:
// <
escape = '<';
break;
case 62:
// >
escape = '>';
break;
default:
continue;
}
if (lastIndex !== index) {
html += str.substring(lastIndex, index);
}
lastIndex = index + 1;
html += escape;
}
return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
}
// end code copied and modified from escape-html
/**
* Escapes text to prevent scripting attacks.
*
* @param {*} text Text value to escape.
* @return {string} An escaped string.
*/
function escapeTextContentForBrowser(text) {
if (typeof text === 'boolean' || typeof text === 'number') {
// this shortcircuit helps perf for types that we know will never have
// special characters, especially given that this function is used often
// for numeric dom ids.
return '' + text;
}
return escapeHtml(text);
}
module.exports = escapeTextContentForBrowser;
/***/ },
/* 89 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var DOMLazyTree = __webpack_require__(83);
var ExecutionEnvironment = __webpack_require__(50);
var createNodesFromMarkup = __webpack_require__(90);
var emptyFunction = __webpack_require__(12);
var invariant = __webpack_require__(8);
var Danger = {
/**
* 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.') : _prodInvariant('56') : void 0;
!markup ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : _prodInvariant('57') : void 0;
!(oldChild.nodeName !== '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().') : _prodInvariant('58') : void 0;
if (typeof markup === 'string') {
var newChild = createNodesFromMarkup(markup, emptyFunction)[0];
oldChild.parentNode.replaceChild(newChild, oldChild);
} else {
DOMLazyTree.replaceChildWithTree(oldChild, markup);
}
}
};
module.exports = Danger;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 90 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {'use strict';
/**
* Copyright (c) 2013-present, 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
*/
/*eslint-disable fb-www/unsafe-html*/
var ExecutionEnvironment = __webpack_require__(50);
var createArrayFromMixed = __webpack_require__(91);
var getMarkupWrap = __webpack_require__(92);
var invariant = __webpack_require__(8);
/**
* 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) : void 0;
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) : void 0;
createArrayFromMixed(scripts).forEach(handleScript);
}
var nodes = Array.from(node.childNodes);
while (node.lastChild) {
node.removeChild(node.lastChild);
}
return nodes;
}
module.exports = createNodesFromMarkup;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 91 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {'use strict';
/**
* Copyright (c) 2013-present, 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
*/
var invariant = __webpack_require__(8);
/**
* 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 browsers 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) : void 0;
!(typeof length === 'number') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object needs a length property') : invariant(false) : void 0;
!(length === 0 || length - 1 in obj) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object should have keys for indices') : invariant(false) : void 0;
!(typeof obj.callee !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object can\'t be `arguments`. Use rest params ' + '(function(...args) {}) or Array.from() instead.') : invariant(false) : void 0;
// 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;
}
/**
* 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;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 92 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {'use strict';
/**
* Copyright (c) 2013-present, 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.
*
*/
/*eslint-disable fb-www/unsafe-html */
var ExecutionEnvironment = __webpack_require__(50);
var invariant = __webpack_require__(8);
/**
* 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) : void 0;
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__(3)))
/***/ },
/* 93 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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__(23);
/**
* 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;
/***/ },
/* 94 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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
*/
'use strict';
var DOMChildrenOperations = __webpack_require__(82);
var ReactDOMComponentTree = __webpack_require__(37);
/**
* Operations used to process updates to DOM nodes.
*/
var ReactDOMIDOperations = {
/**
* Updates a component's children by processing a series of updates.
*
* @param {array<object>} updates List of update configurations.
* @internal
*/
dangerouslyProcessChildrenUpdates: function (parentInst, updates) {
var node = ReactDOMComponentTree.getNodeFromInstance(parentInst);
DOMChildrenOperations.processUpdates(node, updates);
}
};
module.exports = ReactDOMIDOperations;
/***/ },
/* 95 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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
*/
/* global hasOwnProperty:true */
'use strict';
var _prodInvariant = __webpack_require__(7),
_assign = __webpack_require__(4);
var AutoFocusUtils = __webpack_require__(96);
var CSSPropertyOperations = __webpack_require__(98);
var DOMLazyTree = __webpack_require__(83);
var DOMNamespaces = __webpack_require__(84);
var DOMProperty = __webpack_require__(38);
var DOMPropertyOperations = __webpack_require__(106);
var EventConstants = __webpack_require__(42);
var EventPluginHub = __webpack_require__(44);
var EventPluginRegistry = __webpack_require__(45);
var ReactBrowserEventEmitter = __webpack_require__(112);
var ReactComponentBrowserEnvironment = __webpack_require__(81);
var ReactDOMButton = __webpack_require__(115);
var ReactDOMComponentFlags = __webpack_require__(39);
var ReactDOMComponentTree = __webpack_require__(37);
var ReactDOMInput = __webpack_require__(117);
var ReactDOMOption = __webpack_require__(119);
var ReactDOMSelect = __webpack_require__(120);
var ReactDOMTextarea = __webpack_require__(121);
var ReactInstrumentation = __webpack_require__(63);
var ReactMultiChild = __webpack_require__(122);
var ReactServerRenderingTransaction = __webpack_require__(134);
var emptyFunction = __webpack_require__(12);
var escapeTextContentForBrowser = __webpack_require__(88);
var invariant = __webpack_require__(8);
var isEventSupported = __webpack_require__(72);
var keyOf = __webpack_require__(25);
var shallowEqual = __webpack_require__(129);
var validateDOMNesting = __webpack_require__(137);
var warning = __webpack_require__(11);
var Flags = ReactDOMComponentFlags;
var deleteListener = EventPluginHub.deleteListener;
var getNode = ReactDOMComponentTree.getNodeFromInstance;
var listenTo = ReactBrowserEventEmitter.listenTo;
var registrationNameModules = EventPluginRegistry.registrationNameModules;
// For quickly matching children type, to test if can be treated as content.
var CONTENT_TYPES = { 'string': true, 'number': true };
var STYLE = keyOf({ style: null });
var HTML = keyOf({ __html: null });
var RESERVED_PROPS = {
children: null,
dangerouslySetInnerHTML: null,
suppressContentEditableWarning: null
};
// Node type for document fragments (Node.DOCUMENT_FRAGMENT_NODE).
var DOC_FRAGMENT_TYPE = 11;
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 '';
}
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 because 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)) : void 0;
}
/**
* @param {object} component
* @param {?object} props
*/
function assertValidProps(component, props) {
if (!props) {
return;
}
// Note the use of `==` which checks for null or undefined.
if (voidElementTags[component._tag]) {
!(props.children == null && props.dangerouslySetInnerHTML == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.%s', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : _prodInvariant('137', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : void 0;
}
if (props.dangerouslySetInnerHTML != null) {
!(props.children == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : _prodInvariant('60') : void 0;
!(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.') : _prodInvariant('61') : void 0;
}
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`.') : void 0;
process.env.NODE_ENV !== 'production' ? warning(props.suppressContentEditableWarning || !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.') : void 0;
process.env.NODE_ENV !== 'production' ? warning(props.onFocusIn == null && props.onFocusOut == null, 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.') : void 0;
}
!(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)) : _prodInvariant('62', getDeclarationErrorAddendum(component)) : void 0;
}
function enqueuePutListener(inst, registrationName, listener, transaction) {
if (transaction instanceof ReactServerRenderingTransaction) {
return;
}
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') : void 0;
}
var containerInfo = inst._hostContainerInfo;
var isDocumentFragment = containerInfo._node && containerInfo._node.nodeType === DOC_FRAGMENT_TYPE;
var doc = isDocumentFragment ? containerInfo._node : containerInfo._ownerDocument;
listenTo(registrationName, doc);
transaction.getReactMountReady().enqueue(putListener, {
inst: inst,
registrationName: registrationName,
listener: listener
});
}
function putListener() {
var listenerToPut = this;
EventPluginHub.putListener(listenerToPut.inst, listenerToPut.registrationName, listenerToPut.listener);
}
function inputPostMount() {
var inst = this;
ReactDOMInput.postMountWrapper(inst);
}
function textareaPostMount() {
var inst = this;
ReactDOMTextarea.postMountWrapper(inst);
}
function optionPostMount() {
var inst = this;
ReactDOMOption.postMountWrapper(inst);
}
var setContentChildForInstrumentation = emptyFunction;
if (process.env.NODE_ENV !== 'production') {
setContentChildForInstrumentation = function (content) {
var hasExistingContent = this._contentDebugID != null;
var debugID = this._debugID;
var contentDebugID = debugID + '#text';
if (content == null) {
if (hasExistingContent) {
ReactInstrumentation.debugTool.onUnmountComponent(this._contentDebugID);
}
this._contentDebugID = null;
return;
}
this._contentDebugID = contentDebugID;
var text = '' + content;
ReactInstrumentation.debugTool.onSetDisplayName(contentDebugID, '#text');
ReactInstrumentation.debugTool.onSetParent(contentDebugID, debugID);
ReactInstrumentation.debugTool.onSetText(contentDebugID, text);
if (hasExistingContent) {
ReactInstrumentation.debugTool.onBeforeUpdateComponent(contentDebugID, content);
ReactInstrumentation.debugTool.onUpdateComponent(contentDebugID);
} else {
ReactInstrumentation.debugTool.onBeforeMountComponent(contentDebugID, content);
ReactInstrumentation.debugTool.onMountComponent(contentDebugID);
ReactInstrumentation.debugTool.onSetChildren(debugID, [contentDebugID]);
}
};
}
// 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') : _prodInvariant('63') : void 0;
var node = getNode(inst);
!node ? process.env.NODE_ENV !== 'production' ? invariant(false, 'trapBubbledEvent(...): Requires node to be rendered.') : _prodInvariant('64') : void 0;
switch (inst._tag) {
case 'iframe':
case 'object':
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 'source':
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topError, 'error', 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;
case 'input':
case 'select':
case 'textarea':
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topInvalid, 'invalid', node)];
break;
}
}
function postUpdateSelectWrapper() {
ReactDOMSelect.postUpdateWrapper(this);
}
// For HTML, certain tags should omit their close tag. We keep a whitelist for
// those special-case 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) : _prodInvariant('65', tag) : void 0;
validatedTagCache[tag] = true;
}
}
function isCustomComponent(tagName, props) {
return tagName.indexOf('-') >= 0 || props.is != null;
}
var globalIdCounter = 1;
/**
* 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(element) {
var tag = element.type;
validateDangerousTag(tag);
this._currentElement = element;
this._tag = tag.toLowerCase();
this._namespaceURI = null;
this._renderedChildren = null;
this._previousStyle = null;
this._previousStyleCopy = null;
this._hostNode = null;
this._hostParent = null;
this._rootNodeID = null;
this._domID = null;
this._hostContainerInfo = null;
this._wrapperState = null;
this._topLevelWrapper = null;
this._flags = 0;
if (process.env.NODE_ENV !== 'production') {
this._ancestorInfo = null;
setContentChildForInstrumentation.call(this, null);
}
}
ReactDOMComponent.displayName = 'ReactDOMComponent';
ReactDOMComponent.Mixin = {
/**
* Generates root tag markup then recurses. This method has side effects and
* is not idempotent.
*
* @internal
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {?ReactDOMComponent} the containing DOM component instance
* @param {?object} info about the host container
* @param {object} context
* @return {string} The computed markup.
*/
mountComponent: function (transaction, hostParent, hostContainerInfo, context) {
var _this = this;
this._rootNodeID = globalIdCounter++;
this._domID = hostContainerInfo._idCounter++;
this._hostParent = hostParent;
this._hostContainerInfo = hostContainerInfo;
var props = this._currentElement.props;
switch (this._tag) {
case 'audio':
case 'form':
case 'iframe':
case 'img':
case 'link':
case 'object':
case 'source':
case 'video':
this._wrapperState = {
listeners: null
};
transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
break;
case 'button':
props = ReactDOMButton.getHostProps(this, props, hostParent);
break;
case 'input':
ReactDOMInput.mountWrapper(this, props, hostParent);
props = ReactDOMInput.getHostProps(this, props);
transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
break;
case 'option':
ReactDOMOption.mountWrapper(this, props, hostParent);
props = ReactDOMOption.getHostProps(this, props);
break;
case 'select':
ReactDOMSelect.mountWrapper(this, props, hostParent);
props = ReactDOMSelect.getHostProps(this, props);
transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
break;
case 'textarea':
ReactDOMTextarea.mountWrapper(this, props, hostParent);
props = ReactDOMTextarea.getHostProps(this, props);
transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
break;
}
assertValidProps(this, props);
// We create tags in the namespace of their parent container, except HTML
// tags get no namespace.
var namespaceURI;
var parentTag;
if (hostParent != null) {
namespaceURI = hostParent._namespaceURI;
parentTag = hostParent._tag;
} else if (hostContainerInfo._tag) {
namespaceURI = hostContainerInfo._namespaceURI;
parentTag = hostContainerInfo._tag;
}
if (namespaceURI == null || namespaceURI === DOMNamespaces.svg && parentTag === 'foreignobject') {
namespaceURI = DOMNamespaces.html;
}
if (namespaceURI === DOMNamespaces.html) {
if (this._tag === 'svg') {
namespaceURI = DOMNamespaces.svg;
} else if (this._tag === 'math') {
namespaceURI = DOMNamespaces.mathml;
}
}
this._namespaceURI = namespaceURI;
if (process.env.NODE_ENV !== 'production') {
var parentInfo;
if (hostParent != null) {
parentInfo = hostParent._ancestorInfo;
} else if (hostContainerInfo._tag) {
parentInfo = hostContainerInfo._ancestorInfo;
}
if (parentInfo) {
// parentInfo should always be present except for the top-level
// component when server rendering
validateDOMNesting(this._tag, this, parentInfo);
}
this._ancestorInfo = validateDOMNesting.updatedAncestorInfo(parentInfo, this._tag, this);
}
var mountImage;
if (transaction.useCreateElement) {
var ownerDocument = hostContainerInfo._ownerDocument;
var el;
if (namespaceURI === DOMNamespaces.html) {
if (this._tag === 'script') {
// Create the script via .innerHTML so its "parser-inserted" flag is
// set to true and it does not execute
var div = ownerDocument.createElement('div');
var type = this._currentElement.type;
div.innerHTML = '<' + type + '></' + type + '>';
el = div.removeChild(div.firstChild);
} else if (props.is) {
el = ownerDocument.createElement(this._currentElement.type, props.is);
} else {
// Separate else branch instead of using `props.is || undefined` above becuase of a Firefox bug.
// See discussion in https://github.com/facebook/react/pull/6896
// and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240
el = ownerDocument.createElement(this._currentElement.type);
}
} else {
el = ownerDocument.createElementNS(namespaceURI, this._currentElement.type);
}
ReactDOMComponentTree.precacheNode(this, el);
this._flags |= Flags.hasCachedChildNodes;
if (!this._hostParent) {
DOMPropertyOperations.setAttributeForRoot(el);
}
this._updateDOMProperties(null, props, transaction);
var lazyTree = DOMLazyTree(el);
this._createInitialChildren(transaction, props, context, lazyTree);
mountImage = lazyTree;
} 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(inputPostMount, this);
if (props.autoFocus) {
transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this);
}
break;
case 'textarea':
transaction.getReactMountReady().enqueue(textareaPostMount, this);
if (props.autoFocus) {
transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this);
}
break;
case 'select':
if (props.autoFocus) {
transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this);
}
break;
case 'button':
if (props.autoFocus) {
transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this);
}
break;
case 'option':
transaction.getReactMountReady().enqueue(optionPostMount, this);
break;
}
if (process.env.NODE_ENV !== 'production') {
if (this._debugID) {
var callback = function () {
return ReactInstrumentation.debugTool.onComponentHasMounted(_this._debugID);
};
transaction.getReactMountReady().enqueue(callback, this);
}
}
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, 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, this);
}
var markup = null;
if (this._tag != null && isCustomComponent(this._tag, props)) {
if (!RESERVED_PROPS.hasOwnProperty(propKey)) {
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;
}
if (!this._hostParent) {
ret += ' ' + DOMPropertyOperations.createMarkupForRoot();
}
ret += ' ' + DOMPropertyOperations.createMarkupForID(this._domID);
return ret;
},
/**
* 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);
if (process.env.NODE_ENV !== 'production') {
setContentChildForInstrumentation.call(this, 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, lazyTree) {
// Intentional use of != to avoid catching zero/false.
var innerHTML = props.dangerouslySetInnerHTML;
if (innerHTML != null) {
if (innerHTML.__html != null) {
DOMLazyTree.queueHTML(lazyTree, 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
if (process.env.NODE_ENV !== 'production') {
setContentChildForInstrumentation.call(this, contentToUse);
}
DOMLazyTree.queueText(lazyTree, contentToUse);
} else if (childrenToUse != null) {
var mountImages = this.mountChildren(childrenToUse, transaction, context);
for (var i = 0; i < mountImages.length; i++) {
DOMLazyTree.queueChild(lazyTree, 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 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 _this2 = this;
var lastProps = prevElement.props;
var nextProps = this._currentElement.props;
switch (this._tag) {
case 'button':
lastProps = ReactDOMButton.getHostProps(this, lastProps);
nextProps = ReactDOMButton.getHostProps(this, nextProps);
break;
case 'input':
ReactDOMInput.updateWrapper(this);
lastProps = ReactDOMInput.getHostProps(this, lastProps);
nextProps = ReactDOMInput.getHostProps(this, nextProps);
break;
case 'option':
lastProps = ReactDOMOption.getHostProps(this, lastProps);
nextProps = ReactDOMOption.getHostProps(this, nextProps);
break;
case 'select':
lastProps = ReactDOMSelect.getHostProps(this, lastProps);
nextProps = ReactDOMSelect.getHostProps(this, nextProps);
break;
case 'textarea':
ReactDOMTextarea.updateWrapper(this);
lastProps = ReactDOMTextarea.getHostProps(this, lastProps);
nextProps = ReactDOMTextarea.getHostProps(this, nextProps);
break;
}
assertValidProps(this, nextProps);
this._updateDOMProperties(lastProps, nextProps, transaction);
this._updateDOMChildren(lastProps, nextProps, transaction, context);
if (this._tag === 'select') {
// <select> value update needs to occur after <option> children
// reconciliation
transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this);
}
if (process.env.NODE_ENV !== 'production') {
if (this._debugID) {
var callback = function () {
return ReactInstrumentation.debugTool.onComponentHasUpdated(_this2._debugID);
};
transaction.getReactMountReady().enqueue(callback, 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 {?DOMElement} node
*/
_updateDOMProperties: function (lastProps, nextProps, transaction) {
var propKey;
var styleName;
var styleUpdates;
for (propKey in lastProps) {
if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) {
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, propKey);
}
} else if (isCustomComponent(this._tag, lastProps)) {
if (!RESERVED_PROPS.hasOwnProperty(propKey)) {
DOMPropertyOperations.deleteValueForAttribute(getNode(this), propKey);
}
} else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) {
DOMPropertyOperations.deleteValueForProperty(getNode(this), propKey);
}
}
for (propKey in nextProps) {
var nextProp = nextProps[propKey];
var lastProp = propKey === STYLE ? this._previousStyleCopy : lastProps != null ? lastProps[propKey] : undefined;
if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) {
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, propKey, nextProp, transaction);
} else if (lastProp) {
deleteListener(this, propKey);
}
} else if (isCustomComponent(this._tag, nextProps)) {
if (!RESERVED_PROPS.hasOwnProperty(propKey)) {
DOMPropertyOperations.setValueForAttribute(getNode(this), propKey, nextProp);
}
} else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) {
var node = getNode(this);
// If we're updating to null or undefined, we should remove the property
// from the DOM node instead of inadvertently 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) {
CSSPropertyOperations.setValueForStyles(getNode(this), styleUpdates, this);
}
},
/**
* 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 (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onSetChildren(this._debugID, []);
}
}
if (nextContent != null) {
if (lastContent !== nextContent) {
this.updateTextContent('' + nextContent);
if (process.env.NODE_ENV !== 'production') {
setContentChildForInstrumentation.call(this, nextContent);
}
}
} else if (nextHtml != null) {
if (lastHtml !== nextHtml) {
this.updateMarkup('' + nextHtml);
}
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onSetChildren(this._debugID, []);
}
} else if (nextChildren != null) {
if (process.env.NODE_ENV !== 'production') {
setContentChildForInstrumentation.call(this, null);
}
this.updateChildren(nextChildren, transaction, context);
}
},
getHostNode: function () {
return getNode(this);
},
/**
* Destroys all event registrations for this instance. Does not remove from
* the DOM. That must be done by the parent.
*
* @internal
*/
unmountComponent: function (safely) {
switch (this._tag) {
case 'audio':
case 'form':
case 'iframe':
case 'img':
case 'link':
case 'object':
case 'source':
case 'video':
var listeners = this._wrapperState.listeners;
if (listeners) {
for (var i = 0; i < listeners.length; i++) {
listeners[i].remove();
}
}
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) : _prodInvariant('66', this._tag) : void 0;
break;
}
this.unmountChildren(safely);
ReactDOMComponentTree.uncacheNode(this);
EventPluginHub.deleteAllListeners(this);
ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID);
this._rootNodeID = null;
this._domID = null;
this._wrapperState = null;
if (process.env.NODE_ENV !== 'production') {
setContentChildForInstrumentation.call(this, null);
}
},
getPublicInstance: function () {
return getNode(this);
}
};
_assign(ReactDOMComponent.prototype, ReactDOMComponent.Mixin, ReactMultiChild.Mixin);
module.exports = ReactDOMComponent;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 96 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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
*/
'use strict';
var ReactDOMComponentTree = __webpack_require__(37);
var focusNode = __webpack_require__(97);
var AutoFocusUtils = {
focusDOMComponent: function () {
focusNode(ReactDOMComponentTree.getNodeFromInstance(this));
}
};
module.exports = AutoFocusUtils;
/***/ },
/* 97 */
/***/ function(module, exports) {
/**
* Copyright (c) 2013-present, 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.
*
*/
'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;
/***/ },
/* 98 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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
*/
'use strict';
var CSSProperty = __webpack_require__(99);
var ExecutionEnvironment = __webpack_require__(50);
var ReactInstrumentation = __webpack_require__(63);
var camelizeStyleName = __webpack_require__(100);
var dangerousStyleValue = __webpack_require__(102);
var hyphenateStyleName = __webpack_require__(103);
var memoizeStringOnly = __webpack_require__(105);
var warning = __webpack_require__(11);
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 warnedForNaNValue = false;
var warnHyphenatedStyleName = function (name, owner) {
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?%s', name, camelizeStyleName(name), checkRenderMessage(owner)) : void 0;
};
var warnBadVendoredStyleName = function (name, owner) {
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?%s', name, name.charAt(0).toUpperCase() + name.slice(1), checkRenderMessage(owner)) : void 0;
};
var warnStyleValueWithSemicolon = function (name, value, owner) {
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.%s ' + 'Try "%s: %s" instead.', checkRenderMessage(owner), name, value.replace(badStyleValueWithSemicolonPattern, '')) : void 0;
};
var warnStyleValueIsNaN = function (name, value, owner) {
if (warnedForNaNValue) {
return;
}
warnedForNaNValue = true;
process.env.NODE_ENV !== 'production' ? warning(false, '`NaN` is an invalid value for the `%s` css style property.%s', name, checkRenderMessage(owner)) : void 0;
};
var checkRenderMessage = function (owner) {
if (owner) {
var name = owner.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
};
/**
* @param {string} name
* @param {*} value
* @param {ReactDOMComponent} component
*/
var warnValidStyle = function (name, value, component) {
var owner;
if (component) {
owner = component._currentElement._owner;
}
if (name.indexOf('-') > -1) {
warnHyphenatedStyleName(name, owner);
} else if (badVendoredStyleNamePattern.test(name)) {
warnBadVendoredStyleName(name, owner);
} else if (badStyleValueWithSemicolonPattern.test(value)) {
warnStyleValueWithSemicolon(name, value, owner);
}
if (typeof value === 'number' && isNaN(value)) {
warnStyleValueIsNaN(name, value, owner);
}
};
}
/**
* 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
* @param {ReactDOMComponent} component
* @return {?string}
*/
createMarkupForStyles: function (styles, component) {
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, component);
}
if (styleValue != null) {
serialized += processStyleName(styleName) + ':';
serialized += dangerousStyleValue(styleName, styleValue, component) + ';';
}
}
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
* @param {ReactDOMComponent} component
*/
setValueForStyles: function (node, styles, component) {
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation(component._debugID, 'update styles', 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], component);
}
var styleValue = dangerousStyleValue(styleName, styles[styleName], component);
if (styleName === 'float' || styleName === 'cssFloat') {
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] = '';
}
}
}
}
};
module.exports = CSSPropertyOperations;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 99 */
/***/ function(module, exports) {
/**
* Copyright 2013-present, 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,
borderImageOutset: true,
borderImageSlice: true,
borderImageWidth: true,
boxFlex: true,
boxFlexGroup: true,
boxOrdinalGroup: true,
columnCount: true,
flex: true,
flexGrow: true,
flexPositive: true,
flexShrink: true,
flexNegative: true,
flexOrder: true,
gridRow: true,
gridColumn: 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,
floodOpacity: true,
stopOpacity: true,
strokeDasharray: true,
strokeDashoffset: true,
strokeMiterlimit: 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;
/***/ },
/* 100 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright (c) 2013-present, 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
*/
'use strict';
var camelize = __webpack_require__(101);
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;
/***/ },
/* 101 */
/***/ function(module, exports) {
"use strict";
/**
* Copyright (c) 2013-present, 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
*/
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;
/***/ },
/* 102 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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
*/
'use strict';
var CSSProperty = __webpack_require__(99);
var warning = __webpack_require__(11);
var isUnitlessNumber = CSSProperty.isUnitlessNumber;
var styleWarnings = {};
/**
* 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`.
* @param {ReactDOMComponent} component
* @return {string} Normalized style value with dimensions applied.
*/
function dangerousStyleValue(name, value, component) {
// 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') {
if (process.env.NODE_ENV !== 'production') {
// Allow '0' to pass through without warning. 0 is already special and
// doesn't require units, so we don't need to warn about it.
if (component && value !== '0') {
var owner = component._currentElement._owner;
var ownerName = owner ? owner.getName() : null;
if (ownerName && !styleWarnings[ownerName]) {
styleWarnings[ownerName] = {};
}
var warned = false;
if (ownerName) {
var warnings = styleWarnings[ownerName];
warned = warnings[name];
if (!warned) {
warnings[name] = true;
}
}
if (!warned) {
process.env.NODE_ENV !== 'production' ? warning(false, 'a `%s` tag (owner: `%s`) was passed a numeric string value ' + 'for CSS property `%s` (value: `%s`) which will be treated ' + 'as a unitless number in a future version of React.', component._currentElement.type, ownerName || 'unknown', name, value) : void 0;
}
}
}
value = value.trim();
}
return value + 'px';
}
module.exports = dangerousStyleValue;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 103 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright (c) 2013-present, 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
*/
'use strict';
var hyphenate = __webpack_require__(104);
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;
/***/ },
/* 104 */
/***/ function(module, exports) {
'use strict';
/**
* Copyright (c) 2013-present, 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
*/
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;
/***/ },
/* 105 */
/***/ function(module, exports) {
/**
* Copyright (c) 2013-present, 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
*/
'use strict';
/**
* Memoizes the return value of a function that accepts one string argument.
*/
function memoizeStringOnly(callback) {
var cache = {};
return function (string) {
if (!cache.hasOwnProperty(string)) {
cache[string] = callback.call(this, string);
}
return cache[string];
};
}
module.exports = memoizeStringOnly;
/***/ },
/* 106 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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
*/
'use strict';
var DOMProperty = __webpack_require__(38);
var ReactDOMComponentTree = __webpack_require__(37);
var ReactDOMInstrumentation = __webpack_require__(107);
var ReactInstrumentation = __webpack_require__(63);
var quoteAttributeValueForBrowser = __webpack_require__(111);
var warning = __webpack_require__(11);
var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + DOMProperty.ATTRIBUTE_NAME_START_CHAR + '][' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$');
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) : void 0;
return false;
}
function shouldIgnoreValue(propertyInfo, value) {
return value == null || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && isNaN(value) || propertyInfo.hasPositiveNumericValue && value < 1 || propertyInfo.hasOverloadedBooleanValue && value === false;
}
/**
* 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);
},
createMarkupForRoot: function () {
return DOMProperty.ROOT_ATTRIBUTE_NAME + '=""';
},
setAttributeForRoot: function (node) {
node.setAttribute(DOMProperty.ROOT_ATTRIBUTE_NAME, '');
},
/**
* 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) {
if (process.env.NODE_ENV !== 'production') {
ReactDOMInstrumentation.debugTool.onCreateMarkupForProperty(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);
}
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);
return;
} else if (propertyInfo.mustUseProperty) {
// Contrary to `setAttribute`, object properties are properly
// `toString`ed by IE8/9.
node[propertyInfo.propertyName] = value;
} else {
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 if (DOMProperty.isCustomAttribute(name)) {
DOMPropertyOperations.setValueForAttribute(node, name, value);
return;
}
if (process.env.NODE_ENV !== 'production') {
ReactDOMInstrumentation.debugTool.onSetValueForProperty(node, name, value);
var payload = {};
payload[name] = value;
ReactInstrumentation.debugTool.onHostOperation(ReactDOMComponentTree.getInstanceFromNode(node)._debugID, 'update attribute', payload);
}
},
setValueForAttribute: function (node, name, value) {
if (!isAttributeNameSafe(name)) {
return;
}
if (value == null) {
node.removeAttribute(name);
} else {
node.setAttribute(name, '' + value);
}
if (process.env.NODE_ENV !== 'production') {
var payload = {};
payload[name] = value;
ReactInstrumentation.debugTool.onHostOperation(ReactDOMComponentTree.getInstanceFromNode(node)._debugID, 'update attribute', payload);
}
},
/**
* Deletes an attributes from a node.
*
* @param {DOMElement} node
* @param {string} name
*/
deleteValueForAttribute: function (node, name) {
node.removeAttribute(name);
if (process.env.NODE_ENV !== 'production') {
ReactDOMInstrumentation.debugTool.onDeleteValueForProperty(node, name);
ReactInstrumentation.debugTool.onHostOperation(ReactDOMComponentTree.getInstanceFromNode(node)._debugID, 'remove attribute', name);
}
},
/**
* 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.mustUseProperty) {
var propName = propertyInfo.propertyName;
if (propertyInfo.hasBooleanValue) {
node[propName] = false;
} else {
node[propName] = '';
}
} else {
node.removeAttribute(propertyInfo.attributeName);
}
} else if (DOMProperty.isCustomAttribute(name)) {
node.removeAttribute(name);
}
if (process.env.NODE_ENV !== 'production') {
ReactDOMInstrumentation.debugTool.onDeleteValueForProperty(node, name);
ReactInstrumentation.debugTool.onHostOperation(ReactDOMComponentTree.getInstanceFromNode(node)._debugID, 'remove attribute', name);
}
}
};
module.exports = DOMPropertyOperations;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 107 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 ReactDOMInstrumentation
*/
'use strict';
var debugTool = null;
if (process.env.NODE_ENV !== 'production') {
var ReactDOMDebugTool = __webpack_require__(108);
debugTool = ReactDOMDebugTool;
}
module.exports = { debugTool: debugTool };
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 108 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 ReactDOMDebugTool
*/
'use strict';
var ReactDOMNullInputValuePropDevtool = __webpack_require__(109);
var ReactDOMUnknownPropertyDevtool = __webpack_require__(110);
var ReactDebugTool = __webpack_require__(64);
var warning = __webpack_require__(11);
var eventHandlers = [];
var handlerDoesThrowForEvent = {};
function emitEvent(handlerFunctionName, arg1, arg2, arg3, arg4, arg5) {
eventHandlers.forEach(function (handler) {
try {
if (handler[handlerFunctionName]) {
handler[handlerFunctionName](arg1, arg2, arg3, arg4, arg5);
}
} catch (e) {
process.env.NODE_ENV !== 'production' ? warning(handlerDoesThrowForEvent[handlerFunctionName], 'exception thrown by devtool while handling %s: %s', handlerFunctionName, e + '\n' + e.stack) : void 0;
handlerDoesThrowForEvent[handlerFunctionName] = true;
}
});
}
var ReactDOMDebugTool = {
addDevtool: function (devtool) {
ReactDebugTool.addDevtool(devtool);
eventHandlers.push(devtool);
},
removeDevtool: function (devtool) {
ReactDebugTool.removeDevtool(devtool);
for (var i = 0; i < eventHandlers.length; i++) {
if (eventHandlers[i] === devtool) {
eventHandlers.splice(i, 1);
i--;
}
}
},
onCreateMarkupForProperty: function (name, value) {
emitEvent('onCreateMarkupForProperty', name, value);
},
onSetValueForProperty: function (node, name, value) {
emitEvent('onSetValueForProperty', node, name, value);
},
onDeleteValueForProperty: function (node, name) {
emitEvent('onDeleteValueForProperty', node, name);
},
onTestEvent: function () {
emitEvent('onTestEvent');
}
};
ReactDOMDebugTool.addDevtool(ReactDOMUnknownPropertyDevtool);
ReactDOMDebugTool.addDevtool(ReactDOMNullInputValuePropDevtool);
module.exports = ReactDOMDebugTool;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 109 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 ReactDOMNullInputValuePropDevtool
*/
'use strict';
var ReactComponentTreeDevtool = __webpack_require__(29);
var warning = __webpack_require__(11);
var didWarnValueNull = false;
function handleElement(debugID, element) {
if (element == null) {
return;
}
if (element.type !== 'input' && element.type !== 'textarea' && element.type !== 'select') {
return;
}
if (element.props != null && element.props.value === null && !didWarnValueNull) {
process.env.NODE_ENV !== 'production' ? warning(false, '`value` prop on `%s` should not be null. ' + 'Consider using the empty string to clear the component or `undefined` ' + 'for uncontrolled components.%s', element.type, ReactComponentTreeDevtool.getStackAddendumByID(debugID)) : void 0;
didWarnValueNull = true;
}
}
var ReactDOMUnknownPropertyDevtool = {
onBeforeMountComponent: function (debugID, element) {
handleElement(debugID, element);
},
onBeforeUpdateComponent: function (debugID, element) {
handleElement(debugID, element);
}
};
module.exports = ReactDOMUnknownPropertyDevtool;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 110 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 ReactDOMUnknownPropertyDevtool
*/
'use strict';
var DOMProperty = __webpack_require__(38);
var EventPluginRegistry = __webpack_require__(45);
var ReactComponentTreeDevtool = __webpack_require__(29);
var warning = __webpack_require__(11);
if (process.env.NODE_ENV !== 'production') {
var reactProps = {
children: true,
dangerouslySetInnerHTML: true,
key: true,
ref: true,
autoFocus: true,
defaultValue: true,
valueLink: true,
defaultChecked: true,
checkedLink: true,
innerHTML: true,
suppressContentEditableWarning: true,
onFocusIn: true,
onFocusOut: true
};
var warnedProperties = {};
var validateProperty = function (tagName, name, debugID) {
if (DOMProperty.properties.hasOwnProperty(name) || DOMProperty.isCustomAttribute(name)) {
return true;
}
if (reactProps.hasOwnProperty(name) && reactProps[name] || warnedProperties.hasOwnProperty(name) && warnedProperties[name]) {
return true;
}
if (EventPluginRegistry.registrationNameModules.hasOwnProperty(name)) {
return true;
}
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;
var registrationName = EventPluginRegistry.possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? EventPluginRegistry.possibleRegistrationNames[lowerCasedName] : null;
if (standardName != null) {
process.env.NODE_ENV !== 'production' ? warning(standardName == null, 'Unknown DOM property %s. Did you mean %s?%s', name, standardName, ReactComponentTreeDevtool.getStackAddendumByID(debugID)) : void 0;
return true;
} else if (registrationName != null) {
process.env.NODE_ENV !== 'production' ? warning(registrationName == null, 'Unknown event handler property %s. Did you mean `%s`?%s', name, registrationName, ReactComponentTreeDevtool.getStackAddendumByID(debugID)) : void 0;
return true;
} else {
// We were unable to guess which prop the user intended.
// It is likely that the user was just blindly spreading/forwarding props
// Components should be careful to only render valid props/attributes.
// Warning will be invoked in warnUnknownProperties to allow grouping.
return false;
}
};
}
var warnUnknownProperties = function (debugID, element) {
var unknownProps = [];
for (var key in element.props) {
var isValid = validateProperty(element.type, key, debugID);
if (!isValid) {
unknownProps.push(key);
}
}
var unknownPropString = unknownProps.map(function (prop) {
return '`' + prop + '`';
}).join(', ');
if (unknownProps.length === 1) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Unknown prop %s on <%s> tag. Remove this prop from the element. ' + 'For details, see https://fb.me/react-unknown-prop%s', unknownPropString, element.type, ReactComponentTreeDevtool.getStackAddendumByID(debugID)) : void 0;
} else if (unknownProps.length > 1) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Unknown props %s on <%s> tag. Remove these props from the element. ' + 'For details, see https://fb.me/react-unknown-prop%s', unknownPropString, element.type, ReactComponentTreeDevtool.getStackAddendumByID(debugID)) : void 0;
}
};
function handleElement(debugID, element) {
if (element == null || typeof element.type !== 'string') {
return;
}
if (element.type.indexOf('-') >= 0 || element.props.is) {
return;
}
warnUnknownProperties(debugID, element);
}
var ReactDOMUnknownPropertyDevtool = {
onBeforeMountComponent: function (debugID, element) {
handleElement(debugID, element);
},
onBeforeUpdateComponent: function (debugID, element) {
handleElement(debugID, element);
}
};
module.exports = ReactDOMUnknownPropertyDevtool;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 111 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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__(88);
/**
* 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;
/***/ },
/* 112 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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
*/
'use strict';
var _assign = __webpack_require__(4);
var EventConstants = __webpack_require__(42);
var EventPluginRegistry = __webpack_require__(45);
var ReactEventEmitterMixin = __webpack_require__(113);
var ViewportMetrics = __webpack_require__(78);
var getVendorPrefixedEventName = __webpack_require__(114);
var isEventSupported = __webpack_require__(72);
/**
* 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 hasEventPageXY;
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',
topAnimationEnd: getVendorPrefixedEventName('animationend') || 'animationend',
topAnimationIteration: getVendorPrefixedEventName('animationiteration') || 'animationiteration',
topAnimationStart: getVendorPrefixedEventName('animationstart') || 'animationstart',
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',
topTransitionEnd: getVendorPrefixedEventName('transitionend') || 'transitionend',
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:
*
* EventPluginHub.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.
*
* ViewportMetrics is only used by SyntheticMouse/TouchEvent and only when
* pageX/pageY isn't supported (legacy browsers).
*
* NOTE: Scroll events do not bubble.
*
* @see http://www.quirksmode.org/dom/events/scroll.html
*/
ensureScrollValueMonitoring: function () {
if (hasEventPageXY === undefined) {
hasEventPageXY = document.createEvent && 'pageX' in document.createEvent('MouseEvent');
}
if (!hasEventPageXY && !isMonitoringScrollValue) {
var refresh = ViewportMetrics.refreshScrollValues;
ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh);
isMonitoringScrollValue = true;
}
}
});
module.exports = ReactBrowserEventEmitter;
/***/ },
/* 113 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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__(44);
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.
*/
handleTopLevel: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var events = EventPluginHub.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget);
runEventQueueInBatch(events);
}
};
module.exports = ReactEventEmitterMixin;
/***/ },
/* 114 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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 getVendorPrefixedEventName
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(50);
/**
* Generate a mapping of standard vendor prefixes using the defined style property and event name.
*
* @param {string} styleProp
* @param {string} eventName
* @returns {object}
*/
function makePrefixMap(styleProp, eventName) {
var prefixes = {};
prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
prefixes['Webkit' + styleProp] = 'webkit' + eventName;
prefixes['Moz' + styleProp] = 'moz' + eventName;
prefixes['ms' + styleProp] = 'MS' + eventName;
prefixes['O' + styleProp] = 'o' + eventName.toLowerCase();
return prefixes;
}
/**
* A list of event names to a configurable list of vendor prefixes.
*/
var vendorPrefixes = {
animationend: makePrefixMap('Animation', 'AnimationEnd'),
animationiteration: makePrefixMap('Animation', 'AnimationIteration'),
animationstart: makePrefixMap('Animation', 'AnimationStart'),
transitionend: makePrefixMap('Transition', 'TransitionEnd')
};
/**
* Event names that have already been detected and prefixed (if applicable).
*/
var prefixedEventNames = {};
/**
* Element to check for prefixes on.
*/
var style = {};
/**
* Bootstrap if a DOM exists.
*/
if (ExecutionEnvironment.canUseDOM) {
style = document.createElement('div').style;
// On some platforms, in particular some releases of Android 4.x,
// the un-prefixed "animation" and "transition" properties are defined on the
// style object but the events that fire will still be prefixed, so we need
// to check if the un-prefixed events are usable, and if not remove them from the map.
if (!('AnimationEvent' in window)) {
delete vendorPrefixes.animationend.animation;
delete vendorPrefixes.animationiteration.animation;
delete vendorPrefixes.animationstart.animation;
}
// Same as above
if (!('TransitionEvent' in window)) {
delete vendorPrefixes.transitionend.transition;
}
}
/**
* Attempts to determine the correct vendor prefixed event name.
*
* @param {string} eventName
* @returns {string}
*/
function getVendorPrefixedEventName(eventName) {
if (prefixedEventNames[eventName]) {
return prefixedEventNames[eventName];
} else if (!vendorPrefixes[eventName]) {
return eventName;
}
var prefixMap = vendorPrefixes[eventName];
for (var styleProp in prefixMap) {
if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
return prefixedEventNames[eventName] = prefixMap[styleProp];
}
}
return '';
}
module.exports = getVendorPrefixedEventName;
/***/ },
/* 115 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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 DisabledInputUtils = __webpack_require__(116);
/**
* Implements a <button> host component that does not receive mouse events
* when `disabled` is set.
*/
var ReactDOMButton = {
getHostProps: DisabledInputUtils.getHostProps
};
module.exports = ReactDOMButton;
/***/ },
/* 116 */
/***/ function(module, exports) {
/**
* Copyright 2013-present, 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 DisabledInputUtils
*/
'use strict';
var disableableMouseListenerNames = {
onClick: true,
onDoubleClick: true,
onMouseDown: true,
onMouseMove: true,
onMouseUp: true,
onClickCapture: true,
onDoubleClickCapture: true,
onMouseDownCapture: true,
onMouseMoveCapture: true,
onMouseUpCapture: true
};
/**
* Implements a host component that does not receive mouse events
* when `disabled` is set.
*/
var DisabledInputUtils = {
getHostProps: function (inst, props) {
if (!props.disabled) {
return props;
}
// Copy the props, except the mouse listeners
var hostProps = {};
for (var key in props) {
if (!disableableMouseListenerNames[key] && props.hasOwnProperty(key)) {
hostProps[key] = props[key];
}
}
return hostProps;
}
};
module.exports = DisabledInputUtils;
/***/ },
/* 117 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 _prodInvariant = __webpack_require__(7),
_assign = __webpack_require__(4);
var DisabledInputUtils = __webpack_require__(116);
var DOMPropertyOperations = __webpack_require__(106);
var LinkedValueUtils = __webpack_require__(118);
var ReactDOMComponentTree = __webpack_require__(37);
var ReactUpdates = __webpack_require__(57);
var invariant = __webpack_require__(8);
var warning = __webpack_require__(11);
var didWarnValueLink = false;
var didWarnCheckedLink = false;
var didWarnValueDefaultValue = false;
var didWarnCheckedDefaultChecked = false;
var didWarnControlledToUncontrolled = false;
var didWarnUncontrolledToControlled = false;
function forceUpdateIfMounted() {
if (this._rootNodeID) {
// DOM component is still mounted; update
ReactDOMInput.updateWrapper(this);
}
}
function isControlled(props) {
var usesChecked = props.type === 'checkbox' || props.type === 'radio';
return usesChecked ? props.checked !== undefined : props.value !== undefined;
}
/**
* Implements an <input> host 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 = {
getHostProps: function (inst, props) {
var value = LinkedValueUtils.getValue(props);
var checked = LinkedValueUtils.getChecked(props);
var hostProps = _assign({
// Make sure we set .type before any other properties (setting .value
// before .type means .value is lost in IE11 and below)
type: undefined,
// Make sure we set .step before .value (setting .value before .step
// means .value is rounded on mount, based upon step precision)
step: undefined
}, DisabledInputUtils.getHostProps(inst, props), {
defaultChecked: undefined,
defaultValue: undefined,
value: value != null ? value : inst._wrapperState.initialValue,
checked: checked != null ? checked : inst._wrapperState.initialChecked,
onChange: inst._wrapperState.onChange
});
return hostProps;
},
mountWrapper: function (inst, props) {
if (process.env.NODE_ENV !== 'production') {
LinkedValueUtils.checkPropTypes('input', props, inst._currentElement._owner);
var owner = inst._currentElement._owner;
if (props.valueLink !== undefined && !didWarnValueLink) {
process.env.NODE_ENV !== 'production' ? warning(false, '`valueLink` prop on `input` is deprecated; set `value` and `onChange` instead.') : void 0;
didWarnValueLink = true;
}
if (props.checkedLink !== undefined && !didWarnCheckedLink) {
process.env.NODE_ENV !== 'production' ? warning(false, '`checkedLink` prop on `input` is deprecated; set `value` and `onChange` instead.') : void 0;
didWarnCheckedLink = true;
}
if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) {
process.env.NODE_ENV !== 'production' ? warning(false, '%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0;
didWarnCheckedDefaultChecked = true;
}
if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) {
process.env.NODE_ENV !== 'production' ? warning(false, '%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0;
didWarnValueDefaultValue = true;
}
}
var defaultValue = props.defaultValue;
inst._wrapperState = {
initialChecked: props.checked != null ? props.checked : props.defaultChecked,
initialValue: props.value != null ? props.value : defaultValue,
listeners: null,
onChange: _handleChange.bind(inst)
};
if (process.env.NODE_ENV !== 'production') {
inst._wrapperState.controlled = isControlled(props);
}
},
updateWrapper: function (inst) {
var props = inst._currentElement.props;
if (process.env.NODE_ENV !== 'production') {
var controlled = isControlled(props);
var owner = inst._currentElement._owner;
if (!inst._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) {
process.env.NODE_ENV !== 'production' ? warning(false, '%s is changing an uncontrolled input of type %s to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0;
didWarnUncontrolledToControlled = true;
}
if (inst._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) {
process.env.NODE_ENV !== 'production' ? warning(false, '%s is changing a controlled input of type %s to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0;
didWarnControlledToUncontrolled = true;
}
}
// TODO: Shouldn't this be getChecked(props)?
var checked = props.checked;
if (checked != null) {
DOMPropertyOperations.setValueForProperty(ReactDOMComponentTree.getNodeFromInstance(inst), 'checked', checked || false);
}
var node = ReactDOMComponentTree.getNodeFromInstance(inst);
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.
var newValue = '' + value;
// To avoid side effects (such as losing text selection), only set value if changed
if (newValue !== node.value) {
node.value = newValue;
}
} else {
if (props.value == null && props.defaultValue != null) {
node.defaultValue = '' + props.defaultValue;
}
if (props.checked == null && props.defaultChecked != null) {
node.defaultChecked = !!props.defaultChecked;
}
}
},
postMountWrapper: function (inst) {
var props = inst._currentElement.props;
// This is in postMount because we need access to the DOM node, which is not
// available until after the component has mounted.
var node = ReactDOMComponentTree.getNodeFromInstance(inst);
// Detach value from defaultValue. We won't do anything if we're working on
// submit or reset inputs as those values & defaultValues are linked. They
// are not resetable nodes so this operation doesn't matter and actually
// removes browser-default values (eg "Submit Query") when no value is
// provided.
if (props.type !== 'submit' && props.type !== 'reset') {
node.value = node.value;
}
// Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug
// this is needed to work around a chrome bug where setting defaultChecked
// will sometimes influence the value of checked (even after detachment).
// Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416
// We need to temporarily unset name to avoid disrupting radio button groups.
var name = node.name;
if (name !== '') {
node.name = '';
}
node.defaultChecked = !node.defaultChecked;
node.defaultChecked = !node.defaultChecked;
if (name !== '') {
node.name = name;
}
}
};
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 = ReactDOMComponentTree.getNodeFromInstance(this);
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 radio buttons with non-React ones.
var otherInstance = ReactDOMComponentTree.getInstanceFromNode(otherNode);
!otherInstance ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.') : _prodInvariant('90') : void 0;
// 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__(3)))
/***/ },
/* 118 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var ReactPropTypes = __webpack_require__(32);
var ReactPropTypeLocations = __webpack_require__(22);
var ReactPropTypesSecret = __webpack_require__(31);
var invariant = __webpack_require__(8);
var warning = __webpack_require__(11);
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.') : _prodInvariant('87') : void 0;
}
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.') : _prodInvariant('88') : void 0;
}
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') : _prodInvariant('89') : void 0;
}
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, null, ReactPropTypesSecret);
}
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) : void 0;
}
}
},
/**
* @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__(3)))
/***/ },
/* 119 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 _assign = __webpack_require__(4);
var ReactChildren = __webpack_require__(5);
var ReactDOMComponentTree = __webpack_require__(37);
var ReactDOMSelect = __webpack_require__(120);
var warning = __webpack_require__(11);
var didWarnInvalidOptionChildren = false;
function flattenChildren(children) {
var content = '';
// Flatten children and warn if they aren't strings or numbers;
// invalid types are ignored.
ReactChildren.forEach(children, function (child) {
if (child == null) {
return;
}
if (typeof child === 'string' || typeof child === 'number') {
content += child;
} else if (!didWarnInvalidOptionChildren) {
didWarnInvalidOptionChildren = true;
process.env.NODE_ENV !== 'production' ? warning(false, 'Only strings and numbers are supported as <option> children.') : void 0;
}
});
return content;
}
/**
* Implements an <option> host component that warns when `selected` is set.
*/
var ReactDOMOption = {
mountWrapper: function (inst, props, hostParent) {
// 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>.') : void 0;
}
// Look up whether this option is 'selected'
var selectValue = null;
if (hostParent != null) {
var selectParent = hostParent;
if (selectParent._tag === 'optgroup') {
selectParent = selectParent._hostParent;
}
if (selectParent != null && selectParent._tag === 'select') {
selectValue = ReactDOMSelect.getSelectValueContext(selectParent);
}
}
// If the value 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) {
var value;
if (props.value != null) {
value = props.value + '';
} else {
value = flattenChildren(props.children);
}
selected = false;
if (Array.isArray(selectValue)) {
// multiple
for (var i = 0; i < selectValue.length; i++) {
if ('' + selectValue[i] === value) {
selected = true;
break;
}
}
} else {
selected = '' + selectValue === value;
}
}
inst._wrapperState = { selected: selected };
},
postMountWrapper: function (inst) {
// value="" should make a value attribute (#6219)
var props = inst._currentElement.props;
if (props.value != null) {
var node = ReactDOMComponentTree.getNodeFromInstance(inst);
node.setAttribute('value', props.value);
}
},
getHostProps: function (inst, props) {
var hostProps = _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) {
hostProps.selected = inst._wrapperState.selected;
}
var content = flattenChildren(props.children);
if (content) {
hostProps.children = content;
}
return hostProps;
}
};
module.exports = ReactDOMOption;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 120 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 _assign = __webpack_require__(4);
var DisabledInputUtils = __webpack_require__(116);
var LinkedValueUtils = __webpack_require__(118);
var ReactDOMComponentTree = __webpack_require__(37);
var ReactUpdates = __webpack_require__(57);
var warning = __webpack_require__(11);
var didWarnValueLink = false;
var didWarnValueDefaultValue = false;
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);
if (props.valueLink !== undefined && !didWarnValueLink) {
process.env.NODE_ENV !== 'production' ? warning(false, '`valueLink` prop on `select` is deprecated; set `value` and `onChange` instead.') : void 0;
didWarnValueLink = true;
}
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)) : void 0;
} 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)) : void 0;
}
}
}
/**
* @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 = ReactDOMComponentTree.getNodeFromInstance(inst).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> host 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 = {
getHostProps: function (inst, props) {
return _assign({}, DisabledInputUtils.getHostProps(inst, 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,
listeners: null,
onChange: _handleChange.bind(inst),
wasMultiple: Boolean(props.multiple)
};
if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components') : void 0;
didWarnValueDefaultValue = true;
}
},
getSelectValueContext: function (inst) {
// ReactDOMOption looks at this initial value so the initial generated
// markup has correct `selected` attributes
return inst._wrapperState.initialValue;
},
postUpdateWrapper: function (inst) {
var props = inst._currentElement.props;
// After the initial mount, we control selected-ness manually so don't pass
// this 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);
if (this._rootNodeID) {
this._wrapperState.pendingUpdate = true;
}
ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this);
return returnValue;
}
module.exports = ReactDOMSelect;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 121 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 _prodInvariant = __webpack_require__(7),
_assign = __webpack_require__(4);
var DisabledInputUtils = __webpack_require__(116);
var LinkedValueUtils = __webpack_require__(118);
var ReactDOMComponentTree = __webpack_require__(37);
var ReactUpdates = __webpack_require__(57);
var invariant = __webpack_require__(8);
var warning = __webpack_require__(11);
var didWarnValueLink = false;
var didWarnValDefaultVal = false;
function forceUpdateIfMounted() {
if (this._rootNodeID) {
// DOM component is still mounted; update
ReactDOMTextarea.updateWrapper(this);
}
}
/**
* Implements a <textarea> host 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 = {
getHostProps: function (inst, props) {
!(props.dangerouslySetInnerHTML == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : _prodInvariant('91') : void 0;
// Always set children to the same thing. In IE9, the selection range will
// get reset if `textContent` is mutated. We could add a check in setTextContent
// to only set the value if/when the value differs from the node value (which would
// completely solve this IE9 bug), but Sebastian+Ben seemed to like this solution.
// The value can be a boolean or object so that's why it's forced to be a string.
var hostProps = _assign({}, DisabledInputUtils.getHostProps(inst, props), {
value: undefined,
defaultValue: undefined,
children: '' + inst._wrapperState.initialValue,
onChange: inst._wrapperState.onChange
});
return hostProps;
},
mountWrapper: function (inst, props) {
if (process.env.NODE_ENV !== 'production') {
LinkedValueUtils.checkPropTypes('textarea', props, inst._currentElement._owner);
if (props.valueLink !== undefined && !didWarnValueLink) {
process.env.NODE_ENV !== 'production' ? warning(false, '`valueLink` prop on `textarea` is deprecated; set `value` and `onChange` instead.') : void 0;
didWarnValueLink = true;
}
if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components') : void 0;
didWarnValDefaultVal = true;
}
}
var value = LinkedValueUtils.getValue(props);
var initialValue = value;
// Only bother fetching default value if we're going to use it
if (value == null) {
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>.') : void 0;
}
!(defaultValue == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : _prodInvariant('92') : void 0;
if (Array.isArray(children)) {
!(children.length <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, '<textarea> can only have at most one child.') : _prodInvariant('93') : void 0;
children = children[0];
}
defaultValue = '' + children;
}
if (defaultValue == null) {
defaultValue = '';
}
initialValue = defaultValue;
}
inst._wrapperState = {
initialValue: '' + initialValue,
listeners: null,
onChange: _handleChange.bind(inst)
};
},
updateWrapper: function (inst) {
var props = inst._currentElement.props;
var node = ReactDOMComponentTree.getNodeFromInstance(inst);
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.
var newValue = '' + value;
// To avoid side effects (such as losing text selection), only set value if changed
if (newValue !== node.value) {
node.value = newValue;
}
if (props.defaultValue == null) {
node.defaultValue = newValue;
}
}
if (props.defaultValue != null) {
node.defaultValue = props.defaultValue;
}
},
postMountWrapper: function (inst) {
// This is in postMount because we need access to the DOM node, which is not
// available until after the component has mounted.
var node = ReactDOMComponentTree.getNodeFromInstance(inst);
// Warning: node.value may be the empty string at this point (IE11) if placeholder is set.
node.value = node.textContent; // Detach value from defaultValue
}
};
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__(3)))
/***/ },
/* 122 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var ReactComponentEnvironment = __webpack_require__(123);
var ReactInstanceMap = __webpack_require__(124);
var ReactInstrumentation = __webpack_require__(63);
var ReactMultiChildUpdateTypes = __webpack_require__(93);
var ReactCurrentOwner = __webpack_require__(10);
var ReactReconciler = __webpack_require__(60);
var ReactChildReconciler = __webpack_require__(125);
var emptyFunction = __webpack_require__(12);
var flattenChildren = __webpack_require__(133);
var invariant = __webpack_require__(8);
/**
* Make an update for markup to be rendered and inserted at a supplied index.
*
* @param {string} markup Markup that renders into an element.
* @param {number} toIndex Destination index.
* @private
*/
function makeInsertMarkup(markup, afterNode, toIndex) {
// NOTE: Null values reduce hidden classes.
return {
type: ReactMultiChildUpdateTypes.INSERT_MARKUP,
content: markup,
fromIndex: null,
fromNode: null,
toIndex: toIndex,
afterNode: afterNode
};
}
/**
* Make an update for moving an existing element to another index.
*
* @param {number} fromIndex Source index of the existing element.
* @param {number} toIndex Destination index of the element.
* @private
*/
function makeMove(child, afterNode, toIndex) {
// NOTE: Null values reduce hidden classes.
return {
type: ReactMultiChildUpdateTypes.MOVE_EXISTING,
content: null,
fromIndex: child._mountIndex,
fromNode: ReactReconciler.getHostNode(child),
toIndex: toIndex,
afterNode: afterNode
};
}
/**
* Make an update for removing an element at an index.
*
* @param {number} fromIndex Index of the element to remove.
* @private
*/
function makeRemove(child, node) {
// NOTE: Null values reduce hidden classes.
return {
type: ReactMultiChildUpdateTypes.REMOVE_NODE,
content: null,
fromIndex: child._mountIndex,
fromNode: node,
toIndex: null,
afterNode: null
};
}
/**
* Make an update for setting the markup of a node.
*
* @param {string} markup Markup that renders into an element.
* @private
*/
function makeSetMarkup(markup) {
// NOTE: Null values reduce hidden classes.
return {
type: ReactMultiChildUpdateTypes.SET_MARKUP,
content: markup,
fromIndex: null,
fromNode: null,
toIndex: null,
afterNode: null
};
}
/**
* Make an update for setting the text content.
*
* @param {string} textContent Text content to set.
* @private
*/
function makeTextContent(textContent) {
// NOTE: Null values reduce hidden classes.
return {
type: ReactMultiChildUpdateTypes.TEXT_CONTENT,
content: textContent,
fromIndex: null,
fromNode: null,
toIndex: null,
afterNode: null
};
}
/**
* Push an update, if any, onto the queue. Creates a new queue if none is
* passed and always returns the queue. Mutative.
*/
function enqueue(queue, update) {
if (update) {
queue = queue || [];
queue.push(update);
}
return queue;
}
/**
* Processes any enqueued updates.
*
* @private
*/
function processQueue(inst, updateQueue) {
ReactComponentEnvironment.processChildrenUpdates(inst, updateQueue);
}
var setParentForInstrumentation = emptyFunction;
var setChildrenForInstrumentation = emptyFunction;
if (process.env.NODE_ENV !== 'production') {
var getDebugID = function (inst) {
if (!inst._debugID) {
// Check for ART-like instances. TODO: This is silly/gross.
var internal;
if (internal = ReactInstanceMap.get(inst)) {
inst = internal;
}
}
return inst._debugID;
};
setParentForInstrumentation = function (child) {
if (child._debugID !== 0) {
ReactInstrumentation.debugTool.onSetParent(child._debugID, getDebugID(this));
}
};
setChildrenForInstrumentation = function (children) {
var debugID = getDebugID(this);
// TODO: React Native empty components are also multichild.
// This means they still get into this method but don't have _debugID.
if (debugID !== 0) {
ReactInstrumentation.debugTool.onSetChildren(debugID, children ? Object.keys(children).map(function (key) {
return children[key]._debugID;
}) : []);
}
};
}
/**
* 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, this._debugID);
} finally {
ReactCurrentOwner.current = null;
}
}
}
return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context);
},
_reconcilerUpdateChildren: function (prevChildren, nextNestedChildrenElements, mountImages, removedNodes, transaction, context) {
var nextChildren;
if (process.env.NODE_ENV !== 'production') {
if (this._currentElement) {
try {
ReactCurrentOwner.current = this._currentElement._owner;
nextChildren = flattenChildren(nextNestedChildrenElements, this._debugID);
} finally {
ReactCurrentOwner.current = null;
}
ReactChildReconciler.updateChildren(prevChildren, nextChildren, mountImages, removedNodes, transaction, this, this._hostContainerInfo, context);
return nextChildren;
}
}
nextChildren = flattenChildren(nextNestedChildrenElements);
ReactChildReconciler.updateChildren(prevChildren, nextChildren, mountImages, removedNodes, transaction, this, this._hostContainerInfo, context);
return nextChildren;
},
/**
* 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];
if (process.env.NODE_ENV !== 'production') {
setParentForInstrumentation.call(this, child);
}
var mountImage = ReactReconciler.mountComponent(child, transaction, this, this._hostContainerInfo, context);
child._mountIndex = index++;
mountImages.push(mountImage);
}
}
if (process.env.NODE_ENV !== 'production') {
setChildrenForInstrumentation.call(this, children);
}
return mountImages;
},
/**
* Replaces any rendered children with a text content string.
*
* @param {string} nextContent String of content.
* @internal
*/
updateTextContent: function (nextContent) {
var prevChildren = this._renderedChildren;
// Remove any rendered children.
ReactChildReconciler.unmountChildren(prevChildren, false);
for (var name in prevChildren) {
if (prevChildren.hasOwnProperty(name)) {
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'updateTextContent called on non-empty component.') : _prodInvariant('118') : void 0;
}
}
// Set new text content.
var updates = [makeTextContent(nextContent)];
processQueue(this, updates);
},
/**
* Replaces any rendered children with a markup string.
*
* @param {string} nextMarkup String of markup.
* @internal
*/
updateMarkup: function (nextMarkup) {
var prevChildren = this._renderedChildren;
// Remove any rendered children.
ReactChildReconciler.unmountChildren(prevChildren, false);
for (var name in prevChildren) {
if (prevChildren.hasOwnProperty(name)) {
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'updateTextContent called on non-empty component.') : _prodInvariant('118') : void 0;
}
}
var updates = [makeSetMarkup(nextMarkup)];
processQueue(this, updates);
},
/**
* Updates the rendered children with new children.
*
* @param {?object} nextNestedChildrenElements Nested child element maps.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
updateChildren: function (nextNestedChildrenElements, transaction, context) {
// Hook used by React ART
this._updateChildren(nextNestedChildrenElements, transaction, context);
},
/**
* @param {?object} nextNestedChildrenElements Nested child element maps.
* @param {ReactReconcileTransaction} transaction
* @final
* @protected
*/
_updateChildren: function (nextNestedChildrenElements, transaction, context) {
var prevChildren = this._renderedChildren;
var removedNodes = {};
var mountImages = [];
var nextChildren = this._reconcilerUpdateChildren(prevChildren, nextNestedChildrenElements, mountImages, removedNodes, transaction, context);
if (!nextChildren && !prevChildren) {
return;
}
var updates = null;
var name;
// `nextIndex` will increment for each child in `nextChildren`, but
// `lastIndex` will be the last index visited in `prevChildren`.
var nextIndex = 0;
var lastIndex = 0;
// `nextMountIndex` will increment for each newly mounted child.
var nextMountIndex = 0;
var lastPlacedNode = null;
for (name in nextChildren) {
if (!nextChildren.hasOwnProperty(name)) {
continue;
}
var prevChild = prevChildren && prevChildren[name];
var nextChild = nextChildren[name];
if (prevChild === nextChild) {
updates = enqueue(updates, this.moveChild(prevChild, lastPlacedNode, 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);
// The `removedNodes` loop below will actually remove the child.
}
// The child must be instantiated before it's mounted.
updates = enqueue(updates, this._mountChildAtIndex(nextChild, mountImages[nextMountIndex], lastPlacedNode, nextIndex, transaction, context));
nextMountIndex++;
}
nextIndex++;
lastPlacedNode = ReactReconciler.getHostNode(nextChild);
}
// Remove children that are no longer present.
for (name in removedNodes) {
if (removedNodes.hasOwnProperty(name)) {
updates = enqueue(updates, this._unmountChild(prevChildren[name], removedNodes[name]));
}
}
if (updates) {
processQueue(this, updates);
}
this._renderedChildren = nextChildren;
if (process.env.NODE_ENV !== 'production') {
setChildrenForInstrumentation.call(this, nextChildren);
}
},
/**
* Unmounts all rendered children. This should be used to clean up children
* when this component is unmounted. It does not actually perform any
* backend operations.
*
* @internal
*/
unmountChildren: function (safely) {
var renderedChildren = this._renderedChildren;
ReactChildReconciler.unmountChildren(renderedChildren, safely);
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, afterNode, 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) {
return makeMove(child, afterNode, toIndex);
}
},
/**
* Creates a child component.
*
* @param {ReactComponent} child Component to create.
* @param {string} mountImage Markup to insert.
* @protected
*/
createChild: function (child, afterNode, mountImage) {
return makeInsertMarkup(mountImage, afterNode, child._mountIndex);
},
/**
* Removes a child component.
*
* @param {ReactComponent} child Child to remove.
* @protected
*/
removeChild: function (child, node) {
return makeRemove(child, node);
},
/**
* 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
*/
_mountChildAtIndex: function (child, mountImage, afterNode, index, transaction, context) {
child._mountIndex = index;
return this.createChild(child, afterNode, 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, node) {
var update = this.removeChild(child, node);
child._mountIndex = null;
return update;
}
}
};
module.exports = ReactMultiChild;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 123 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2014-present, 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 _prodInvariant = __webpack_require__(7);
var invariant = __webpack_require__(8);
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.
*/
replaceNodeWithMarkup: 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.') : _prodInvariant('104') : void 0;
ReactComponentEnvironment.unmountIDFromEnvironment = environment.unmountIDFromEnvironment;
ReactComponentEnvironment.replaceNodeWithMarkup = environment.replaceNodeWithMarkup;
ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates;
injected = true;
}
}
};
module.exports = ReactComponentEnvironment;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 124 */
/***/ function(module, exports) {
/**
* Copyright 2013-present, 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;
/***/ },
/* 125 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2014-present, 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
*/
'use strict';
var ReactReconciler = __webpack_require__(60);
var instantiateReactComponent = __webpack_require__(126);
var KeyEscapeUtils = __webpack_require__(16);
var shouldUpdateReactComponent = __webpack_require__(130);
var traverseAllChildren = __webpack_require__(14);
var warning = __webpack_require__(11);
var ReactComponentTreeDevtool;
if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test') {
// Temporary hack.
// Inline requires don't work well with Jest:
// https://github.com/facebook/react/issues/7240
// Remove the inline requires when we don't need them anymore:
// https://github.com/facebook/react/pull/7178
ReactComponentTreeDevtool = __webpack_require__(29);
}
function instantiateChild(childInstances, child, name, selfDebugID) {
// We found a component instance.
var keyUnique = childInstances[name] === undefined;
if (process.env.NODE_ENV !== 'production') {
if (!ReactComponentTreeDevtool) {
ReactComponentTreeDevtool = __webpack_require__(29);
}
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.%s', KeyEscapeUtils.unescape(name), ReactComponentTreeDevtool.getStackAddendumByID(selfDebugID)) : void 0;
}
if (child != null && keyUnique) {
childInstances[name] = instantiateReactComponent(child, true);
}
}
/**
* 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, selfDebugID // __DEV__ only
) {
if (nestedChildNodes == null) {
return null;
}
var childInstances = {};
if (process.env.NODE_ENV !== 'production') {
traverseAllChildren(nestedChildNodes, function (childInsts, child, name) {
return instantiateChild(childInsts, child, name, selfDebugID);
}, childInstances);
} else {
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, mountImages, removedNodes, transaction, hostParent, hostContainerInfo, 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;
}
var name;
var prevChild;
for (name in nextChildren) {
if (!nextChildren.hasOwnProperty(name)) {
continue;
}
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) {
removedNodes[name] = ReactReconciler.getHostNode(prevChild);
ReactReconciler.unmountComponent(prevChild, false);
}
// The child must be instantiated before it's mounted.
var nextChildInstance = instantiateReactComponent(nextElement, true);
nextChildren[name] = nextChildInstance;
// Creating mount image now ensures refs are resolved in right order
// (see https://github.com/facebook/react/pull/7101 for explanation).
var nextChildMountImage = ReactReconciler.mountComponent(nextChildInstance, transaction, hostParent, hostContainerInfo, context);
mountImages.push(nextChildMountImage);
}
}
// Unmount children that are no longer present.
for (name in prevChildren) {
if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) {
prevChild = prevChildren[name];
removedNodes[name] = ReactReconciler.getHostNode(prevChild);
ReactReconciler.unmountComponent(prevChild, false);
}
}
},
/**
* 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, safely) {
for (var name in renderedChildren) {
if (renderedChildren.hasOwnProperty(name)) {
var renderedChild = renderedChildren[name];
ReactReconciler.unmountComponent(renderedChild, safely);
}
}
}
};
module.exports = ReactChildReconciler;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 126 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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
*/
'use strict';
var _prodInvariant = __webpack_require__(7),
_assign = __webpack_require__(4);
var ReactCompositeComponent = __webpack_require__(127);
var ReactEmptyComponent = __webpack_require__(131);
var ReactHostComponent = __webpack_require__(132);
var ReactInstrumentation = __webpack_require__(63);
var invariant = __webpack_require__(8);
var warning = __webpack_require__(11);
// To avoid a cyclic dependency, we create the final class in this module
var ReactCompositeComponentWrapper = function (element) {
this.construct(element);
};
_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 '';
}
function getDisplayName(instance) {
var element = instance._currentElement;
if (element == null) {
return '#empty';
} else if (typeof element === 'string' || typeof element === 'number') {
return '#text';
} else if (typeof element.type === 'string') {
return element.type;
} else if (instance.getName) {
return instance.getName() || 'Unknown';
} else {
return element.type.displayName || element.type.name || 'Unknown';
}
}
/**
* 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';
}
var nextDebugID = 1;
/**
* Given a ReactNode, create an instance that will actually be mounted.
*
* @param {ReactNode} node
* @param {boolean} shouldHaveDebugID
* @return {object} A new instance of the element's constructor.
* @protected
*/
function instantiateReactComponent(node, shouldHaveDebugID) {
var instance;
if (node === null || node === false) {
instance = ReactEmptyComponent.create(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)) : _prodInvariant('130', element.type == null ? element.type : typeof element.type, getDeclarationErrorAddendum(element._owner)) : void 0;
// Special case string values
if (typeof element.type === 'string') {
instance = ReactHostComponent.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);
// We renamed this. Allow the old name for compat. :(
if (!instance.getHostNode) {
instance.getHostNode = instance.getNativeNode;
}
} else {
instance = new ReactCompositeComponentWrapper(element);
}
} else if (typeof node === 'string' || typeof node === 'number') {
instance = ReactHostComponent.createInstanceForText(node);
} else {
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Encountered invalid React node of type %s', typeof node) : _prodInvariant('131', typeof node) : void 0;
}
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.getHostNode === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.') : void 0;
}
// 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') {
if (shouldHaveDebugID) {
var debugID = nextDebugID++;
instance._debugID = debugID;
var displayName = getDisplayName(instance);
ReactInstrumentation.debugTool.onSetDisplayName(debugID, displayName);
var owner = node && node._owner;
if (owner) {
ReactInstrumentation.debugTool.onSetOwner(debugID, owner._debugID);
}
} else {
instance._debugID = 0;
}
}
// 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__(3)))
/***/ },
/* 127 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 _prodInvariant = __webpack_require__(7),
_assign = __webpack_require__(4);
var ReactComponentEnvironment = __webpack_require__(123);
var ReactCurrentOwner = __webpack_require__(10);
var ReactElement = __webpack_require__(9);
var ReactErrorUtils = __webpack_require__(47);
var ReactInstanceMap = __webpack_require__(124);
var ReactInstrumentation = __webpack_require__(63);
var ReactNodeTypes = __webpack_require__(128);
var ReactPropTypeLocations = __webpack_require__(22);
var ReactReconciler = __webpack_require__(60);
var checkReactTypeSpec = __webpack_require__(30);
var emptyObject = __webpack_require__(19);
var invariant = __webpack_require__(8);
var shallowEqual = __webpack_require__(129);
var shouldUpdateReactComponent = __webpack_require__(130);
var warning = __webpack_require__(11);
var CompositeTypes = {
ImpureClass: 0,
PureClass: 1,
StatelessFunctional: 2
};
function StatelessComponent(Component) {}
StatelessComponent.prototype.render = function () {
var Component = ReactInstanceMap.get(this)._currentElement.type;
var element = Component(this.props, this.context, this.updater);
warnIfInvalidElement(Component, element);
return element;
};
function warnIfInvalidElement(Component, element) {
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(element === null || element === false || ReactElement.isValidElement(element), '%s(...): A valid React element (or null) must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : void 0;
process.env.NODE_ENV !== 'production' ? warning(!Component.childContextTypes, '%s(...): childContextTypes cannot be defined on a functional component.', Component.displayName || Component.name || 'Component') : void 0;
}
}
function invokeComponentDidMountWithTimer() {
var publicInstance = this._instance;
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentDidMount');
}
publicInstance.componentDidMount();
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentDidMount');
}
}
function invokeComponentDidUpdateWithTimer(prevProps, prevState, prevContext) {
var publicInstance = this._instance;
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentDidUpdate');
}
publicInstance.componentDidUpdate(prevProps, prevState, prevContext);
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentDidUpdate');
}
}
function shouldConstruct(Component) {
return !!(Component.prototype && Component.prototype.isReactComponent);
}
function isPureComponent(Component) {
return !!(Component.prototype && Component.prototype.isPureReactComponent);
}
/**
* ------------------ 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._compositeType = null;
this._instance = null;
this._hostParent = null;
this._hostContainerInfo = null;
// See ReactUpdateQueue
this._updateBatchNumber = null;
this._pendingElement = null;
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
this._renderedNodeType = null;
this._renderedComponent = null;
this._context = null;
this._mountOrder = 0;
this._topLevelWrapper = null;
// See ReactUpdates and ReactUpdateQueue.
this._pendingCallbacks = null;
// ComponentWillUnmount shall only be called once
this._calledComponentWillUnmount = false;
if (process.env.NODE_ENV !== 'production') {
this._warnedAboutRefsInRender = false;
}
},
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {?object} hostParent
* @param {?object} hostContainerInfo
* @param {?object} context
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: function (transaction, hostParent, hostContainerInfo, context) {
var _this = this;
this._context = context;
this._mountOrder = nextMountID++;
this._hostParent = hostParent;
this._hostContainerInfo = hostContainerInfo;
var publicProps = this._currentElement.props;
var publicContext = this._processContext(context);
var Component = this._currentElement.type;
var updateQueue = transaction.getUpdateQueue();
// Initialize the public class
var doConstruct = shouldConstruct(Component);
var inst = this._constructComponent(doConstruct, publicProps, publicContext, updateQueue);
var renderedElement;
// Support functional components
if (!doConstruct && (inst == null || inst.render == null)) {
renderedElement = inst;
warnIfInvalidElement(Component, renderedElement);
!(inst === null || inst === false || ReactElement.isValidElement(inst)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : _prodInvariant('105', Component.displayName || Component.name || 'Component') : void 0;
inst = new StatelessComponent(Component);
this._compositeType = CompositeTypes.StatelessFunctional;
} else {
if (isPureComponent(Component)) {
this._compositeType = CompositeTypes.PureClass;
} else {
this._compositeType = CompositeTypes.ImpureClass;
}
}
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`.', Component.displayName || Component.name || 'Component') : void 0;
}
var propsMutated = inst.props !== publicProps;
var componentName = Component.displayName || Component.name || 'Component';
process.env.NODE_ENV !== 'production' ? warning(inst.props === undefined || !propsMutated, '%s(...): When calling super() in `%s`, make sure to pass ' + 'up the same props that your component\'s constructor was passed.', componentName, componentName) : void 0;
}
// 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 = updateQueue;
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') : void 0;
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') : void 0;
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') : void 0;
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') : void 0;
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') : void 0;
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') : void 0;
process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentWillRecieveProps !== 'function', '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', this.getName() || 'A component') : void 0;
}
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') : _prodInvariant('106', this.getName() || 'ReactCompositeComponent') : void 0;
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
var markup;
if (inst.unstable_handleError) {
markup = this.performInitialMountWithErrorHandling(renderedElement, hostParent, hostContainerInfo, transaction, context);
} else {
markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context);
}
if (inst.componentDidMount) {
if (process.env.NODE_ENV !== 'production') {
transaction.getReactMountReady().enqueue(invokeComponentDidMountWithTimer, this);
} else {
transaction.getReactMountReady().enqueue(inst.componentDidMount, inst);
}
}
if (process.env.NODE_ENV !== 'production') {
if (this._debugID) {
var callback = function (component) {
return ReactInstrumentation.debugTool.onComponentHasMounted(_this._debugID);
};
transaction.getReactMountReady().enqueue(callback, this);
}
}
return markup;
},
_constructComponent: function (doConstruct, publicProps, publicContext, updateQueue) {
if (process.env.NODE_ENV !== 'production') {
ReactCurrentOwner.current = this;
try {
return this._constructComponentWithoutOwner(doConstruct, publicProps, publicContext, updateQueue);
} finally {
ReactCurrentOwner.current = null;
}
} else {
return this._constructComponentWithoutOwner(doConstruct, publicProps, publicContext, updateQueue);
}
},
_constructComponentWithoutOwner: function (doConstruct, publicProps, publicContext, updateQueue) {
var Component = this._currentElement.type;
var instanceOrElement;
if (doConstruct) {
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'ctor');
}
}
instanceOrElement = new Component(publicProps, publicContext, updateQueue);
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'ctor');
}
}
} else {
// This can still be an instance in case of factory components
// but we'll count this as time spent rendering as the more common case.
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'render');
}
}
instanceOrElement = Component(publicProps, publicContext, updateQueue);
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'render');
}
}
}
return instanceOrElement;
},
performInitialMountWithErrorHandling: function (renderedElement, hostParent, hostContainerInfo, transaction, context) {
var markup;
var checkpoint = transaction.checkpoint();
try {
markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context);
} catch (e) {
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onError();
}
}
// Roll back to checkpoint, handle error (which may add items to the transaction), and take a new checkpoint
transaction.rollback(checkpoint);
this._instance.unstable_handleError(e);
if (this._pendingStateQueue) {
this._instance.state = this._processPendingState(this._instance.props, this._instance.context);
}
checkpoint = transaction.checkpoint();
this._renderedComponent.unmountComponent(true);
transaction.rollback(checkpoint);
// Try again - we've informed the component about the error, so they can render an error message this time.
// If this throws again, the error will bubble up (and can be caught by a higher error boundary).
markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context);
}
return markup;
},
performInitialMount: function (renderedElement, hostParent, hostContainerInfo, transaction, context) {
var inst = this._instance;
if (inst.componentWillMount) {
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentWillMount');
}
}
inst.componentWillMount();
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, '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();
}
var nodeType = ReactNodeTypes.getType(renderedElement);
this._renderedNodeType = nodeType;
var child = this._instantiateReactComponent(renderedElement, nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */
);
this._renderedComponent = child;
if (process.env.NODE_ENV !== 'production') {
if (child._debugID !== 0 && this._debugID !== 0) {
ReactInstrumentation.debugTool.onSetParent(child._debugID, this._debugID);
}
}
var markup = ReactReconciler.mountComponent(child, transaction, hostParent, hostContainerInfo, this._processChildContext(context));
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onSetChildren(this._debugID, child._debugID !== 0 ? [child._debugID] : []);
}
}
return markup;
},
getHostNode: function () {
return ReactReconciler.getHostNode(this._renderedComponent);
},
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function (safely) {
if (!this._renderedComponent) {
return;
}
var inst = this._instance;
if (inst.componentWillUnmount && !inst._calledComponentWillUnmount) {
inst._calledComponentWillUnmount = true;
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentWillUnmount');
}
}
if (safely) {
var name = this.getName() + '.componentWillUnmount()';
ReactErrorUtils.invokeGuardedCallback(name, inst.componentWillUnmount.bind(inst));
} else {
inst.componentWillUnmount();
}
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentWillUnmount');
}
}
}
if (this._renderedComponent) {
ReactReconciler.unmountComponent(this._renderedComponent, safely);
this._renderedNodeType = null;
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 Component = this._currentElement.type;
var contextTypes = Component.contextTypes;
if (!contextTypes) {
return emptyObject;
}
var 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._checkContextTypes(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;
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onBeginProcessingChildContext();
}
var childContext = inst.getChildContext && inst.getChildContext();
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onEndProcessingChildContext();
}
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') : _prodInvariant('107', this.getName() || 'ReactCompositeComponent') : void 0;
if (process.env.NODE_ENV !== 'production') {
this._checkContextTypes(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) : _prodInvariant('108', this.getName() || 'ReactCompositeComponent', name) : void 0;
}
return _assign({}, currentContext, childContext);
}
return currentContext;
},
/**
* Assert that the context types are valid
*
* @param {object} typeSpecs Map of context field to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @private
*/
_checkContextTypes: function (typeSpecs, values, location) {
checkReactTypeSpec(typeSpecs, values, location, this.getName(), null, this._debugID);
},
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, transaction, this._context);
} else if (this._pendingStateQueue !== null || this._pendingForceUpdate) {
this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context);
} else {
this._updateBatchNumber = null;
}
},
/**
* 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;
!(inst != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Attempted to update component `%s` that has already been unmounted (or failed to mount).', this.getName() || 'ReactCompositeComponent') : _prodInvariant('136', this.getName() || 'ReactCompositeComponent') : void 0;
var willReceive = false;
var nextContext;
// Determine if the context has changed or not
if (this._context === nextUnmaskedContext) {
nextContext = inst.context;
} else {
nextContext = this._processContext(nextUnmaskedContext);
willReceive = true;
}
var prevProps = prevParentElement.props;
var nextProps = nextParentElement.props;
// Not a simple state update but a props update
if (prevParentElement !== nextParentElement) {
willReceive = true;
}
// 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 (willReceive && inst.componentWillReceiveProps) {
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentWillReceiveProps');
}
}
inst.componentWillReceiveProps(nextProps, nextContext);
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentWillReceiveProps');
}
}
}
var nextState = this._processPendingState(nextProps, nextContext);
var shouldUpdate = true;
if (!this._pendingForceUpdate) {
if (inst.shouldComponentUpdate) {
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'shouldComponentUpdate');
}
}
shouldUpdate = inst.shouldComponentUpdate(nextProps, nextState, nextContext);
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'shouldComponentUpdate');
}
}
} else {
if (this._compositeType === CompositeTypes.PureClass) {
shouldUpdate = !shallowEqual(prevProps, nextProps) || !shallowEqual(inst.state, nextState);
}
}
}
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(shouldUpdate !== undefined, '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', this.getName() || 'ReactCompositeComponent') : void 0;
}
this._updateBatchNumber = null;
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 _this2 = this;
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) {
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentWillUpdate');
}
}
inst.componentWillUpdate(nextProps, nextState, nextContext);
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentWillUpdate');
}
}
}
this._currentElement = nextElement;
this._context = unmaskedContext;
inst.props = nextProps;
inst.state = nextState;
inst.context = nextContext;
this._updateRenderedComponent(transaction, unmaskedContext);
if (hasComponentDidUpdate) {
if (process.env.NODE_ENV !== 'production') {
transaction.getReactMountReady().enqueue(invokeComponentDidUpdateWithTimer.bind(this, prevProps, prevState, prevContext), this);
} else {
transaction.getReactMountReady().enqueue(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), inst);
}
}
if (process.env.NODE_ENV !== 'production') {
if (this._debugID) {
var callback = function () {
return ReactInstrumentation.debugTool.onComponentHasUpdated(_this2._debugID);
};
transaction.getReactMountReady().enqueue(callback, this);
}
}
},
/**
* 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 {
var oldHostNode = ReactReconciler.getHostNode(prevComponentInstance);
ReactReconciler.unmountComponent(prevComponentInstance, false);
var nodeType = ReactNodeTypes.getType(nextRenderedElement);
this._renderedNodeType = nodeType;
var child = this._instantiateReactComponent(nextRenderedElement, nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */
);
this._renderedComponent = child;
if (process.env.NODE_ENV !== 'production') {
if (child._debugID !== 0 && this._debugID !== 0) {
ReactInstrumentation.debugTool.onSetParent(child._debugID, this._debugID);
}
}
var nextMarkup = ReactReconciler.mountComponent(child, transaction, this._hostParent, this._hostContainerInfo, this._processChildContext(context));
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onSetChildren(this._debugID, child._debugID !== 0 ? [child._debugID] : []);
}
}
this._replaceNodeWithMarkup(oldHostNode, nextMarkup, prevComponentInstance);
}
},
/**
* Overridden in shallow rendering.
*
* @protected
*/
_replaceNodeWithMarkup: function (oldHostNode, nextMarkup, prevInstance) {
ReactComponentEnvironment.replaceNodeWithMarkup(oldHostNode, nextMarkup, prevInstance);
},
/**
* @protected
*/
_renderValidatedComponentWithoutOwnerOrContext: function () {
var inst = this._instance;
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'render');
}
}
var renderedComponent = inst.render();
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'render');
}
}
if (process.env.NODE_ENV !== 'production') {
// We allow auto-mocks to proceed as if they're returning null.
if (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;
if (process.env.NODE_ENV !== 'production' || this._compositeType !== CompositeTypes.StatelessFunctional) {
ReactCurrentOwner.current = this;
try {
renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext();
} finally {
ReactCurrentOwner.current = null;
}
} else {
renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext();
}
!(
// 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 React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.', this.getName() || 'ReactCompositeComponent') : _prodInvariant('109', this.getName() || 'ReactCompositeComponent') : void 0;
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.') : _prodInvariant('110') : void 0;
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()) : void 0;
}
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 (this._compositeType === CompositeTypes.StatelessFunctional) {
return null;
}
return inst;
},
// Stub
_instantiateReactComponent: null
};
var ReactCompositeComponent = {
Mixin: ReactCompositeComponentMixin
};
module.exports = ReactCompositeComponent;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 128 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 ReactNodeTypes
*
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var ReactElement = __webpack_require__(9);
var invariant = __webpack_require__(8);
var ReactNodeTypes = {
HOST: 0,
COMPOSITE: 1,
EMPTY: 2,
getType: function (node) {
if (node === null || node === false) {
return ReactNodeTypes.EMPTY;
} else if (ReactElement.isValidElement(node)) {
if (typeof node.type === 'function') {
return ReactNodeTypes.COMPOSITE;
} else {
return ReactNodeTypes.HOST;
}
}
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Unexpected node: %s', node) : _prodInvariant('26', node) : void 0;
}
};
module.exports = ReactNodeTypes;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 129 */
/***/ function(module, exports) {
/**
* Copyright (c) 2013-present, 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
*
*/
/*eslint-disable no-self-compare */
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/**
* 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 (is(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.
for (var i = 0; i < keysA.length; i++) {
if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
return false;
}
}
return true;
}
module.exports = shallowEqual;
/***/ },
/* 130 */
/***/ function(module, exports) {
/**
* Copyright 2013-present, 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
*/
'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;
}
}
module.exports = shouldUpdateReactComponent;
/***/ },
/* 131 */
/***/ function(module, exports) {
/**
* Copyright 2014-present, 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 emptyComponentFactory;
var ReactEmptyComponentInjection = {
injectEmptyComponentFactory: function (factory) {
emptyComponentFactory = factory;
}
};
var ReactEmptyComponent = {
create: function (instantiate) {
return emptyComponentFactory(instantiate);
}
};
ReactEmptyComponent.injection = ReactEmptyComponentInjection;
module.exports = ReactEmptyComponent;
/***/ },
/* 132 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2014-present, 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 ReactHostComponent
*/
'use strict';
var _prodInvariant = __webpack_require__(7),
_assign = __webpack_require__(4);
var invariant = __webpack_require__(8);
var genericComponentClass = null;
// This registry keeps track of wrapper classes around host tags.
var tagToComponentClass = {};
var textComponentClass = null;
var ReactHostComponentInjection = {
// 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 host 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) : _prodInvariant('111', element.type) : void 0;
return new genericComponentClass(element);
}
/**
* @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 ReactHostComponent = {
createInternalComponent: createInternalComponent,
createInstanceForText: createInstanceForText,
isTextComponent: isTextComponent,
injection: ReactHostComponentInjection
};
module.exports = ReactHostComponent;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 133 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 KeyEscapeUtils = __webpack_require__(16);
var traverseAllChildren = __webpack_require__(14);
var warning = __webpack_require__(11);
var ReactComponentTreeDevtool;
if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test') {
// Temporary hack.
// Inline requires don't work well with Jest:
// https://github.com/facebook/react/issues/7240
// Remove the inline requires when we don't need them anymore:
// https://github.com/facebook/react/pull/7178
ReactComponentTreeDevtool = __webpack_require__(29);
}
/**
* @param {function} traverseContext Context passed through traversal.
* @param {?ReactComponent} child React child component.
* @param {!string} name String name of key path to child.
* @param {number=} selfDebugID Optional debugID of the current internal instance.
*/
function flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID) {
// We found a component instance.
if (traverseContext && typeof traverseContext === 'object') {
var result = traverseContext;
var keyUnique = result[name] === undefined;
if (process.env.NODE_ENV !== 'production') {
if (!ReactComponentTreeDevtool) {
ReactComponentTreeDevtool = __webpack_require__(29);
}
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.%s', KeyEscapeUtils.unescape(name), ReactComponentTreeDevtool.getStackAddendumByID(selfDebugID)) : void 0;
}
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, selfDebugID) {
if (children == null) {
return children;
}
var result = {};
if (process.env.NODE_ENV !== 'production') {
traverseAllChildren(children, function (traverseContext, child, name) {
return flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID);
}, result);
} else {
traverseAllChildren(children, flattenSingleChildIntoContext, result);
}
return result;
}
module.exports = flattenChildren;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 134 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2014-present, 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
*/
'use strict';
var _assign = __webpack_require__(4);
var PooledClass = __webpack_require__(6);
var Transaction = __webpack_require__(70);
var ReactInstrumentation = __webpack_require__(63);
var ReactServerUpdateQueue = __webpack_require__(135);
/**
* 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 = [];
if (process.env.NODE_ENV !== 'production') {
TRANSACTION_WRAPPERS.push({
initialize: ReactInstrumentation.debugTool.onBeginFlush,
close: ReactInstrumentation.debugTool.onEndFlush
});
}
var noopCallbackQueue = {
enqueue: function () {}
};
/**
* @class ReactServerRenderingTransaction
* @param {boolean} renderToStaticMarkup
*/
function ReactServerRenderingTransaction(renderToStaticMarkup) {
this.reinitializeTransaction();
this.renderToStaticMarkup = renderToStaticMarkup;
this.useCreateElement = false;
this.updateQueue = new ReactServerUpdateQueue(this);
}
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 noopCallbackQueue;
},
/**
* @return {object} The queue to collect React async events.
*/
getUpdateQueue: function () {
return this.updateQueue;
},
/**
* `PooledClass` looks for this, and will invoke this before allowing this
* instance to be reused.
*/
destructor: function () {},
checkpoint: function () {},
rollback: function () {}
};
_assign(ReactServerRenderingTransaction.prototype, Transaction.Mixin, Mixin);
PooledClass.addPoolingTo(ReactServerRenderingTransaction);
module.exports = ReactServerRenderingTransaction;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 135 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2015-present, 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 ReactServerUpdateQueue
*
*/
'use strict';
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var ReactUpdateQueue = __webpack_require__(136);
var Transaction = __webpack_require__(70);
var warning = __webpack_require__(11);
function warnNoop(publicInstance, callerName) {
if (process.env.NODE_ENV !== 'production') {
var constructor = publicInstance.constructor;
process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, constructor && (constructor.displayName || constructor.name) || 'ReactClass') : void 0;
}
}
/**
* This is the update queue used for server rendering.
* It delegates to ReactUpdateQueue while server rendering is in progress and
* switches to ReactNoopUpdateQueue after the transaction has completed.
* @class ReactServerUpdateQueue
* @param {Transaction} transaction
*/
var ReactServerUpdateQueue = function () {
/* :: transaction: Transaction; */
function ReactServerUpdateQueue(transaction) {
_classCallCheck(this, ReactServerUpdateQueue);
this.transaction = transaction;
}
/**
* 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
*/
ReactServerUpdateQueue.prototype.isMounted = function isMounted(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
*/
ReactServerUpdateQueue.prototype.enqueueCallback = function enqueueCallback(publicInstance, callback, callerName) {
if (this.transaction.isInTransaction()) {
ReactUpdateQueue.enqueueCallback(publicInstance, callback, callerName);
}
};
/**
* 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
*/
ReactServerUpdateQueue.prototype.enqueueForceUpdate = function enqueueForceUpdate(publicInstance) {
if (this.transaction.isInTransaction()) {
ReactUpdateQueue.enqueueForceUpdate(publicInstance);
} else {
warnNoop(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|function} completeState Next state.
* @internal
*/
ReactServerUpdateQueue.prototype.enqueueReplaceState = function enqueueReplaceState(publicInstance, completeState) {
if (this.transaction.isInTransaction()) {
ReactUpdateQueue.enqueueReplaceState(publicInstance, completeState);
} else {
warnNoop(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|function} partialState Next partial state to be merged with state.
* @internal
*/
ReactServerUpdateQueue.prototype.enqueueSetState = function enqueueSetState(publicInstance, partialState) {
if (this.transaction.isInTransaction()) {
ReactUpdateQueue.enqueueSetState(publicInstance, partialState);
} else {
warnNoop(publicInstance, 'setState');
}
};
return ReactServerUpdateQueue;
}();
module.exports = ReactServerUpdateQueue;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 136 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2015-present, 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 _prodInvariant = __webpack_require__(7);
var ReactCurrentOwner = __webpack_require__(10);
var ReactInstanceMap = __webpack_require__(124);
var ReactInstrumentation = __webpack_require__(63);
var ReactUpdates = __webpack_require__(57);
var invariant = __webpack_require__(8);
var warning = __webpack_require__(11);
function enqueueUpdate(internalInstance) {
ReactUpdates.enqueueUpdate(internalInstance);
}
function formatUnexpectedArgument(arg) {
var type = typeof arg;
if (type !== 'object') {
return type;
}
var displayName = arg.constructor && arg.constructor.name || type;
var keys = Object.keys(arg);
if (keys.length > 0 && keys.length < 20) {
return displayName + ' (keys: ' + keys.join(', ') + ')';
}
return displayName;
}
function getInternalInstanceReadyForUpdate(publicInstance, callerName) {
var internalInstance = ReactInstanceMap.get(publicInstance);
if (!internalInstance) {
if (process.env.NODE_ENV !== 'production') {
var ctor = publicInstance.constructor;
// 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, ctor && (ctor.displayName || ctor.name) || 'ReactClass') : void 0;
}
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` or another component\'s constructor). Render methods ' + 'should be a pure function of props and state; constructor ' + 'side-effects are an anti-pattern, but can be moved to ' + '`componentWillMount`.', callerName) : void 0;
}
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') : void 0;
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.
* @param {string} callerName Name of the calling function in the public API.
* @internal
*/
enqueueCallback: function (publicInstance, callback, callerName) {
ReactUpdateQueue.validateCallback(callback, callerName);
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) {
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) {
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onSetState();
process.env.NODE_ENV !== 'production' ? warning(partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().') : void 0;
}
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setState');
if (!internalInstance) {
return;
}
var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []);
queue.push(partialState);
enqueueUpdate(internalInstance);
},
enqueueElementInternal: function (internalInstance, nextElement, nextContext) {
internalInstance._pendingElement = nextElement;
// TODO: introduce _pendingContext instead of setting it directly.
internalInstance._context = nextContext;
enqueueUpdate(internalInstance);
},
validateCallback: function (callback, callerName) {
!(!callback || typeof callback === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s(...): Expected the last optional `callback` argument to be a function. Instead received: %s.', callerName, formatUnexpectedArgument(callback)) : _prodInvariant('122', callerName, formatUnexpectedArgument(callback)) : void 0;
}
};
module.exports = ReactUpdateQueue;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 137 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2015-present, 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__(4);
var emptyFunction = __webpack_require__(12);
var warning = __webpack_require__(11);
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 = {
current: 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.current = 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';
case '#document':
return tag === 'html';
}
// 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 'body':
case 'caption':
case 'col':
case 'colgroup':
case 'frame':
case 'head':
case 'html':
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 = [];
do {
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.current;
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;
var tagDisplayName = childTag;
if (childTag !== '#text') {
tagDisplayName = '<' + childTag + '>';
}
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', tagDisplayName, ancestorTag, ownerInfo, info) : void 0;
} else {
process.env.NODE_ENV !== 'production' ? warning(false, 'validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>. See %s.', tagDisplayName, ancestorTag, ownerInfo) : void 0;
}
}
};
validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo;
// For testing
validateDOMNesting.isTagValidInContext = function (tag, ancestorInfo) {
ancestorInfo = ancestorInfo || emptyAncestorInfo;
var parentInfo = ancestorInfo.current;
var parentTag = parentInfo && parentInfo.tag;
return isTagValidWithParent(tag, parentTag) && !findInvalidAncestorForTag(tag, ancestorInfo);
};
}
module.exports = validateDOMNesting;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 138 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2014-present, 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 ReactDOMEmptyComponent
*/
'use strict';
var _assign = __webpack_require__(4);
var DOMLazyTree = __webpack_require__(83);
var ReactDOMComponentTree = __webpack_require__(37);
var ReactDOMEmptyComponent = function (instantiate) {
// ReactCompositeComponent uses this:
this._currentElement = null;
// ReactDOMComponentTree uses these:
this._hostNode = null;
this._hostParent = null;
this._hostContainerInfo = null;
this._domID = null;
};
_assign(ReactDOMEmptyComponent.prototype, {
mountComponent: function (transaction, hostParent, hostContainerInfo, context) {
var domID = hostContainerInfo._idCounter++;
this._domID = domID;
this._hostParent = hostParent;
this._hostContainerInfo = hostContainerInfo;
var nodeValue = ' react-empty: ' + this._domID + ' ';
if (transaction.useCreateElement) {
var ownerDocument = hostContainerInfo._ownerDocument;
var node = ownerDocument.createComment(nodeValue);
ReactDOMComponentTree.precacheNode(this, node);
return DOMLazyTree(node);
} else {
if (transaction.renderToStaticMarkup) {
// Normally we'd insert a comment node, but since this is a situation
// where React won't take over (static pages), we can simply return
// nothing.
return '';
}
return '<!--' + nodeValue + '-->';
}
},
receiveComponent: function () {},
getHostNode: function () {
return ReactDOMComponentTree.getNodeFromInstance(this);
},
unmountComponent: function () {
ReactDOMComponentTree.uncacheNode(this);
}
});
module.exports = ReactDOMEmptyComponent;
/***/ },
/* 139 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2015-present, 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 ReactDOMTreeTraversal
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var invariant = __webpack_require__(8);
/**
* Return the lowest common ancestor of A and B, or null if they are in
* different trees.
*/
function getLowestCommonAncestor(instA, instB) {
!('_hostNode' in instA) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0;
!('_hostNode' in instB) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0;
var depthA = 0;
for (var tempA = instA; tempA; tempA = tempA._hostParent) {
depthA++;
}
var depthB = 0;
for (var tempB = instB; tempB; tempB = tempB._hostParent) {
depthB++;
}
// If A is deeper, crawl up.
while (depthA - depthB > 0) {
instA = instA._hostParent;
depthA--;
}
// If B is deeper, crawl up.
while (depthB - depthA > 0) {
instB = instB._hostParent;
depthB--;
}
// Walk in lockstep until we find a match.
var depth = depthA;
while (depth--) {
if (instA === instB) {
return instA;
}
instA = instA._hostParent;
instB = instB._hostParent;
}
return null;
}
/**
* Return if A is an ancestor of B.
*/
function isAncestor(instA, instB) {
!('_hostNode' in instA) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'isAncestor: Invalid argument.') : _prodInvariant('35') : void 0;
!('_hostNode' in instB) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'isAncestor: Invalid argument.') : _prodInvariant('35') : void 0;
while (instB) {
if (instB === instA) {
return true;
}
instB = instB._hostParent;
}
return false;
}
/**
* Return the parent instance of the passed-in instance.
*/
function getParentInstance(inst) {
!('_hostNode' in inst) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getParentInstance: Invalid argument.') : _prodInvariant('36') : void 0;
return inst._hostParent;
}
/**
* Simulates the traversal of a two-phase, capture/bubble event dispatch.
*/
function traverseTwoPhase(inst, fn, arg) {
var path = [];
while (inst) {
path.push(inst);
inst = inst._hostParent;
}
var i;
for (i = path.length; i-- > 0;) {
fn(path[i], false, arg);
}
for (i = 0; i < path.length; i++) {
fn(path[i], true, arg);
}
}
/**
* Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
* should would receive a `mouseEnter` or `mouseLeave` event.
*
* Does not invoke the callback on the nearest common ancestor because nothing
* "entered" or "left" that element.
*/
function traverseEnterLeave(from, to, fn, argFrom, argTo) {
var common = from && to ? getLowestCommonAncestor(from, to) : null;
var pathFrom = [];
while (from && from !== common) {
pathFrom.push(from);
from = from._hostParent;
}
var pathTo = [];
while (to && to !== common) {
pathTo.push(to);
to = to._hostParent;
}
var i;
for (i = 0; i < pathFrom.length; i++) {
fn(pathFrom[i], true, argFrom);
}
for (i = pathTo.length; i-- > 0;) {
fn(pathTo[i], false, argTo);
}
}
module.exports = {
isAncestor: isAncestor,
getLowestCommonAncestor: getLowestCommonAncestor,
getParentInstance: getParentInstance,
traverseTwoPhase: traverseTwoPhase,
traverseEnterLeave: traverseEnterLeave
};
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 140 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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
*/
'use strict';
var _prodInvariant = __webpack_require__(7),
_assign = __webpack_require__(4);
var DOMChildrenOperations = __webpack_require__(82);
var DOMLazyTree = __webpack_require__(83);
var ReactDOMComponentTree = __webpack_require__(37);
var ReactInstrumentation = __webpack_require__(63);
var escapeTextContentForBrowser = __webpack_require__(88);
var invariant = __webpack_require__(8);
var validateDOMNesting = __webpack_require__(137);
/**
* 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 between comment nodes 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 (text) {
// TODO: This is really a ReactText (ReactNode), not a ReactElement
this._currentElement = text;
this._stringText = '' + text;
// ReactDOMComponentTree uses these:
this._hostNode = null;
this._hostParent = null;
// Properties
this._domID = null;
this._mountIndex = 0;
this._closingComment = null;
this._commentNodes = null;
};
_assign(ReactDOMTextComponent.prototype, {
/**
* Creates the markup for this text node. This node is not intended to have
* any features besides containing text content.
*
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @return {string} Markup for this text node.
* @internal
*/
mountComponent: function (transaction, hostParent, hostContainerInfo, context) {
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onSetText(this._debugID, this._stringText);
var parentInfo;
if (hostParent != null) {
parentInfo = hostParent._ancestorInfo;
} else if (hostContainerInfo != null) {
parentInfo = hostContainerInfo._ancestorInfo;
}
if (parentInfo) {
// parentInfo should always be present except for the top-level
// component when server rendering
validateDOMNesting('#text', this, parentInfo);
}
}
var domID = hostContainerInfo._idCounter++;
var openingValue = ' react-text: ' + domID + ' ';
var closingValue = ' /react-text ';
this._domID = domID;
this._hostParent = hostParent;
if (transaction.useCreateElement) {
var ownerDocument = hostContainerInfo._ownerDocument;
var openingComment = ownerDocument.createComment(openingValue);
var closingComment = ownerDocument.createComment(closingValue);
var lazyTree = DOMLazyTree(ownerDocument.createDocumentFragment());
DOMLazyTree.queueChild(lazyTree, DOMLazyTree(openingComment));
if (this._stringText) {
DOMLazyTree.queueChild(lazyTree, DOMLazyTree(ownerDocument.createTextNode(this._stringText)));
}
DOMLazyTree.queueChild(lazyTree, DOMLazyTree(closingComment));
ReactDOMComponentTree.precacheNode(this, openingComment);
this._closingComment = closingComment;
return lazyTree;
} else {
var escapedText = escapeTextContentForBrowser(this._stringText);
if (transaction.renderToStaticMarkup) {
// Normally we'd wrap this between comment nodes 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 '<!--' + openingValue + '-->' + escapedText + '<!--' + closingValue + '-->';
}
},
/**
* 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 commentNodes = this.getHostNode();
DOMChildrenOperations.replaceDelimitedText(commentNodes[0], commentNodes[1], nextStringText);
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onSetText(this._debugID, nextStringText);
}
}
}
},
getHostNode: function () {
var hostNode = this._commentNodes;
if (hostNode) {
return hostNode;
}
if (!this._closingComment) {
var openingComment = ReactDOMComponentTree.getNodeFromInstance(this);
var node = openingComment.nextSibling;
while (true) {
!(node != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Missing closing comment for text component %s', this._domID) : _prodInvariant('67', this._domID) : void 0;
if (node.nodeType === 8 && node.nodeValue === ' /react-text ') {
this._closingComment = node;
break;
}
node = node.nextSibling;
}
}
hostNode = [this._hostNode, this._closingComment];
this._commentNodes = hostNode;
return hostNode;
},
unmountComponent: function () {
this._closingComment = null;
this._commentNodes = null;
ReactDOMComponentTree.uncacheNode(this);
}
});
module.exports = ReactDOMTextComponent;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 141 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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 _assign = __webpack_require__(4);
var ReactUpdates = __webpack_require__(57);
var Transaction = __webpack_require__(70);
var emptyFunction = __webpack_require__(12);
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;
/***/ },
/* 142 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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
*/
'use strict';
var _assign = __webpack_require__(4);
var EventListener = __webpack_require__(143);
var ExecutionEnvironment = __webpack_require__(50);
var PooledClass = __webpack_require__(6);
var ReactDOMComponentTree = __webpack_require__(37);
var ReactUpdates = __webpack_require__(57);
var getEventTarget = __webpack_require__(71);
var getUnboundedScrollPosition = __webpack_require__(144);
/**
* Find the deepest React component completely containing the root of the
* passed-in instance (for use when entire React trees are nested within each
* other). If React trees are not nested, returns null.
*/
function findParent(inst) {
// 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.
while (inst._hostParent) {
inst = inst._hostParent;
}
var rootNode = ReactDOMComponentTree.getNodeFromInstance(inst);
var container = rootNode.parentNode;
return ReactDOMComponentTree.getClosestInstanceFromNode(container);
}
// 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) {
var nativeEventTarget = getEventTarget(bookKeeping.nativeEvent);
var targetInst = ReactDOMComponentTree.getClosestInstanceFromNode(nativeEventTarget);
// 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 = targetInst;
do {
bookKeeping.ancestors.push(ancestor);
ancestor = ancestor && findParent(ancestor);
} while (ancestor);
for (var i = 0; i < bookKeeping.ancestors.length; i++) {
targetInst = bookKeeping.ancestors[i];
ReactEventListener._handleTopLevel(bookKeeping.topLevelType, targetInst, 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;
/***/ },
/* 143 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {'use strict';
/**
* Copyright (c) 2013-present, 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.
*
* @typechecks
*/
var emptyFunction = __webpack_require__(12);
/**
* 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 listen(target, eventType, callback) {
if (target.addEventListener) {
target.addEventListener(eventType, callback, false);
return {
remove: function remove() {
target.removeEventListener(eventType, callback, false);
}
};
} else if (target.attachEvent) {
target.attachEvent('on' + eventType, callback);
return {
remove: function remove() {
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 capture(target, eventType, callback) {
if (target.addEventListener) {
target.addEventListener(eventType, callback, true);
return {
remove: function remove() {
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 registerDefault() {}
};
module.exports = EventListener;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 144 */
/***/ function(module, exports) {
/**
* Copyright (c) 2013-present, 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
*/
'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;
/***/ },
/* 145 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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__(38);
var EventPluginHub = __webpack_require__(44);
var EventPluginUtils = __webpack_require__(46);
var ReactComponentEnvironment = __webpack_require__(123);
var ReactClass = __webpack_require__(21);
var ReactEmptyComponent = __webpack_require__(131);
var ReactBrowserEventEmitter = __webpack_require__(112);
var ReactHostComponent = __webpack_require__(132);
var ReactUpdates = __webpack_require__(57);
var ReactInjection = {
Component: ReactComponentEnvironment.injection,
Class: ReactClass.injection,
DOMProperty: DOMProperty.injection,
EmptyComponent: ReactEmptyComponent.injection,
EventPluginHub: EventPluginHub.injection,
EventPluginUtils: EventPluginUtils.injection,
EventEmitter: ReactBrowserEventEmitter.injection,
HostComponent: ReactHostComponent.injection,
Updates: ReactUpdates.injection
};
module.exports = ReactInjection;
/***/ },
/* 146 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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
*/
'use strict';
var _assign = __webpack_require__(4);
var CallbackQueue = __webpack_require__(58);
var PooledClass = __webpack_require__(6);
var ReactBrowserEventEmitter = __webpack_require__(112);
var ReactInputSelection = __webpack_require__(147);
var ReactInstrumentation = __webpack_require__(63);
var Transaction = __webpack_require__(70);
var ReactUpdateQueue = __webpack_require__(136);
/**
* 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 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];
if (process.env.NODE_ENV !== 'production') {
TRANSACTION_WRAPPERS.push({
initialize: ReactInstrumentation.debugTool.onBeginFlush,
close: ReactInstrumentation.debugTool.onEndFlush
});
}
/**
* 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(useCreateElement) {
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
// `ReactDOMTextComponent` checks it in `mountComponent`.`
this.renderToStaticMarkup = false;
this.reactMountReady = CallbackQueue.getPooled(null);
this.useCreateElement = 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;
},
/**
* @return {object} The queue to collect React async events.
*/
getUpdateQueue: function () {
return ReactUpdateQueue;
},
/**
* Save current transaction state -- if the return value from this method is
* passed to `rollback`, the transaction will be reset to that state.
*/
checkpoint: function () {
// reactMountReady is the our only stateful wrapper
return this.reactMountReady.checkpoint();
},
rollback: function (checkpoint) {
this.reactMountReady.rollback(checkpoint);
},
/**
* `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;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 147 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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__(148);
var containsNode = __webpack_require__(150);
var focusNode = __webpack_require__(97);
var getActiveElement = __webpack_require__(153);
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 (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;
/***/ },
/* 148 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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__(50);
var getNodeForCharacterOffset = __webpack_require__(149);
var getTextContentAccessor = __webpack_require__(52);
/**
* 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 (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 programmatically 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 = 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;
/***/ },
/* 149 */
/***/ function(module, exports) {
/**
* Copyright 2013-present, 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;
/***/ },
/* 150 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
/**
* Copyright (c) 2013-present, 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.
*
*
*/
var isTextNode = __webpack_require__(151);
/*eslint-disable no-bitwise */
/**
* Checks if a given DOM node contains or is another DOM node.
*/
function containsNode(outerNode, innerNode) {
if (!outerNode || !innerNode) {
return false;
} else if (outerNode === innerNode) {
return true;
} else if (isTextNode(outerNode)) {
return false;
} else if (isTextNode(innerNode)) {
return containsNode(outerNode, innerNode.parentNode);
} else if ('contains' in outerNode) {
return outerNode.contains(innerNode);
} else if (outerNode.compareDocumentPosition) {
return !!(outerNode.compareDocumentPosition(innerNode) & 16);
} else {
return false;
}
}
module.exports = containsNode;
/***/ },
/* 151 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
/**
* Copyright (c) 2013-present, 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
*/
var isNode = __webpack_require__(152);
/**
* @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;
/***/ },
/* 152 */
/***/ function(module, exports) {
'use strict';
/**
* Copyright (c) 2013-present, 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
*/
/**
* @param {*} object The object to check.
* @return {boolean} Whether or not the object is a DOM node.
*/
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;
/***/ },
/* 153 */
/***/ function(module, exports) {
'use strict';
/**
* Copyright (c) 2013-present, 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
*/
/* eslint-disable fb-www/typeof-undefined */
/**
* 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 or document body is not
* yet defined.
*/
function getActiveElement() /*?DOMElement*/{
if (typeof document === 'undefined') {
return null;
}
try {
return document.activeElement || document.body;
} catch (e) {
return document.body;
}
}
module.exports = getActiveElement;
/***/ },
/* 154 */
/***/ function(module, exports) {
/**
* Copyright 2013-present, 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 NS = {
xlink: 'http://www.w3.org/1999/xlink',
xml: 'http://www.w3.org/XML/1998/namespace'
};
// We use attributes for everything SVG so let's avoid some duplication and run
// code instead.
// The following are all specified in the HTML config already so we exclude here.
// - class (as className)
// - color
// - height
// - id
// - lang
// - max
// - media
// - method
// - min
// - name
// - style
// - target
// - type
// - width
var ATTRS = {
accentHeight: 'accent-height',
accumulate: 0,
additive: 0,
alignmentBaseline: 'alignment-baseline',
allowReorder: 'allowReorder',
alphabetic: 0,
amplitude: 0,
arabicForm: 'arabic-form',
ascent: 0,
attributeName: 'attributeName',
attributeType: 'attributeType',
autoReverse: 'autoReverse',
azimuth: 0,
baseFrequency: 'baseFrequency',
baseProfile: 'baseProfile',
baselineShift: 'baseline-shift',
bbox: 0,
begin: 0,
bias: 0,
by: 0,
calcMode: 'calcMode',
capHeight: 'cap-height',
clip: 0,
clipPath: 'clip-path',
clipRule: 'clip-rule',
clipPathUnits: 'clipPathUnits',
colorInterpolation: 'color-interpolation',
colorInterpolationFilters: 'color-interpolation-filters',
colorProfile: 'color-profile',
colorRendering: 'color-rendering',
contentScriptType: 'contentScriptType',
contentStyleType: 'contentStyleType',
cursor: 0,
cx: 0,
cy: 0,
d: 0,
decelerate: 0,
descent: 0,
diffuseConstant: 'diffuseConstant',
direction: 0,
display: 0,
divisor: 0,
dominantBaseline: 'dominant-baseline',
dur: 0,
dx: 0,
dy: 0,
edgeMode: 'edgeMode',
elevation: 0,
enableBackground: 'enable-background',
end: 0,
exponent: 0,
externalResourcesRequired: 'externalResourcesRequired',
fill: 0,
fillOpacity: 'fill-opacity',
fillRule: 'fill-rule',
filter: 0,
filterRes: 'filterRes',
filterUnits: 'filterUnits',
floodColor: 'flood-color',
floodOpacity: 'flood-opacity',
focusable: 0,
fontFamily: 'font-family',
fontSize: 'font-size',
fontSizeAdjust: 'font-size-adjust',
fontStretch: 'font-stretch',
fontStyle: 'font-style',
fontVariant: 'font-variant',
fontWeight: 'font-weight',
format: 0,
from: 0,
fx: 0,
fy: 0,
g1: 0,
g2: 0,
glyphName: 'glyph-name',
glyphOrientationHorizontal: 'glyph-orientation-horizontal',
glyphOrientationVertical: 'glyph-orientation-vertical',
glyphRef: 'glyphRef',
gradientTransform: 'gradientTransform',
gradientUnits: 'gradientUnits',
hanging: 0,
horizAdvX: 'horiz-adv-x',
horizOriginX: 'horiz-origin-x',
ideographic: 0,
imageRendering: 'image-rendering',
'in': 0,
in2: 0,
intercept: 0,
k: 0,
k1: 0,
k2: 0,
k3: 0,
k4: 0,
kernelMatrix: 'kernelMatrix',
kernelUnitLength: 'kernelUnitLength',
kerning: 0,
keyPoints: 'keyPoints',
keySplines: 'keySplines',
keyTimes: 'keyTimes',
lengthAdjust: 'lengthAdjust',
letterSpacing: 'letter-spacing',
lightingColor: 'lighting-color',
limitingConeAngle: 'limitingConeAngle',
local: 0,
markerEnd: 'marker-end',
markerMid: 'marker-mid',
markerStart: 'marker-start',
markerHeight: 'markerHeight',
markerUnits: 'markerUnits',
markerWidth: 'markerWidth',
mask: 0,
maskContentUnits: 'maskContentUnits',
maskUnits: 'maskUnits',
mathematical: 0,
mode: 0,
numOctaves: 'numOctaves',
offset: 0,
opacity: 0,
operator: 0,
order: 0,
orient: 0,
orientation: 0,
origin: 0,
overflow: 0,
overlinePosition: 'overline-position',
overlineThickness: 'overline-thickness',
paintOrder: 'paint-order',
panose1: 'panose-1',
pathLength: 'pathLength',
patternContentUnits: 'patternContentUnits',
patternTransform: 'patternTransform',
patternUnits: 'patternUnits',
pointerEvents: 'pointer-events',
points: 0,
pointsAtX: 'pointsAtX',
pointsAtY: 'pointsAtY',
pointsAtZ: 'pointsAtZ',
preserveAlpha: 'preserveAlpha',
preserveAspectRatio: 'preserveAspectRatio',
primitiveUnits: 'primitiveUnits',
r: 0,
radius: 0,
refX: 'refX',
refY: 'refY',
renderingIntent: 'rendering-intent',
repeatCount: 'repeatCount',
repeatDur: 'repeatDur',
requiredExtensions: 'requiredExtensions',
requiredFeatures: 'requiredFeatures',
restart: 0,
result: 0,
rotate: 0,
rx: 0,
ry: 0,
scale: 0,
seed: 0,
shapeRendering: 'shape-rendering',
slope: 0,
spacing: 0,
specularConstant: 'specularConstant',
specularExponent: 'specularExponent',
speed: 0,
spreadMethod: 'spreadMethod',
startOffset: 'startOffset',
stdDeviation: 'stdDeviation',
stemh: 0,
stemv: 0,
stitchTiles: 'stitchTiles',
stopColor: 'stop-color',
stopOpacity: 'stop-opacity',
strikethroughPosition: 'strikethrough-position',
strikethroughThickness: 'strikethrough-thickness',
string: 0,
stroke: 0,
strokeDasharray: 'stroke-dasharray',
strokeDashoffset: 'stroke-dashoffset',
strokeLinecap: 'stroke-linecap',
strokeLinejoin: 'stroke-linejoin',
strokeMiterlimit: 'stroke-miterlimit',
strokeOpacity: 'stroke-opacity',
strokeWidth: 'stroke-width',
surfaceScale: 'surfaceScale',
systemLanguage: 'systemLanguage',
tableValues: 'tableValues',
targetX: 'targetX',
targetY: 'targetY',
textAnchor: 'text-anchor',
textDecoration: 'text-decoration',
textRendering: 'text-rendering',
textLength: 'textLength',
to: 0,
transform: 0,
u1: 0,
u2: 0,
underlinePosition: 'underline-position',
underlineThickness: 'underline-thickness',
unicode: 0,
unicodeBidi: 'unicode-bidi',
unicodeRange: 'unicode-range',
unitsPerEm: 'units-per-em',
vAlphabetic: 'v-alphabetic',
vHanging: 'v-hanging',
vIdeographic: 'v-ideographic',
vMathematical: 'v-mathematical',
values: 0,
vectorEffect: 'vector-effect',
version: 0,
vertAdvY: 'vert-adv-y',
vertOriginX: 'vert-origin-x',
vertOriginY: 'vert-origin-y',
viewBox: 'viewBox',
viewTarget: 'viewTarget',
visibility: 0,
widths: 0,
wordSpacing: 'word-spacing',
writingMode: 'writing-mode',
x: 0,
xHeight: 'x-height',
x1: 0,
x2: 0,
xChannelSelector: 'xChannelSelector',
xlinkActuate: 'xlink:actuate',
xlinkArcrole: 'xlink:arcrole',
xlinkHref: 'xlink:href',
xlinkRole: 'xlink:role',
xlinkShow: 'xlink:show',
xlinkTitle: 'xlink:title',
xlinkType: 'xlink:type',
xmlBase: 'xml:base',
xmlns: 0,
xmlnsXlink: 'xmlns:xlink',
xmlLang: 'xml:lang',
xmlSpace: 'xml:space',
y: 0,
y1: 0,
y2: 0,
yChannelSelector: 'yChannelSelector',
z: 0,
zoomAndPan: 'zoomAndPan'
};
var SVGDOMPropertyConfig = {
Properties: {},
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: {}
};
Object.keys(ATTRS).forEach(function (key) {
SVGDOMPropertyConfig.Properties[key] = 0;
if (ATTRS[key]) {
SVGDOMPropertyConfig.DOMAttributeNames[key] = ATTRS[key];
}
});
module.exports = SVGDOMPropertyConfig;
/***/ },
/* 155 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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__(42);
var EventPropagators = __webpack_require__(43);
var ExecutionEnvironment = __webpack_require__(50);
var ReactDOMComponentTree = __webpack_require__(37);
var ReactInputSelection = __webpack_require__(147);
var SyntheticEvent = __webpack_require__(54);
var getActiveElement = __webpack_require__(153);
var isTextInputElement = __webpack_require__(73);
var keyOf = __webpack_require__(25);
var shallowEqual = __webpack_require__(129);
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 activeElementInst = null;
var lastSelection = null;
var mouseDown = false;
// Track whether a listener exists for this plugin. If none exist, we do
// not extract events. See #3639.
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, activeElementInst, 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,
extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
if (!hasListener) {
return null;
}
var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window;
switch (topLevelType) {
// Track the input node that has focus.
case topLevelTypes.topFocus:
if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') {
activeElement = targetNode;
activeElementInst = targetInst;
lastSelection = null;
}
break;
case topLevelTypes.topBlur:
activeElement = null;
activeElementInst = 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 (inst, registrationName, listener) {
if (registrationName === ON_SELECT_KEY) {
hasListener = true;
}
}
};
module.exports = SelectEventPlugin;
/***/ },
/* 156 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 _prodInvariant = __webpack_require__(7);
var EventConstants = __webpack_require__(42);
var EventListener = __webpack_require__(143);
var EventPropagators = __webpack_require__(43);
var ReactDOMComponentTree = __webpack_require__(37);
var SyntheticAnimationEvent = __webpack_require__(157);
var SyntheticClipboardEvent = __webpack_require__(158);
var SyntheticEvent = __webpack_require__(54);
var SyntheticFocusEvent = __webpack_require__(159);
var SyntheticKeyboardEvent = __webpack_require__(160);
var SyntheticMouseEvent = __webpack_require__(76);
var SyntheticDragEvent = __webpack_require__(163);
var SyntheticTouchEvent = __webpack_require__(164);
var SyntheticTransitionEvent = __webpack_require__(165);
var SyntheticUIEvent = __webpack_require__(77);
var SyntheticWheelEvent = __webpack_require__(166);
var emptyFunction = __webpack_require__(12);
var getEventCharCode = __webpack_require__(161);
var invariant = __webpack_require__(8);
var keyOf = __webpack_require__(25);
var topLevelTypes = EventConstants.topLevelTypes;
var eventTypes = {
abort: {
phasedRegistrationNames: {
bubbled: keyOf({ onAbort: true }),
captured: keyOf({ onAbortCapture: true })
}
},
animationEnd: {
phasedRegistrationNames: {
bubbled: keyOf({ onAnimationEnd: true }),
captured: keyOf({ onAnimationEndCapture: true })
}
},
animationIteration: {
phasedRegistrationNames: {
bubbled: keyOf({ onAnimationIteration: true }),
captured: keyOf({ onAnimationIterationCapture: true })
}
},
animationStart: {
phasedRegistrationNames: {
bubbled: keyOf({ onAnimationStart: true }),
captured: keyOf({ onAnimationStartCapture: 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 })
}
},
invalid: {
phasedRegistrationNames: {
bubbled: keyOf({ onInvalid: true }),
captured: keyOf({ onInvalidCapture: 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: {
bubbled: keyOf({ onTimeUpdate: true }),
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 })
}
},
transitionEnd: {
phasedRegistrationNames: {
bubbled: keyOf({ onTransitionEnd: true }),
captured: keyOf({ onTransitionEndCapture: 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,
topAnimationEnd: eventTypes.animationEnd,
topAnimationIteration: eventTypes.animationIteration,
topAnimationStart: eventTypes.animationStart,
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,
topInvalid: eventTypes.invalid,
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,
topTransitionEnd: eventTypes.transitionEnd,
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 = {};
function getDictionaryKey(inst) {
return '.' + inst._rootNodeID;
}
var SimpleEventPlugin = {
eventTypes: eventTypes,
extractEvents: function (topLevelType, targetInst, 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.topInvalid:
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.topAnimationEnd:
case topLevelTypes.topAnimationIteration:
case topLevelTypes.topAnimationStart:
EventConstructor = SyntheticAnimationEvent;
break;
case topLevelTypes.topTransitionEnd:
EventConstructor = SyntheticTransitionEvent;
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) : _prodInvariant('86', topLevelType) : void 0;
var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget);
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
},
didPutListener: function (inst, 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 key = getDictionaryKey(inst);
var node = ReactDOMComponentTree.getNodeFromInstance(inst);
if (!onClickListeners[key]) {
onClickListeners[key] = EventListener.listen(node, 'click', emptyFunction);
}
}
},
willDeleteListener: function (inst, registrationName) {
if (registrationName === ON_CLICK_KEY) {
var key = getDictionaryKey(inst);
onClickListeners[key].remove();
delete onClickListeners[key];
}
}
};
module.exports = SimpleEventPlugin;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 157 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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 SyntheticAnimationEvent
*/
'use strict';
var SyntheticEvent = __webpack_require__(54);
/**
* @interface Event
* @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
* @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
*/
var AnimationEventInterface = {
animationName: null,
elapsedTime: null,
pseudoElement: 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 {SyntheticEvent}
*/
function SyntheticAnimationEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticAnimationEvent, AnimationEventInterface);
module.exports = SyntheticAnimationEvent;
/***/ },
/* 158 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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
*/
'use strict';
var SyntheticEvent = __webpack_require__(54);
/**
* @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) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface);
module.exports = SyntheticClipboardEvent;
/***/ },
/* 159 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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
*/
'use strict';
var SyntheticUIEvent = __webpack_require__(77);
/**
* @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) {
return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface);
module.exports = SyntheticFocusEvent;
/***/ },
/* 160 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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
*/
'use strict';
var SyntheticUIEvent = __webpack_require__(77);
var getEventCharCode = __webpack_require__(161);
var getEventKey = __webpack_require__(162);
var getEventModifierState = __webpack_require__(79);
/**
* @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) {
return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface);
module.exports = SyntheticKeyboardEvent;
/***/ },
/* 161 */
/***/ function(module, exports) {
/**
* Copyright 2013-present, 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
*/
'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;
/***/ },
/* 162 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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
*/
'use strict';
var getEventCharCode = __webpack_require__(161);
/**
* 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;
/***/ },
/* 163 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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
*/
'use strict';
var SyntheticMouseEvent = __webpack_require__(76);
/**
* @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) {
return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface);
module.exports = SyntheticDragEvent;
/***/ },
/* 164 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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
*/
'use strict';
var SyntheticUIEvent = __webpack_require__(77);
var getEventModifierState = __webpack_require__(79);
/**
* @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) {
return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface);
module.exports = SyntheticTouchEvent;
/***/ },
/* 165 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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 SyntheticTransitionEvent
*/
'use strict';
var SyntheticEvent = __webpack_require__(54);
/**
* @interface Event
* @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
* @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
*/
var TransitionEventInterface = {
propertyName: null,
elapsedTime: null,
pseudoElement: 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 {SyntheticEvent}
*/
function SyntheticTransitionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticTransitionEvent, TransitionEventInterface);
module.exports = SyntheticTransitionEvent;
/***/ },
/* 166 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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
*/
'use strict';
var SyntheticMouseEvent = __webpack_require__(76);
/**
* @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) {
return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface);
module.exports = SyntheticWheelEvent;
/***/ },
/* 167 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 _prodInvariant = __webpack_require__(7);
var DOMLazyTree = __webpack_require__(83);
var DOMProperty = __webpack_require__(38);
var ReactBrowserEventEmitter = __webpack_require__(112);
var ReactCurrentOwner = __webpack_require__(10);
var ReactDOMComponentTree = __webpack_require__(37);
var ReactDOMContainerInfo = __webpack_require__(168);
var ReactDOMFeatureFlags = __webpack_require__(169);
var ReactElement = __webpack_require__(9);
var ReactFeatureFlags = __webpack_require__(59);
var ReactInstanceMap = __webpack_require__(124);
var ReactInstrumentation = __webpack_require__(63);
var ReactMarkupChecksum = __webpack_require__(170);
var ReactReconciler = __webpack_require__(60);
var ReactUpdateQueue = __webpack_require__(136);
var ReactUpdates = __webpack_require__(57);
var emptyObject = __webpack_require__(19);
var instantiateReactComponent = __webpack_require__(126);
var invariant = __webpack_require__(8);
var setInnerHTML = __webpack_require__(85);
var shouldUpdateReactComponent = __webpack_require__(130);
var warning = __webpack_require__(11);
var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME;
var ROOT_ATTR_NAME = DOMProperty.ROOT_ATTRIBUTE_NAME;
var ELEMENT_NODE_TYPE = 1;
var DOC_NODE_TYPE = 9;
var DOCUMENT_FRAGMENT_NODE_TYPE = 11;
var instancesByReactRootID = {};
/**
* 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;
}
}
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.getAttribute && node.getAttribute(ATTR_NAME) || '';
}
/**
* Mounts this component and inserts it into the DOM.
*
* @param {ReactComponent} componentInstance The instance to mount.
* @param {DOMElement} container DOM element to mount into.
* @param {ReactReconcileTransaction} transaction
* @param {boolean} shouldReuseMarkup If true, do not insert markup
*/
function mountComponentIntoNode(wrapperInstance, container, transaction, shouldReuseMarkup, context) {
var markerName;
if (ReactFeatureFlags.logTopLevelRenders) {
var wrappedElement = wrapperInstance._currentElement.props;
var type = wrappedElement.type;
markerName = 'React mount: ' + (typeof type === 'string' ? type : type.displayName || type.name);
console.time(markerName);
}
var markup = ReactReconciler.mountComponent(wrapperInstance, transaction, null, ReactDOMContainerInfo(wrapperInstance, container), context);
if (markerName) {
console.timeEnd(markerName);
}
wrapperInstance._renderedComponent._topLevelWrapper = wrapperInstance;
ReactMount._mountImageIntoNode(markup, container, wrapperInstance, shouldReuseMarkup, transaction);
}
/**
* Batched mount.
*
* @param {ReactComponent} componentInstance The instance to mount.
* @param {DOMElement} container DOM element to mount into.
* @param {boolean} shouldReuseMarkup If true, do not insert markup
*/
function batchedMountComponentIntoNode(componentInstance, container, shouldReuseMarkup, context) {
var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(
/* useCreateElement */
!shouldReuseMarkup && ReactDOMFeatureFlags.useCreateElement);
transaction.perform(mountComponentIntoNode, null, componentInstance, 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, safely) {
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onBeginFlush();
}
ReactReconciler.unmountComponent(instance, safely);
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onEndFlush();
}
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(container) {
var rootEl = getReactRootElementInContainer(container);
if (rootEl) {
var inst = ReactDOMComponentTree.getInstanceFromNode(rootEl);
return !!(inst && inst._hostParent);
}
}
function getHostRootInstanceInContainer(container) {
var rootEl = getReactRootElementInContainer(container);
var prevHostInstance = rootEl && ReactDOMComponentTree.getInstanceFromNode(rootEl);
return prevHostInstance && !prevHostInstance._hostParent ? prevHostInstance : null;
}
function getTopLevelWrapperInContainer(container) {
var root = getHostRootInstanceInContainer(container);
return root ? root._hostContainerInfo._topLevelWrapper : 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 topLevelRootCounter = 1;
var TopLevelWrapper = function () {
this.rootID = topLevelRootCounter++;
};
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,
/**
* Used by devtools. The keys are not important.
*/
_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, nextContext, container, callback) {
ReactMount.scrollMonitor(container, function () {
ReactUpdateQueue.enqueueElementInternal(prevComponent, nextElement, nextContext);
if (callback) {
ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback);
}
});
return prevComponent;
},
/**
* Render a new component into the DOM. Hooked by devtools!
*
* @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') : void 0;
!(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.') : _prodInvariant('37') : void 0;
ReactBrowserEventEmitter.ensureScrollValueMonitoring();
var componentInstance = instantiateReactComponent(nextElement, false);
// 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, container, shouldReuseMarkup, context);
var wrapperID = componentInstance._instance.rootID;
instancesByReactRootID[wrapperID] = componentInstance;
if (process.env.NODE_ENV !== 'production') {
// The instance here is TopLevelWrapper so we report mount for its child.
ReactInstrumentation.debugTool.onMountRootComponent(componentInstance._renderedComponent._debugID);
}
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 && ReactInstanceMap.has(parentComponent)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'parentComponent must be a valid React Component') : _prodInvariant('38') : void 0;
return ReactMount._renderSubtreeIntoContainer(parentComponent, nextElement, container, callback);
},
_renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) {
ReactUpdateQueue.validateCallback(callback, 'ReactDOM.render');
!ReactElement.isValidElement(nextElement) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOM.render(): Invalid component element.%s', typeof nextElement === 'string' ? ' Instead of passing a string like \'div\', pass ' + 'React.createElement(\'div\') or <div />.' : typeof nextElement === 'function' ? ' Instead of passing a class like Foo, pass ' + 'React.createElement(Foo) or <Foo />.' :
// Check if it quacks like an element
nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : _prodInvariant('39', typeof nextElement === 'string' ? ' Instead of passing a string like \'div\', pass ' + 'React.createElement(\'div\') or <div />.' : typeof nextElement === 'function' ? ' Instead of passing a class like Foo, pass ' + 'React.createElement(Foo) or <Foo />.' : nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : void 0;
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.') : void 0;
var nextWrappedElement = ReactElement(TopLevelWrapper, null, null, null, null, null, nextElement);
var nextContext;
if (parentComponent) {
var parentInst = ReactInstanceMap.get(parentComponent);
nextContext = parentInst._processChildContext(parentInst._context);
} else {
nextContext = emptyObject;
}
var prevComponent = getTopLevelWrapperInContainer(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, nextContext, 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.') : void 0;
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.') : void 0;
break;
}
rootElementSibling = rootElementSibling.nextSibling;
}
}
}
var shouldReuseMarkup = containerHasReactMarkup && !prevComponent && !containerHasNonRootReactChild;
var component = ReactMount._renderNewRootComponent(nextWrappedElement, container, shouldReuseMarkup, nextContext)._renderedComponent.getPublicInstance();
if (callback) {
callback.call(component);
}
return component;
},
/**
* Renders a React component into the DOM in the supplied `container`.
* See https://facebook.github.io/react/docs/top-level-api.html#reactdom.render
*
* 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);
},
/**
* Unmounts and destroys the React component rendered in the `container`.
* See https://facebook.github.io/react/docs/top-level-api.html#reactdom.unmountcomponentatnode
*
* @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') : void 0;
!(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.') : _prodInvariant('40') : void 0;
var prevComponent = getTopLevelWrapperInContainer(container);
if (!prevComponent) {
// 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 isContainerReactRoot = container.nodeType === 1 && container.hasAttribute(ROOT_ATTR_NAME);
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.') : void 0;
}
return false;
}
delete instancesByReactRootID[prevComponent._instance.rootID];
ReactUpdates.batchedUpdates(unmountComponentFromNode, prevComponent, container, false);
return true;
},
_mountImageIntoNode: function (markup, container, instance, 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.') : _prodInvariant('41') : void 0;
if (shouldReuseMarkup) {
var rootElement = getReactRootElementInContainer(container);
if (ReactMarkupChecksum.canReuseMarkup(markup, rootElement)) {
ReactDOMComponentTree.precacheNode(instance, 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) : _prodInvariant('42', difference) : void 0;
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) : void 0;
}
}
}
!(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.') : _prodInvariant('43') : void 0;
if (transaction.useCreateElement) {
while (container.lastChild) {
container.removeChild(container.lastChild);
}
DOMLazyTree.insertTreeBefore(container, markup, null);
} else {
setInnerHTML(container, markup);
ReactDOMComponentTree.precacheNode(instance, container.firstChild);
}
if (process.env.NODE_ENV !== 'production') {
var hostNode = ReactDOMComponentTree.getInstanceFromNode(container.firstChild);
if (hostNode._debugID !== 0) {
ReactInstrumentation.debugTool.onHostOperation(hostNode._debugID, 'mount', markup.toString());
}
}
}
};
module.exports = ReactMount;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 168 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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 ReactDOMContainerInfo
*/
'use strict';
var validateDOMNesting = __webpack_require__(137);
var DOC_NODE_TYPE = 9;
function ReactDOMContainerInfo(topLevelWrapper, node) {
var info = {
_topLevelWrapper: topLevelWrapper,
_idCounter: 1,
_ownerDocument: node ? node.nodeType === DOC_NODE_TYPE ? node : node.ownerDocument : null,
_node: node,
_tag: node ? node.nodeName.toLowerCase() : null,
_namespaceURI: node ? node.namespaceURI : null
};
if (process.env.NODE_ENV !== 'production') {
info._ancestorInfo = node ? validateDOMNesting.updatedAncestorInfo(null, info._tag, null) : null;
}
return info;
}
module.exports = ReactDOMContainerInfo;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 169 */
/***/ function(module, exports) {
/**
* Copyright 2013-present, 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: true
};
module.exports = ReactDOMFeatureFlags;
/***/ },
/* 170 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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__(171);
var TAG_END = /\/?>/;
var COMMENT_START = /^<\!\-\-/;
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, comments and self-closing tags)
if (COMMENT_START.test(markup)) {
return markup;
} else {
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;
/***/ },
/* 171 */
/***/ function(module, exports) {
/**
* Copyright 2013-present, 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) {
var n = Math.min(i + 4096, m);
for (; i < n; 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;
/***/ },
/* 172 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-present, 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
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var ReactCurrentOwner = __webpack_require__(10);
var ReactDOMComponentTree = __webpack_require__(37);
var ReactInstanceMap = __webpack_require__(124);
var getHostComponentFromComposite = __webpack_require__(173);
var invariant = __webpack_require__(8);
var warning = __webpack_require__(11);
/**
* Returns the DOM node rendered by this element.
*
* See https://facebook.github.io/react/docs/top-level-api.html#reactdom.finddomnode
*
* @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 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') : void 0;
owner._warnedAboutRefsInRender = true;
}
}
if (componentOrElement == null) {
return null;
}
if (componentOrElement.nodeType === 1) {
return componentOrElement;
}
var inst = ReactInstanceMap.get(componentOrElement);
if (inst) {
inst = getHostComponentFromComposite(inst);
return inst ? ReactDOMComponentTree.getNodeFromInstance(inst) : null;
}
if (typeof componentOrElement.render === 'function') {
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : _prodInvariant('44') : void 0;
} else {
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : _prodInvariant('45', Object.keys(componentOrElement)) : void 0;
}
}
module.exports = findDOMNode;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 173 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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 getHostComponentFromComposite
*/
'use strict';
var ReactNodeTypes = __webpack_require__(128);
function getHostComponentFromComposite(inst) {
var type;
while ((type = inst._renderedNodeType) === ReactNodeTypes.COMPOSITE) {
inst = inst._renderedComponent;
}
if (type === ReactNodeTypes.HOST) {
return inst._renderedComponent;
} else if (type === ReactNodeTypes.EMPTY) {
return null;
}
}
module.exports = getHostComponentFromComposite;
/***/ },
/* 174 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, 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__(167);
module.exports = ReactMount.renderSubtreeIntoContainer;
/***/ },
/* 175 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _Radio = __webpack_require__(176);
var _Radio2 = _interopRequireDefault(_Radio);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var RadioGroup = function (_Component) {
_inherits(RadioGroup, _Component);
function RadioGroup() {
var _Object$getPrototypeO;
var _temp, _this, _ret;
_classCallCheck(this, RadioGroup);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(RadioGroup)).call.apply(_Object$getPrototypeO, [this].concat(args))), _this), _this.state = {
data: _this.props.options,
name: _this.props.name
}, _this.getChecked = function () {
return _this.checked;
}, _this.setChecked = function (value) {
_this.checked = value;
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(RadioGroup, [{
key: 'render',
value: function render() {
return _react2.default.createElement(
'div',
null,
this.state.data.map(function (item, index) {
return _react2.default.createElement(_Radio2.default, {
key: index,
name: this.state.name,
item: item,
parentCallback: this.setChecked
});
}.bind(this))
);
}
}]);
return RadioGroup;
}(_react.Component);
RadioGroup.propTypes = {
options: _react.PropTypes.array.isRequired,
name: _react.PropTypes.string
};
RadioGroup.defaultProps = {
name: 'radio-' + new Date()
};
exports.default = RadioGroup;
/***/ },
/* 176 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Radios = function (_Component) {
_inherits(Radios, _Component);
function Radios() {
var _Object$getPrototypeO;
var _temp, _this, _ret;
_classCallCheck(this, Radios);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(Radios)).call.apply(_Object$getPrototypeO, [this].concat(args))), _this), _this.state = {
label: _this.props.item.label,
value: _this.props.item.value,
checked: _this.props.item.checked
}, _this.handleChange = function (e) {
_this.props.parentCallback(e.target.value);
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(Radios, [{
key: "render",
value: function render() {
return _react2.default.createElement(
"label",
null,
_react2.default.createElement("input", {
type: "radio",
name: this.props.name,
defaultChecked: !!this.state.checked,
value: this.state.value,
onChange: this.handleChange
}),
_react2.default.createElement(
"span",
null,
this.state.label
)
);
}
}]);
return Radios;
}(_react.Component);
exports.default = Radios;
/***/ }
/******/ ]); |
// Set up: npm install
var http = require("http"),
fs = require("fs"),
path = require("path"),
ws = require("ws"),
open = require("open"),
ProtoBuf = require("protobufjs");
// Initialize from .proto file
var Message = ProtoBuf.protoFromFile("example.proto").build("Message");
// HTTP server
var server = http.createServer(function(req, res) {
var file = null;
if (req.url == "/") {
file = "index.html";
} else if (req.url == "/example.proto") {
file = "example.proto";
}
if (file) {
fs.readFile(path.join(__dirname, file), function(err, data) {
if (err) {
res.writeHead(500, {"Content-Type": "text/html"});
res.end("Internal Server Error: "+err);
} else {
res.writeHead(200, {"Content-Type": "text/html"});
res.write(data);
res.end();
}
});
} else {
res.writeHead(404, {"Content-Type": "text/html"});
res.end("Not Found");
}
});
server.listen(8080);
server.on("listening", function() {
console.log("Server started");
open("http://localhost:8080/");
});
server.on("error", function(err) {
console.log("Failed to start server:", err);
process.exit(1);
});
// WebSocket adapter
var wss = new ws.Server({server: server});
wss.on("connection", function(socket) {
console.log("New connection");
socket.on("close", function() {
console.log("Disconnected");
});
socket.on("message", function(data, flags) {
if (flags.binary) {
try {
// Decode the Message
var msg = Message.decode(data);
console.log("Processing: "+msg.text);
// Transform the text to upper case
msg.text = msg.text.toUpperCase();
// Re-encode it and send it back
socket.send(msg.toBuffer());
} catch (err) {
console.log("Processing failed:", err);
}
} else {
console.log("Not binary data");
}
});
});
|
'use strict';
describe('Controller: FooterCtrl', function () {
// load the controller's module
beforeEach(module('pulsarClientApp'));
var FooterCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
FooterCtrl = $controller('FooterCtrl', {
$scope: scope
});
}));
// it('should attach a list of awesomeThings to the scope', function () {
// expect(scope.awesomeThings.length).toBe(3);
// });
});
|
function MantisBTExtension() {
var self = this;
setTimeout(function(){
self.poll();
}, 10000);
}
MantisBTExtension.prototype = {
'poll' : function(){
var self = this,
tasks = app.storage.urls().map(function(url){
return app.ajax(url);
});
if (tasks.length > 0) {
Q.all(tasks).then(
function(results){
var dates = [];
results.forEach(function(n){
if (!n.error) {
var list = !n.item ? [] : !Array.isArray(n.item) ? [n.item] : n.item; delete n.item;
list.forEach(function(item){
dates.push(Date.parse(item.pubDate));
});
}
});
app.badge.handle(Math.max.apply(Math, dates));
},
function(err){
console.error(err);
}
);
} else {
app.badge.touch('?');
}
setTimeout(function(){
self.poll();
}, 10*60*1000);
}
};
var extension = new MantisBTExtension();
|
//>>built
(function(l,a){"function"===typeof define&&define.amd?define(["cldr","../globalize","./number","./plural"],a):"object"===typeof exports?module.exports=a(require("cldrjs"),require("../globalize")):a(l.Cldr,l.Globalize)})(this,function(l,a){function q(b){var g,a;if(b)for(a in g={},b)g[a.replace(/unitPattern-count-/,"")]=b[a];return g}var k=a._formatMessage,r=a._runtimeBind,m=a._validateParameterPresence,t=a._validateParameterTypePlainObject,n=a._validateParameterTypeNumber,u=a._validateParameterTypeString,
v=function(b,g,a){return function(c){m(c,"value");n(c,"value");var f;var e=a;f=e.compoundUnitPattern;var d,h,e=e.unitProperties;d=b(c);h=g(c);e instanceof Array?(d=e[0],e=e[1],c=k(d[h],[c]),h=k(e.one,[""]).trim(),f=k(f,[c,h])):f=k(e[h],[d]);return f}},w="acceleration angle area digital duration length mass power pressure speed temperature volume".split(" "),p=function(b,a,d){var c;b=b.replace(/\//,"-per-");[""].concat(w).some(function(g){return c=d.main(["units",a,g.length?g+"-"+b:b])});c=q(c);return c||
!/-per-/.test(b)||(b=b.split("-per-"),c=b.map(function(b){return p(b,a,d)}),c[0]&&c[1])?c:void 0},x=p;a.formatUnit=a.prototype.formatUnit=function(b,a,d){m(b,"value");n(b,"value");return this.unitFormatter(a,d)(b)};a.unitFormatter=a.prototype.unitFormatter=function(b,a){var d,c,f;m(b,"unit");u(b,"unit");t(a,"options");a=a||{};d=[b,a];c=a.form||"long";var e=this.cldr;f=e.main(["units",c,"per/compoundUnitPattern"]);b=x(b,c,e);f={compoundUnitPattern:f,unitProperties:b};a=a.numberFormatter||this.numberFormatter();
b=this.pluralGenerator();c=v(a,b,f);r(d,this.cldr,c,[a,b,f]);return c};return a}); |
import {
clickable,
isVisible,
text
} from 'ember-cli-page-object';
import codeThemeSelector from 'code-corps-ember/tests/pages/components/code-theme-selector';
import editorWithPreview from 'code-corps-ember/tests/pages/components/editor-with-preview';
export default {
scope: '.task-details',
cancel: {
scope: '.cancel',
click: clickable(),
isVisible: isVisible()
},
codeThemeSelector,
commentBody: {
scope: '.comment-body',
hasStrongText: isVisible('strong'),
text: text()
},
nullCommentBody:{
scope: '[data-test-markdown-body-empty]'
},
edit: {
scope: '.edit',
click: clickable(),
isVisible: isVisible()
},
editorWithPreview,
save: {
scope: '.save',
click: clickable(),
isVisible: isVisible()
}
};
|
import { reset } from 'redux-form';
import fetch from 'isomorphic-fetch';
import { loginActionCreators } from '../../../../../login/modules/index';
import { trelloUrl } from '../../../../../../../utils/url';
import {
starredBoardActionCreators,
organizationActionCreators,
boardActionCreators
} from '../../../../../home/modules/index.js';
const CLOSE_CREATE_CARD_ITEM_FORM = 'CLOSE_CREATE_CARD_ITEM_FORM';
const OPEN_CREATE_CARD_ITEM_FORM = 'OPEN_CREATE_CARD_ITEM_FORM';
const FOCUS_CREATE_CARD_ITEM_FORM = 'FOCUS_CREATE_CARD_ITEM_FORM';
const BLUR_CREATE_CARD_ITEM_FORM = 'BLUR_CREATE_CARD_ITEM_FORM';
const MOVE_CARD = 'MOVE_CARD';
const LOAD_CARDS_REQUEST = 'LOAD_CARDS_REQUEST';
const LOAD_CARDS_SUCCESS = 'LOAD_CARDS_SUCCESS';
const LOAD_CARDS_FAIL = 'LOAD_CARDS_FAIL';
const SAVE_CARD_REQUEST = 'SAVE_CARD_REQUEST';
const SAVE_CARD_SUCCESS = 'SAVE_CARD_SUCCESS';
const SAVE_CARD_FAIL = 'SAVE_CARD_FAIL';
const SAVE_CARD_ITEM_REQUEST = 'SAVE_CARD_ITEM_REQUEST';
const SAVE_CARD_ITEM_SUCCESS = 'SAVE_CARD_ITEM_SUCCESS';
const SAVE_CARD_ITEM_FAIL = 'SAVE_CARD_ITEM_FAIL';
const UPDATE_CARDS = 'UPDATE_CARDS';
const UPDATE_CARDS_REQUEST = 'UPDATE_CARDS_REQUEST';
const UPDATE_CARDS_SUCCESS = 'UPDATE_CARDS_SUCCESS';
const UPDATE_CARDS_FAIL = 'UPDATE_CARDS_FAIL';
const RESET_CARDS = 'RESET_CARDS';
const initialState = {
isFocusOnCreateCardItemForm: false,
createCardFormIndexToOpen: 0,
isCreateCardItemFormOpen: false,
cards: [],
errorMessage: '',
pathname:'',
isFetchingCardsSuccessful: false,
isFetchingCards: false,
isSavingCardSuccessful: false,
isSavingCard: false,
isSavingCardItemSuccessful: false,
isSavingCardItem: false,
isUpdatingCardsSuccessful: false,
isUpdatingCards: false,
}
function loadCardsRequest(payload) {
return {
type: LOAD_CARDS_REQUEST,
payload
}
}
function loadCardsSuccess() {
return {
type: LOAD_CARDS_SUCCESS
}
}
function loadCardsFail(payload) {
return {
type: LOAD_CARDS_FAIL,
payload
}
}
function saveCardRequest() {
return {
type: SAVE_CARD_REQUEST
}
}
function saveCardSuccess() {
return {
type: SAVE_CARD_SUCCESS
}
}
function saveCardFail(payload) {
return {
type: SAVE_CARD_FAIL,
payload
}
}
function saveCardItemRequest() {
return {
type: SAVE_CARD_ITEM_REQUEST
}
}
function saveCardItemSuccess() {
return {
type: SAVE_CARD_ITEM_SUCCESS
}
}
function saveCardItemFail(payload) {
return {
type: SAVE_CARD_ITEM_FAIL,
payload
}
}
function updateCardsRequest() {
return {
type: UPDATE_CARDS_REQUEST
}
}
function updateCardsSuccess() {
return {
type: UPDATE_CARDS_SUCCESS
}
}
function updateCardsFail(payload) {
return {
type: UPDATE_CARDS_FAIL,
payload
}
}
function moveCard(previousAndNextPositions) {
return {
type: MOVE_CARD,
...previousAndNextPositions
};
}
export function openCreateCardItemForm (payload) {
return {
type: OPEN_CREATE_CARD_ITEM_FORM,
payload
}
}
export function closeCreateCardItemForm () {
return {
type: CLOSE_CREATE_CARD_ITEM_FORM
}
}
export function focusOnCardItemForm() {
return {
type: FOCUS_CREATE_CARD_ITEM_FORM,
}
}
export function blurOnCardItemForm() {
return {
type: BLUR_CREATE_CARD_ITEM_FORM,
}
}
export function updateCards(payload) {
return {
type: UPDATE_CARDS,
payload
}
}
export function resetCards() {
return {
type: RESET_CARDS
}
}
export function moveCardItemAndUpdateCards(previousAndNextPositions, cards, pathname) {
return dispatch => {
dispatch(moveCard(previousAndNextPositions));
dispatch(updateCardsRequest());
return fetch(`${trelloUrl}api${pathname}/cards`,
{ method: 'PUT',
body: JSON.stringify({
cards
}),
headers: {
'Content-Type': 'application/json; charset=utf-8',
'csrf': localStorage.getItem('csrf')
},
credentials: 'include'
})
.then(response => {
if (response.status === 401) {
dispatch(loginActionCreators.logoutUser());
} else {
return response.json();
}
})
.then(json => {
if (json.uiError || json.error) {
dispatch(updateCardsFail(json))
} else {
dispatch(updateCardsSuccess());
}
})
}
}
export function getCards(pathname) {
return dispatch => {
dispatch(loadCardsRequest(pathname))
return fetch(`${trelloUrl}api${pathname}/cards`,
{ method: 'GET',
headers: {
'csrf': localStorage.getItem('csrf')
},
credentials: 'include'
})
.then(response => {
if (response.status === 401) {
dispatch(loginActionCreators.logoutUser());
} else {
return response.json();
}
})
.then(json => {
if (json.uiError || json.error) {
dispatch(loadCardsFail(json))
} else {
const jsonData = json.data;
dispatch(loadCardsSuccess());
dispatch(organizationActionCreators.updateOrganizations(jsonData));
dispatch(starredBoardActionCreators.updateStarredBoards(jsonData));
dispatch(boardActionCreators.updateBoards(jsonData));
dispatch(updateCards(jsonData));
}
})
}
}
export function saveCard(pathname, cardName) {
return dispatch => {
dispatch(saveCardRequest())
return fetch(`${trelloUrl}api${pathname}/cards`,
{ method: 'POST',
body: JSON.stringify({
name: cardName
}),
headers: {
'Content-Type': 'application/json; charset=utf-8',
'csrf': localStorage.getItem('csrf')
},
credentials: 'include'
})
.then(response => {
if (response.status === 401) {
dispatch(loginActionCreators.logoutUser());
} else {
return response.json();
}
})
.then(json => {
if (json.uiError || json.error) {
dispatch(saveCardFail(json))
} else {
dispatch(saveCardSuccess());
dispatch(reset('createCardForm'));
dispatch(updateCards(json.data));
}
})
}
}
export function saveCardItem(pathname, cardId, cardItemName) {
return dispatch => {
dispatch(saveCardItemRequest())
return fetch(`${trelloUrl}api${pathname}/cards/${cardId}`,
{ method: 'POST',
body: JSON.stringify({
name: cardItemName
}),
headers: {
'Content-Type': 'application/json; charset=utf-8',
'csrf': localStorage.getItem('csrf')
},
credentials: 'include'
})
.then(response => {
if (response.status !== 200) {
dispatch(loginActionCreators.logoutUser());
} else {
return response.json();
}
})
.then(json => {
if (json.uiError || json.error) {
dispatch(saveCardItemFail(json));
} else {
dispatch(closeCreateCardItemForm());
dispatch(saveCardItemSuccess());
dispatch(reset('createCardItemForm'));
dispatch(updateCards(json.data));
}
})
}
}
export default function boardView(state = initialState, action) {
switch (action.type) {
case LOAD_CARDS_REQUEST:
return Object.assign({}, state, {
isFetchingCards: true,
pathname: action.payload
});
case LOAD_CARDS_SUCCESS:
return Object.assign({}, state, {
isFetchingCardsSuccessful: true,
isFetchingCards: false
});
case LOAD_CARDS_FAIL:
return Object.assign({}, state, {
isFetchingCardsSuccessful: false,
isFetchingCards: false,
errorMessage: action.payload.error,
cards: []
});
case UPDATE_CARDS_REQUEST:
return Object.assign({}, state, {
isUpdatingCards: true
});
case UPDATE_CARDS_SUCCESS:
return Object.assign({}, state, {
isUpdatingCardsSuccessful: true,
isUpdatingCards: false
});
case UPDATE_CARDS_FAIL:
return Object.assign({}, state, {
isUpdatingCardsSuccessful: false,
isUpdatingCards: false,
errorMessage: action.payload.error
});
case SAVE_CARD_REQUEST:
return Object.assign({}, state, {
isSavingCard: true,
});
case SAVE_CARD_SUCCESS:
return Object.assign({}, state, {
isSavinCardSuccessful: true,
isSavingCard: false
});
case SAVE_CARD_FAIL:
return Object.assign({}, state, {
isSavinCardSuccessful: false,
isSavingCard: false,
errorMessage: action.payload.error,
});
case SAVE_CARD_ITEM_REQUEST:
return Object.assign({}, state, {
isSavingCardItem: true,
});
case SAVE_CARD_ITEM_SUCCESS:
return Object.assign({}, state, {
isSavinCardItemSuccessful: true,
isSavingCardItem: false
});
case SAVE_CARD_ITEM_FAIL:
return Object.assign({}, state, {
isSavinCardItemSuccessful: false,
isSavingCardItem: false,
errorMessage: action.payload.error
});
case UPDATE_CARDS:
return Object.assign({}, state, {
cards: action.payload.cards
});
case RESET_CARDS:
return Object.assign({}, state, {
cards: []
});
case OPEN_CREATE_CARD_ITEM_FORM:
return Object.assign({}, state, {
createCardFormIndexToOpen: action.payload,
isCreateCardItemFormOpen: true
});
case CLOSE_CREATE_CARD_ITEM_FORM:
return Object.assign({}, state, {
createCardFormIndexToOpen: 0,
isCreateCardItemFormOpen: false
});
case FOCUS_CREATE_CARD_ITEM_FORM:
return Object.assign({}, state, {
isFocusOnCreateCardItemForm: true
});
case BLUR_CREATE_CARD_ITEM_FORM:
return Object.assign({}, state, {
isFocusOnCreateCardItemForm: false
});
case MOVE_CARD: {
const newCards = [...state.cards];
const { lastX, lastY, nextX, nextY } = action;
if (lastX === nextX) {
newCards[lastX].cardItems.splice(nextY, 0, newCards[lastX].cardItems.splice(lastY, 1)[0]);
} else {
newCards[nextX].cardItems.splice(nextY, 0, newCards[lastX].cardItems[lastY]);
newCards[lastX].cardItems.splice(lastY, 1);
}
return Object.assign({}, state, {
cards: newCards
});
}
default: return state;
}
} |
/*
* Copyright 2003-2006, 2009, 2017, United States Government, as represented by the Administrator of the
* National Aeronautics and Space Administration. All rights reserved.
*
* The NASAWorldWind/WebWorldWind platform is 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.
*/
define([
'./KmlElements',
'./KmlAbstractView',
'./util/KmlNodeTransformers'
], function (KmlElements,
KmlAbstractView,
NodeTransformers) {
"use strict";
/**
* Constructs an KmlCamera. Applications usually don't call this constructor. It is called by {@link KmlFile} as
* objects from Kml file are read. This object is already concrete implementation.
* @alias KmlCamera
* @classdesc Contains the data associated with Camera node.
* @param options {Object}
* @param options.objectNode {Node} Node representing camera in the document.
* @constructor
* @throws {ArgumentError} If the node is null or undefined.
* @see https://developers.google.com/kml/documentation/kmlreference#camera
* @augments KmlAbstractView
*/
var KmlCamera = function (options) {
KmlAbstractView.call(this, options);
};
KmlCamera.prototype = Object.create(KmlAbstractView.prototype);
Object.defineProperties(KmlCamera.prototype, {
/**
* Longitude of the virtual camera (eye point). Angular distance in degrees, relative to the Prime Meridian.
* Values west of the Meridian range from +-180 to 0 degrees. Values east of the Meridian range from 0
* to 180 degrees.
* @memberof KmlCamera.prototype
* @readonly
* @type {String}
*/
kmlLongitude: {
get: function () {
return this._factory.specific(this, {name: 'longitude', transformer: NodeTransformers.string});
}
},
/**
* Latitude of the virtual camera. Degrees north or south of the Equator (0 degrees). Values range from -90
* degrees to 90 degrees.
* @memberof KmlCamera.prototype
* @readonly
* @type {String}
*/
kmlLatitude: {
get: function () {
return this._factory.specific(this, {name: 'latitude', transformer: NodeTransformers.string});
}
},
/**
* Distance of the camera from the earth's surface, in meters. Interpreted according to the Camera's
* <altitudeMode> or <gx:altitudeMode>.
* @memberof KmlCamera.prototype
* @readonly
* @type {String}
*/
kmlAltitude: {
get: function () {
return this._factory.specific(this, {name: 'altitude', transformer: NodeTransformers.string});
}
},
/**
* Direction (azimuth) of the camera, in degrees. Default=0 (true North). (See diagram.) Values range from
* 0 to 360 degrees.
* @memberof KmlCamera.prototype
* @readonly
* @type {String}
*/
kmlHeading: {
get: function () {
return this._factory.specific(this, {name: 'heading', transformer: NodeTransformers.string});
}
},
/**
* Rotation, in degrees, of the camera around the X axis. A value of 0 indicates that the view is aimed
* straight down toward the earth (the most common case). A value for 90 for <tilt> indicates that the
* view
* is aimed toward the horizon. Values greater than 90 indicate that the view is pointed up into the sky.
* Values for <tilt> are clamped at +180 degrees.
* @memberof KmlCamera.prototype
* @readonly
* @type {String}
*/
kmlTilt: {
get: function () {
return this._factory.specific(this, {name: 'tilt', transformer: NodeTransformers.string});
}
},
/**
* Rotation, in degrees, of the camera around the Z axis. Values range from -180 to +180 degrees.
* @memberof KmlCamera.prototype
* @readonly
* @type {String}
*/
kmlRoll: {
get: function () {
return this._factory.specific(this, {name: 'roll', transformer: NodeTransformers.string});
}
},
/**
* Specifies how the <altitude> specified for the Camera is interpreted. Possible values are as
* follows:
* relativeToGround - (default) Interprets the <altitude> as a value in meters above the ground. If the
* point is over water, the <altitude> will be interpreted as a value in meters above sea level. See
* <gx:altitudeMode> below to specify points relative to the sea floor. clampToGround - For a camera, this
* setting also places the camera relativeToGround, since putting the camera exactly at terrain height
* would
* mean that the eye would intersect the terrain (and the view would be blocked). absolute - Interprets the
* <altitude> as a value in meters above sea level.
* @memberof KmlCamera.prototype
* @readonly
* @type {String}
*/
kmlAltitudeMode: {
get: function () {
return this._factory.specific(this, {name: 'altitudeMode', transformer: NodeTransformers.string});
}
}
});
/**
* @inheritDoc
*/
KmlCamera.prototype.getTagNames = function () {
return ['Camera'];
};
KmlElements.addKey(KmlCamera.prototype.getTagNames()[0], KmlCamera);
return KmlCamera;
}); |
// All Set!
|
import sinon from 'sinon';
import childProcess from 'child_process';
import ExecQueue from '../src/exec-queue';
describe('ExecQueue', () => {
let queue;
beforeEach(() => {
sinon.stub(childProcess, 'exec', () => {});
queue = new ExecQueue({ concurrency: 3 });
});
afterEach(() => {
childProcess.exec.restore();
});
it('immediately services requests if execs are available', (done) => {
['1', '2', '3'].forEach(cmd => queue.enqueue(cmd));
process.nextTick(() => {
expect(queue.queue.length).to.equal(0);
done();
});
});
it('queues requests flooded with requests', (done) => {
['1', '2', '3', '4'].forEach(cmd => queue.enqueue(cmd));
process.nextTick(() => {
expect(queue.queue.length).to.equal(1);
done();
});
});
it('queues requests all execs are in flight', (done) => {
['1', '2', '3'].forEach(cmd => queue.enqueue(cmd));
process.nextTick(() => {
expect(queue.queue.length).to.equal(0);
queue.enqueue('4');
process.nextTick(() => {
expect(queue.queue.length).to.equal(1);
done();
});
});
});
});
|
'use strict';
import Backbone from 'backbone';
import MyModel from './MyModel.js';
/**
* Provides a basic `Backbone.Collection` using MyModel
*/
class MyCollection extends Backbone.Collection
{
/**
* Reference to this collection's model.
*
* @returns {MyModel}
*/
get model() { return MyModel; }
}
/**
* Exports an instance of MyCollection.
*/
export default new MyCollection(); |
System.register(["angular2/di", "angular2/src/facade/collection", "angular2/src/facade/lang"], function($__export) {
"use strict";
var Injectable,
List,
ListWrapper,
SetWrapper,
int,
NumberWrapper,
StringJoiner,
StringWrapper,
TOKEN_TYPE_CHARACTER,
TOKEN_TYPE_IDENTIFIER,
TOKEN_TYPE_KEYWORD,
TOKEN_TYPE_STRING,
TOKEN_TYPE_OPERATOR,
TOKEN_TYPE_NUMBER,
Lexer,
Token,
EOF,
$EOF,
$TAB,
$LF,
$VTAB,
$FF,
$CR,
$SPACE,
$BANG,
$DQ,
$HASH,
$$,
$PERCENT,
$AMPERSAND,
$SQ,
$LPAREN,
$RPAREN,
$STAR,
$PLUS,
$COMMA,
$MINUS,
$PERIOD,
$SLASH,
$COLON,
$SEMICOLON,
$LT,
$EQ,
$GT,
$QUESTION,
$0,
$9,
$A,
$B,
$C,
$D,
$E,
$F,
$G,
$H,
$I,
$J,
$K,
$L,
$M,
$N,
$O,
$P,
$Q,
$R,
$S,
$T,
$U,
$V,
$W,
$X,
$Y,
$Z,
$LBRACKET,
$BACKSLASH,
$RBRACKET,
$CARET,
$_,
$a,
$b,
$c,
$d,
$e,
$f,
$g,
$h,
$i,
$j,
$k,
$l,
$m,
$n,
$o,
$p,
$q,
$r,
$s,
$t,
$u,
$v,
$w,
$x,
$y,
$z,
$LBRACE,
$BAR,
$RBRACE,
$TILDE,
$NBSP,
ScannerError,
_Scanner,
OPERATORS,
KEYWORDS;
function newCharacterToken(index, code) {
return new Token(index, TOKEN_TYPE_CHARACTER, code, StringWrapper.fromCharCode(code));
}
function newIdentifierToken(index, text) {
return new Token(index, TOKEN_TYPE_IDENTIFIER, 0, text);
}
function newKeywordToken(index, text) {
return new Token(index, TOKEN_TYPE_KEYWORD, 0, text);
}
function newOperatorToken(index, text) {
return new Token(index, TOKEN_TYPE_OPERATOR, 0, text);
}
function newStringToken(index, text) {
return new Token(index, TOKEN_TYPE_STRING, 0, text);
}
function newNumberToken(index, n) {
return new Token(index, TOKEN_TYPE_NUMBER, n, "");
}
function isWhitespace(code) {
return (code >= $TAB && code <= $SPACE) || (code == $NBSP);
}
function isIdentifierStart(code) {
return ($a <= code && code <= $z) || ($A <= code && code <= $Z) || (code == $_) || (code == $$);
}
function isIdentifierPart(code) {
return ($a <= code && code <= $z) || ($A <= code && code <= $Z) || ($0 <= code && code <= $9) || (code == $_) || (code == $$);
}
function isDigit(code) {
return $0 <= code && code <= $9;
}
function isExponentStart(code) {
return code == $e || code == $E;
}
function isExponentSign(code) {
return code == $MINUS || code == $PLUS;
}
function unescape(code) {
switch (code) {
case $n:
return $LF;
case $f:
return $FF;
case $r:
return $CR;
case $t:
return $TAB;
case $v:
return $VTAB;
default:
return code;
}
}
return {
setters: [function($__m) {
Injectable = $__m.Injectable;
}, function($__m) {
List = $__m.List;
ListWrapper = $__m.ListWrapper;
SetWrapper = $__m.SetWrapper;
}, function($__m) {
int = $__m.int;
NumberWrapper = $__m.NumberWrapper;
StringJoiner = $__m.StringJoiner;
StringWrapper = $__m.StringWrapper;
}],
execute: function() {
TOKEN_TYPE_CHARACTER = $__export("TOKEN_TYPE_CHARACTER", 1);
TOKEN_TYPE_IDENTIFIER = $__export("TOKEN_TYPE_IDENTIFIER", 2);
TOKEN_TYPE_KEYWORD = $__export("TOKEN_TYPE_KEYWORD", 3);
TOKEN_TYPE_STRING = $__export("TOKEN_TYPE_STRING", 4);
TOKEN_TYPE_OPERATOR = $__export("TOKEN_TYPE_OPERATOR", 5);
TOKEN_TYPE_NUMBER = $__export("TOKEN_TYPE_NUMBER", 6);
Lexer = $__export("Lexer", (function() {
var Lexer = function Lexer() {};
return ($traceurRuntime.createClass)(Lexer, {tokenize: function(text) {
var scanner = new _Scanner(text);
var tokens = [];
var token = scanner.scanToken();
while (token != null) {
ListWrapper.push(tokens, token);
token = scanner.scanToken();
}
return tokens;
}}, {});
}()));
Object.defineProperty(Lexer, "annotations", {get: function() {
return [new Injectable()];
}});
Object.defineProperty(Lexer.prototype.tokenize, "parameters", {get: function() {
return [[assert.type.string]];
}});
Token = $__export("Token", (function() {
var Token = function Token(index, type, numValue, strValue) {
this.index = index;
this.type = type;
this._numValue = numValue;
this._strValue = strValue;
};
return ($traceurRuntime.createClass)(Token, {
isCharacter: function(code) {
return (this.type == TOKEN_TYPE_CHARACTER && this._numValue == code);
},
isNumber: function() {
return (this.type == TOKEN_TYPE_NUMBER);
},
isString: function() {
return (this.type == TOKEN_TYPE_STRING);
},
isOperator: function(operater) {
return (this.type == TOKEN_TYPE_OPERATOR && this._strValue == operater);
},
isIdentifier: function() {
return (this.type == TOKEN_TYPE_IDENTIFIER);
},
isKeyword: function() {
return (this.type == TOKEN_TYPE_KEYWORD);
},
isKeywordVar: function() {
return (this.type == TOKEN_TYPE_KEYWORD && this._strValue == "var");
},
isKeywordNull: function() {
return (this.type == TOKEN_TYPE_KEYWORD && this._strValue == "null");
},
isKeywordUndefined: function() {
return (this.type == TOKEN_TYPE_KEYWORD && this._strValue == "undefined");
},
isKeywordTrue: function() {
return (this.type == TOKEN_TYPE_KEYWORD && this._strValue == "true");
},
isKeywordFalse: function() {
return (this.type == TOKEN_TYPE_KEYWORD && this._strValue == "false");
},
toNumber: function() {
return (this.type == TOKEN_TYPE_NUMBER) ? this._numValue : -1;
},
toString: function() {
var type = this.type;
if (type >= TOKEN_TYPE_CHARACTER && type <= TOKEN_TYPE_STRING) {
return this._strValue;
} else if (type == TOKEN_TYPE_NUMBER) {
return this._numValue.toString();
} else {
return null;
}
}
}, {});
}()));
Object.defineProperty(Token, "parameters", {get: function() {
return [[int], [int], [assert.type.number], [assert.type.string]];
}});
Object.defineProperty(Token.prototype.isCharacter, "parameters", {get: function() {
return [[int]];
}});
Object.defineProperty(Token.prototype.isOperator, "parameters", {get: function() {
return [[assert.type.string]];
}});
Object.defineProperty(newCharacterToken, "parameters", {get: function() {
return [[int], [int]];
}});
Object.defineProperty(newIdentifierToken, "parameters", {get: function() {
return [[int], [assert.type.string]];
}});
Object.defineProperty(newKeywordToken, "parameters", {get: function() {
return [[int], [assert.type.string]];
}});
Object.defineProperty(newOperatorToken, "parameters", {get: function() {
return [[int], [assert.type.string]];
}});
Object.defineProperty(newStringToken, "parameters", {get: function() {
return [[int], [assert.type.string]];
}});
Object.defineProperty(newNumberToken, "parameters", {get: function() {
return [[int], [assert.type.number]];
}});
EOF = $__export("EOF", new Token(-1, 0, 0, ""));
$EOF = $__export("$EOF", 0);
$TAB = $__export("$TAB", 9);
$LF = $__export("$LF", 10);
$VTAB = $__export("$VTAB", 11);
$FF = $__export("$FF", 12);
$CR = $__export("$CR", 13);
$SPACE = $__export("$SPACE", 32);
$BANG = $__export("$BANG", 33);
$DQ = $__export("$DQ", 34);
$HASH = $__export("$HASH", 35);
$$ = $__export("$$", 36);
$PERCENT = $__export("$PERCENT", 37);
$AMPERSAND = $__export("$AMPERSAND", 38);
$SQ = $__export("$SQ", 39);
$LPAREN = $__export("$LPAREN", 40);
$RPAREN = $__export("$RPAREN", 41);
$STAR = $__export("$STAR", 42);
$PLUS = $__export("$PLUS", 43);
$COMMA = $__export("$COMMA", 44);
$MINUS = $__export("$MINUS", 45);
$PERIOD = $__export("$PERIOD", 46);
$SLASH = $__export("$SLASH", 47);
$COLON = $__export("$COLON", 58);
$SEMICOLON = $__export("$SEMICOLON", 59);
$LT = $__export("$LT", 60);
$EQ = $__export("$EQ", 61);
$GT = $__export("$GT", 62);
$QUESTION = $__export("$QUESTION", 63);
$0 = 48;
$9 = 57;
$A = 65, $B = 66, $C = 67, $D = 68, $E = 69, $F = 70, $G = 71, $H = 72, $I = 73, $J = 74, $K = 75, $L = 76, $M = 77, $N = 78, $O = 79, $P = 80, $Q = 81, $R = 82, $S = 83, $T = 84, $U = 85, $V = 86, $W = 87, $X = 88, $Y = 89, $Z = 90;
$LBRACKET = $__export("$LBRACKET", 91);
$BACKSLASH = $__export("$BACKSLASH", 92);
$RBRACKET = $__export("$RBRACKET", 93);
$CARET = 94;
$_ = 95;
$a = 97, $b = 98, $c = 99, $d = 100, $e = 101, $f = 102, $g = 103, $h = 104, $i = 105, $j = 106, $k = 107, $l = 108, $m = 109, $n = 110, $o = 111, $p = 112, $q = 113, $r = 114, $s = 115, $t = 116, $u = 117, $v = 118, $w = 119, $x = 120, $y = 121, $z = 122;
$LBRACE = $__export("$LBRACE", 123);
$BAR = $__export("$BAR", 124);
$RBRACE = $__export("$RBRACE", 125);
$TILDE = 126;
$NBSP = 160;
ScannerError = $__export("ScannerError", (function($__super) {
var ScannerError = function ScannerError(message) {
$traceurRuntime.superConstructor(ScannerError).call(this);
this.message = message;
};
return ($traceurRuntime.createClass)(ScannerError, {toString: function() {
return this.message;
}}, {}, $__super);
}(Error)));
_Scanner = (function() {
var _Scanner = function _Scanner(input) {
this.input = input;
this.length = input.length;
this.peek = 0;
this.index = -1;
this.advance();
};
return ($traceurRuntime.createClass)(_Scanner, {
advance: function() {
this.peek = ++this.index >= this.length ? $EOF : StringWrapper.charCodeAt(this.input, this.index);
},
scanToken: function() {
var input = this.input,
length = this.length,
peek = this.peek,
index = this.index;
while (peek <= $SPACE) {
if (++index >= length) {
peek = $EOF;
break;
} else {
peek = StringWrapper.charCodeAt(input, index);
}
}
this.peek = peek;
this.index = index;
if (index >= length) {
return null;
}
if (isIdentifierStart(peek))
return this.scanIdentifier();
if (isDigit(peek))
return this.scanNumber(index);
var start = index;
switch (peek) {
case $PERIOD:
this.advance();
return isDigit(this.peek) ? this.scanNumber(start) : newCharacterToken(start, $PERIOD);
case $LPAREN:
case $RPAREN:
case $LBRACE:
case $RBRACE:
case $LBRACKET:
case $RBRACKET:
case $COMMA:
case $COLON:
case $SEMICOLON:
return this.scanCharacter(start, peek);
case $SQ:
case $DQ:
return this.scanString();
case $HASH:
return this.scanOperator(start, StringWrapper.fromCharCode(peek));
case $PLUS:
case $MINUS:
case $STAR:
case $SLASH:
case $PERCENT:
case $CARET:
case $QUESTION:
return this.scanOperator(start, StringWrapper.fromCharCode(peek));
case $LT:
case $GT:
case $BANG:
case $EQ:
return this.scanComplexOperator(start, $EQ, StringWrapper.fromCharCode(peek), '=');
case $AMPERSAND:
return this.scanComplexOperator(start, $AMPERSAND, '&', '&');
case $BAR:
return this.scanComplexOperator(start, $BAR, '|', '|');
case $TILDE:
return this.scanComplexOperator(start, $SLASH, '~', '/');
case $NBSP:
while (isWhitespace(this.peek))
this.advance();
return this.scanToken();
}
this.error(("Unexpected character [" + StringWrapper.fromCharCode(peek) + "]"), 0);
return null;
},
scanCharacter: function(start, code) {
assert(this.peek == code);
this.advance();
return newCharacterToken(start, code);
},
scanOperator: function(start, str) {
assert(this.peek == StringWrapper.charCodeAt(str, 0));
assert(SetWrapper.has(OPERATORS, str));
this.advance();
return newOperatorToken(start, str);
},
scanComplexOperator: function(start, code, one, two) {
assert(this.peek == StringWrapper.charCodeAt(one, 0));
this.advance();
var str = one;
if (this.peek == code) {
this.advance();
str += two;
}
assert(SetWrapper.has(OPERATORS, str));
return newOperatorToken(start, str);
},
scanIdentifier: function() {
assert(isIdentifierStart(this.peek));
var start = this.index;
this.advance();
while (isIdentifierPart(this.peek))
this.advance();
var str = this.input.substring(start, this.index);
if (SetWrapper.has(KEYWORDS, str)) {
return newKeywordToken(start, str);
} else {
return newIdentifierToken(start, str);
}
},
scanNumber: function(start) {
assert(isDigit(this.peek));
var simple = (this.index === start);
this.advance();
while (true) {
if (isDigit(this.peek)) {} else if (this.peek == $PERIOD) {
simple = false;
} else if (isExponentStart(this.peek)) {
this.advance();
if (isExponentSign(this.peek))
this.advance();
if (!isDigit(this.peek))
this.error('Invalid exponent', -1);
simple = false;
} else {
break;
}
this.advance();
}
var str = this.input.substring(start, this.index);
var value = simple ? NumberWrapper.parseIntAutoRadix(str) : NumberWrapper.parseFloat(str);
return newNumberToken(start, value);
},
scanString: function() {
assert(this.peek == $SQ || this.peek == $DQ);
var start = this.index;
var quote = this.peek;
this.advance();
var buffer;
var marker = this.index;
var input = this.input;
while (this.peek != quote) {
if (this.peek == $BACKSLASH) {
if (buffer == null)
buffer = new StringJoiner();
buffer.add(input.substring(marker, this.index));
this.advance();
var unescapedCode = void 0;
if (this.peek == $u) {
var hex = input.substring(this.index + 1, this.index + 5);
try {
unescapedCode = NumberWrapper.parseInt(hex, 16);
} catch (e) {
this.error(("Invalid unicode escape [\\u" + hex + "]"), 0);
}
for (var i = 0; i < 5; i++) {
this.advance();
}
} else {
unescapedCode = unescape(this.peek);
this.advance();
}
buffer.add(StringWrapper.fromCharCode(unescapedCode));
marker = this.index;
} else if (this.peek == $EOF) {
this.error('Unterminated quote', 0);
} else {
this.advance();
}
}
var last = input.substring(marker, this.index);
this.advance();
var unescaped = last;
if (buffer != null) {
buffer.add(last);
unescaped = buffer.toString();
}
return newStringToken(start, unescaped);
},
error: function(message, offset) {
var position = this.index + offset;
throw new ScannerError(("Lexer Error: " + message + " at column " + position + " in expression [" + this.input + "]"));
}
}, {});
}());
Object.defineProperty(_Scanner, "parameters", {get: function() {
return [[assert.type.string]];
}});
Object.defineProperty(_Scanner.prototype.scanCharacter, "parameters", {get: function() {
return [[int], [int]];
}});
Object.defineProperty(_Scanner.prototype.scanOperator, "parameters", {get: function() {
return [[int], [assert.type.string]];
}});
Object.defineProperty(_Scanner.prototype.scanComplexOperator, "parameters", {get: function() {
return [[int], [int], [assert.type.string], [assert.type.string]];
}});
Object.defineProperty(_Scanner.prototype.scanNumber, "parameters", {get: function() {
return [[int]];
}});
Object.defineProperty(_Scanner.prototype.error, "parameters", {get: function() {
return [[assert.type.string], [int]];
}});
Object.defineProperty(isWhitespace, "parameters", {get: function() {
return [[int]];
}});
Object.defineProperty(isIdentifierStart, "parameters", {get: function() {
return [[int]];
}});
Object.defineProperty(isIdentifierPart, "parameters", {get: function() {
return [[int]];
}});
Object.defineProperty(isDigit, "parameters", {get: function() {
return [[int]];
}});
Object.defineProperty(isExponentStart, "parameters", {get: function() {
return [[int]];
}});
Object.defineProperty(isExponentSign, "parameters", {get: function() {
return [[int]];
}});
Object.defineProperty(unescape, "parameters", {get: function() {
return [[int]];
}});
OPERATORS = SetWrapper.createFromList(['+', '-', '*', '/', '~/', '%', '^', '=', '==', '!=', '<', '>', '<=', '>=', '&&', '||', '&', '|', '!', '?', '#']);
KEYWORDS = SetWrapper.createFromList(['var', 'null', 'undefined', 'true', 'false']);
}
};
});
//# sourceMappingURL=src/change_detection/parser/lexer.map
//# sourceMappingURL=../../../src/change_detection/parser/lexer.js.map |
// Generated by CoffeeScript 1.6.3
(function() {
var Parser, alt, alternatives, grammar, name, o, operators, token, tokens, unwrap;
Parser = require('jison').Parser;
unwrap = /^function\s*\(\)\s*\{\s*return\s*([\s\S]*);\s*\}/;
o = function(patternString, action, options) {
var addLocationDataFn, match, patternCount;
patternString = patternString.replace(/\s{2,}/g, ' ');
patternCount = patternString.split(' ').length;
if (!action) {
return [patternString, '$$ = $1;', options];
}
action = (match = unwrap.exec(action)) ? match[1] : "(" + action + "())";
action = action.replace(/\bnew /g, '$&yy.');
action = action.replace(/\b(?:Block\.wrap|extend)\b/g, 'yy.$&');
addLocationDataFn = function(first, last) {
if (!last) {
return "yy.addLocationDataFn(@" + first + ")";
} else {
return "yy.addLocationDataFn(@" + first + ", @" + last + ")";
}
};
action = action.replace(/LOC\(([0-9]*)\)/g, addLocationDataFn('$1'));
action = action.replace(/LOC\(([0-9]*),\s*([0-9]*)\)/g, addLocationDataFn('$1', '$2'));
return [patternString, "$$ = " + (addLocationDataFn(1, patternCount)) + "(" + action + ");", options];
};
grammar = {
Root: [
o('', function() {
return new Block;
}), o('Body')
],
Body: [
o('Line', function() {
return Block.wrap([$1]);
}), o('Body TERMINATOR Line', function() {
return $1.push($3);
}), o('Body TERMINATOR')
],
Line: [o('Expression'), o('Statement')],
Statement: [
o('Return'), o('Comment'), o('STATEMENT', function() {
return new Literal($1);
})
],
Expression: [o('Value'), o('Invocation'), o('Code'), o('Operation'), o('Assign'), o('If'), o('Try'), o('While'), o('For'), o('Switch'), o('Class'), o('Throw')],
Block: [
o('INDENT OUTDENT', function() {
return new Block;
}), o('INDENT Body OUTDENT', function() {
return $2;
})
],
Identifier: [
o('IDENTIFIER', function() {
return new Literal($1);
})
],
AlphaNumeric: [
o('NUMBER', function() {
return new Literal($1);
}), o('STRING', function() {
return new Literal($1);
})
],
Literal: [
o('AlphaNumeric'), o('JS', function() {
return new Literal($1);
}), o('REGEX', function() {
return new Literal($1);
}), o('DEBUGGER', function() {
return new Literal($1);
}), o('UNDEFINED', function() {
return new Undefined;
}), o('NULL', function() {
return new Null;
}), o('BOOL', function() {
return new Bool($1);
})
],
Assign: [
o('Assignable = Expression', function() {
return new Assign($1, $3);
}), o('Assignable = TERMINATOR Expression', function() {
return new Assign($1, $4);
}), o('Assignable = INDENT Expression OUTDENT', function() {
return new Assign($1, $4);
})
],
AssignObj: [
o('ObjAssignable', function() {
return new Value($1);
}), o('ObjAssignable : Expression', function() {
return new Assign(LOC(1)(new Value($1)), $3, 'object');
}), o('ObjAssignable :\
INDENT Expression OUTDENT', function() {
return new Assign(LOC(1)(new Value($1)), $4, 'object');
}), o('Comment')
],
ObjAssignable: [o('Identifier'), o('AlphaNumeric'), o('ThisProperty')],
Return: [
o('RETURN Expression', function() {
return new Return($2);
}), o('RETURN', function() {
return new Return;
})
],
Comment: [
o('HERECOMMENT', function() {
return new Comment($1);
})
],
Code: [
o('PARAM_START ParamList PARAM_END FuncGlyph Block', function() {
return new Code($2, $5, $4);
}), o('FuncGlyph Block', function() {
return new Code([], $2, $1);
})
],
FuncGlyph: [
o('->', function() {
return 'func';
}), o('=>', function() {
return 'boundfunc';
})
],
OptComma: [o(''), o(',')],
ParamList: [
o('', function() {
return [];
}), o('Param', function() {
return [$1];
}), o('ParamList , Param', function() {
return $1.concat($3);
}), o('ParamList OptComma TERMINATOR Param', function() {
return $1.concat($4);
}), o('ParamList OptComma INDENT ParamList OptComma OUTDENT', function() {
return $1.concat($4);
})
],
Param: [
o('ParamVar', function() {
return new Param($1);
}), o('ParamVar ...', function() {
return new Param($1, null, true);
}), o('ParamVar = Expression', function() {
return new Param($1, $3);
})
],
ParamVar: [o('Identifier'), o('ThisProperty'), o('Array'), o('Object')],
Splat: [
o('Expression ...', function() {
return new Splat($1);
})
],
SimpleAssignable: [
o('Identifier', function() {
return new Value($1);
}), o('Value Accessor', function() {
return $1.add($2);
}), o('Invocation Accessor', function() {
return new Value($1, [].concat($2));
}), o('ThisProperty')
],
Assignable: [
o('SimpleAssignable'), o('Array', function() {
return new Value($1);
}), o('Object', function() {
return new Value($1);
})
],
Value: [
o('Assignable'), o('Literal', function() {
return new Value($1);
}), o('Parenthetical', function() {
return new Value($1);
}), o('Range', function() {
return new Value($1);
}), o('This')
],
Accessor: [
o('. Identifier', function() {
return new Access($2);
}), o('?. Identifier', function() {
return new Access($2, 'soak');
}), o(':: Identifier', function() {
return [LOC(1)(new Access(new Literal('prototype'))), LOC(2)(new Access($2))];
}), o('?:: Identifier', function() {
return [LOC(1)(new Access(new Literal('prototype'), 'soak')), LOC(2)(new Access($2))];
}), o('::', function() {
return new Access(new Literal('prototype'));
}), o('Index')
],
Index: [
o('INDEX_START IndexValue INDEX_END', function() {
return $2;
}), o('INDEX_SOAK Index', function() {
return extend($2, {
soak: true
});
})
],
IndexValue: [
o('Expression', function() {
return new Index($1);
}), o('Slice', function() {
return new Slice($1);
})
],
Object: [
o('{ AssignList OptComma }', function() {
return new Obj($2, $1.generated);
})
],
AssignList: [
o('', function() {
return [];
}), o('AssignObj', function() {
return [$1];
}), o('AssignList , AssignObj', function() {
return $1.concat($3);
}), o('AssignList OptComma TERMINATOR AssignObj', function() {
return $1.concat($4);
}), o('AssignList OptComma INDENT AssignList OptComma OUTDENT', function() {
return $1.concat($4);
})
],
Class: [
o('CLASS', function() {
return new Class;
}), o('CLASS Block', function() {
return new Class(null, null, $2);
}), o('CLASS EXTENDS Expression', function() {
return new Class(null, $3);
}), o('CLASS EXTENDS Expression Block', function() {
return new Class(null, $3, $4);
}), o('CLASS SimpleAssignable', function() {
return new Class($2);
}), o('CLASS SimpleAssignable Block', function() {
return new Class($2, null, $3);
}), o('CLASS SimpleAssignable EXTENDS Expression', function() {
return new Class($2, $4);
}), o('CLASS SimpleAssignable EXTENDS Expression Block', function() {
return new Class($2, $4, $5);
})
],
Invocation: [
o('Value OptFuncExist Arguments', function() {
return new Call($1, $3, $2);
}), o('Invocation OptFuncExist Arguments', function() {
return new Call($1, $3, $2);
}), o('SUPER', function() {
return new Call('super', [new Splat(new Literal('arguments'))]);
}), o('SUPER Arguments', function() {
return new Call('super', $2);
})
],
OptFuncExist: [
o('', function() {
return false;
}), o('FUNC_EXIST', function() {
return true;
})
],
Arguments: [
o('CALL_START CALL_END', function() {
return [];
}), o('CALL_START ArgList OptComma CALL_END', function() {
return $2;
})
],
This: [
o('THIS', function() {
return new Value(new Literal('this'));
}), o('@', function() {
return new Value(new Literal('this'));
})
],
ThisProperty: [
o('@ Identifier', function() {
return new Value(LOC(1)(new Literal('this')), [LOC(2)(new Access($2))], 'this');
})
],
Array: [
o('[ ]', function() {
return new Arr([]);
}), o('[ ArgList OptComma ]', function() {
return new Arr($2);
})
],
RangeDots: [
o('..', function() {
return 'inclusive';
}), o('...', function() {
return 'exclusive';
})
],
Range: [
o('[ Expression RangeDots Expression ]', function() {
return new Range($2, $4, $3);
})
],
Slice: [
o('Expression RangeDots Expression', function() {
return new Range($1, $3, $2);
}), o('Expression RangeDots', function() {
return new Range($1, null, $2);
}), o('RangeDots Expression', function() {
return new Range(null, $2, $1);
}), o('RangeDots', function() {
return new Range(null, null, $1);
})
],
ArgList: [
o('Arg', function() {
return [$1];
}), o('ArgList , Arg', function() {
return $1.concat($3);
}), o('ArgList OptComma TERMINATOR Arg', function() {
return $1.concat($4);
}), o('INDENT ArgList OptComma OUTDENT', function() {
return $2;
}), o('ArgList OptComma INDENT ArgList OptComma OUTDENT', function() {
return $1.concat($4);
})
],
Arg: [o('Expression'), o('Splat')],
SimpleArgs: [
o('Expression'), o('SimpleArgs , Expression', function() {
return [].concat($1, $3);
})
],
Try: [
o('TRY Block', function() {
return new Try($2);
}), o('TRY Block Catch', function() {
return new Try($2, $3[0], $3[1]);
}), o('TRY Block FINALLY Block', function() {
return new Try($2, null, null, $4);
}), o('TRY Block Catch FINALLY Block', function() {
return new Try($2, $3[0], $3[1], $5);
})
],
Catch: [
o('CATCH Identifier Block', function() {
return [$2, $3];
}), o('CATCH Object Block', function() {
return [LOC(2)(new Value($2)), $3];
}), o('CATCH Block', function() {
return [null, $2];
})
],
Throw: [
o('THROW Expression', function() {
return new Throw($2);
})
],
Parenthetical: [
o('( Body )', function() {
return new Parens($2);
}), o('( INDENT Body OUTDENT )', function() {
return new Parens($3);
})
],
WhileSource: [
o('WHILE Expression', function() {
return new While($2);
}), o('WHILE Expression WHEN Expression', function() {
return new While($2, {
guard: $4
});
}), o('UNTIL Expression', function() {
return new While($2, {
invert: true
});
}), o('UNTIL Expression WHEN Expression', function() {
return new While($2, {
invert: true,
guard: $4
});
})
],
While: [
o('WhileSource Block', function() {
return $1.addBody($2);
}), o('Statement WhileSource', function() {
return $2.addBody(LOC(1)(Block.wrap([$1])));
}), o('Expression WhileSource', function() {
return $2.addBody(LOC(1)(Block.wrap([$1])));
}), o('Loop', function() {
return $1;
})
],
Loop: [
o('LOOP Block', function() {
return new While(LOC(1)(new Literal('true'))).addBody($2);
}), o('LOOP Expression', function() {
return new While(LOC(1)(new Literal('true'))).addBody(LOC(2)(Block.wrap([$2])));
})
],
For: [
o('Statement ForBody', function() {
return new For($1, $2);
}), o('Expression ForBody', function() {
return new For($1, $2);
}), o('ForBody Block', function() {
return new For($2, $1);
})
],
ForBody: [
o('FOR Range', function() {
return {
source: LOC(2)(new Value($2))
};
}), o('ForStart ForSource', function() {
$2.own = $1.own;
$2.name = $1[0];
$2.index = $1[1];
return $2;
})
],
ForStart: [
o('FOR ForVariables', function() {
return $2;
}), o('FOR OWN ForVariables', function() {
$3.own = true;
return $3;
})
],
ForValue: [
o('Identifier'), o('ThisProperty'), o('Array', function() {
return new Value($1);
}), o('Object', function() {
return new Value($1);
})
],
ForVariables: [
o('ForValue', function() {
return [$1];
}), o('ForValue , ForValue', function() {
return [$1, $3];
})
],
ForSource: [
o('FORIN Expression', function() {
return {
source: $2
};
}), o('FOROF Expression', function() {
return {
source: $2,
object: true
};
}), o('FORIN Expression WHEN Expression', function() {
return {
source: $2,
guard: $4
};
}), o('FOROF Expression WHEN Expression', function() {
return {
source: $2,
guard: $4,
object: true
};
}), o('FORIN Expression BY Expression', function() {
return {
source: $2,
step: $4
};
}), o('FORIN Expression WHEN Expression BY Expression', function() {
return {
source: $2,
guard: $4,
step: $6
};
}), o('FORIN Expression BY Expression WHEN Expression', function() {
return {
source: $2,
step: $4,
guard: $6
};
})
],
Switch: [
o('SWITCH Expression INDENT Whens OUTDENT', function() {
return new Switch($2, $4);
}), o('SWITCH Expression INDENT Whens ELSE Block OUTDENT', function() {
return new Switch($2, $4, $6);
}), o('SWITCH INDENT Whens OUTDENT', function() {
return new Switch(null, $3);
}), o('SWITCH INDENT Whens ELSE Block OUTDENT', function() {
return new Switch(null, $3, $5);
})
],
Whens: [
o('When'), o('Whens When', function() {
return $1.concat($2);
})
],
When: [
o('LEADING_WHEN SimpleArgs Block', function() {
return [[$2, $3]];
}), o('LEADING_WHEN SimpleArgs Block TERMINATOR', function() {
return [[$2, $3]];
})
],
IfBlock: [
o('IF Expression Block', function() {
return new If($2, $3, {
type: $1
});
}), o('IfBlock ELSE IF Expression Block', function() {
return $1.addElse(LOC(3, 5)(new If($4, $5, {
type: $3
})));
})
],
If: [
o('IfBlock'), o('IfBlock ELSE Block', function() {
return $1.addElse($3);
}), o('Statement POST_IF Expression', function() {
return new If($3, LOC(1)(Block.wrap([$1])), {
type: $2,
statement: true
});
}), o('Expression POST_IF Expression', function() {
return new If($3, LOC(1)(Block.wrap([$1])), {
type: $2,
statement: true
});
})
],
Operation: [
o('UNARY Expression', function() {
return new Op($1, $2);
}), o('- Expression', (function() {
return new Op('-', $2);
}), {
prec: 'UNARY'
}), o('+ Expression', (function() {
return new Op('+', $2);
}), {
prec: 'UNARY'
}), o('-- SimpleAssignable', function() {
return new Op('--', $2);
}), o('++ SimpleAssignable', function() {
return new Op('++', $2);
}), o('SimpleAssignable --', function() {
return new Op('--', $1, null, true);
}), o('SimpleAssignable ++', function() {
return new Op('++', $1, null, true);
}), o('Expression ?', function() {
return new Existence($1);
}), o('Expression + Expression', function() {
return new Op('+', $1, $3);
}), o('Expression - Expression', function() {
return new Op('-', $1, $3);
}), o('Expression MATH Expression', function() {
return new Op($2, $1, $3);
}), o('Expression SHIFT Expression', function() {
return new Op($2, $1, $3);
}), o('Expression COMPARE Expression', function() {
return new Op($2, $1, $3);
}), o('Expression LOGIC Expression', function() {
return new Op($2, $1, $3);
}), o('Expression RELATION Expression', function() {
if ($2.charAt(0) === '!') {
return new Op($2.slice(1), $1, $3).invert();
} else {
return new Op($2, $1, $3);
}
}), o('SimpleAssignable COMPOUND_ASSIGN\
Expression', function() {
return new Assign($1, $3, $2);
}), o('SimpleAssignable COMPOUND_ASSIGN\
INDENT Expression OUTDENT', function() {
return new Assign($1, $4, $2);
}), o('SimpleAssignable COMPOUND_ASSIGN TERMINATOR\
Expression', function() {
return new Assign($1, $4, $2);
}), o('SimpleAssignable EXTENDS Expression', function() {
return new Extends($1, $3);
})
]
};
operators = [['left', '.', '?.', '::', '?::'], ['left', 'CALL_START', 'CALL_END'], ['nonassoc', '++', '--'], ['left', '?'], ['right', 'UNARY'], ['left', 'MATH'], ['left', '+', '-'], ['left', 'SHIFT'], ['left', 'RELATION'], ['left', 'COMPARE'], ['left', 'LOGIC'], ['nonassoc', 'INDENT', 'OUTDENT'], ['right', '=', ':', 'COMPOUND_ASSIGN', 'RETURN', 'THROW', 'EXTENDS'], ['right', 'FORIN', 'FOROF', 'BY', 'WHEN'], ['right', 'IF', 'ELSE', 'FOR', 'WHILE', 'UNTIL', 'LOOP', 'SUPER', 'CLASS'], ['right', 'POST_IF']];
tokens = [];
for (name in grammar) {
alternatives = grammar[name];
grammar[name] = (function() {
var _i, _j, _len, _len1, _ref, _results;
_results = [];
for (_i = 0, _len = alternatives.length; _i < _len; _i++) {
alt = alternatives[_i];
_ref = alt[0].split(' ');
for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
token = _ref[_j];
if (!grammar[token]) {
tokens.push(token);
}
}
if (name === 'Root') {
alt[1] = "return " + alt[1];
}
_results.push(alt);
}
return _results;
})();
}
exports.parser = new Parser({
tokens: tokens.join(' '),
bnf: grammar,
operators: operators.reverse(),
startSymbol: 'Root'
});
}).call(this);
|
/**
* @license
* Copyright 2016 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var ts = require("typescript");
var Lint = require("../index");
var OPTION_IGNORE_FOR_LOOP = "ignore-for-loop";
var Rule = (function (_super) {
__extends(Rule, _super);
function Rule() {
_super.apply(this, arguments);
}
Rule.prototype.apply = function (sourceFile) {
var oneVarWalker = new OneVariablePerDeclarationWalker(sourceFile, this.getOptions());
return this.applyWithWalker(oneVarWalker);
};
/* tslint:disable:object-literal-sort-keys */
Rule.metadata = {
ruleName: "one-variable-per-declaration",
description: "Disallows multiple variable definitions in the same declaration statement.",
optionsDescription: (_a = ["\n One argument may be optionally provided:\n\n * `", "` allows multiple variable definitions in a for loop declaration."], _a.raw = ["\n One argument may be optionally provided:\n\n * \\`", "\\` allows multiple variable definitions in a for loop declaration."], Lint.Utils.dedent(_a, OPTION_IGNORE_FOR_LOOP)),
options: {
type: "array",
items: {
type: "string",
enum: [OPTION_IGNORE_FOR_LOOP],
},
minLength: 0,
maxLength: 1,
},
optionExamples: ["true", ("[true, \"" + OPTION_IGNORE_FOR_LOOP + "\"]")],
type: "style",
typescriptOnly: false,
};
/* tslint:enable:object-literal-sort-keys */
Rule.FAILURE_STRING = "Multiple variable declarations in the same statement are forbidden";
return Rule;
var _a;
}(Lint.Rules.AbstractRule));
exports.Rule = Rule;
var OneVariablePerDeclarationWalker = (function (_super) {
__extends(OneVariablePerDeclarationWalker, _super);
function OneVariablePerDeclarationWalker() {
_super.apply(this, arguments);
}
OneVariablePerDeclarationWalker.prototype.visitVariableStatement = function (node) {
var declarationList = node.declarationList;
if (declarationList.declarations.length > 1) {
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING));
}
_super.prototype.visitVariableStatement.call(this, node);
};
OneVariablePerDeclarationWalker.prototype.visitForStatement = function (node) {
var initializer = node.initializer;
var shouldIgnoreForLoop = this.hasOption(OPTION_IGNORE_FOR_LOOP);
if (!shouldIgnoreForLoop
&& initializer != null
&& initializer.kind === ts.SyntaxKind.VariableDeclarationList
&& initializer.declarations.length > 1) {
this.addFailure(this.createFailure(initializer.getStart(), initializer.getWidth(), Rule.FAILURE_STRING));
}
_super.prototype.visitForStatement.call(this, node);
};
return OneVariablePerDeclarationWalker;
}(Lint.RuleWalker));
|
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
const path = require('path');
const fs = require('graceful-fs');
/**
* How many bytes we should look at for the Flow pragma.
*/
const PRAGMA_BYTES = 5000;
/**
* Finds all of the Flow files in the provided directory as efficiently as
* possible.
*/
// If we use promises then Node.js will quickly run out of memory on
// large codebases. Instead we use the callback API.
module.exports = function findFlowFiles(
rootDirectory: string,
options: {+all: boolean},
): Promise<Array<string>> {
return new Promise((_resolve, _reject) => {
// Tracks whether or not we have rejected our promise.
let rejected = false;
// How many asynchronous tasks are waiting at the moment.
let waiting = 0;
// All the valid file paths that we have found.
const filePaths = [];
// Begin the recursion!
processDirectory(rootDirectory);
/**
* Process a directory by looking at all of its entries and recursing
* through child directories as is appropriate.
*/
function processDirectory(directory: string) {
// If we were rejected then we should not continue.
if (rejected === true) {
return;
}
// We are now waiting on this asynchronous task.
waiting++;
// Read the directory...
fs.readdir(directory, (error, fileNames) => {
if (error) {
return reject(error);
}
// Process every file name that we got from reading the directory.
for (let i = 0; i < fileNames.length; i++) {
processFilePath(directory, fileNames[i]);
}
// We are done with this async task.
done();
});
}
/**
* Process a directory file path by seeing if it is a directory and either
* recursing or adding it to filePaths.
*/
function processFilePath(directory: string, fileName: string) {
// If we were rejected then we should not continue.
if (rejected === true) {
return;
}
// We are now waiting on this asynchronous task.
waiting++;
// Get the file file path for this file.
const filePath = path.join(directory, fileName);
// Get the stats for the file.
fs.lstat(filePath, (error, stats) => {
if (error) {
return reject(error);
}
// If this is a directory...
if (stats.isDirectory()) {
// ...and it is not an ignored directory...
if (
fileName !== 'node_modules' &&
fileName !== 'flow-typed' &&
fileName !== '__flowtests__'
) {
// ...then recursively process the directory.
processDirectory(filePath);
}
} else if (stats.isFile()) {
// Otherwise if this is a JavaScript/JSX file and it is not an ignored
// JavaScript file...
const fileIsJsOrJsx = /\.jsx?$/.test(fileName);
const fileIsIgnored = fileName.endsWith('-flowtest.js');
if (fileIsJsOrJsx && !fileIsIgnored) {
// Then process the file path as JavaScript.
processJavaScriptFilePath(filePath, stats.size);
}
// If this is a Flow file then we don't need to check the file pragma
// and can add the file to our paths immediately.
if (fileName.endsWith('.flow')) {
filePaths.push(filePath);
}
}
// We are done with this async task
done();
});
}
/**
* Check if a file path really is a Flow file by looking for the @flow
* header pragma.
*/
function processJavaScriptFilePath(filePath: string, fileByteSize: number) {
// If `all` was configured then we don't need to check for the Flow
// header pragma.
if (options.all) {
filePaths.push(filePath);
return;
}
// If we were rejected then we should not continue.
if (rejected === true) {
return;
}
// We are now waiting on this asynchronous task.
waiting++;
// Open the file path.
fs.open(filePath, 'r', (error, file) => {
if (error) {
return reject(error);
}
// Get the smaller of our pragma chars constant and the file byte size.
const bytes = Math.min(PRAGMA_BYTES, fileByteSize);
// Create the buffer we will read to.
const buffer = new Buffer(bytes);
// Read a set number of bytes from the file.
fs.read(file, buffer, 0, bytes, 0, error => {
if (error) {
return reject(error);
}
// If the buffer has the @flow pragma then add the file path to our
// final file paths array.
if (buffer.includes('@flow')) {
filePaths.push(filePath);
}
// Close the file.
fs.close(file, error => {
if (error) {
return reject(error);
}
// We are done with this async task
done();
});
});
});
}
/**
* Our implementation of resolve that will only actually resolve if we are
* done waiting everywhere.
*/
function done() {
// We don't care if we were rejected.
if (rejected === true) {
return;
}
// Decrement the number of async tasks we are waiting on.
waiting--;
// If we are finished waiting then we want to resolve our promise.
if (waiting <= 0) {
if (waiting === 0) {
_resolve(filePaths);
} else {
reject(new Error(`Expected a positive number: ${waiting}`));
}
}
}
/**
* Our implementation of reject that also sets `rejected` to false.
*/
function reject(error) {
rejected = true;
_reject(error);
}
});
};
|
/* eslint no-undef: 0 */
describe('add to compare', () => {
it('Two products should be added to comparison table', () => {
cy.visit('/c/jackets-23');
cy.get('[data-testid="productLink"]').eq(1).as('firstProduct')
cy.get('@firstProduct').click().should('have.attr', 'href').and('include', 'olivia-14-zip-light-jacket')
cy.get('[data-testid="addToCompare"]').click();
cy.go('back').wait(1000)
cy.get('[data-testid="addToCompare"]').eq(2).click()
cy.scrollTo('top');
cy.get('[data-testid="compare-list-icon"]').click();
cy.get('[data-testid="comparedProduct"]').should('have.length', 2)
});
});
|
(function (angular) {
angular.module('App')
.controller('AppCtrl', [AppCtrl]);
function AppCtrl() {
}
})(angular);
|
/**
* Represents an Event managed by Stopwatch.
*
* @memberOf Jymfony.Contracts.Stopwatch
*/
class StopwatchEventInterface {
/**
* Gets the category.
*
* @returns {string} The category
*/
get category() { }
/**
* Gets the origin.
*
* @returns {number} The origin in milliseconds
*/
get origin() { }
/**
* Starts a new event period.
*
* @returns {Jymfony.Contracts.Stopwatch.StopwatchEventInterface}
*/
start() { }
/**
* Stops the last started event period.
*
* @returns {Jymfony.Contracts.Stopwatch.StopwatchEventInterface}
*
* @throws {LogicException} When stop() is called without a matching call to start()
*/
stop() { }
/**
* Checks if the event was started.
*
* @returns {boolean}
*/
isStarted() { }
/**
* Stops the current period and then starts a new one.
*
* @returns {Jymfony.Contracts.Stopwatch.StopwatchEventInterface}
*/
lap() { }
/**
* Stops all non already stopped periods.
*/
ensureStopped() { }
/**
* Gets all event periods.
*
* @returns {Jymfony.Contracts.Stopwatch.StopwatchPeriodInterface[]} An array of StopwatchPeriod instances
*/
get periods() { }
/**
* Gets the relative time of the start of the first period.
*
* @returns {number} The time (in milliseconds)
*/
get startTime() { }
/**
* Gets the relative time of the end of the last period.
*
* @returns {number} The time (in milliseconds)
*/
get endTime() { }
/**
* Gets the duration of the events (including all periods).
*
* @returns {number} The duration (in milliseconds)
*/
get duration() { }
/**
* Gets the max memory usage of all periods.
*
* @returns {int} The memory usage (in bytes)
*/
get memory() { }
}
export default getInterface(StopwatchEventInterface);
|
/*
购物车功能
购物车商品的处理
支持删除购物车商品(立刻购买时不显示)
支持更新商品的购买数量到服务器
支持保存购物车商品信息到订单创建参数
计算价格完成后刷新商品总价和商品单价
*/
/* 购物车商品的处理 */
$(function () {
// 绑定购物车商品改变时的事件
var $cartContainer = $(".cart-container");
var $cartProductTable = $cartContainer.find(".cart-product-table");
var $parametersList = $cartContainer.find("[name='createOrderProductParametersList']");
var $cartProducts = $cartContainer.find("[name='cartProducts']");
var cartProductChangeEventName = "cartProductChange.cartView";
var cartProductChangeEventMask = false;
$cartContainer.on(cartProductChangeEventName, function () {
if (cartProductChangeEventMask) {
return;
}
cartProductChangeEventMask = true; // 设置事件处理中,防止重复处理
var createOrderProductParametersList = []; // 创建订单商品的参数列表
var totalCount = 0; // 购物车商品数量总计
var cartProducts = {}; // 购物车商品Id和数量
$cartProductTable.find(".cart-product").each(function () {
var $cartProduct = $(this);
// 没有勾选时跳过
var $checkbox = $cartProduct.find(".selection input");
if (!$checkbox.is(":checked")) {
return;
}
// 数量等于0时取消勾选并跳过
var $orderCount = $cartProduct.find(".order-count input");
var orderCount = $orderCount.val() || 0;
if (orderCount <= 0) {
$checkbox.prop("checked", false).change();
return;
}
// 添加购物车商品关联的商品Id和匹配参数到列表中
var productId = $cartProduct.data("product-id");
var matchedParameters = $cartProduct.data("matched-parameters") || "{}";
var cartProductId = $cartProduct.data("cart-product-id");
matchedParameters.OrderCount = parseInt(
$cartProduct.find(".order-count input").val()) || 0; // 更新订购数量
createOrderProductParametersList.push({
ProductId: productId,
MatchParameters: matchedParameters,
Extra: { cartProductId: cartProductId }
});
// 统计购物车商品数量
totalCount += matchedParameters.OrderCount;
// 保存购物车商品Id和数量
// 用于修改服务端数量和提交订单后删除购物车商品
var cartProductId = $cartProduct.data("cart-product-id");
cartProducts[cartProductId] = matchedParameters.OrderCount;
});
// 更新商品数量总计
$cartProductTable.find(".cart-product-total .total-count > em").text(totalCount);
// 保存到控件
$parametersList.val(JSON.stringify(createOrderProductParametersList)).change();
$cartProducts.val(JSON.stringify(cartProducts)).change();
// 设置结束处理
cartProductChangeEventMask = false;
});
// 绑定删除事件,删除后触发改变事件
$cartContainer.on("click", ".delete", function () {
var $delete = $(this);
var id = $delete.data("id");
// 提交到服务器删除
$.post("/api/cart/delete", { id: id }, function (data) {
// 触发迷你购物车的重新初始化事件
$(".minicart-menu").trigger("reinitialize.miniCart");
$.handleAjaxResult(data);
// 删除当前行并触发改变事件
$delete.closest("[role='row']").remove();
$cartContainer.trigger(cartProductChangeEventName);
});
});
// 在勾选改变时触发改变事件
$cartProductTable.on("change", ".selection input", function () {
$cartContainer.trigger(cartProductChangeEventName);
});
// 在数量改变时触发改变事件
var updateCountsHandler = null;
$cartProductTable.on("change", ".order-count input", function () {
// 触发改变事件
$cartContainer.trigger(cartProductChangeEventName);
// 一秒后把数量保存到服务端,防止频繁提交
clearTimeout(updateCountsHandler);
updateCountsHandler = setTimeout(function () {
$.post("/api/cart/update_counts", { counts: $cartProducts.val() }, function (data) {
$.handleAjaxResult(data);
});
}, 1000);
});
// 支持保存购物车商品信息到订单创建参数
$parametersList.attr("data-order-parameter", "CreateOrderProductParametersList");
$cartProducts.attr("data-order-parameter", "CartProducts");
// 页面载入时触发改变事件
$cartContainer.trigger(cartProductChangeEventName);
});
/* 购物车商品计算价格的处理 */
$(function () {
// 计算价格完成后刷新商品总价和商品单价
var $cartContainer = $(".cart-container");
var $cartProductTotalPrice = $cartContainer.find(".cart-product-total .total-price > em");
$cartContainer.on("calcPrice.cartView", function () {
// 显示计算中
$cartProductTotalPrice.html($cartContainer.data("calculatingHtml"));
});
$cartContainer.on("calcPriceSuccess.cartView", function (e, priceInfo) {
// 商品总价
$cartProductTotalPrice.text(priceInfo.orderProductTotalPriceString);
// 商品单价
var cartProductMapping = _.indexBy(
$cartContainer.find(".cart-product-table .cart-product"),
function (elem) { return $(elem).data("cart-product-id"); });
_.each(priceInfo.orderProductUnitPrices, function (info) {
var $cartProduct = $(cartProductMapping[info.extra.cartProductId]);
var $price = $cartProduct.find(".unit-price .price");
$price.attr("title", info.description).text(info.priceString);
});
});
$cartContainer.on("calcPriceFailed.cartView", function (e, error) {
// 滚动到最底部
$cartProductTotalPrice.text("-");
$("html, body").animate({ scrollTop: $(".page-body").height() }, 100);
});
});
|
import React from 'react-native';
const {
Image,
TouchableOpacity,
StyleSheet,
Text,
View,
} = React;
import globalStyles from '../styles/SearchGlobalStyles.js';
import CarMakePicker from './CarMakePicker.js';
import CarModelPicker from './CarModelPicker.js';
const CarMakePickerContainer = (props) => ({
render(){
return (
<View style={globalStyles.container}>
<Text style={globalStyles.label}>Chose your car</Text>
<View style={globalStyles.innerBox}>
<CarMakePicker label='Make' />
<CarModelPicker label='Model' />
</View>
</View>
);
},
handleStartChange(value) {
// this.props.onChange('priceRange', [value, this.props.value[1]]);
},
handleEndChange(value) {
// this.props.onChange('priceRange', [this.props.value[0], value]);
}
});
const styles = StyleSheet.create({
divider: {
height: 20,
width: 1,
backgroundColor: '#ccc'
},
});
export default CarMakePickerContainer;
|
/**
* @author mrdoob / http://mrdoob.com/
* @author Mugen87 / https://github.com/Mugen87
*/
THREE.ColladaLoader = function ( manager ) {
this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
};
THREE.ColladaLoader.prototype = {
constructor: THREE.ColladaLoader,
crossOrigin: 'Anonymous',
load: function ( url, onLoad, onProgress, onError ) {
var scope = this;
var path = scope.path === undefined ? THREE.LoaderUtils.extractUrlBase( url ) : scope.path;
var loader = new THREE.FileLoader( scope.manager );
loader.load( url, function ( text ) {
onLoad( scope.parse( text, path ) );
}, onProgress, onError );
},
setPath: function ( value ) {
this.path = value;
},
options: {
set convertUpAxis( value ) {
console.warn( 'THREE.ColladaLoader: options.convertUpAxis() has been removed. Up axis is converted automatically.' );
}
},
setCrossOrigin: function ( value ) {
this.crossOrigin = value;
},
parse: function ( text, path ) {
function getElementsByTagName( xml, name ) {
// Non recursive xml.getElementsByTagName() ...
var array = [];
var childNodes = xml.childNodes;
for ( var i = 0, l = childNodes.length; i < l; i ++ ) {
var child = childNodes[ i ];
if ( child.nodeName === name ) {
array.push( child );
}
}
return array;
}
function parseStrings( text ) {
if ( text.length === 0 ) return [];
var parts = text.trim().split( /\s+/ );
var array = new Array( parts.length );
for ( var i = 0, l = parts.length; i < l; i ++ ) {
array[ i ] = parts[ i ];
}
return array;
}
function parseFloats( text ) {
if ( text.length === 0 ) return [];
var parts = text.trim().split( /\s+/ );
var array = new Array( parts.length );
for ( var i = 0, l = parts.length; i < l; i ++ ) {
array[ i ] = parseFloat( parts[ i ] );
}
return array;
}
function parseInts( text ) {
if ( text.length === 0 ) return [];
var parts = text.trim().split( /\s+/ );
var array = new Array( parts.length );
for ( var i = 0, l = parts.length; i < l; i ++ ) {
array[ i ] = parseInt( parts[ i ] );
}
return array;
}
function parseId( text ) {
return text.substring( 1 );
}
function generateId() {
return 'three_default_' + ( count ++ );
}
function isEmpty( object ) {
return Object.keys( object ).length === 0;
}
// asset
function parseAsset( xml ) {
return {
unit: parseAssetUnit( getElementsByTagName( xml, 'unit' )[ 0 ] ),
upAxis: parseAssetUpAxis( getElementsByTagName( xml, 'up_axis' )[ 0 ] )
};
}
function parseAssetUnit( xml ) {
return xml !== undefined ? parseFloat( xml.getAttribute( 'meter' ) ) : 1;
}
function parseAssetUpAxis( xml ) {
return xml !== undefined ? xml.textContent : 'Y_UP';
}
// library
function parseLibrary( xml, libraryName, nodeName, parser ) {
var library = getElementsByTagName( xml, libraryName )[ 0 ];
if ( library !== undefined ) {
var elements = getElementsByTagName( library, nodeName );
for ( var i = 0; i < elements.length; i ++ ) {
parser( elements[ i ] );
}
}
}
function buildLibrary( data, builder ) {
for ( var name in data ) {
var object = data[ name ];
object.build = builder( data[ name ] );
}
}
// get
function getBuild( data, builder ) {
if ( data.build !== undefined ) return data.build;
data.build = builder( data );
return data.build;
}
// animation
function parseAnimation( xml ) {
var data = {
sources: {},
samplers: {},
channels: {}
};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
var id;
switch ( child.nodeName ) {
case 'source':
id = child.getAttribute( 'id' );
data.sources[ id ] = parseSource( child );
break;
case 'sampler':
id = child.getAttribute( 'id' );
data.samplers[ id ] = parseAnimationSampler( child );
break;
case 'channel':
id = child.getAttribute( 'target' );
data.channels[ id ] = parseAnimationChannel( child );
break;
default:
console.log( child );
}
}
library.animations[ xml.getAttribute( 'id' ) ] = data;
}
function parseAnimationSampler( xml ) {
var data = {
inputs: {},
};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'input':
var id = parseId( child.getAttribute( 'source' ) );
var semantic = child.getAttribute( 'semantic' );
data.inputs[ semantic ] = id;
break;
}
}
return data;
}
function parseAnimationChannel( xml ) {
var data = {};
var target = xml.getAttribute( 'target' );
// parsing SID Addressing Syntax
var parts = target.split( '/' );
var id = parts.shift();
var sid = parts.shift();
// check selection syntax
var arraySyntax = ( sid.indexOf( '(' ) !== - 1 );
var memberSyntax = ( sid.indexOf( '.' ) !== - 1 );
if ( memberSyntax ) {
// member selection access
parts = sid.split( '.' );
sid = parts.shift();
data.member = parts.shift();
} else if ( arraySyntax ) {
// array-access syntax. can be used to express fields in one-dimensional vectors or two-dimensional matrices.
var indices = sid.split( '(' );
sid = indices.shift();
for ( var i = 0; i < indices.length; i ++ ) {
indices[ i ] = parseInt( indices[ i ].replace( /\)/, '' ) );
}
data.indices = indices;
}
data.id = id;
data.sid = sid;
data.arraySyntax = arraySyntax;
data.memberSyntax = memberSyntax;
data.sampler = parseId( xml.getAttribute( 'source' ) );
return data;
}
function buildAnimation( data ) {
var tracks = [];
var channels = data.channels;
var samplers = data.samplers;
var sources = data.sources;
for ( var target in channels ) {
if ( channels.hasOwnProperty( target ) ) {
var channel = channels[ target ];
var sampler = samplers[ channel.sampler ];
var inputId = sampler.inputs.INPUT;
var outputId = sampler.inputs.OUTPUT;
var inputSource = sources[ inputId ];
var outputSource = sources[ outputId ];
var animation = buildAnimationChannel( channel, inputSource, outputSource );
createKeyframeTracks( animation, tracks );
}
}
return tracks;
}
function getAnimation( id ) {
return getBuild( library.animations[ id ], buildAnimation );
}
function buildAnimationChannel( channel, inputSource, outputSource ) {
var node = library.nodes[ channel.id ];
var object3D = getNode( node.id );
var transform = node.transforms[ channel.sid ];
var defaultMatrix = node.matrix.clone().transpose();
var time, stride;
var i, il, j, jl;
var data = {};
// the collada spec allows the animation of data in various ways.
// depending on the transform type (matrix, translate, rotate, scale), we execute different logic
switch ( transform ) {
case 'matrix':
for ( i = 0, il = inputSource.array.length; i < il; i ++ ) {
time = inputSource.array[ i ];
stride = i * outputSource.stride;
if ( data[ time ] === undefined ) data[ time ] = {};
if ( channel.arraySyntax === true ) {
var value = outputSource.array[ stride ];
var index = channel.indices[ 0 ] + 4 * channel.indices[ 1 ];
data[ time ][ index ] = value;
} else {
for ( j = 0, jl = outputSource.stride; j < jl; j ++ ) {
data[ time ][ j ] = outputSource.array[ stride + j ];
}
}
}
break;
case 'translate':
console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
break;
case 'rotate':
console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
break;
case 'scale':
console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
break;
}
var keyframes = prepareAnimationData( data, defaultMatrix );
var animation = {
name: object3D.uuid,
keyframes: keyframes
};
return animation;
}
function prepareAnimationData( data, defaultMatrix ) {
var keyframes = [];
// transfer data into a sortable array
for ( var time in data ) {
keyframes.push( { time: parseFloat( time ), value: data[ time ] } );
}
// ensure keyframes are sorted by time
keyframes.sort( ascending );
// now we clean up all animation data, so we can use them for keyframe tracks
for ( var i = 0; i < 16; i ++ ) {
transformAnimationData( keyframes, i, defaultMatrix.elements[ i ] );
}
return keyframes;
// array sort function
function ascending( a, b ) {
return a.time - b.time;
}
}
var position = new THREE.Vector3();
var scale = new THREE.Vector3();
var quaternion = new THREE.Quaternion();
function createKeyframeTracks( animation, tracks ) {
var keyframes = animation.keyframes;
var name = animation.name;
var times = [];
var positionData = [];
var quaternionData = [];
var scaleData = [];
for ( var i = 0, l = keyframes.length; i < l; i ++ ) {
var keyframe = keyframes[ i ];
var time = keyframe.time;
var value = keyframe.value;
matrix.fromArray( value ).transpose();
matrix.decompose( position, quaternion, scale );
times.push( time );
positionData.push( position.x, position.y, position.z );
quaternionData.push( quaternion.x, quaternion.y, quaternion.z, quaternion.w );
scaleData.push( scale.x, scale.y, scale.z );
}
if ( positionData.length > 0 ) tracks.push( new THREE.VectorKeyframeTrack( name + '.position', times, positionData ) );
if ( quaternionData.length > 0 ) tracks.push( new THREE.QuaternionKeyframeTrack( name + '.quaternion', times, quaternionData ) );
if ( scaleData.length > 0 ) tracks.push( new THREE.VectorKeyframeTrack( name + '.scale', times, scaleData ) );
return tracks;
}
function transformAnimationData( keyframes, property, defaultValue ) {
var keyframe;
var empty = true;
var i, l;
// check, if values of a property are missing in our keyframes
for ( i = 0, l = keyframes.length; i < l; i ++ ) {
keyframe = keyframes[ i ];
if ( keyframe.value[ property ] === undefined ) {
keyframe.value[ property ] = null; // mark as missing
} else {
empty = false;
}
}
if ( empty === true ) {
// no values at all, so we set a default value
for ( i = 0, l = keyframes.length; i < l; i ++ ) {
keyframe = keyframes[ i ];
keyframe.value[ property ] = defaultValue;
}
} else {
// filling gaps
createMissingKeyframes( keyframes, property );
}
}
function createMissingKeyframes( keyframes, property ) {
var prev, next;
for ( var i = 0, l = keyframes.length; i < l; i ++ ) {
var keyframe = keyframes[ i ];
if ( keyframe.value[ property ] === null ) {
prev = getPrev( keyframes, i, property );
next = getNext( keyframes, i, property );
if ( prev === null ) {
keyframe.value[ property ] = next.value[ property ];
continue;
}
if ( next === null ) {
keyframe.value[ property ] = prev.value[ property ];
continue;
}
interpolate( keyframe, prev, next, property );
}
}
}
function getPrev( keyframes, i, property ) {
while ( i >= 0 ) {
var keyframe = keyframes[ i ];
if ( keyframe.value[ property ] !== null ) return keyframe;
i --;
}
return null;
}
function getNext( keyframes, i, property ) {
while ( i < keyframes.length ) {
var keyframe = keyframes[ i ];
if ( keyframe.value[ property ] !== null ) return keyframe;
i ++;
}
return null;
}
function interpolate( key, prev, next, property ) {
if ( ( next.time - prev.time ) === 0 ) {
key.value[ property ] = prev.value[ property ];
return;
}
key.value[ property ] = ( ( key.time - prev.time ) * ( next.value[ property ] - prev.value[ property ] ) / ( next.time - prev.time ) ) + prev.value[ property ];
}
// animation clips
function parseAnimationClip( xml ) {
var data = {
name: xml.getAttribute( 'id' ) || 'default',
start: parseFloat( xml.getAttribute( 'start' ) || 0 ),
end: parseFloat( xml.getAttribute( 'end' ) || 0 ),
animations: []
};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'instance_animation':
data.animations.push( parseId( child.getAttribute( 'url' ) ) );
break;
}
}
library.clips[ xml.getAttribute( 'id' ) ] = data;
}
function buildAnimationClip( data ) {
var tracks = [];
var name = data.name;
var duration = ( data.end - data.start ) || - 1;
var animations = data.animations;
for ( var i = 0, il = animations.length; i < il; i ++ ) {
var animationTracks = getAnimation( animations[ i ] );
for ( var j = 0, jl = animationTracks.length; j < jl; j ++ ) {
tracks.push( animationTracks[ j ] );
}
}
return new THREE.AnimationClip( name, duration, tracks );
}
function getAnimationClip( id ) {
return getBuild( library.clips[ id ], buildAnimationClip );
}
// controller
function parseController( xml ) {
var data = {};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'skin':
// there is exactly one skin per controller
data.id = parseId( child.getAttribute( 'source' ) );
data.skin = parseSkin( child );
break;
case 'morph':
data.id = parseId( child.getAttribute( 'source' ) );
console.warn( 'THREE.ColladaLoader: Morph target animation not supported yet.' );
break;
}
}
library.controllers[ xml.getAttribute( 'id' ) ] = data;
}
function parseSkin( xml ) {
var data = {
sources: {}
};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'bind_shape_matrix':
data.bindShapeMatrix = parseFloats( child.textContent );
break;
case 'source':
var id = child.getAttribute( 'id' );
data.sources[ id ] = parseSource( child );
break;
case 'joints':
data.joints = parseJoints( child );
break;
case 'vertex_weights':
data.vertexWeights = parseVertexWeights( child );
break;
}
}
return data;
}
function parseJoints( xml ) {
var data = {
inputs: {}
};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'input':
var semantic = child.getAttribute( 'semantic' );
var id = parseId( child.getAttribute( 'source' ) );
data.inputs[ semantic ] = id;
break;
}
}
return data;
}
function parseVertexWeights( xml ) {
var data = {
inputs: {}
};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'input':
var semantic = child.getAttribute( 'semantic' );
var id = parseId( child.getAttribute( 'source' ) );
var offset = parseInt( child.getAttribute( 'offset' ) );
data.inputs[ semantic ] = { id: id, offset: offset };
break;
case 'vcount':
data.vcount = parseInts( child.textContent );
break;
case 'v':
data.v = parseInts( child.textContent );
break;
}
}
return data;
}
function buildController( data ) {
var build = {
id: data.id
};
var geometry = library.geometries[ build.id ];
if ( data.skin !== undefined ) {
build.skin = buildSkin( data.skin );
// we enhance the 'sources' property of the corresponding geometry with our skin data
geometry.sources.skinIndices = build.skin.indices;
geometry.sources.skinWeights = build.skin.weights;
}
return build;
}
function buildSkin( data ) {
var BONE_LIMIT = 4;
var build = {
joints: [], // this must be an array to preserve the joint order
indices: {
array: [],
stride: BONE_LIMIT
},
weights: {
array: [],
stride: BONE_LIMIT
}
};
var sources = data.sources;
var vertexWeights = data.vertexWeights;
var vcount = vertexWeights.vcount;
var v = vertexWeights.v;
var jointOffset = vertexWeights.inputs.JOINT.offset;
var weightOffset = vertexWeights.inputs.WEIGHT.offset;
var jointSource = data.sources[ data.joints.inputs.JOINT ];
var inverseSource = data.sources[ data.joints.inputs.INV_BIND_MATRIX ];
var weights = sources[ vertexWeights.inputs.WEIGHT.id ].array;
var stride = 0;
var i, j, l;
// procces skin data for each vertex
for ( i = 0, l = vcount.length; i < l; i ++ ) {
var jointCount = vcount[ i ]; // this is the amount of joints that affect a single vertex
var vertexSkinData = [];
for ( j = 0; j < jointCount; j ++ ) {
var skinIndex = v[ stride + jointOffset ];
var weightId = v[ stride + weightOffset ];
var skinWeight = weights[ weightId ];
vertexSkinData.push( { index: skinIndex, weight: skinWeight } );
stride += 2;
}
// we sort the joints in descending order based on the weights.
// this ensures, we only procced the most important joints of the vertex
vertexSkinData.sort( descending );
// now we provide for each vertex a set of four index and weight values.
// the order of the skin data matches the order of vertices
for ( j = 0; j < BONE_LIMIT; j ++ ) {
var d = vertexSkinData[ j ];
if ( d !== undefined ) {
build.indices.array.push( d.index );
build.weights.array.push( d.weight );
} else {
build.indices.array.push( 0 );
build.weights.array.push( 0 );
}
}
}
// setup bind matrix
build.bindMatrix = new THREE.Matrix4().fromArray( data.bindShapeMatrix ).transpose();
// process bones and inverse bind matrix data
for ( i = 0, l = jointSource.array.length; i < l; i ++ ) {
var name = jointSource.array[ i ];
var boneInverse = new THREE.Matrix4().fromArray( inverseSource.array, i * inverseSource.stride ).transpose();
build.joints.push( { name: name, boneInverse: boneInverse } );
}
return build;
// array sort function
function descending( a, b ) {
return b.weight - a.weight;
}
}
function getController( id ) {
return getBuild( library.controllers[ id ], buildController );
}
// image
function parseImage( xml ) {
var data = {
init_from: getElementsByTagName( xml, 'init_from' )[ 0 ].textContent
};
library.images[ xml.getAttribute( 'id' ) ] = data;
}
function buildImage( data ) {
if ( data.build !== undefined ) return data.build;
return data.init_from;
}
function getImage( id ) {
return getBuild( library.images[ id ], buildImage );
}
// effect
function parseEffect( xml ) {
var data = {};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'profile_COMMON':
data.profile = parseEffectProfileCOMMON( child );
break;
}
}
library.effects[ xml.getAttribute( 'id' ) ] = data;
}
function parseEffectProfileCOMMON( xml ) {
var data = {
surfaces: {},
samplers: {}
};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'newparam':
parseEffectNewparam( child, data );
break;
case 'technique':
data.technique = parseEffectTechnique( child );
break;
case 'extra':
data.extra = parseEffectExtra( child );
break;
}
}
return data;
}
function parseEffectNewparam( xml, data ) {
var sid = xml.getAttribute( 'sid' );
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'surface':
data.surfaces[ sid ] = parseEffectSurface( child );
break;
case 'sampler2D':
data.samplers[ sid ] = parseEffectSampler( child );
break;
}
}
}
function parseEffectSurface( xml ) {
var data = {};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'init_from':
data.init_from = child.textContent;
break;
}
}
return data;
}
function parseEffectSampler( xml ) {
var data = {};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'source':
data.source = child.textContent;
break;
}
}
return data;
}
function parseEffectTechnique( xml ) {
var data = {};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'constant':
case 'lambert':
case 'blinn':
case 'phong':
data.type = child.nodeName;
data.parameters = parseEffectParameters( child );
break;
}
}
return data;
}
function parseEffectParameters( xml ) {
var data = {};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'emission':
case 'diffuse':
case 'specular':
case 'shininess':
case 'transparency':
data[ child.nodeName ] = parseEffectParameter( child );
break;
case 'transparent':
data[ child.nodeName ] = {
opaque: child.getAttribute( 'opaque' ),
data: parseEffectParameter( child )
};
break;
}
}
return data;
}
function parseEffectParameter( xml ) {
var data = {};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'color':
data[ child.nodeName ] = parseFloats( child.textContent );
break;
case 'float':
data[ child.nodeName ] = parseFloat( child.textContent );
break;
case 'texture':
data[ child.nodeName ] = { id: child.getAttribute( 'texture' ), extra: parseEffectParameterTexture( child ) };
break;
}
}
return data;
}
function parseEffectParameterTexture( xml ) {
var data = {
technique: {}
};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'extra':
parseEffectParameterTextureExtra( child, data );
break;
}
}
return data;
}
function parseEffectParameterTextureExtra( xml, data ) {
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'technique':
parseEffectParameterTextureExtraTechnique( child, data );
break;
}
}
}
function parseEffectParameterTextureExtraTechnique( xml, data ) {
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'repeatU':
case 'repeatV':
case 'offsetU':
case 'offsetV':
data.technique[ child.nodeName ] = parseFloat( child.textContent );
break;
case 'wrapU':
case 'wrapV':
// some files have values for wrapU/wrapV which become NaN via parseInt
if ( child.textContent.toUpperCase() === 'TRUE' ) {
data.technique[ child.nodeName ] = 1;
} else if ( child.textContent.toUpperCase() === 'FALSE' ) {
data.technique[ child.nodeName ] = 0;
} else {
data.technique[ child.nodeName ] = parseInt( child.textContent );
}
break;
}
}
}
function parseEffectExtra( xml ) {
var data = {};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'technique':
data.technique = parseEffectExtraTechnique( child );
break;
}
}
return data;
}
function parseEffectExtraTechnique( xml ) {
var data = {};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'double_sided':
data[ child.nodeName ] = parseInt( child.textContent );
break;
}
}
return data;
}
function buildEffect( data ) {
return data;
}
function getEffect( id ) {
return getBuild( library.effects[ id ], buildEffect );
}
// material
function parseMaterial( xml ) {
var data = {
name: xml.getAttribute( 'name' )
};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'instance_effect':
data.url = parseId( child.getAttribute( 'url' ) );
break;
}
}
library.materials[ xml.getAttribute( 'id' ) ] = data;
}
function buildMaterial( data ) {
var effect = getEffect( data.url );
var technique = effect.profile.technique;
var extra = effect.profile.extra;
var material;
switch ( technique.type ) {
case 'phong':
case 'blinn':
material = new THREE.MeshPhongMaterial();
break;
case 'lambert':
material = new THREE.MeshLambertMaterial();
break;
default:
material = new THREE.MeshBasicMaterial();
break;
}
material.name = data.name;
function getTexture( textureObject ) {
var sampler = effect.profile.samplers[ textureObject.id ];
var image;
// get image
if ( sampler !== undefined ) {
var surface = effect.profile.surfaces[ sampler.source ];
image = getImage( surface.init_from );
} else {
console.warn( 'THREE.ColladaLoader: Undefined sampler. Access image directly (see #12530).' );
image = getImage( textureObject.id );
}
// create texture if image is avaiable
if ( image !== undefined ) {
var texture = textureLoader.load( image );
var extra = textureObject.extra;
if ( extra !== undefined && extra.technique !== undefined && isEmpty( extra.technique ) === false ) {
var technique = extra.technique;
texture.wrapS = technique.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
texture.wrapT = technique.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
texture.offset.set( technique.offsetU || 0, technique.offsetV || 0 );
texture.repeat.set( technique.repeatU || 1, technique.repeatV || 1 );
} else {
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
}
return texture;
} else {
console.error( 'THREE.ColladaLoader: Unable to load texture with ID:', textureObject.id );
return null;
}
}
var parameters = technique.parameters;
for ( var key in parameters ) {
var parameter = parameters[ key ];
switch ( key ) {
case 'diffuse':
if ( parameter.color ) material.color.fromArray( parameter.color );
if ( parameter.texture ) material.map = getTexture( parameter.texture );
break;
case 'specular':
if ( parameter.color && material.specular ) material.specular.fromArray( parameter.color );
if ( parameter.texture ) material.specularMap = getTexture( parameter.texture );
break;
case 'shininess':
if ( parameter.float && material.shininess )
material.shininess = parameter.float;
break;
case 'emission':
if ( parameter.color && material.emissive )
material.emissive.fromArray( parameter.color );
break;
}
}
//
var transparent = parameters[ 'transparent' ];
var transparency = parameters[ 'transparency' ];
// <transparency> does not exist but <transparent>
if ( transparency === undefined && transparent ) {
transparency = {
float: 1
};
}
// <transparent> does not exist but <transparency>
if ( transparent === undefined && transparency ) {
transparent = {
opaque: 'A_ONE',
data: {
color: [ 1, 1, 1, 1 ]
} };
}
if ( transparent && transparency ) {
// handle case if a texture exists but no color
if ( transparent.data.texture ) {
material.alphaMap = getTexture( transparent.data.texture );
material.transparent = true;
} else {
var color = transparent.data.color;
switch ( transparent.opaque ) {
case 'A_ONE':
material.opacity = color[ 3 ] * transparency.float;
break;
case 'RGB_ZERO':
material.opacity = 1 - ( color[ 0 ] * transparency.float );
break;
case 'A_ZERO':
material.opacity = 1 - ( color[ 3 ] * transparency.float );
break;
case 'RGB_ONE':
material.opacity = color[ 0 ] * transparency.float;
break;
default:
console.warn( 'THREE.ColladaLoader: Invalid opaque type "%s" of transparent tag.', transparent.opaque );
}
if ( material.opacity < 1 ) material.transparent = true;
}
}
//
if ( extra !== undefined && extra.technique !== undefined && extra.technique.double_sided === 1 ) {
material.side = THREE.DoubleSide;
}
return material;
}
function getMaterial( id ) {
return getBuild( library.materials[ id ], buildMaterial );
}
// camera
function parseCamera( xml ) {
var data = {
name: xml.getAttribute( 'name' )
};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'optics':
data.optics = parseCameraOptics( child );
break;
}
}
library.cameras[ xml.getAttribute( 'id' ) ] = data;
}
function parseCameraOptics( xml ) {
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
switch ( child.nodeName ) {
case 'technique_common':
return parseCameraTechnique( child );
}
}
return {};
}
function parseCameraTechnique( xml ) {
var data = {};
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
switch ( child.nodeName ) {
case 'perspective':
case 'orthographic':
data.technique = child.nodeName;
data.parameters = parseCameraParameters( child );
break;
}
}
return data;
}
function parseCameraParameters( xml ) {
var data = {};
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
switch ( child.nodeName ) {
case 'xfov':
case 'yfov':
case 'xmag':
case 'ymag':
case 'znear':
case 'zfar':
case 'aspect_ratio':
data[ child.nodeName ] = parseFloat( child.textContent );
break;
}
}
return data;
}
function buildCamera( data ) {
var camera;
switch ( data.optics.technique ) {
case 'perspective':
camera = new THREE.PerspectiveCamera(
data.optics.parameters.yfov,
data.optics.parameters.aspect_ratio,
data.optics.parameters.znear,
data.optics.parameters.zfar
);
break;
case 'orthographic':
var ymag = data.optics.parameters.ymag;
var xmag = data.optics.parameters.xmag;
var aspectRatio = data.optics.parameters.aspect_ratio;
xmag = ( xmag === undefined ) ? ( ymag * aspectRatio ) : xmag;
ymag = ( ymag === undefined ) ? ( xmag / aspectRatio ) : ymag;
xmag *= 0.5;
ymag *= 0.5;
camera = new THREE.OrthographicCamera(
- xmag, xmag, ymag, - ymag, // left, right, top, bottom
data.optics.parameters.znear,
data.optics.parameters.zfar
);
break;
default:
camera = new THREE.PerspectiveCamera();
break;
}
camera.name = data.name;
return camera;
}
function getCamera( id ) {
var data = library.cameras[ id ];
if ( data !== undefined ) {
return getBuild( data, buildCamera );
}
console.warn( 'THREE.ColladaLoader: Couldn\'t find camera with ID:', id );
return null;
}
// light
function parseLight( xml ) {
var data = {};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'technique_common':
data = parseLightTechnique( child );
break;
}
}
library.lights[ xml.getAttribute( 'id' ) ] = data;
}
function parseLightTechnique( xml ) {
var data = {};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'directional':
case 'point':
case 'spot':
case 'ambient':
data.technique = child.nodeName;
data.parameters = parseLightParameters( child );
}
}
return data;
}
function parseLightParameters( xml ) {
var data = {};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'color':
var array = parseFloats( child.textContent );
data.color = new THREE.Color().fromArray( array );
break;
case 'falloff_angle':
data.falloffAngle = parseFloat( child.textContent );
break;
case 'quadratic_attenuation':
var f = parseFloat( child.textContent );
data.distance = f ? Math.sqrt( 1 / f ) : 0;
break;
}
}
return data;
}
function buildLight( data ) {
var light;
switch ( data.technique ) {
case 'directional':
light = new THREE.DirectionalLight();
break;
case 'point':
light = new THREE.PointLight();
break;
case 'spot':
light = new THREE.SpotLight();
break;
case 'ambient':
light = new THREE.AmbientLight();
break;
}
if ( data.parameters.color ) light.color.copy( data.parameters.color );
if ( data.parameters.distance ) light.distance = data.parameters.distance;
return light;
}
function getLight( id ) {
var data = library.lights[ id ];
if ( data !== undefined ) {
return getBuild( data, buildLight );
}
console.warn( 'THREE.ColladaLoader: Couldn\'t find light with ID:', id );
return null;
}
// geometry
function parseGeometry( xml ) {
var data = {
name: xml.getAttribute( 'name' ),
sources: {},
vertices: {},
primitives: []
};
var mesh = getElementsByTagName( xml, 'mesh' )[ 0 ];
// the following tags inside geometry are not supported yet (see https://github.com/mrdoob/three.js/pull/12606): convex_mesh, spline, brep
if ( mesh === undefined ) return;
for ( var i = 0; i < mesh.childNodes.length; i ++ ) {
var child = mesh.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
var id = child.getAttribute( 'id' );
switch ( child.nodeName ) {
case 'source':
data.sources[ id ] = parseSource( child );
break;
case 'vertices':
// data.sources[ id ] = data.sources[ parseId( getElementsByTagName( child, 'input' )[ 0 ].getAttribute( 'source' ) ) ];
data.vertices = parseGeometryVertices( child );
break;
case 'polygons':
console.warn( 'THREE.ColladaLoader: Unsupported primitive type: ', child.nodeName );
break;
case 'lines':
case 'linestrips':
case 'polylist':
case 'triangles':
data.primitives.push( parseGeometryPrimitive( child ) );
break;
default:
console.log( child );
}
}
library.geometries[ xml.getAttribute( 'id' ) ] = data;
}
function parseSource( xml ) {
var data = {
array: [],
stride: 3
};
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'float_array':
data.array = parseFloats( child.textContent );
break;
case 'Name_array':
data.array = parseStrings( child.textContent );
break;
case 'technique_common':
var accessor = getElementsByTagName( child, 'accessor' )[ 0 ];
if ( accessor !== undefined ) {
data.stride = parseInt( accessor.getAttribute( 'stride' ) );
}
break;
}
}
return data;
}
function parseGeometryVertices( xml ) {
var data = {};
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
data[ child.getAttribute( 'semantic' ) ] = parseId( child.getAttribute( 'source' ) );
}
return data;
}
function parseGeometryPrimitive( xml ) {
var primitive = {
type: xml.nodeName,
material: xml.getAttribute( 'material' ),
count: parseInt( xml.getAttribute( 'count' ) ),
inputs: {},
stride: 0
};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'input':
var id = parseId( child.getAttribute( 'source' ) );
var semantic = child.getAttribute( 'semantic' );
var offset = parseInt( child.getAttribute( 'offset' ) );
primitive.inputs[ semantic ] = { id: id, offset: offset };
primitive.stride = Math.max( primitive.stride, offset + 1 );
break;
case 'vcount':
primitive.vcount = parseInts( child.textContent );
break;
case 'p':
primitive.p = parseInts( child.textContent );
break;
}
}
return primitive;
}
function groupPrimitives( primitives ) {
var build = {};
for ( var i = 0; i < primitives.length; i ++ ) {
var primitive = primitives[ i ];
if ( build[ primitive.type ] === undefined ) build[ primitive.type ] = [];
build[ primitive.type ].push( primitive );
}
return build;
}
function buildGeometry( data ) {
var build = {};
var sources = data.sources;
var vertices = data.vertices;
var primitives = data.primitives;
if ( primitives.length === 0 ) return {};
// our goal is to create one buffer geoemtry for a single type of primitives
// first, we group all primitives by their type
var groupedPrimitives = groupPrimitives( primitives );
for ( var type in groupedPrimitives ) {
// second, we create for each type of primitives (polylist,triangles or lines) a buffer geometry
build[ type ] = buildGeometryType( groupedPrimitives[ type ], sources, vertices );
}
return build;
}
function buildGeometryType( primitives, sources, vertices ) {
var build = {};
var position = { array: [], stride: 0 };
var normal = { array: [], stride: 0 };
var uv = { array: [], stride: 0 };
var color = { array: [], stride: 0 };
var skinIndex = { array: [], stride: 4 };
var skinWeight = { array: [], stride: 4 };
var geometry = new THREE.BufferGeometry();
var materialKeys = [];
var start = 0, count = 0;
for ( var p = 0; p < primitives.length; p ++ ) {
var primitive = primitives[ p ];
var inputs = primitive.inputs;
var triangleCount = 1;
if ( primitive.vcount && primitive.vcount[ 0 ] === 4 ) {
triangleCount = 2; // one quad -> two triangles
}
// groups
if ( primitive.type === 'lines' || primitive.type === 'linestrips' ) {
count = primitive.count * 2;
} else {
count = primitive.count * 3 * triangleCount;
}
geometry.addGroup( start, count, p );
start += count;
// material
if ( primitive.material ) {
materialKeys.push( primitive.material );
}
// geometry data
for ( var name in inputs ) {
var input = inputs[ name ];
switch ( name ) {
case 'VERTEX':
for ( var key in vertices ) {
var id = vertices[ key ];
switch ( key ) {
case 'POSITION':
buildGeometryData( primitive, sources[ id ], input.offset, position.array );
position.stride = sources[ id ].stride;
if ( sources.skinWeights && sources.skinIndices ) {
buildGeometryData( primitive, sources.skinIndices, input.offset, skinIndex.array );
buildGeometryData( primitive, sources.skinWeights, input.offset, skinWeight.array );
}
break;
case 'NORMAL':
buildGeometryData( primitive, sources[ id ], input.offset, normal.array );
normal.stride = sources[ id ].stride;
break;
case 'COLOR':
buildGeometryData( primitive, sources[ id ], input.offset, color.array );
color.stride = sources[ id ].stride;
break;
case 'TEXCOORD':
buildGeometryData( primitive, sources[ id ], input.offset, uv.array );
uv.stride = sources[ id ].stride;
break;
default:
console.warn( 'THREE.ColladaLoader: Semantic "%s" not handled in geometry build process.', key );
}
}
break;
case 'NORMAL':
buildGeometryData( primitive, sources[ input.id ], input.offset, normal.array );
normal.stride = sources[ input.id ].stride;
break;
case 'COLOR':
buildGeometryData( primitive, sources[ input.id ], input.offset, color.array );
color.stride = sources[ input.id ].stride;
break;
case 'TEXCOORD':
buildGeometryData( primitive, sources[ input.id ], input.offset, uv.array );
uv.stride = sources[ input.id ].stride;
break;
}
}
}
// build geometry
if ( position.array.length > 0 ) geometry.addAttribute( 'position', new THREE.Float32BufferAttribute( position.array, position.stride ) );
if ( normal.array.length > 0 ) geometry.addAttribute( 'normal', new THREE.Float32BufferAttribute( normal.array, normal.stride ) );
if ( color.array.length > 0 ) geometry.addAttribute( 'color', new THREE.Float32BufferAttribute( color.array, color.stride ) );
if ( uv.array.length > 0 ) geometry.addAttribute( 'uv', new THREE.Float32BufferAttribute( uv.array, uv.stride ) );
if ( skinIndex.array.length > 0 ) geometry.addAttribute( 'skinIndex', new THREE.Float32BufferAttribute( skinIndex.array, skinIndex.stride ) );
if ( skinWeight.array.length > 0 ) geometry.addAttribute( 'skinWeight', new THREE.Float32BufferAttribute( skinWeight.array, skinWeight.stride ) );
build.data = geometry;
build.type = primitives[ 0 ].type;
build.materialKeys = materialKeys;
return build;
}
function buildGeometryData( primitive, source, offset, array ) {
var indices = primitive.p;
var stride = primitive.stride;
var vcount = primitive.vcount;
function pushVector( i ) {
var index = indices[ i + offset ] * sourceStride;
var length = index + sourceStride;
for ( ; index < length; index ++ ) {
array.push( sourceArray[ index ] );
}
}
var maxcount = 0;
var sourceArray = source.array;
var sourceStride = source.stride;
if ( primitive.vcount !== undefined ) {
var index = 0;
for ( var i = 0, l = vcount.length; i < l; i ++ ) {
var count = vcount[ i ];
if ( count === 4 ) {
var a = index + stride * 0;
var b = index + stride * 1;
var c = index + stride * 2;
var d = index + stride * 3;
pushVector( a ); pushVector( b ); pushVector( d );
pushVector( b ); pushVector( c ); pushVector( d );
} else if ( count === 3 ) {
var a = index + stride * 0;
var b = index + stride * 1;
var c = index + stride * 2;
pushVector( a ); pushVector( b ); pushVector( c );
} else {
maxcount = Math.max( maxcount, count );
}
index += stride * count;
}
if ( maxcount > 0 ) {
console.log( 'THREE.ColladaLoader: Geometry has faces with more than 4 vertices.' );
}
} else {
for ( var i = 0, l = indices.length; i < l; i += stride ) {
pushVector( i );
}
}
}
function getGeometry( id ) {
return getBuild( library.geometries[ id ], buildGeometry );
}
// kinematics
function parseKinematicsModel( xml ) {
var data = {
name: xml.getAttribute( 'name' ) || '',
joints: {},
links: []
};
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'technique_common':
parseKinematicsTechniqueCommon( child, data );
break;
}
}
library.kinematicsModels[ xml.getAttribute( 'id' ) ] = data;
}
function buildKinematicsModel( data ) {
if ( data.build !== undefined ) return data.build;
return data;
}
function getKinematicsModel( id ) {
return getBuild( library.kinematicsModels[ id ], buildKinematicsModel );
}
function parseKinematicsTechniqueCommon( xml, data ) {
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'joint':
data.joints[ child.getAttribute( 'sid' ) ] = parseKinematicsJoint( child );
break;
case 'link':
data.links.push( parseKinematicsLink( child ) );
break;
}
}
}
function parseKinematicsJoint( xml ) {
var data;
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'prismatic':
case 'revolute':
data = parseKinematicsJointParameter( child );
break;
}
}
return data;
}
function parseKinematicsJointParameter( xml, data ) {
var data = {
sid: xml.getAttribute( 'sid' ),
name: xml.getAttribute( 'name' ) || '',
axis: new THREE.Vector3(),
limits: {
min: 0,
max: 0
},
type: xml.nodeName,
static: false,
zeroPosition: 0,
middlePosition: 0
};
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'axis':
var array = parseFloats( child.textContent );
data.axis.fromArray( array );
break;
case 'limits':
var max = child.getElementsByTagName( 'max' )[ 0 ];
var min = child.getElementsByTagName( 'min' )[ 0 ];
data.limits.max = parseFloat( max.textContent );
data.limits.min = parseFloat( min.textContent );
break;
}
}
// if min is equal to or greater than max, consider the joint static
if ( data.limits.min >= data.limits.max ) {
data.static = true;
}
// calculate middle position
data.middlePosition = ( data.limits.min + data.limits.max ) / 2.0;
return data;
}
function parseKinematicsLink( xml ) {
var data = {
sid: xml.getAttribute( 'sid' ),
name: xml.getAttribute( 'name' ) || '',
attachments: [],
transforms: []
};
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'attachment_full':
data.attachments.push( parseKinematicsAttachment( child ) );
break;
case 'matrix':
case 'translate':
case 'rotate':
data.transforms.push( parseKinematicsTransform( child ) );
break;
}
}
return data;
}
function parseKinematicsAttachment( xml ) {
var data = {
joint: xml.getAttribute( 'joint' ).split( '/' ).pop(),
transforms: [],
links: []
};
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'link':
data.links.push( parseKinematicsLink( child ) );
break;
case 'matrix':
case 'translate':
case 'rotate':
data.transforms.push( parseKinematicsTransform( child ) );
break;
}
}
return data;
}
function parseKinematicsTransform( xml ) {
var data = {
type: xml.nodeName
};
var array = parseFloats( xml.textContent );
switch ( data.type ) {
case 'matrix':
data.obj = new THREE.Matrix4();
data.obj.fromArray( array ).transpose();
break;
case 'translate':
data.obj = new THREE.Vector3();
data.obj.fromArray( array );
break;
case 'rotate':
data.obj = new THREE.Vector3();
data.obj.fromArray( array );
data.angle = THREE.Math.degToRad( array[ 3 ] );
break;
}
return data;
}
function parseKinematicsScene( xml ) {
var data = {
bindJointAxis: []
};
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'bind_joint_axis':
data.bindJointAxis.push( parseKinematicsBindJointAxis( child ) );
break;
}
}
library.kinematicsScenes[ parseId( xml.getAttribute( 'url' ) ) ] = data;
}
function parseKinematicsBindJointAxis( xml ) {
var data = {
target: xml.getAttribute( 'target' ).split( '/' ).pop()
};
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'axis':
var param = child.getElementsByTagName( 'param' )[ 0 ];
data.axis = param.textContent;
var tmpJointIndex = data.axis.split( 'inst_' ).pop().split( 'axis' )[ 0 ];
data.jointIndex = tmpJointIndex.substr( 0, tmpJointIndex.length - 1 );
break;
}
}
return data;
}
function buildKinematicsScene( data ) {
if ( data.build !== undefined ) return data.build;
return data;
}
function getKinematicsScene( id ) {
return getBuild( library.kinematicsScenes[ id ], buildKinematicsScene );
}
function setupKinematics() {
var kinematicsModelId = Object.keys( library.kinematicsModels )[ 0 ];
var kinematicsSceneId = Object.keys( library.kinematicsScenes )[ 0 ];
var visualSceneId = Object.keys( library.visualScenes )[ 0 ];
if ( kinematicsModelId === undefined || kinematicsSceneId === undefined ) return;
var kinematicsModel = getKinematicsModel( kinematicsModelId );
var kinematicsScene = getKinematicsScene( kinematicsSceneId );
var visualScene = getVisualScene( visualSceneId );
var bindJointAxis = kinematicsScene.bindJointAxis;
var jointMap = {};
for ( var i = 0, l = bindJointAxis.length; i < l; i ++ ) {
var axis = bindJointAxis[ i ];
// the result of the following query is an element of type 'translate', 'rotate','scale' or 'matrix'
var targetElement = collada.querySelector( '[sid="' + axis.target + '"]' );
if ( targetElement ) {
// get the parent of the transfrom element
var parentVisualElement = targetElement.parentElement;
// connect the joint of the kinematics model with the element in the visual scene
connect( axis.jointIndex, parentVisualElement );
}
}
function connect( jointIndex, visualElement ) {
var visualElementName = visualElement.getAttribute( 'name' );
var joint = kinematicsModel.joints[ jointIndex ];
visualScene.traverse( function ( object ) {
if ( object.name === visualElementName ) {
jointMap[ jointIndex ] = {
object: object,
transforms: buildTransformList( visualElement ),
joint: joint,
position: joint.zeroPosition
};
}
} );
}
var m0 = new THREE.Matrix4();
kinematics = {
joints: kinematicsModel && kinematicsModel.joints,
getJointValue: function ( jointIndex ) {
var jointData = jointMap[ jointIndex ];
if ( jointData ) {
return jointData.position;
} else {
console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' doesn\'t exist.' );
}
},
setJointValue: function ( jointIndex, value ) {
var jointData = jointMap[ jointIndex ];
if ( jointData ) {
var joint = jointData.joint;
if ( value > joint.limits.max || value < joint.limits.min ) {
console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' value ' + value + ' outside of limits (min: ' + joint.limits.min + ', max: ' + joint.limits.max + ').' );
} else if ( joint.static ) {
console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' is static.' );
} else {
var object = jointData.object;
var axis = joint.axis;
var transforms = jointData.transforms;
matrix.identity();
// each update, we have to apply all transforms in the correct order
for ( var i = 0; i < transforms.length; i ++ ) {
var transform = transforms[ i ];
// if there is a connection of the transform node with a joint, apply the joint value
if ( transform.sid && transform.sid.indexOf( jointIndex ) !== - 1 ) {
switch ( joint.type ) {
case 'revolute':
matrix.multiply( m0.makeRotationAxis( axis, THREE.Math.degToRad( value ) ) );
break;
case 'prismatic':
matrix.multiply( m0.makeTranslation( axis.x * value, axis.y * value, axis.z * value ) );
break;
default:
console.warn( 'THREE.ColladaLoader: Unknown joint type: ' + joint.type );
break;
}
} else {
switch ( transform.type ) {
case 'matrix':
matrix.multiply( transform.obj );
break;
case 'translate':
matrix.multiply( m0.makeTranslation( transform.obj.x, transform.obj.y, transform.obj.z ) );
break;
case 'scale':
matrix.scale( transform.obj );
break;
case 'rotate':
matrix.multiply( m0.makeRotationAxis( transform.obj, transform.angle ) );
break;
}
}
}
object.matrix.copy( matrix );
object.matrix.decompose( object.position, object.quaternion, object.scale );
jointMap[ jointIndex ].position = value;
}
} else {
console.log( 'THREE.ColladaLoader: ' + jointIndex + ' does not exist.' );
}
}
};
}
function buildTransformList( node ) {
var transforms = [];
var xml = collada.querySelector( '[id="' + node.id + '"]' );
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'matrix':
var array = parseFloats( child.textContent );
var matrix = new THREE.Matrix4().fromArray( array ).transpose();
transforms.push( {
sid: child.getAttribute( 'sid' ),
type: child.nodeName,
obj: matrix
} );
break;
case 'translate':
case 'scale':
var array = parseFloats( child.textContent );
var vector = new THREE.Vector3().fromArray( array );
transforms.push( {
sid: child.getAttribute( 'sid' ),
type: child.nodeName,
obj: vector
} );
break;
case 'rotate':
var array = parseFloats( child.textContent );
var vector = new THREE.Vector3().fromArray( array );
var angle = THREE.Math.degToRad( array[ 3 ] );
transforms.push( {
sid: child.getAttribute( 'sid' ),
type: child.nodeName,
obj: vector,
angle: angle
} );
break;
}
}
return transforms;
}
// nodes
function prepareNodes( xml ) {
var elements = xml.getElementsByTagName( 'node' );
// ensure all node elements have id attributes
for ( var i = 0; i < elements.length; i ++ ) {
var element = elements[ i ];
if ( element.hasAttribute( 'id' ) === false ) {
element.setAttribute( 'id', generateId() );
}
}
}
var matrix = new THREE.Matrix4();
var vector = new THREE.Vector3();
function parseNode( xml ) {
var data = {
name: xml.getAttribute( 'name' ) || '',
type: xml.getAttribute( 'type' ),
id: xml.getAttribute( 'id' ),
sid: xml.getAttribute( 'sid' ),
matrix: new THREE.Matrix4(),
nodes: [],
instanceCameras: [],
instanceControllers: [],
instanceLights: [],
instanceGeometries: [],
instanceNodes: [],
transforms: {}
};
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'node':
data.nodes.push( child.getAttribute( 'id' ) );
parseNode( child );
break;
case 'instance_camera':
data.instanceCameras.push( parseId( child.getAttribute( 'url' ) ) );
break;
case 'instance_controller':
data.instanceControllers.push( parseNodeInstance( child ) );
break;
case 'instance_light':
data.instanceLights.push( parseId( child.getAttribute( 'url' ) ) );
break;
case 'instance_geometry':
data.instanceGeometries.push( parseNodeInstance( child ) );
break;
case 'instance_node':
data.instanceNodes.push( parseId( child.getAttribute( 'url' ) ) );
break;
case 'matrix':
var array = parseFloats( child.textContent );
data.matrix.multiply( matrix.fromArray( array ).transpose() );
data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
break;
case 'translate':
var array = parseFloats( child.textContent );
vector.fromArray( array );
data.matrix.multiply( matrix.makeTranslation( vector.x, vector.y, vector.z ) );
data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
break;
case 'rotate':
var array = parseFloats( child.textContent );
var angle = THREE.Math.degToRad( array[ 3 ] );
data.matrix.multiply( matrix.makeRotationAxis( vector.fromArray( array ), angle ) );
data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
break;
case 'scale':
var array = parseFloats( child.textContent );
data.matrix.scale( vector.fromArray( array ) );
data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
break;
case 'extra':
break;
default:
console.log( child );
}
}
library.nodes[ data.id ] = data;
return data;
}
function parseNodeInstance( xml ) {
var data = {
id: parseId( xml.getAttribute( 'url' ) ),
materials: {},
skeletons: []
};
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
switch ( child.nodeName ) {
case 'bind_material':
var instances = child.getElementsByTagName( 'instance_material' );
for ( var j = 0; j < instances.length; j ++ ) {
var instance = instances[ j ];
var symbol = instance.getAttribute( 'symbol' );
var target = instance.getAttribute( 'target' );
data.materials[ symbol ] = parseId( target );
}
break;
case 'skeleton':
data.skeletons.push( parseId( child.textContent ) );
break;
default:
break;
}
}
return data;
}
function buildSkeleton( skeletons, joints ) {
var boneData = [];
var sortedBoneData = [];
var i, j, data;
// a skeleton can have multiple root bones. collada expresses this
// situtation with multiple "skeleton" tags per controller instance
for ( i = 0; i < skeletons.length; i ++ ) {
var skeleton = skeletons[ i ];
var root = getNode( skeleton );
// setup bone data for a single bone hierarchy
buildBoneHierarchy( root, joints, boneData );
}
// sort bone data (the order is defined in the corresponding controller)
for ( i = 0; i < joints.length; i ++ ) {
for ( j = 0; j < boneData.length; j ++ ) {
data = boneData[ j ];
if ( data.bone.name === joints[ i ].name ) {
sortedBoneData[ i ] = data;
data.processed = true;
break;
}
}
}
// add unprocessed bone data at the end of the list
for ( i = 0; i < boneData.length; i ++ ) {
data = boneData[ i ];
if ( data.processed === false ) {
sortedBoneData.push( data );
data.processed = true;
}
}
// setup arrays for skeleton creation
var bones = [];
var boneInverses = [];
for ( i = 0; i < sortedBoneData.length; i ++ ) {
data = sortedBoneData[ i ];
bones.push( data.bone );
boneInverses.push( data.boneInverse );
}
return new THREE.Skeleton( bones, boneInverses );
}
function buildBoneHierarchy( root, joints, boneData ) {
// setup bone data from visual scene
root.traverse( function ( object ) {
if ( object.isBone === true ) {
var boneInverse;
// retrieve the boneInverse from the controller data
for ( var i = 0; i < joints.length; i ++ ) {
var joint = joints[ i ];
if ( joint.name === object.name ) {
boneInverse = joint.boneInverse;
break;
}
}
if ( boneInverse === undefined ) {
// Unfortunately, there can be joints in the visual scene that are not part of the
// corresponding controller. In this case, we have to create a dummy boneInverse matrix
// for the respective bone. This bone won't affect any vertices, because there are no skin indices
// and weights defined for it. But we still have to add the bone to the sorted bone list in order to
// ensure a correct animation of the model.
boneInverse = new THREE.Matrix4();
}
boneData.push( { bone: object, boneInverse: boneInverse, processed: false } );
}
} );
}
function buildNode( data ) {
var objects = [];
var matrix = data.matrix;
var nodes = data.nodes;
var type = data.type;
var instanceCameras = data.instanceCameras;
var instanceControllers = data.instanceControllers;
var instanceLights = data.instanceLights;
var instanceGeometries = data.instanceGeometries;
var instanceNodes = data.instanceNodes;
// nodes
for ( var i = 0, l = nodes.length; i < l; i ++ ) {
objects.push( getNode( nodes[ i ] ) );
}
// instance cameras
for ( var i = 0, l = instanceCameras.length; i < l; i ++ ) {
var instanceCamera = getCamera( instanceCameras[ i ] );
if ( instanceCamera !== null ) {
objects.push( instanceCamera.clone() );
}
}
// instance controllers
for ( var i = 0, l = instanceControllers.length; i < l; i ++ ) {
var instance = instanceControllers[ i ];
var controller = getController( instance.id );
var geometries = getGeometry( controller.id );
var newObjects = buildObjects( geometries, instance.materials );
var skeletons = instance.skeletons;
var joints = controller.skin.joints;
var skeleton = buildSkeleton( skeletons, joints );
for ( var j = 0, jl = newObjects.length; j < jl; j ++ ) {
var object = newObjects[ j ];
if ( object.isSkinnedMesh ) {
object.bind( skeleton, controller.skin.bindMatrix );
object.normalizeSkinWeights();
}
objects.push( object );
}
}
// instance lights
for ( var i = 0, l = instanceLights.length; i < l; i ++ ) {
var instanceLight = getLight( instanceLights[ i ] );
if ( instanceLight !== null ) {
objects.push( instanceLight.clone() );
}
}
// instance geometries
for ( var i = 0, l = instanceGeometries.length; i < l; i ++ ) {
var instance = instanceGeometries[ i ];
// a single geometry instance in collada can lead to multiple object3Ds.
// this is the case when primitives are combined like triangles and lines
var geometries = getGeometry( instance.id );
var newObjects = buildObjects( geometries, instance.materials );
for ( var j = 0, jl = newObjects.length; j < jl; j ++ ) {
objects.push( newObjects[ j ] );
}
}
// instance nodes
for ( var i = 0, l = instanceNodes.length; i < l; i ++ ) {
objects.push( getNode( instanceNodes[ i ] ).clone() );
}
var object;
if ( nodes.length === 0 && objects.length === 1 ) {
object = objects[ 0 ];
} else {
object = ( type === 'JOINT' ) ? new THREE.Bone() : new THREE.Group();
for ( var i = 0; i < objects.length; i ++ ) {
object.add( objects[ i ] );
}
}
object.name = ( type === 'JOINT' ) ? data.sid : data.name;
object.matrix.copy( matrix );
object.matrix.decompose( object.position, object.quaternion, object.scale );
return object;
}
function resolveMaterialBinding( keys, instanceMaterials ) {
var materials = [];
for ( var i = 0, l = keys.length; i < l; i ++ ) {
var id = instanceMaterials[ keys[ i ] ];
materials.push( getMaterial( id ) );
}
return materials;
}
function buildObjects( geometries, instanceMaterials ) {
var objects = [];
for ( var type in geometries ) {
var geometry = geometries[ type ];
var materials = resolveMaterialBinding( geometry.materialKeys, instanceMaterials );
// handle case if no materials are defined
if ( materials.length === 0 ) {
if ( type === 'lines' || type === 'linestrips' ) {
materials.push( new THREE.LineBasicMaterial() );
} else {
materials.push( new THREE.MeshPhongMaterial() );
}
}
// regard skinning
var skinning = ( geometry.data.attributes.skinIndex !== undefined );
if ( skinning ) {
for ( var i = 0, l = materials.length; i < l; i ++ ) {
materials[ i ].skinning = true;
}
}
// choose between a single or multi materials (material array)
var material = ( materials.length === 1 ) ? materials[ 0 ] : materials;
// now create a specific 3D object
var object;
switch ( type ) {
case 'lines':
object = new THREE.LineSegments( geometry.data, material );
break;
case 'linestrips':
object = new THREE.Line( geometry.data, material );
break;
case 'triangles':
case 'polylist':
if ( skinning ) {
object = new THREE.SkinnedMesh( geometry.data, material );
} else {
object = new THREE.Mesh( geometry.data, material );
}
break;
}
objects.push( object );
}
return objects;
}
function getNode( id ) {
return getBuild( library.nodes[ id ], buildNode );
}
// visual scenes
function parseVisualScene( xml ) {
var data = {
name: xml.getAttribute( 'name' ),
children: []
};
prepareNodes( xml );
var elements = getElementsByTagName( xml, 'node' );
for ( var i = 0; i < elements.length; i ++ ) {
data.children.push( parseNode( elements[ i ] ) );
}
library.visualScenes[ xml.getAttribute( 'id' ) ] = data;
}
function buildVisualScene( data ) {
var group = new THREE.Group();
group.name = data.name;
var children = data.children;
for ( var i = 0; i < children.length; i ++ ) {
var child = children[ i ];
if ( child.id === null ) {
group.add( buildNode( child ) );
} else {
// if there is an ID, let's try to get the finished build (e.g. joints are already build)
group.add( getNode( child.id ) );
}
}
return group;
}
function getVisualScene( id ) {
return getBuild( library.visualScenes[ id ], buildVisualScene );
}
// scenes
function parseScene( xml ) {
var instance = getElementsByTagName( xml, 'instance_visual_scene' )[ 0 ];
return getVisualScene( parseId( instance.getAttribute( 'url' ) ) );
}
function setupAnimations() {
var clips = library.clips;
if ( isEmpty( clips ) === true ) {
if ( isEmpty( library.animations ) === false ) {
// if there are animations but no clips, we create a default clip for playback
var tracks = [];
for ( var id in library.animations ) {
var animationTracks = getAnimation( id );
for ( var i = 0, l = animationTracks.length; i < l; i ++ ) {
tracks.push( animationTracks[ i ] );
}
}
animations.push( new THREE.AnimationClip( 'default', - 1, tracks ) );
}
} else {
for ( var id in clips ) {
animations.push( getAnimationClip( id ) );
}
}
}
console.time( 'THREE.ColladaLoader' );
if ( text.length === 0 ) {
return { scene: new THREE.Scene() };
}
console.time( 'THREE.ColladaLoader: DOMParser' );
var xml = new DOMParser().parseFromString( text, 'application/xml' );
console.timeEnd( 'THREE.ColladaLoader: DOMParser' );
var collada = getElementsByTagName( xml, 'COLLADA' )[ 0 ];
// metadata
var version = collada.getAttribute( 'version' );
console.log( 'THREE.ColladaLoader: File version', version );
var asset = parseAsset( getElementsByTagName( collada, 'asset' )[ 0 ] );
var textureLoader = new THREE.TextureLoader( this.manager );
textureLoader.setPath( path ).setCrossOrigin( this.crossOrigin );
//
var animations = [];
var kinematics = {};
var count = 0;
//
var library = {
animations: {},
clips: {},
controllers: {},
images: {},
effects: {},
materials: {},
cameras: {},
lights: {},
geometries: {},
nodes: {},
visualScenes: {},
kinematicsModels: {},
kinematicsScenes: {}
};
console.time( 'THREE.ColladaLoader: Parse' );
parseLibrary( collada, 'library_animations', 'animation', parseAnimation );
parseLibrary( collada, 'library_animation_clips', 'animation_clip', parseAnimationClip );
parseLibrary( collada, 'library_controllers', 'controller', parseController );
parseLibrary( collada, 'library_images', 'image', parseImage );
parseLibrary( collada, 'library_effects', 'effect', parseEffect );
parseLibrary( collada, 'library_materials', 'material', parseMaterial );
parseLibrary( collada, 'library_cameras', 'camera', parseCamera );
parseLibrary( collada, 'library_lights', 'light', parseLight );
parseLibrary( collada, 'library_geometries', 'geometry', parseGeometry );
parseLibrary( collada, 'library_nodes', 'node', parseNode );
parseLibrary( collada, 'library_visual_scenes', 'visual_scene', parseVisualScene );
parseLibrary( collada, 'library_kinematics_models', 'kinematics_model', parseKinematicsModel );
parseLibrary( collada, 'scene', 'instance_kinematics_scene', parseKinematicsScene );
console.timeEnd( 'THREE.ColladaLoader: Parse' );
console.time( 'THREE.ColladaLoader: Build' );
buildLibrary( library.animations, buildAnimation );
buildLibrary( library.clips, buildAnimationClip );
buildLibrary( library.controllers, buildController );
buildLibrary( library.images, buildImage );
buildLibrary( library.effects, buildEffect );
buildLibrary( library.materials, buildMaterial );
buildLibrary( library.cameras, buildCamera );
buildLibrary( library.lights, buildLight );
buildLibrary( library.geometries, buildGeometry );
buildLibrary( library.visualScenes, buildVisualScene );
console.timeEnd( 'THREE.ColladaLoader: Build' );
setupAnimations();
setupKinematics();
var scene = parseScene( getElementsByTagName( collada, 'scene' )[ 0 ] );
if ( asset.upAxis === 'Z_UP' ) {
scene.rotation.x = - Math.PI / 2;
}
scene.scale.multiplyScalar( asset.unit );
console.timeEnd( 'THREE.ColladaLoader' );
return {
animations: animations,
kinematics: kinematics,
library: library,
scene: scene
};
}
};
|
'use strict';
var convert = require('./convert'),
func = convert('pad', require('../pad'));
func.placeholder = require('./placeholder');
module.exports = func;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL2NsaWVudC9saWIvbG9kYXNoL2ZwL3BhZC5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLElBQUksVUFBVSxRQUFRLFdBQVIsQ0FBZDtJQUNJLE9BQU8sUUFBUSxLQUFSLEVBQWUsUUFBUSxRQUFSLENBQWYsQ0FEWDs7QUFHQSxLQUFLLFdBQUwsR0FBbUIsUUFBUSxlQUFSLENBQW5CO0FBQ0EsT0FBTyxPQUFQLEdBQWlCLElBQWpCIiwiZmlsZSI6InBhZC5qcyIsInNvdXJjZXNDb250ZW50IjpbInZhciBjb252ZXJ0ID0gcmVxdWlyZSgnLi9jb252ZXJ0JyksXG4gICAgZnVuYyA9IGNvbnZlcnQoJ3BhZCcsIHJlcXVpcmUoJy4uL3BhZCcpKTtcblxuZnVuYy5wbGFjZWhvbGRlciA9IHJlcXVpcmUoJy4vcGxhY2Vob2xkZXInKTtcbm1vZHVsZS5leHBvcnRzID0gZnVuYztcbiJdfQ== |
var env = require('../../test-environment'),
helper = require('./test-helper');
describe('JSON Schema - parse number params', function() {
'use strict';
it('should parse a valid number param',
function(done) {
var schema = {
type: 'number',
multipleOf: 5.5,
minimum: 11,
exclusiveMinimum: true,
maximum: 16.5,
exclusiveMaximum: false
};
var express = helper.integrationTest(schema, 16.5, done);
express.post('/api/test', env.spy(function(req, res, next) {
expect(req.header('Test')).to.equal(16.5);
}));
}
);
it('should parse an optional, unspecified number param',
function(done) {
var schema = {
type: 'number'
};
var express = helper.integrationTest(schema, undefined, done);
express.post('/api/test', env.spy(function(req, res, next) {
expect(req.header('Test')).to.be.undefined;
}));
}
);
it('should parse the default value if no value is specified',
function(done) {
var schema = {
type: 'number',
default: 3.402823e38
};
var express = helper.integrationTest(schema, undefined, done);
express.post('/api/test', env.spy(function(req, res, next) {
expect(req.header('Test')).to.equal(3.402823e38);
}));
}
);
it('should parse the default value if the specified value is blank',
function(done) {
var schema = {
type: 'number',
default: -3.402823e38
};
var express = helper.integrationTest(schema, '', done);
express.post('/api/test', env.spy(function(req, res, next) {
expect(req.header('Test')).to.equal(-3.402823e38);
}));
}
);
it('should throw an error if the value is blank',
function(done) {
var schema = {
type: 'number'
};
var express = helper.integrationTest(schema, '', done);
express.use('/api/test', env.spy(function(err, req, res, next) {
expect(err).to.be.an.instanceOf(Error);
expect(err.status).to.equal(400);
expect(err.message).to.contain('"" is not a valid numeric value');
}));
}
);
it('should throw an error if the value is not a valid number',
function(done) {
var schema = {
type: 'number'
};
var express = helper.integrationTest(schema, 'hello world', done);
express.use('/api/test', env.spy(function(err, req, res, next) {
expect(err).to.be.an.instanceOf(Error);
expect(err.status).to.equal(400);
expect(err.message).to.contain('"hello world" is not a valid numeric value');
}));
}
);
it('should throw an error if the value fails schema validation',
function(done) {
var schema = {
type: 'number',
multipleOf: 87.29
};
var express = helper.integrationTest(schema, '94.8', done);
express.use('/api/test', env.spy(function(err, req, res, next) {
expect(err).to.be.an.instanceOf(Error);
expect(err.status).to.equal(400);
expect(err.message).to.contain('Value 94.8 is not a multiple of 87.29');
}));
}
);
it('should throw an error if the value is above the float maximum',
function(done) {
var schema = {
type: 'number',
format: 'float'
};
var express = helper.integrationTest(schema, '3.402824e+38', done);
express.use('/api/test', env.spy(function(err, req, res, next) {
expect(err).to.be.an.instanceOf(Error);
expect(err.status).to.equal(400);
expect(err.message).to.contain('"3.402824e+38" is not a valid float. Must be between');
}));
}
);
it('should throw an error if the value is below the float minimum',
function(done) {
var schema = {
type: 'number',
format: 'float'
};
var express = helper.integrationTest(schema, '-3.402824e+38', done);
express.use('/api/test', env.spy(function(err, req, res, next) {
expect(err).to.be.an.instanceOf(Error);
expect(err.status).to.equal(400);
expect(err.message).to.contain('"-3.402824e+38" is not a valid float. Must be between');
}));
}
);
it('should throw an error if the value is above the double maximum',
function(done) {
var schema = {
type: 'number',
format: 'double'
};
var express = helper.integrationTest(schema, '1.7976931348629999E+308', done);
express.use('/api/test', env.spy(function(err, req, res, next) {
expect(err).to.be.an.instanceOf(Error);
expect(err.status).to.equal(400);
expect(err.message).to.contain('"1.7976931348629999E+308" is not a valid numeric value');
}));
}
);
it('should throw an error if the value is below the double minimum',
function(done) {
var schema = {
type: 'number',
format: 'double'
};
var express = helper.integrationTest(schema, '-1.7976931348629999E+308', done);
express.use('/api/test', env.spy(function(err, req, res, next) {
expect(err).to.be.an.instanceOf(Error);
expect(err.status).to.equal(400);
expect(err.message).to.contain('"-1.7976931348629999E+308" is not a valid numeric value');
}));
}
);
it('should throw an error if required and not specified',
function(done) {
var schema = {
type: 'number',
required: true
};
var express = helper.integrationTest(schema, undefined, done);
express.use('/api/test', env.spy(function(err, req, res, next) {
expect(err).to.be.an.instanceOf(Error);
expect(err.status).to.equal(400);
expect(err.message).to.contain('Missing required header parameter "Test"');
}));
}
);
});
|
module.exports = function(app) {
app.get('/', function(req, res){
res.redirect('/tests/index.html?hidepassed');
});
app.get('/tests', function(req, res){
res.redirect('/tests/index.html');
});
};
|
// @flow
/**
* React Flip Move
* (c) 2016-present Joshua Comeau
*
* These methods read from and write to the DOM.
* They almost always have side effects, and will hopefully become the
* only spot in the codebase with impure functions.
*/
import { findDOMNode } from 'react-dom';
import type { Component } from 'react';
import { hyphenate } from './helpers';
import type {
Styles,
ClientRect,
GetPosition,
NodeData,
VerticalAlignment,
ConvertedProps,
} from './typings';
export function applyStylesToDOMNode({ domNode, styles }: {
domNode: HTMLElement,
styles: Styles,
}) {
// Can't just do an object merge because domNode.styles is no regular object.
// Need to do it this way for the engine to fire its `set` listeners.
Object.keys(styles).forEach((key) => {
domNode.style.setProperty(hyphenate(key), styles[key]);
});
}
// Modified from Modernizr
export function whichTransitionEvent(): string {
const transitions = {
transition: 'transitionend',
'-o-transition': 'oTransitionEnd',
'-moz-transition': 'transitionend',
'-webkit-transition': 'webkitTransitionEnd',
};
// If we're running in a browserless environment (eg. SSR), it doesn't apply.
// Return a placeholder string, for consistent type return.
if (typeof document === 'undefined') return '';
const el = document.createElement('fakeelement');
const match = Object.keys(transitions).find(t => (
el.style.getPropertyValue(t) !== undefined
));
// If no `transition` is found, we must be running in a browser so ancient,
// React itself won't run. Return an empty string, for consistent type return
return match ? transitions[match] : '';
}
export const getRelativeBoundingBox = ({
childDomNode,
parentDomNode,
getPosition,
}: {
childDomNode: HTMLElement,
parentDomNode: HTMLElement,
getPosition: GetPosition,
}): ClientRect => {
const parentBox = getPosition(parentDomNode);
const { top, left, right, bottom, width, height } = getPosition(childDomNode);
return {
top: top - parentBox.top,
left: left - parentBox.left,
right: parentBox.right - right,
bottom: parentBox.bottom - bottom,
width,
height,
};
};
/** getPositionDelta
* This method returns the delta between two bounding boxes, to figure out
* how many pixels on each axis the element has moved.
*
*/
export const getPositionDelta = ({
childDomNode,
childBoundingBox,
parentBoundingBox,
getPosition,
}: {
childDomNode: HTMLElement,
childBoundingBox: ?ClientRect,
parentBoundingBox: ?ClientRect,
getPosition: GetPosition,
}): [number, number] => {
// TEMP: A mystery bug is sometimes causing unnecessary boundingBoxes to
// remain. Until this bug can be solved, this band-aid fix does the job:
const defaultBox: ClientRect = { top: 0, left: 0, right: 0, bottom: 0, height: 0, width: 0 };
// Our old box is its last calculated position, derived on mount or at the
// start of the previous animation.
const oldRelativeBox = childBoundingBox || defaultBox;
const parentBox = parentBoundingBox || defaultBox;
// Our new box is the new final resting place: Where we expect it to wind up
// after the animation. First we get the box in absolute terms (AKA relative
// to the viewport), and then we calculate its relative box (relative to the
// parent container)
const newAbsoluteBox = getPosition(childDomNode);
const newRelativeBox = {
top: newAbsoluteBox.top - parentBox.top,
left: newAbsoluteBox.left - parentBox.left,
};
return [
oldRelativeBox.left - newRelativeBox.left,
oldRelativeBox.top - newRelativeBox.top,
];
};
/** removeNodeFromDOMFlow
* This method does something very sneaky: it removes a DOM node from the
* document flow, but without actually changing its on-screen position.
*
* It works by calculating where the node is, and then applying styles
* so that it winds up being positioned absolutely, but in exactly the
* same place.
*
* This is a vital part of the FLIP technique.
*/
export const removeNodeFromDOMFlow = (
childData: NodeData,
verticalAlignment: VerticalAlignment
) => {
const { domNode, boundingBox } = childData;
if (!domNode || !boundingBox) {
return;
}
// For this to work, we have to offset any given `margin`.
const computed: CSSStyleDeclaration = window.getComputedStyle(domNode);
// We need to clean up margins, by converting and removing suffix:
// eg. '21px' -> 21
const marginAttrs = ['margin-top', 'margin-left', 'margin-right'];
const margins: {
[string]: number,
} = marginAttrs.reduce((acc, margin) => {
const propertyVal = computed.getPropertyValue(margin);
return {
...acc,
[margin]: Number(propertyVal.replace('px', '')),
};
}, {});
// If we're bottom-aligned, we need to add the height of the child to its
// top offset. This is because, when the container is bottom-aligned, its
// height shrinks from the top, not the bottom. We're removing this node
// from the flow, so the top is going to drop by its height.
const topOffset = verticalAlignment === 'bottom'
? boundingBox.top - boundingBox.height
: boundingBox.top;
const styles: Styles = {
position: 'absolute',
top: `${topOffset - margins['margin-top']}px`,
left: `${boundingBox.left - margins['margin-left']}px`,
right: `${boundingBox.right - margins['margin-right']}px`,
};
applyStylesToDOMNode({ domNode, styles });
};
/** updateHeightPlaceholder
* An optional property to FlipMove is a `maintainContainerHeight` boolean.
* This property creates a node that fills space, so that the parent
* container doesn't collapse when its children are removed from the
* document flow.
*/
export const updateHeightPlaceholder = ({
domNode,
parentData,
getPosition,
}: {
domNode: HTMLElement,
parentData: NodeData,
getPosition: GetPosition,
}) => {
const parentDomNode = parentData.domNode;
const parentBoundingBox = parentData.boundingBox;
if (!parentDomNode || !parentBoundingBox) {
return;
}
// We need to find the height of the container *without* the placeholder.
// Since it's possible that the placeholder might already be present,
// we first set its height to 0.
// This allows the container to collapse down to the size of just its
// content (plus container padding or borders if any).
applyStylesToDOMNode({ domNode, styles: { height: '0' } });
// Find the distance by which the container would be collapsed by elements
// leaving. We compare the freshly-available parent height with the original,
// cached container height.
const originalParentHeight = parentBoundingBox.height;
const collapsedParentHeight = getPosition(parentDomNode).height;
const reductionInHeight = originalParentHeight - collapsedParentHeight;
// If the container has become shorter, update the padding element's
// height to take up the difference. Otherwise set its height to zero,
// so that it has no effect.
const styles: Styles = {
height: reductionInHeight > 0 ? `${reductionInHeight}px` : '0',
};
applyStylesToDOMNode({ domNode, styles });
};
export const getNativeNode = (element: HTMLElement | Component<*, *, *>): ?HTMLElement => {
// When running in a windowless environment, abort!
if (typeof HTMLElement === 'undefined') {
return null;
}
// `element` may already be a native node.
if (element instanceof HTMLElement) {
return element;
}
// While ReactDOM's `findDOMNode` is discouraged, it's the only
// publicly-exposed way to find the underlying DOM node for
// composite components.
const foundNode: ?(Element | Text) = findDOMNode(element);
if (!(foundNode instanceof HTMLElement)) {
// Text nodes are not supported
return null;
}
return foundNode;
};
export const createTransitionString = (index: number, props: ConvertedProps): string => {
let { delay, duration } = props;
const { staggerDurationBy, staggerDelayBy, easing } = props;
delay += index * staggerDelayBy;
duration += index * staggerDurationBy;
const cssProperties = ['transform', 'opacity'];
return cssProperties
.map(prop => `${prop} ${duration}ms ${easing} ${delay}ms`)
.join(', ');
};
|
/*
* /MathJax/jax/output/HTML-CSS/fonts/TeX/Main/Bold/CombDiacritMarks.js
*
* Copyright (c) 2009-2013 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.Hub.Insert(MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS["MathJax_Main-bold"],{768:[706,-503,0,-461,-237],769:[706,-503,0,-339,-115],770:[694,-520,0,-449,-127],771:[694,-552,0,-479,-97],772:[607,-540,0,-495,-81],774:[694,-500,0,-473,-103],775:[695,-525,0,-373,-203],776:[695,-535,0,-479,-97],778:[702,-536,0,-415,-161],779:[714,-511,0,-442,-82],780:[660,-515,0,-445,-131],824:[711,210,0,-734,-161]});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir+"/Main/Bold/CombDiacritMarks.js");
|
var core = require("../pixi"),
BaseTexture = require('./BaseTexture'),
Texture = require('./Texture'),
RenderTarget = require('../renderers/webgl/utils/RenderTarget'),
CanvasBuffer = require('../renderers/canvas/utils/CanvasBuffer'),
math = require('../math'),
CONST = require('../const');
/**
* A RenderTexture is a special texture that allows any Pixi display object to be rendered to it.
*
* __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded
* otherwise black rectangles will be drawn instead.
*
* A RenderTexture takes a snapshot of any Display Object given to its render method. The position
* and rotation of the given Display Objects is ignored. For example:
*
* ```js
* var renderTexture = new PIXI.RenderTexture(800, 600);
* var sprite = PIXI.Sprite.fromImage("spinObj_01.png");
*
* sprite.position.x = 800/2;
* sprite.position.y = 600/2;
* sprite.anchor.x = 0.5;
* sprite.anchor.y = 0.5;
*
* renderTexture.render(sprite);
* ```
*
* The Sprite in this case will be rendered to a position of 0,0. To render this sprite at its actual
* position a Container should be used:
*
* ```js
* var doc = new Container();
*
* doc.addChild(sprite);
*
* renderTexture.render(doc); // Renders to center of renderTexture
* ```
*
* @class
* @extends Texture
* @namespace PIXI
* @param renderer {CanvasRenderer|WebGLRenderer} The renderer used for this RenderTexture
* @param [width=100] {number} The width of the render texture
* @param [height=100] {number} The height of the render texture
* @param [scaleMode] {number} See {@link scaleModes} for possible values
*/
function RenderTexture(renderer, width, height, scaleMode)
{
if (!renderer)
{
throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.');
}
width = width || 100;
height = height || 100;
/**
* The base texture object that this texture uses
*
* @member {BaseTexture}
*/
var baseTexture = new BaseTexture();
baseTexture.width = width;
baseTexture.height = height;
baseTexture.scaleMode = scaleMode || CONST.scaleModes.DEFAULT;
Texture.call(this,
baseTexture,
new math.Rectangle(0, 0, width, height)
);
/**
* The with of the render texture
*
* @member {number}
*/
this.width = width;
/**
* The height of the render texture
*
* @member {number}
*/
this.height = height;
/**
* The framing rectangle of the render texture
*
* @member {Rectangle}
*/
//this._frame = new math.Rectangle(0, 0, this.width, this.height);
/**
* This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering,
* irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases)
*
* @member {Rectangle}
*/
//this.crop = new math.Rectangle(0, 0, this.width, this.height);
/**
* The renderer this RenderTexture uses. A RenderTexture can only belong to one renderer at the moment if its webGL.
*
* @member {CanvasRenderer|WebGLRenderer}
*/
this.renderer = renderer;
if (this.renderer.type === CONST.RENDERER_TYPE.WEBGL)
{
this.renderTarget = new RenderTarget(this.width, this.height);
this.baseTexture._glTexture = this.renderTarget.texture;
}
else
{
this.renderTarget = new CanvasBuffer(this.width, this.height);
this.baseTexture.source = this.renderTarget.canvas;
}
/**
* @member {boolean}
*/
this.valid = true;
this._updateUvs();
}
RenderTexture.prototype = Object.create(Texture.prototype);
RenderTexture.prototype.constructor = RenderTexture;
module.exports = RenderTexture;
/**
* Resizes the RenderTexture.
*
* @param width {number} The width to resize to.
* @param height {number} The height to resize to.
* @param updateBase {boolean} Should the baseTexture.width and height values be resized as well?
*/
RenderTexture.prototype.resize = function (width, height, updateBase)
{
if (width === this.width && height === this.height)
{
return;
}
this.valid = (width > 0 && height > 0);
this.width = this._frame.width = this.crop.width = width;
this.height = this._frame.height = this.crop.height = height;
if (updateBase)
{
this.baseTexture.width = this.width;
this.baseTexture.height = this.height;
}
if (this.renderer.type === CONST.RENDERER_TYPE.WEBGL)
{
this.projection.set(this.width / 2, -this.height / 2);
}
if (!this.valid)
{
return;
}
this.renderTarget.resize(this.width, this.height);
};
/**
* Clears the RenderTexture.
*
*/
RenderTexture.prototype.clear = function ()
{
if (!this.valid)
{
return;
}
this.renderTarget.clear();
};
/**
* Internal method assigned to the `render` property if using a CanvasRenderer.
*
* @private
* @param displayObject {DisplayObject} The display object to render this texture on
* @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering.
* transformations will be restored. Not restoring this information will be a little faster.
*/
RenderTexture.prototype.render = function (displayObject, matrix)
{
if (!this.valid)
{
return;
}
//Let's create a nice matrix to apply to our display object. Frame buffers come in upside down so we need to flip the matrix
var wt = displayObject.worldTransform;
wt.identity();
if (matrix)
{
wt.append(matrix);
}
// Time to update all the children of the displayObject with the new matrix..
displayObject.children.forEach(function(child){
child.updateTransform();
});
this.renderer.renderDisplayObject(displayObject, this.renderer.type === CONST.RENDERER_TYPE.WEBGL ? this.renderTarget : this.renderTarget.context);
if (this.renderer.renderTarget)
{
this.renderer.setRenderTarget(this.renderer.renderTarget);
}
};
RenderTexture.prototype.destroy = function ()
{
Texture.prototype.destroy.call(this, true);
this.renderTarget.destroy();
this.renderer = null;
};
/**
* Will return a HTML Image of the texture
*
* @return {Image}
*/
RenderTexture.prototype.getImage = function ()
{
var image = new Image();
image.src = this.getBase64();
return image;
};
/**
* Will return a a base64 encoded string of this texture. It works by calling RenderTexture.getCanvas and then running toDataURL on that.
*
* @return {string} A base64 encoded string of the texture.
*/
RenderTexture.prototype.getBase64 = function ()
{
return this.getCanvas().toDataURL();
};
/**
* Creates a Canvas element, renders this RenderTexture to it and then returns it.
*
* @return {HTMLCanvasElement} A Canvas element with the texture rendered on.
*/
RenderTexture.prototype.getCanvas = function ()
{
if (this.renderer.type === CONST.RENDERER_TYPE.WEBGL)
{
var gl = core.gl;
var width = this.renderTarget.width;
var height = this.renderTarget.height;
var webGLPixels = new Uint8Array(4 * width * height);
gl.bindFramebuffer(gl.FRAMEBUFFER, this.renderTarget.frameBuffer);
gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webGLPixels);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
var canvas = document.createElement('canvas');
canvas.getContext('2d').putImageData(new ImageData(new Uint8ClampedArray(webGLPixels), width, height), 0, 0);
return canvas;
}
else
{
return this.renderTarget.canvas;
}
};
|
define([
'esri/units',
'esri/geometry/Extent',
'esri/config',
'esri/tasks/GeometryService',
'esri/layers/ImageParameters'
], function(units, Extent, esriConfig, GeometryService, ImageParameters) {
// url to your proxy page, must be on same machine hosting you app. See proxy folder for readme.
esriConfig.defaults.io.proxyUrl = 'proxy/proxy.ashx';
esriConfig.defaults.io.alwaysUseProxy = false;
// url to your geometry server.
esriConfig.defaults.geometryService = new GeometryService('http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer');
//image parameters for dynamic services, set to png32 for higher quality exports.
var imageParameters = new ImageParameters();
imageParameters.format = 'png32';
return {
// used for debugging your app
isDebug: false,
//default mapClick mode, mapClickMode lets widgets know what mode the map is in to avoid multipult map click actions from taking place (ie identify while drawing).
defaultMapClickMode: 'identify',
// map options, passed to map constructor. see: https://developers.arcgis.com/javascript/jsapi/map-amd.html#map1
mapOptions: {
basemap: 'streets',
center: [-96.59179687497497, 39.09596293629694],
zoom: 5,
sliderStyle: 'small'
},
// panes: {
// left: {
// splitter: true
// },
// right: {
// id: 'sidebarRight',
// placeAt: 'outer',
// region: 'right',
// splitter: true,
// collapsible: true
// },
// bottom: {
// id: 'sidebarBottom',
// placeAt: 'outer',
// splitter: true,
// collapsible: true,
// region: 'bottom'
// },
// top: {
// id: 'sidebarTop',
// placeAt: 'outer',
// collapsible: true,
// splitter: true,
// region: 'top'
// }
// },
// collapseButtonsPane: 'center', //center or outer
// operationalLayers: Array of Layers to load on top of the basemap: valid 'type' options: 'dynamic', 'tiled', 'feature'.
// The 'options' object is passed as the layers options for constructor. Title will be used in the legend only. id's must be unique and have no spaces.
// 3 'mode' options: MODE_SNAPSHOT = 0, MODE_ONDEMAND = 1, MODE_SELECTION = 2
operationalLayers: [{
type: 'feature',
url: 'http://services1.arcgis.com/g2TonOxuRkIqSOFx/arcgis/rest/services/MeetUpHomeTowns/FeatureServer/0',
title: 'STLJS Meetup Home Towns',
options: {
id: 'meetupHometowns',
opacity: 1.0,
visible: true,
outFields: ['*'],
mode: 0
},
editorLayerInfos: {
disableGeometryUpdate: false
}
}, {
type: 'feature',
url: 'http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/SanFrancisco/311Incidents/FeatureServer/0',
title: 'San Francisco 311 Incidents',
options: {
id: 'sf311Incidents',
opacity: 1.0,
visible: true,
outFields: ['req_type', 'req_date', 'req_time', 'address', 'district'],
mode: 0
}
}, {
type: 'dynamic',
url: 'http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/PublicSafety/PublicSafetyOperationalLayers/MapServer',
title: 'Louisville Public Safety',
slider: true,
noLegend: false,
collapsed: false,
sublayerToggle: false, //true to automatically turn on sublayers
options: {
id: 'louisvillePubSafety',
opacity: 1.0,
visible: true,
imageParameters: imageParameters
},
identifyLayerInfos: {
layerIds: [2, 4, 5, 8, 12, 21]
}
}, {
type: 'dynamic',
url: 'http://sampleserver6.arcgisonline.com/arcgis/rest/services/DamageAssessment/MapServer',
title: 'Damage Assessment',
slider: true,
noLegend: false,
collapsed: false,
options: {
id: 'DamageAssessment',
opacity: 1.0,
visible: true,
imageParameters: imageParameters
},
layerControlLayerInfos: {
swipe: true
}
}],
// set include:true to load. For titlePane type set position the the desired order in the sidebar
widgets: {
growler: {
include: true,
id: 'growler',
type: 'domNode',
path: 'gis/dijit/Growler',
srcNodeRef: 'growlerDijit',
options: {}
},
geocoder: {
include: true,
id: 'geocoder',
type: 'domNode',
path: 'gis/dijit/Geocoder',
srcNodeRef: 'geocodeDijit',
options: {
map: true,
mapRightClickMenu: true,
geocoderOptions: {
autoComplete: true,
arcgisGeocoder: {
placeholder: 'Enter an address or place'
}
}
}
},
identify: {
include: false,
id: 'identify',
type: 'titlePane',
path: 'gis/dijit/Identify',
title: 'Identify',
open: false,
position: 3,
options: 'config/identify'
},
basemaps: {
include: true,
id: 'basemaps',
type: 'domNode',
path: 'gis/dijit/Basemaps',
srcNodeRef: 'basemapsDijit',
options: 'config/basemaps'
},
mapInfo: {
include: false,
id: 'mapInfo',
type: 'domNode',
path: 'gis/dijit/MapInfo',
srcNodeRef: 'mapInfoDijit',
options: {
map: true,
mode: 'dms',
firstCoord: 'y',
unitScale: 3,
showScale: true,
xLabel: '',
yLabel: '',
minWidth: 286
}
},
scalebar: {
include: true,
id: 'scalebar',
type: 'map',
path: 'esri/dijit/Scalebar',
options: {
map: true,
attachTo: 'bottom-left',
scalebarStyle: 'line',
scalebarUnit: 'dual'
}
},
locateButton: {
include: true,
id: 'locateButton',
type: 'domNode',
path: 'gis/dijit/LocateButton',
srcNodeRef: 'locateButton',
options: {
map: true,
publishGPSPosition: true,
highlightLocation: true,
useTracking: true,
geolocationOptions: {
maximumAge: 0,
timeout: 15000,
enableHighAccuracy: true
}
}
},
overviewMap: {
include: true,
id: 'overviewMap',
type: 'map',
path: 'esri/dijit/OverviewMap',
options: {
map: true,
attachTo: 'bottom-right',
color: '#0000CC',
height: 100,
width: 125,
opacity: 0.30,
visible: false
}
},
homeButton: {
include: true,
id: 'homeButton',
type: 'domNode',
path: 'esri/dijit/HomeButton',
srcNodeRef: 'homeButton',
options: {
map: true,
extent: new Extent({
xmin: -180,
ymin: -85,
xmax: 180,
ymax: 85,
spatialReference: {
wkid: 4326
}
})
}
},
legend: {
include: true,
id: 'legend',
type: 'titlePane',
path: 'esri/dijit/Legend',
title: 'Legend',
open: false,
position: 0,
options: {
map: true,
legendLayerInfos: true
}
},
layerControl: {
include: true,
id: 'layerControl',
type: 'titlePane',
path: 'gis/dijit/LayerControl',
title: 'Layers',
open: false,
position: 0,
options: {
map: true,
layerControlLayerInfos: true,
separated: true,
vectorReorder: true,
overlayReorder: true
}
},
gotocoord: {
include: true,
id: 'goto',
type: 'titlePane',
canFloat: true,
position: 1,
path: 'viewer/dijit/Goto/Goto',
title: 'Go To Coordinate',
options: {
map: true
}
},
dnd: {
include: true,
id: 'dnd',
type: 'titlePane',
canFloat: true,
position: 2,
path: 'viewer/dijit/DnD/DnD',
title: 'Drag and Drop',
options: {
map: true
}
},
nearby: {
include: true,
id: 'nearby',
type: 'titlePane',
canFloat: true,
path: 'viewer/dijit/Nearby/Nearby',
title: 'Nearby',
open: false,
position: 5,
options: {
map: true,
mapClickMode: true
}
},
help: {
include: true,
id: 'help',
type: 'floating',
path: 'gis/dijit/Help',
title: 'Help',
options: {}
},
navhash: {
include: true,
id: 'navhash',
type: 'invisible',
path: 'viewer/dijit/MapNavigationHash/MapNavigationHash',
title: 'Map Navigation Hash',
options: {
map: true
}
}
}
};
});
|
var a = '123'; // not 1
function test() { // not 2
return a; // not 3
}
if (typeof true === "boolean") { // not 6
var b = test(); // not 7
} |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S12.10_A3.5_T3;
* @section: 12.10;
* @assertion: No matter how control leaves the embedded 'Statement',
* the scope chain is always restored to its former state;
* @description: Using "with" statement within "for-in" statement, leading to completion by exception;
* @strict_mode_negative
*/
this.p1 = 1;
var result = "result";
var myObj = {
p1: 'a',
value: 'myObj_value',
valueOf : function(){return 'obj_valueOf';}
}
try {
for(var prop in myObj){
with(myObj){
throw value;
p1 = 'x1';
}
}
} catch(e){
result = p1;
}
//////////////////////////////////////////////////////////////////////////////
//CHECK#1
if(result !== 1){
$ERROR('#1: result === 1. Actual: result ==='+ result );
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//CHECK#2
if(p1 !== 1){
$ERROR('#2: p1 === 1. Actual: p1 ==='+ p1 );
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//CHECK#3
if(myObj.p1 !== "a"){
$ERROR('#3: myObj.p1 === "a". Actual: myObj.p1 ==='+ myObj.p1 );
}
//
//////////////////////////////////////////////////////////////////////////////
|
// vim: ts=4:sw=4:et
var localFile, reader;
var Hour = new Timespan("Hour", 1/24);
var Day = new Timespan("Day", 1);
var Week = new Timespan("Week", 7);
var Month = new Timespan("Month", 30);
var Year = new Timespan("Year", 365);
var refreshRate = 30;
var timespans = [];
var summaryCoinRate, summaryCoin;
var earningsOutputCoinRate, earningsOutputCoin;
var outputCurrencyDisplayMode = 'all'
var validOutputCurrencyDisplayModes = ['all', 'summary'];
var effRateMode = 'lentperc';
var validEffRateModes = ['lentperc', 'onlyfee'];
// BTC DisplayUnit
var BTC = new BTCDisplayUnit("BTC", 1);
var mBTC = new BTCDisplayUnit("mBTC", 1000);
var Bits = new BTCDisplayUnit("Bits", 1000000);
var Satoshi = new BTCDisplayUnit("Satoshi", 100000000);
var displayUnit = BTC;
var btcDisplayUnitsModes = [BTC, mBTC, Bits, Satoshi];
function updateJson(data) {
$('#status').text(data.last_status);
$('#updated').text(data.last_update);
$('#title').text(data.exchange + ' ' + data.label)
document.title = data.exchange + ' ' + data.label
var rowCount = data.log.length;
var table = $('#logtable');
table.empty();
for (var i = rowCount - 1; i >=0; i--) {
table.append($('<tr/>').append($('<td colspan="2" />').text(data.log[i])));
}
updateOutputCurrency(data.outputCurrency);
updateRawValues(data.raw_data);
updateNavbar(data.plugins);
}
function updateNavbar(plugins) {
// No plugins enabled. Nothing to do.
if (plugins == undefined || plugins.enabled == undefined)
return;
var enabled = plugins.enabled
var navbar = $('#navbar-menu')
var navbarItems = Array()
// Build list of navbar items
$.each($('#navbar-menu li'), function() {
if ($(this).attr('id') != undefined) {
navbarItems.push($(this).attr('id').toLowerCase())
}
});
// iterate through enabled plugins; look for 'navbar': true
$.each(enabled, function(i, val) {
var v = val.toLowerCase()
if ((v in plugins) && ('navbar' in plugins[v]) && (plugins[v]['navbar'])) {
// this plugin wants a link in the navbar.
// Search current navbar and add if needed
var newId = v + "-navbar"
if (navbarItems.indexOf(newId) < 0) {
var newItem = '<li id="' + newId + '" data-toggle="collapse" data-target=".navbar-collapse.in">'
newItem += '<a href="' + v + '.html">' + val + '</a></li>'
navbar.prepend(newItem);
}
}
});
}
function updateOutputCurrency(outputCurrency){
var OutCurr = Object.keys(outputCurrency);
summaryCoin = outputCurrency['currency'];
summaryCoinRate = parseFloat(outputCurrency['highestBid']);
// switch between using outputCoin for summary only or all lending coins earnings
if(outputCurrencyDisplayMode == 'all') {
earningsOutputCoin = summaryCoin;
earningsOutputCoinRate = summaryCoinRate;
} else {
earningsOutputCoin = 'BTC'
earningsOutputCoinRate = 1;
}
}
// prints a pretty float with accuracy.
// above zero accuracy will be used for float precision
// below zero accuracy will indicate precision after must significat digit
// strips trailing zeros
function prettyFloat(value, accuracy) {
var precision = Math.round(Math.log10(value));
var result = precision < 0 ? value.toFixed(Math.min((accuracy - precision), 8)) : value.toFixed(accuracy);
return isNaN(result) ? '0' : result.replace(/(?:\.0+|(\.\d+?)0+)$/, '$1');
}
function printFloat(value, precision) {
var multiplier = Math.pow(10, precision);
var result = Math.round(value * multiplier) / multiplier;
return result = isNaN(result) ? '0' : result.toFixed(precision);
}
function updateRawValues(rawData){
var table = document.getElementById("detailsTable");
table.innerHTML = "";
var currencies = Object.keys(rawData);
var totalBTCEarnings = {};
for (var keyIndex = 0; keyIndex < currencies.length; ++keyIndex)
{
var currency = currencies[keyIndex];
var btcMultiplier = currency == 'BTC' ? displayUnit.multiplier : 1;
var averageLendingRate = parseFloat(rawData[currency]['averageLendingRate']);
var lentSum = parseFloat(rawData[currency]['lentSum']);
var totalCoins = parseFloat(rawData[currency]['totalCoins']);
var maxToLend = parseFloat(rawData[currency]['maxToLend']);
var highestBidBTC = parseFloat(rawData[currency]['highestBid']);
if (currency == 'BTC') {
// no bids for BTC provided by poloniex
// this is added so BTC can be handled like other coins for conversions
highestBidBTC = 1;
}
var couple = rawData[currency]['couple'];
if (!isNaN(averageLendingRate) && !isNaN(lentSum) || !isNaN(totalCoins))
{
// cover cases where totalCoins isn't updated because all coins are lent
if (isNaN(totalCoins) && !isNaN(lentSum)) {
totalCoins = lentSum;
}
var rate = +averageLendingRate * 0.85 / 100; // 15% goes to exchange fees
var earnings = '';
var earningsSummaryCoin = '';
timespans.forEach(function(timespan) {
// init totalBTCEarnings
if (isNaN(totalBTCEarnings[timespan.name])) {
totalBTCEarnings[timespan.name] = 0;
}
// calculate coin earnings
timespanEarning = timespan.calcEarnings(lentSum, rate);
earnings += timespan.formatEarnings(currency, timespanEarning, true);
// sum BTC earnings for all coins
if(!isNaN(highestBidBTC)) {
timespanEarningBTC = timespan.calcEarnings(lentSum * highestBidBTC, rate);
totalBTCEarnings[timespan.name] += timespanEarningBTC;
if(currency != earningsOutputCoin) {
earningsSummaryCoin += timespan.formatEarnings(earningsOutputCoin, timespanEarningBTC * earningsOutputCoinRate);
}
}
});
var effRateModePerc = 1;
if (effRateMode == 'lentperc')
effRateModePerc = lentSum / totalCoins;
var effectiveRate = rate * 100 * effRateModePerc;
var yearlyRate = rate * 100 * 365 * effRateModePerc; // no reinvestment
var yearlyRateComp = (Math.pow(rate + 1, 365) - 1) * 100 * effRateModePerc; // with daily reinvestment
var lentPerc = lentSum / totalCoins * 100;
var lentPercLendable = lentSum / maxToLend * 100;
function makeTooltip(title, text) {
return ' <a data-toggle="tooltip" class="plb-tooltip" title="' + title + '">' + text + '</a>';
}
var avgRateText = makeTooltip("Average loan rate, simple average calculation of active loans rates.", "Avg.");
var effRateText;
if (effRateMode == 'lentperc')
effRateText = makeTooltip("Effective loan rate, considering lent precentage and exchange 15% fee.", "Eff.");
else
effRateText = makeTooltip("Effective loan rate, considering exchange 15% fee.", "Eff.");
var compoundRateText = makeTooltip("Compound rate, the result of reinvesting the interest.", "Comp.");
var lentStr = 'Lent ' + printFloat(lentSum * btcMultiplier, 4) +' of ' + printFloat(totalCoins * btcMultiplier, 4) + ' (' + printFloat(lentPerc, 2) + '%)';
if (totalCoins != maxToLend) {
lentStr += ' <b>Total</b><br/>Lent ' + printFloat(lentSum * btcMultiplier, 4) + ' of ' + printFloat(maxToLend * btcMultiplier, 4) + ' (' + printFloat(lentPercLendable, 2) + '%) <b>Lendable</b>';
}
var displayCurrency = currency == 'BTC' ? displayUnit.name : currency;
var currencyStr = "<b>" + displayCurrency + "</b>";
if(!isNaN(highestBidBTC) && earningsOutputCoin != currency) {
currencyStr += "<br/>1 "+ displayCurrency + " = " + prettyFloat(earningsOutputCoinRate * highestBidBTC / btcMultiplier , 2) + ' ' + earningsOutputCoin;
}
var rowValues = [currencyStr, lentStr,
"<div class='inlinediv' >" + printFloat(averageLendingRate, 5) + '% Day' + avgRateText + '<br/>'
+ printFloat(effectiveRate, 5) + '% Day' + effRateText + '<br/></div>'
+ "<div class='inlinediv' >" + printFloat(yearlyRate, 2) + '% Year<br/>'
+ printFloat(yearlyRateComp, 2) + '% Year' + compoundRateText + "</div>" ];
// print coin status
var row = table.insertRow();
for (var i = 0; i < rowValues.length; ++i) {
var cell = row.appendChild(document.createElement("td"));
cell.innerHTML = rowValues[i];
cell.style.verticalAlign = "text-top";
if (i == 0) {
cell.setAttribute("width", "20%");
}
}
$(row).find('[data-toggle="tooltip"]').tooltip();
var earningsColspan = rowValues.length - 1;
// print coin earnings
var row = table.insertRow();
if (lentSum > 0) {
var cell1 = row.appendChild(document.createElement("td"));
cell1.innerHTML = "<span class='hidden-xs'>"+ displayCurrency +"<br/></span>Est. "+ compoundRateText +"<br/>Earnings";
var cell2 = row.appendChild(document.createElement("td"));
cell2.setAttribute("colspan", earningsColspan);
if (earningsSummaryCoin != '') {
cell2.innerHTML = "<div class='inlinediv' >" + earnings + "<br/></div><div class='inlinediv' style='padding-right:0px'>"+ earningsSummaryCoin + "</div>";
} else {
cell2.innerHTML = "<div class='inlinediv' >" + earnings + "</div>";
}
}
}
}
// add headers
var thead = table.createTHead();
// show account summary
if (currencies.length > 1 || summaryCoin != earningsOutputCoin) {
earnings = '';
timespans.forEach(function(timespan) {
earnings += timespan.formatEarnings( summaryCoin, totalBTCEarnings[timespan.name] * summaryCoinRate);
});
var row = thead.insertRow(0);
var cell = row.appendChild(document.createElement("th"));
cell.innerHTML = "Account<br/>Estimated<br/>Earnings";
cell.style.verticalAlign = "text-top";
cell = row.appendChild(document.createElement("th"));
cell.setAttribute("colspan", 2);
cell.innerHTML = earnings;
}
}
function handleLocalFile(file) {
localFile = file;
reader = new FileReader();
reader.onload = function(e) {
updateJson(JSON.parse(reader.result));
};
reader.readAsText(localFile, 'utf-8');
}
function loadData() {
if (localFile) {
reader.readAsText(localFile, 'utf-8');
setTimeout('loadData()', refreshRate * 1000)
} else {
// expect the botlog.json to be in the same folder on the webserver
var file = 'botlog.json';
$.getJSON(file, function (data) {
updateJson(data);
// reload every 30sec
setTimeout('loadData()', refreshRate * 1000)
}).fail( function(d, textStatus, error) {
$('#status').text("getJSON failed, status: " + textStatus + ", error: "+error);
// retry after 60sec
setTimeout('loadData()', 60000)
});;
}
}
function Timespan(name, multiplier) {
this.name = name;
this.multiplier = multiplier;
this.calcEarnings = function(sum, rate) {
return sum * Math.pow(1 + rate, multiplier) - sum;
};
this.formatEarnings = function(currency, earnings, minimize_currency_xs) {
if (currency == "BTC" && this == Hour) {
return printFloat(earnings * 100000000, 0) + " Satoshi / " + name + "<br/>";
} else {
var currencyClass = '';
if (minimize_currency_xs) {
currencyClass = 'hidden-xs';
}
if (currency == "BTC") {
return displayUnit.formatValue(earnings) + " <span class=" + currencyClass + ">" + displayUnit.name + "</span> / " + name + "<br/>"
} else if (currency == "USD" || currency == "USDT" || currency == "EUR") {
return prettyFloat(earnings, 2) + " <span class=" + currencyClass + ">" + currency + "</span> / "+ name + "<br/>";
} else {
return printFloat(earnings, 8) + " <span class=" + currencyClass + ">" + currency + "</span> / "+ name + "<br/>";
}
}
};
}
function BTCDisplayUnit(name, multiplier) {
this.name = name;
this.multiplier = multiplier;
this.precision = Math.log10(multiplier);
this.formatValue = function(value) {
return printFloat(value * this.multiplier, 8 - this.precision);
}
}
function setEffRateMode() {
var q = location.search.match(/[\?&]effrate=[^&]+/);
if (q) {
//console.log('Got effective rate mode from URI');
effRateMode = q[0].split('=')[1];
} else {
if (localStorage.effRateMode) {
//console.log('Got effective rate mode from localStorage');
effRateMode = localStorage.effRateMode;
}
}
if (validEffRateModes.indexOf(effRateMode) == -1) {
console.error(effRateMode + ' is not valid effective rate mode! Valid values are ' + validModes);
effRateMode = validEffRateModes[0];
}
localStorage.effRateMode = effRateMode;
$("input[name='effRateMode'][value='"+ effRateMode +"']").prop('checked', true);;
console.log('Effective rate mode: ' + effRateMode);
}
function setBTCDisplayUnit() {
var q = location.search.match(/[\?&]displayUnit=[^&]+/);
var displayUnitText = 'BTC';
if (q) {
//console.log('Got displayUnitText from URI');
displayUnitText = q[0].split('=')[1];
} else {
if (localStorage.displayUnitText) {
//console.log('Got displayUnitText from localStorage');
displayUnitText = localStorage.displayUnitText;
}
}
$("input[name='btcDisplayUnit'][value='"+ displayUnitText +"']").prop('checked', true);;
btcDisplayUnitsModes.forEach(function(unit) {
if(unit.name == displayUnitText) {
displayUnit = unit;
localStorage.displayUnitText = displayUnitText;
}
})
console.log('displayUnitText: ' + displayUnitText);
}
function setOutputCurrencyDisplayMode() {
var q = location.search.match(/[\?&]earningsInOutputCurrency=[^&]+/);
var outputCurrencyDisplayModeText = 'all';
if (q) {
outputCurrencyDisplayModeText = q[0].split('=')[1];
} else {
if (localStorage.outputCurrencyDisplayModeText) {
outputCurrencyDisplayModeText = localStorage.outputCurrencyDisplayModeText;
}
}
$("input[name='outputCurrencyDisplayMode'][value='"+ outputCurrencyDisplayModeText +"']").prop('checked', true);;
validOutputCurrencyDisplayModes.forEach(function(mode) {
if(mode == outputCurrencyDisplayModeText) {
outputCurrencyDisplayMode = mode;
localStorage.outputCurrencyDisplayModeText = outputCurrencyDisplayModeText;
}
})
console.log('outputCurrencyDisplayMode: ' + outputCurrencyDisplayModeText);
}
function loadSettings() {
// Refresh rate
refreshRate = localStorage.getItem('refreshRate') || 30
$('#refresh_interval').val(refreshRate)
// Time spans
var timespanNames = JSON.parse(localStorage.getItem('timespanNames')) || ["Year", "Month", "Week", "Day", "Hour"]
timespans = [Year, Month, Week, Day, Hour].filter(function(t) {
// filters out timespans not specified
return timespanNames.indexOf(t.name) !== -1;
});
timespanNames.forEach(function(t) {
$('input[data-timespan="' + t + '"]').prop('checked', true);
});
}
function doSave() {
// Validation
var tempRefreshRate = $('#refresh_interval').val()
if(tempRefreshRate < 10 || tempRefreshRate > 60) {
alert('Please input a value between 10 and 60 for refresh rate')
return false
}
// Refresh rate
localStorage.setItem('refreshRate', tempRefreshRate)
// Time spans
var timespanNames = [];
$('input[type="checkbox"]:checked').each(function(i, c){
timespanNames.push($(c).attr('data-timespan'));
});
localStorage.setItem('timespanNames', JSON.stringify(timespanNames))
// Bitcoin Display Unit
localStorage.displayUnitText = $('input[name="btcDisplayUnit"]:checked').val();
btcDisplayUnitsModes.forEach(function(unit) {
if(unit.name == localStorage.displayUnitText) {
displayUnit = unit;
}
})
// OutputCurrencyDisplayMode
localStorage.outputCurrencyDisplayModeText = $('input[name="outputCurrencyDisplayMode"]:checked').val();
if(validOutputCurrencyDisplayModes.indexOf(localStorage.outputCurrencyDisplayModeText) !== -1) {
outputCurrencyDisplayMode = localStorage.outputCurrencyDisplayModeText;
}
//Effective rate calculation
localStorage.effRateMode = $('input[name="effRateMode"]:checked').val();
if(validEffRateModes.indexOf(localStorage.effRateMode) !== -1) {
effRateMode = localStorage.effRateMode;
}
toastr.success("Settings saved!");
$('#settings_modal').modal('hide');
// Now we actually *use* these settings!
update();
}
function update() {
loadSettings();
setEffRateMode();
setBTCDisplayUnit();
setOutputCurrencyDisplayMode();
loadData();
if (window.location.protocol == "file:") {
$('#file').show();
}
}
// https://github.com/twbs/bootstrap/issues/14040#issuecomment-253840676
function bsNavbarBugWorkaround() {
var nb = $('nav.navbar-fixed-top');
$('.modal').on('show.bs.modal', function () {
nb.width(nb.width());
}).on('hidden.bs.modal', function () {
nb.width(nb.width('auto'));
});
}
$(document).ready(function () {
toastr.options = {
"positionClass": "toast-top-center"
}
update();
bsNavbarBugWorkaround();
});
|
function foo(foo, qux = (() => {
var _foo$bar;
return (_foo$bar = foo.bar) != null ? _foo$bar : "qux";
})()) {}
function bar(bar, qux = bar != null ? bar : "qux") {}
|
var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
var lineChartData = {
labels : ["Jan","Feb","Mar","Apr","May","June","July","Aug","Sep","Oct","Nov","Dec"],
datasets : [
{
label: "My First dataset",
fillColor : "rgba(74,125,254,0.4)",
strokeColor : "rgba(255,255,255,1)",
pointColor : "rgba(255,255,255,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(181,181,181,1)",
data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
},
{
label: "My Second dataset",
fillColor : "rgba(144,93,209,0.4)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(151,187,205,1)",
data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
}
]
}
window.onload = function(){
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {
responsive: true
});
} |
"use strict"
var pack = require('../../common/package');
var client = {
entry: pack.get('paths:bin') + 'client-test.js'
};
var server = function (folder) {
return {
entry: ['./**/__test__/**/*.js', '!./client/**']
};
};
var config = {
client: client,
server: server
};
module.exports = config;
|
import Story from "database/model/Story"
import checkUser from "core/auth/checkUser"
async function addChapter(_, {storyId, chapter}, ctx) {
const viewer = ctx.state.user.id
return await Story.addOneChapter(viewer, storyId, chapter)
}
export default checkUser(addChapter)
|
/*
* grunt-cmd-concat
* https://github.com/spmjs/grunt-cmd-concat
*
* Copyright (c) 2013 Hsiaoming Yang
* Licensed under the MIT license.
*/
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
concat: {
self: {
files: {
'tmp/self.js': ['demo/self.js', 'demo/relative.js']
}
},
relative: {
options: {
include: 'relative'
},
files: {
// it will auto concat demo/self.js
'tmp/relative.js': ['demo/relative.js']
}
},
all: {
options: {
include: 'all',
// the modules path
paths: ['assets']
},
files: {
// it will include all dependencies
// demo/all.js demo/relative.js demo/self.js assets/foo.js
'tmp/all.js': ['demo/all.js']
}
}
}
});
// Actually load this plugin's task(s).
grunt.loadTasks('../tasks');
// for real project:
// grunt.loadNpmTasks('grunt-cmd-concat')
// By default, lint and run all tests.
grunt.registerTask('default', ['concat']);
};
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const q = require("smartq");
const paths = require("../npmts.paths");
const plugins = require("./mod.plugins");
const mod_check_1 = require("../mod_compile/mod.check");
exports.run = function (configArg) {
let done = q.defer();
let config = configArg;
plugins.beautylog.ora.text('now looking at ' + 'required assets');
if (config.cli === true) {
let mainJsPath = mod_check_1.projectInfo.packageJson.main;
let cliJsString = plugins.smartfile.fs.toStringSync(plugins.path.join(paths.npmtsAssetsDir, 'cli.js'));
cliJsString = cliJsString.replace('{{pathToIndex}}', mainJsPath);
plugins.smartfile.memory.toFsSync(cliJsString, plugins.path.join(paths.distDir, 'cli.js'));
plugins.beautylog.ok('installed CLI assets!');
done.resolve(config);
}
else {
plugins.beautylog.ok('No additional assets required!');
done.resolve(config);
}
return done.promise;
};
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M2 22h20V2L2 22z"
}), 'SignalCellular4BarOutlined'); |
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.ajaxform = factory();
}
}(this, function() {
/**
* @preserve
* Author: http://mrhenry.be
*
* How to use:
*
* var Ajaxform = require('./ajaxform'),
* formContainer = $('.parent-of-form');
*
* new Ajaxform(formContainer);
*
* Be sure that the form_container only contains 1 form
*/
'use strict';
/**
* jQuery function
*
* @param {Object} options
*
* @return {jQuery array}
*/
$.fn.ajaxform = function(options) {
return this.each(function() {
if ( !$.data(this, 'ajaxform') ) {
$.data(this, 'ajaxform', new Ajaxform( $(this), options));
}
});
}
/**
* @constructor
*
* @param {jQuery element} element
* @param {Object} options
*
* @return {Ajaxform}
*/
function Ajaxform($element, options) {
this.$element = $element;
this.$form = this.$element.find('form').first();
this.$token = $('<input type="hidden" name="token" value="' + options.token + '">');
this.busy = false;
if ( options.callback === undefined || !$.isFunction(options.callback) ) {
this.callback = function(){};
} else {
this.callback = options.callback;
}
this.init();
}
/**
* Initialize
*/
Ajaxform.prototype.init = function() {
var _this = this;
// Append security token
_this.$form.append( _this.$token );
// Form submit event
_this.$element.on('submit', 'form', $.proxy(this.onSubmit, this));
};
/**
* Form submit handler
*
* @param {jQuery event} e
*/
Ajaxform.prototype.onSubmit = function(e) {
if ( this.busy ) {
return;
}
e.preventDefault();
// Act busy
this.busy = true;
this.$form.addClass('busy');
// Make ajax request
$.ajax({
data: this.$form.serialize(),
error: $.proxy(this.requestError, this),
success: $.proxy(this.requestSuccess, this),
type: this.$form.attr('method'),
url: this.$form.attr('action')
});
};
/**
* Request sucess handler
*
* @param {String} responseData
*/
Ajaxform.prototype.requestSuccess = function(responseData) {
var _this = this,
$responseData = Ajaxform.cleanResponse( responseData ),
$newForm = $responseData.find("form").first();
// Stop acting busy
_this.busy = false;
_this.$form.removeClass('busy');
// Replace old form with new form
_this.$form.replaceWith($newForm);
_this.$form = $newForm;
// Execute callback
_this.callback();
};
/**
* Request error handler
*
* Show an alert message and
* removes the busy state
*
* @param {Object} jqXHR
* @param {String} textStatus
* @param {String} errorThrown
*/
Ajaxform.prototype.requestError = function(jqXHR, textStatus, errorThrown) {
window.alert("Oops, something went wrong. Please try again.");
// Stop acting busy
this.busy = false;
this.$form.removeClass('busy');
};
/*
* Strip out script tags of jQuery ajax response data and
* returns a traversable jQuery object
*
* @return [jQuery object]
*/
Ajaxform.cleanResponse = function(responseData) {
var regexScript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
return $('<div>').append(responseData.replace(regexScript, ''));
};
return Ajaxform;
}));
|
/*
* angular-ui-bootstrap
* http://angular-ui.github.io/bootstrap/
* Version: 0.10.0 - 2014-01-13
* License: MIT
*/
angular.module("ui.bootstrap", ["ui.bootstrap.tpls", "ui.bootstrap.transition","ui.bootstrap.collapse","ui.bootstrap.accordion","ui.bootstrap.alert","ui.bootstrap.bindHtml","ui.bootstrap.buttons","ui.bootstrap.carousel","ui.bootstrap.position","ui.bootstrap.datepicker","ui.bootstrap.dropdownToggle","ui.bootstrap.modal","ui.bootstrap.pagination","ui.bootstrap.tooltip","ui.bootstrap.popover","ui.bootstrap.progressbar","ui.bootstrap.rating","ui.bootstrap.tabs","ui.bootstrap.timepicker","ui.bootstrap.typeahead"]);
angular.module("ui.bootstrap.tpls", ["template/accordion/accordion-group.html","template/accordion/accordion.html","template/alert/alert.html","template/carousel/carousel.html","template/carousel/slide.html","template/datepicker/datepicker.html","template/datepicker/popup.html","template/modal/backdrop.html","template/modal/window.html","template/pagination/pager.html","template/pagination/pagination.html","template/tooltip/tooltip-html-unsafe-popup.html","template/tooltip/tooltip-popup.html","template/popover/popover.html","template/progressbar/bar.html","template/progressbar/progress.html","template/progressbar/progressbar.html","template/rating/rating.html","template/tabs/tab.html","template/tabs/tabset.html","template/timepicker/timepicker.html","template/typeahead/typeahead-match.html","template/typeahead/typeahead-popup.html"]);
angular.module('ui.bootstrap.transition', [])
/**
* $transition service provides a consistent interface to trigger CSS 3 transitions and to be informed when they complete.
* @param {DOMElement} element The DOMElement that will be animated.
* @param {string|object|function} trigger The thing that will cause the transition to start:
* - As a string, it represents the css class to be added to the element.
* - As an object, it represents a hash of style attributes to be applied to the element.
* - As a function, it represents a function to be called that will cause the transition to occur.
* @return {Promise} A promise that is resolved when the transition finishes.
*/
.factory('$transition', ['$q', '$timeout', '$rootScope', function($q, $timeout, $rootScope) {
var $transition = function(element, trigger, options) {
options = options || {};
var deferred = $q.defer();
var endEventName = $transition[options.animation ? "animationEndEventName" : "transitionEndEventName"];
var transitionEndHandler = function(event) {
$rootScope.$apply(function() {
element.unbind(endEventName, transitionEndHandler);
deferred.resolve(element);
});
};
if (endEventName) {
element.bind(endEventName, transitionEndHandler);
}
// Wrap in a timeout to allow the browser time to update the DOM before the transition is to occur
$timeout(function() {
if ( angular.isString(trigger) ) {
element.addClass(trigger);
} else if ( angular.isFunction(trigger) ) {
trigger(element);
} else if ( angular.isObject(trigger) ) {
element.css(trigger);
}
//If browser does not support transitions, instantly resolve
if ( !endEventName ) {
deferred.resolve(element);
}
});
// Add our custom cancel function to the promise that is returned
// We can call this if we are about to run a new transition, which we know will prevent this transition from ending,
// i.e. it will therefore never raise a transitionEnd event for that transition
deferred.promise.cancel = function() {
if ( endEventName ) {
element.unbind(endEventName, transitionEndHandler);
}
deferred.reject('Transition cancelled');
};
return deferred.promise;
};
// Work out the name of the transitionEnd event
var transElement = document.createElement('trans');
var transitionEndEventNames = {
'WebkitTransition': 'webkitTransitionEnd',
'MozTransition': 'transitionend',
'OTransition': 'oTransitionEnd',
'transition': 'transitionend'
};
var animationEndEventNames = {
'WebkitTransition': 'webkitAnimationEnd',
'MozTransition': 'animationend',
'OTransition': 'oAnimationEnd',
'transition': 'animationend'
};
function findEndEventName(endEventNames) {
for (var name in endEventNames){
if (transElement.style[name] !== undefined) {
return endEventNames[name];
}
}
}
$transition.transitionEndEventName = findEndEventName(transitionEndEventNames);
$transition.animationEndEventName = findEndEventName(animationEndEventNames);
return $transition;
}]);
angular.module('ui.bootstrap.collapse', ['ui.bootstrap.transition'])
.directive('collapse', ['$transition', function ($transition, $timeout) {
return {
link: function (scope, element, attrs) {
var initialAnimSkip = true;
var currentTransition;
function doTransition(change) {
var newTransition = $transition(element, change);
if (currentTransition) {
currentTransition.cancel();
}
currentTransition = newTransition;
newTransition.then(newTransitionDone, newTransitionDone);
return newTransition;
function newTransitionDone() {
// Make sure it's this transition, otherwise, leave it alone.
if (currentTransition === newTransition) {
currentTransition = undefined;
}
}
}
function expand() {
if (initialAnimSkip) {
initialAnimSkip = false;
expandDone();
} else {
element.removeClass('collapse').addClass('collapsing');
doTransition({ height: element[0].scrollHeight + 'px' }).then(expandDone);
}
}
function expandDone() {
element.removeClass('collapsing');
element.addClass('collapse in');
element.css({height: 'auto'});
}
function collapse() {
if (initialAnimSkip) {
initialAnimSkip = false;
collapseDone();
element.css({height: 0});
} else {
// CSS transitions don't work with height: auto, so we have to manually change the height to a specific value
element.css({ height: element[0].scrollHeight + 'px' });
//trigger reflow so a browser realizes that height was updated from auto to a specific value
var x = element[0].offsetWidth;
element.removeClass('collapse in').addClass('collapsing');
doTransition({ height: 0 }).then(collapseDone);
}
}
function collapseDone() {
element.removeClass('collapsing');
element.addClass('collapse');
}
scope.$watch(attrs.collapse, function (shouldCollapse) {
if (shouldCollapse) {
collapse();
} else {
expand();
}
});
}
};
}]);
angular.module('ui.bootstrap.accordion', ['ui.bootstrap.collapse'])
.constant('accordionConfig', {
closeOthers: true
})
.controller('AccordionController', ['$scope', '$attrs', 'accordionConfig', function ($scope, $attrs, accordionConfig) {
// This array keeps track of the accordion groups
this.groups = [];
// Ensure that all the groups in this accordion are closed, unless close-others explicitly says not to
this.closeOthers = function(openGroup) {
var closeOthers = angular.isDefined($attrs.closeOthers) ? $scope.$eval($attrs.closeOthers) : accordionConfig.closeOthers;
if ( closeOthers ) {
angular.forEach(this.groups, function (group) {
if ( group !== openGroup ) {
group.isOpen = false;
}
});
}
};
// This is called from the accordion-group directive to add itself to the accordion
this.addGroup = function(groupScope) {
var that = this;
this.groups.push(groupScope);
groupScope.$on('$destroy', function (event) {
that.removeGroup(groupScope);
});
};
// This is called from the accordion-group directive when to remove itself
this.removeGroup = function(group) {
var index = this.groups.indexOf(group);
if ( index !== -1 ) {
this.groups.splice(this.groups.indexOf(group), 1);
}
};
}])
// The accordion directive simply sets up the directive controller
// and adds an accordion CSS class to itself element.
.directive('accordion', function () {
return {
restrict:'EA',
controller:'AccordionController',
transclude: true,
replace: false,
templateUrl: 'template/accordion/accordion.html'
};
})
// The accordion-group directive indicates a block of html that will expand and collapse in an accordion
.directive('accordionGroup', ['$parse', function($parse) {
return {
require:'^accordion', // We need this directive to be inside an accordion
restrict:'EA',
transclude:true, // It transcludes the contents of the directive into the template
replace: true, // The element containing the directive will be replaced with the template
templateUrl:'template/accordion/accordion-group.html',
scope:{ heading:'@' }, // Create an isolated scope and interpolate the heading attribute onto this scope
controller: function() {
this.setHeading = function(element) {
this.heading = element;
};
},
link: function(scope, element, attrs, accordionCtrl) {
var getIsOpen, setIsOpen;
accordionCtrl.addGroup(scope);
scope.isOpen = false;
if ( attrs.isOpen ) {
getIsOpen = $parse(attrs.isOpen);
setIsOpen = getIsOpen.assign;
scope.$parent.$watch(getIsOpen, function(value) {
scope.isOpen = !!value;
});
}
scope.$watch('isOpen', function(value) {
if ( value ) {
accordionCtrl.closeOthers(scope);
}
if ( setIsOpen ) {
setIsOpen(scope.$parent, value);
}
});
}
};
}])
// Use accordion-heading below an accordion-group to provide a heading containing HTML
// <accordion-group>
// <accordion-heading>Heading containing HTML - <img src="..."></accordion-heading>
// </accordion-group>
.directive('accordionHeading', function() {
return {
restrict: 'EA',
transclude: true, // Grab the contents to be used as the heading
template: '', // In effect remove this element!
replace: true,
require: '^accordionGroup',
compile: function(element, attr, transclude) {
return function link(scope, element, attr, accordionGroupCtrl) {
// Pass the heading to the accordion-group controller
// so that it can be transcluded into the right place in the template
// [The second parameter to transclude causes the elements to be cloned so that they work in ng-repeat]
accordionGroupCtrl.setHeading(transclude(scope, function() {}));
};
}
};
})
// Use in the accordion-group template to indicate where you want the heading to be transcluded
// You must provide the property on the accordion-group controller that will hold the transcluded element
// <div class="accordion-group">
// <div class="accordion-heading" ><a ... accordion-transclude="heading">...</a></div>
// ...
// </div>
.directive('accordionTransclude', function() {
return {
require: '^accordionGroup',
link: function(scope, element, attr, controller) {
scope.$watch(function() { return controller[attr.accordionTransclude]; }, function(heading) {
if ( heading ) {
element.html('');
element.append(heading);
}
});
}
};
});
angular.module("ui.bootstrap.alert", [])
.controller('AlertController', ['$scope', '$attrs', function ($scope, $attrs) {
$scope.closeable = 'close' in $attrs;
}])
.directive('alert', function () {
return {
restrict:'EA',
controller:'AlertController',
templateUrl:'template/alert/alert.html',
transclude:true,
replace:true,
scope: {
type: '=',
close: '&'
}
};
});
angular.module('ui.bootstrap.bindHtml', [])
.directive('bindHtmlUnsafe', function () {
return function (scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.bindHtmlUnsafe);
scope.$watch(attr.bindHtmlUnsafe, function bindHtmlUnsafeWatchAction(value) {
element.html(value || '');
});
};
});
angular.module('ui.bootstrap.buttons', [])
.constant('buttonConfig', {
activeClass: 'active',
toggleEvent: 'click'
})
.controller('ButtonsController', ['buttonConfig', function(buttonConfig) {
this.activeClass = buttonConfig.activeClass || 'active';
this.toggleEvent = buttonConfig.toggleEvent || 'click';
}])
.directive('btnRadio', function () {
return {
require: ['btnRadio', 'ngModel'],
controller: 'ButtonsController',
link: function (scope, element, attrs, ctrls) {
var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];
//model -> UI
ngModelCtrl.$render = function () {
element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, scope.$eval(attrs.btnRadio)));
};
//ui->model
element.bind(buttonsCtrl.toggleEvent, function () {
if (!element.hasClass(buttonsCtrl.activeClass)) {
scope.$apply(function () {
ngModelCtrl.$setViewValue(scope.$eval(attrs.btnRadio));
ngModelCtrl.$render();
});
}
});
}
};
})
.directive('btnCheckbox', function () {
return {
require: ['btnCheckbox', 'ngModel'],
controller: 'ButtonsController',
link: function (scope, element, attrs, ctrls) {
var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];
function getTrueValue() {
return getCheckboxValue(attrs.btnCheckboxTrue, true);
}
function getFalseValue() {
return getCheckboxValue(attrs.btnCheckboxFalse, false);
}
function getCheckboxValue(attributeValue, defaultValue) {
var val = scope.$eval(attributeValue);
return angular.isDefined(val) ? val : defaultValue;
}
//model -> UI
ngModelCtrl.$render = function () {
element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, getTrueValue()));
};
//ui->model
element.bind(buttonsCtrl.toggleEvent, function () {
scope.$apply(function () {
ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue());
ngModelCtrl.$render();
});
});
}
};
});
/**
* @ngdoc overview
* @name ui.bootstrap.carousel
*
* @description
* AngularJS version of an image carousel.
*
*/
angular.module('ui.bootstrap.carousel', ['ui.bootstrap.transition'])
.controller('CarouselController', ['$scope', '$timeout', '$transition', '$q', function ($scope, $timeout, $transition, $q) {
var self = this,
slides = self.slides = [],
currentIndex = -1,
currentTimeout, isPlaying;
self.currentSlide = null;
var destroyed = false;
/* direction: "prev" or "next" */
self.select = function(nextSlide, direction) {
var nextIndex = slides.indexOf(nextSlide);
//Decide direction if it's not given
if (direction === undefined) {
direction = nextIndex > currentIndex ? "next" : "prev";
}
if (nextSlide && nextSlide !== self.currentSlide) {
if ($scope.$currentTransition) {
$scope.$currentTransition.cancel();
//Timeout so ng-class in template has time to fix classes for finished slide
$timeout(goNext);
} else {
goNext();
}
}
function goNext() {
// Scope has been destroyed, stop here.
if (destroyed) { return; }
//If we have a slide to transition from and we have a transition type and we're allowed, go
if (self.currentSlide && angular.isString(direction) && !$scope.noTransition && nextSlide.$element) {
//We shouldn't do class manip in here, but it's the same weird thing bootstrap does. need to fix sometime
nextSlide.$element.addClass(direction);
var reflow = nextSlide.$element[0].offsetWidth; //force reflow
//Set all other slides to stop doing their stuff for the new transition
angular.forEach(slides, function(slide) {
angular.extend(slide, {direction: '', entering: false, leaving: false, active: false});
});
angular.extend(nextSlide, {direction: direction, active: true, entering: true});
angular.extend(self.currentSlide||{}, {direction: direction, leaving: true});
$scope.$currentTransition = $transition(nextSlide.$element, {});
//We have to create new pointers inside a closure since next & current will change
(function(next,current) {
$scope.$currentTransition.then(
function(){ transitionDone(next, current); },
function(){ transitionDone(next, current); }
);
}(nextSlide, self.currentSlide));
} else {
transitionDone(nextSlide, self.currentSlide);
}
self.currentSlide = nextSlide;
currentIndex = nextIndex;
//every time you change slides, reset the timer
restartTimer();
}
function transitionDone(next, current) {
angular.extend(next, {direction: '', active: true, leaving: false, entering: false});
angular.extend(current||{}, {direction: '', active: false, leaving: false, entering: false});
$scope.$currentTransition = null;
}
};
$scope.$on('$destroy', function () {
destroyed = true;
});
/* Allow outside people to call indexOf on slides array */
self.indexOfSlide = function(slide) {
return slides.indexOf(slide);
};
$scope.next = function() {
var newIndex = (currentIndex + 1) % slides.length;
//Prevent this user-triggered transition from occurring if there is already one in progress
if (!$scope.$currentTransition) {
return self.select(slides[newIndex], 'next');
}
};
$scope.prev = function() {
var newIndex = currentIndex - 1 < 0 ? slides.length - 1 : currentIndex - 1;
//Prevent this user-triggered transition from occurring if there is already one in progress
if (!$scope.$currentTransition) {
return self.select(slides[newIndex], 'prev');
}
};
$scope.select = function(slide) {
self.select(slide);
};
$scope.isActive = function(slide) {
return self.currentSlide === slide;
};
$scope.slides = function() {
return slides;
};
$scope.$watch('interval', restartTimer);
$scope.$on('$destroy', resetTimer);
function restartTimer() {
resetTimer();
var interval = +$scope.interval;
if (!isNaN(interval) && interval>=0) {
currentTimeout = $timeout(timerFn, interval);
}
}
function resetTimer() {
if (currentTimeout) {
$timeout.cancel(currentTimeout);
currentTimeout = null;
}
}
function timerFn() {
if (isPlaying) {
$scope.next();
restartTimer();
} else {
$scope.pause();
}
}
$scope.play = function() {
if (!isPlaying) {
isPlaying = true;
restartTimer();
}
};
$scope.pause = function() {
if (!$scope.noPause) {
isPlaying = false;
resetTimer();
}
};
self.addSlide = function(slide, element) {
slide.$element = element;
slides.push(slide);
//if this is the first slide or the slide is set to active, select it
if(slides.length === 1 || slide.active) {
self.select(slides[slides.length-1]);
if (slides.length == 1) {
$scope.play();
}
} else {
slide.active = false;
}
};
self.removeSlide = function(slide) {
//get the index of the slide inside the carousel
var index = slides.indexOf(slide);
slides.splice(index, 1);
if (slides.length > 0 && slide.active) {
if (index >= slides.length) {
self.select(slides[index-1]);
} else {
self.select(slides[index]);
}
} else if (currentIndex > index) {
currentIndex--;
}
};
}])
/**
* @ngdoc directive
* @name ui.bootstrap.carousel.directive:carousel
* @restrict EA
*
* @description
* Carousel is the outer container for a set of image 'slides' to showcase.
*
* @param {number=} interval The time, in milliseconds, that it will take the carousel to go to the next slide.
* @param {boolean=} noTransition Whether to disable transitions on the carousel.
* @param {boolean=} noPause Whether to disable pausing on the carousel (by default, the carousel interval pauses on hover).
*
* @example
<example module="ui.bootstrap">
<file name="index.html">
<carousel>
<slide>
<img src="http://placekitten.com/150/150" style="margin:auto;">
<div class="carousel-caption">
<p>Beautiful!</p>
</div>
</slide>
<slide>
<img src="http://placekitten.com/100/150" style="margin:auto;">
<div class="carousel-caption">
<p>D'aww!</p>
</div>
</slide>
</carousel>
</file>
<file name="demo.css">
.carousel-indicators {
top: auto;
bottom: 15px;
}
</file>
</example>
*/
.directive('carousel', [function() {
return {
restrict: 'EA',
transclude: true,
replace: true,
controller: 'CarouselController',
require: 'carousel',
templateUrl: 'template/carousel/carousel.html',
scope: {
interval: '=',
noTransition: '=',
noPause: '='
}
};
}])
/**
* @ngdoc directive
* @name ui.bootstrap.carousel.directive:slide
* @restrict EA
*
* @description
* Creates a slide inside a {@link ui.bootstrap.carousel.directive:carousel carousel}. Must be placed as a child of a carousel element.
*
* @param {boolean=} active Model binding, whether or not this slide is currently active.
*
* @example
<example module="ui.bootstrap">
<file name="index.html">
<div ng-controller="CarouselDemoCtrl">
<carousel>
<slide ng-repeat="slide in slides" active="slide.active">
<img ng-src="{{slide.image}}" style="margin:auto;">
<div class="carousel-caption">
<h4>Slide {{$index}}</h4>
<p>{{slide.text}}</p>
</div>
</slide>
</carousel>
<div class="row-fluid">
<div class="span6">
<ul>
<li ng-repeat="slide in slides">
<button class="btn btn-mini" ng-class="{'btn-info': !slide.active, 'btn-success': slide.active}" ng-disabled="slide.active" ng-click="slide.active = true">select</button>
{{$index}}: {{slide.text}}
</li>
</ul>
<a class="btn" ng-click="addSlide()">Add Slide</a>
</div>
<div class="span6">
Interval, in milliseconds: <input type="number" ng-model="myInterval">
<br />Enter a negative number to stop the interval.
</div>
</div>
</div>
</file>
<file name="script.js">
function CarouselDemoCtrl($scope) {
$scope.myInterval = 5000;
var slides = $scope.slides = [];
$scope.addSlide = function() {
var newWidth = 200 + ((slides.length + (25 * slides.length)) % 150);
slides.push({
image: 'http://placekitten.com/' + newWidth + '/200',
text: ['More','Extra','Lots of','Surplus'][slides.length % 4] + ' '
['Cats', 'Kittys', 'Felines', 'Cutes'][slides.length % 4]
});
};
for (var i=0; i<4; i++) $scope.addSlide();
}
</file>
<file name="demo.css">
.carousel-indicators {
top: auto;
bottom: 15px;
}
</file>
</example>
*/
.directive('slide', ['$parse', function($parse) {
return {
require: '^carousel',
restrict: 'EA',
transclude: true,
replace: true,
templateUrl: 'template/carousel/slide.html',
scope: {
},
link: function (scope, element, attrs, carouselCtrl) {
//Set up optional 'active' = binding
if (attrs.active) {
var getActive = $parse(attrs.active);
var setActive = getActive.assign;
var lastValue = scope.active = getActive(scope.$parent);
scope.$watch(function parentActiveWatch() {
var parentActive = getActive(scope.$parent);
if (parentActive !== scope.active) {
// we are out of sync and need to copy
if (parentActive !== lastValue) {
// parent changed and it has precedence
lastValue = scope.active = parentActive;
} else {
// if the parent can be assigned then do so
setActive(scope.$parent, parentActive = lastValue = scope.active);
}
}
return parentActive;
});
}
carouselCtrl.addSlide(scope, element);
//when the scope is destroyed then remove the slide from the current slides array
scope.$on('$destroy', function() {
carouselCtrl.removeSlide(scope);
});
scope.$watch('active', function(active) {
if (active) {
carouselCtrl.select(scope);
}
});
}
};
}]);
angular.module('ui.bootstrap.position', [])
/**
* A set of utility methods that can be use to retrieve position of DOM elements.
* It is meant to be used where we need to absolute-position DOM elements in
* relation to other, existing elements (this is the case for tooltips, popovers,
* typeahead suggestions etc.).
*/
.factory('$position', ['$document', '$window', function ($document, $window) {
function getStyle(el, cssprop) {
if (el.currentStyle) { //IE
return el.currentStyle[cssprop];
} else if ($window.getComputedStyle) {
return $window.getComputedStyle(el)[cssprop];
}
// finally try and get inline style
return el.style[cssprop];
}
/**
* Checks if a given element is statically positioned
* @param element - raw DOM element
*/
function isStaticPositioned(element) {
return (getStyle(element, "position") || 'static' ) === 'static';
}
/**
* returns the closest, non-statically positioned parentOffset of a given element
* @param element
*/
var parentOffsetEl = function (element) {
var docDomEl = $document[0];
var offsetParent = element.offsetParent || docDomEl;
while (offsetParent && offsetParent !== docDomEl && isStaticPositioned(offsetParent) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docDomEl;
};
return {
/**
* Provides read-only equivalent of jQuery's position function:
* http://api.jquery.com/position/
*/
position: function (element) {
var elBCR = this.offset(element);
var offsetParentBCR = { top: 0, left: 0 };
var offsetParentEl = parentOffsetEl(element[0]);
if (offsetParentEl != $document[0]) {
offsetParentBCR = this.offset(angular.element(offsetParentEl));
offsetParentBCR.top += offsetParentEl.clientTop - offsetParentEl.scrollTop;
offsetParentBCR.left += offsetParentEl.clientLeft - offsetParentEl.scrollLeft;
}
var boundingClientRect = element[0].getBoundingClientRect();
return {
width: boundingClientRect.width || element.prop('offsetWidth'),
height: boundingClientRect.height || element.prop('offsetHeight'),
top: elBCR.top - offsetParentBCR.top,
left: elBCR.left - offsetParentBCR.left
};
},
/**
* Provides read-only equivalent of jQuery's offset function:
* http://api.jquery.com/offset/
*/
offset: function (element) {
var boundingClientRect = element[0].getBoundingClientRect();
return {
width: boundingClientRect.width || element.prop('offsetWidth'),
height: boundingClientRect.height || element.prop('offsetHeight'),
top: boundingClientRect.top + ($window.pageYOffset || $document[0].body.scrollTop || $document[0].documentElement.scrollTop),
left: boundingClientRect.left + ($window.pageXOffset || $document[0].body.scrollLeft || $document[0].documentElement.scrollLeft)
};
}
};
}]);
angular.module('ui.bootstrap.datepicker', ['ui.bootstrap.position'])
.constant('datepickerConfig', {
dayFormat: 'dd',
monthFormat: 'MMMM',
yearFormat: 'yyyy',
dayHeaderFormat: 'EEE',
dayTitleFormat: 'MMMM yyyy',
monthTitleFormat: 'yyyy',
showWeeks: true,
startingDay: 0,
yearRange: 20,
minDate: null,
maxDate: null
})
.controller('DatepickerController', ['$scope', '$attrs', 'dateFilter', 'datepickerConfig', function($scope, $attrs, dateFilter, dtConfig) {
var format = {
day: getValue($attrs.dayFormat, dtConfig.dayFormat),
month: getValue($attrs.monthFormat, dtConfig.monthFormat),
year: getValue($attrs.yearFormat, dtConfig.yearFormat),
dayHeader: getValue($attrs.dayHeaderFormat, dtConfig.dayHeaderFormat),
dayTitle: getValue($attrs.dayTitleFormat, dtConfig.dayTitleFormat),
monthTitle: getValue($attrs.monthTitleFormat, dtConfig.monthTitleFormat)
},
startingDay = getValue($attrs.startingDay, dtConfig.startingDay),
yearRange = getValue($attrs.yearRange, dtConfig.yearRange);
this.minDate = dtConfig.minDate ? new Date(dtConfig.minDate) : null;
this.maxDate = dtConfig.maxDate ? new Date(dtConfig.maxDate) : null;
function getValue(value, defaultValue) {
return angular.isDefined(value) ? $scope.$parent.$eval(value) : defaultValue;
}
function getDaysInMonth( year, month ) {
return new Date(year, month, 0).getDate();
}
function getDates(startDate, n) {
var dates = new Array(n);
var current = startDate, i = 0;
while (i < n) {
dates[i++] = new Date(current);
current.setDate( current.getDate() + 1 );
}
return dates;
}
function makeDate(date, format, isSelected, isSecondary) {
return { date: date, label: dateFilter(date, format), selected: !!isSelected, secondary: !!isSecondary };
}
this.modes = [
{
name: 'day',
getVisibleDates: function(date, selected) {
var year = date.getFullYear(), month = date.getMonth(), firstDayOfMonth = new Date(year, month, 1);
var difference = startingDay - firstDayOfMonth.getDay(),
numDisplayedFromPreviousMonth = (difference > 0) ? 7 - difference : - difference,
firstDate = new Date(firstDayOfMonth), numDates = 0;
if ( numDisplayedFromPreviousMonth > 0 ) {
firstDate.setDate( - numDisplayedFromPreviousMonth + 1 );
numDates += numDisplayedFromPreviousMonth; // Previous
}
numDates += getDaysInMonth(year, month + 1); // Current
numDates += (7 - numDates % 7) % 7; // Next
var days = getDates(firstDate, numDates), labels = new Array(7);
for (var i = 0; i < numDates; i ++) {
var dt = new Date(days[i]);
days[i] = makeDate(dt, format.day, (selected && selected.getDate() === dt.getDate() && selected.getMonth() === dt.getMonth() && selected.getFullYear() === dt.getFullYear()), dt.getMonth() !== month);
}
for (var j = 0; j < 7; j++) {
labels[j] = dateFilter(days[j].date, format.dayHeader);
}
return { objects: days, title: dateFilter(date, format.dayTitle), labels: labels };
},
compare: function(date1, date2) {
return (new Date( date1.getFullYear(), date1.getMonth(), date1.getDate() ) - new Date( date2.getFullYear(), date2.getMonth(), date2.getDate() ) );
},
split: 7,
step: { months: 1 }
},
{
name: 'month',
getVisibleDates: function(date, selected) {
var months = new Array(12), year = date.getFullYear();
for ( var i = 0; i < 12; i++ ) {
var dt = new Date(year, i, 1);
months[i] = makeDate(dt, format.month, (selected && selected.getMonth() === i && selected.getFullYear() === year));
}
return { objects: months, title: dateFilter(date, format.monthTitle) };
},
compare: function(date1, date2) {
return new Date( date1.getFullYear(), date1.getMonth() ) - new Date( date2.getFullYear(), date2.getMonth() );
},
split: 3,
step: { years: 1 }
},
{
name: 'year',
getVisibleDates: function(date, selected) {
var years = new Array(yearRange), year = date.getFullYear(), startYear = parseInt((year - 1) / yearRange, 10) * yearRange + 1;
for ( var i = 0; i < yearRange; i++ ) {
var dt = new Date(startYear + i, 0, 1);
years[i] = makeDate(dt, format.year, (selected && selected.getFullYear() === dt.getFullYear()));
}
return { objects: years, title: [years[0].label, years[yearRange - 1].label].join(' - ') };
},
compare: function(date1, date2) {
return date1.getFullYear() - date2.getFullYear();
},
split: 5,
step: { years: yearRange }
}
];
this.isDisabled = function(date, mode) {
var currentMode = this.modes[mode || 0];
return ((this.minDate && currentMode.compare(date, this.minDate) < 0) || (this.maxDate && currentMode.compare(date, this.maxDate) > 0) || ($scope.dateDisabled && $scope.dateDisabled({date: date, mode: currentMode.name})));
};
}])
.directive( 'datepicker', ['dateFilter', '$parse', 'datepickerConfig', '$log', function (dateFilter, $parse, datepickerConfig, $log) {
return {
restrict: 'EA',
replace: true,
templateUrl: 'template/datepicker/datepicker.html',
scope: {
dateDisabled: '&'
},
require: ['datepicker', '?^ngModel'],
controller: 'DatepickerController',
link: function(scope, element, attrs, ctrls) {
var datepickerCtrl = ctrls[0], ngModel = ctrls[1];
if (!ngModel) {
return; // do nothing if no ng-model
}
// Configuration parameters
var mode = 0, selected = new Date(), showWeeks = datepickerConfig.showWeeks;
if (attrs.showWeeks) {
scope.$parent.$watch($parse(attrs.showWeeks), function(value) {
showWeeks = !! value;
updateShowWeekNumbers();
});
} else {
updateShowWeekNumbers();
}
if (attrs.min) {
scope.$parent.$watch($parse(attrs.min), function(value) {
datepickerCtrl.minDate = value ? new Date(value) : null;
refill();
});
}
if (attrs.max) {
scope.$parent.$watch($parse(attrs.max), function(value) {
datepickerCtrl.maxDate = value ? new Date(value) : null;
refill();
});
}
function updateShowWeekNumbers() {
scope.showWeekNumbers = mode === 0 && showWeeks;
}
// Split array into smaller arrays
function split(arr, size) {
var arrays = [];
while (arr.length > 0) {
arrays.push(arr.splice(0, size));
}
return arrays;
}
function refill( updateSelected ) {
var date = null, valid = true;
if ( ngModel.$modelValue ) {
date = new Date( ngModel.$modelValue );
if ( isNaN(date) ) {
valid = false;
$log.error('Datepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.');
} else if ( updateSelected ) {
selected = date;
}
}
ngModel.$setValidity('date', valid);
var currentMode = datepickerCtrl.modes[mode], data = currentMode.getVisibleDates(selected, date);
angular.forEach(data.objects, function(obj) {
obj.disabled = datepickerCtrl.isDisabled(obj.date, mode);
});
ngModel.$setValidity('date-disabled', (!date || !datepickerCtrl.isDisabled(date)));
scope.rows = split(data.objects, currentMode.split);
scope.labels = data.labels || [];
scope.title = data.title;
}
function setMode(value) {
mode = value;
updateShowWeekNumbers();
refill();
}
ngModel.$render = function() {
refill( true );
};
scope.select = function( date ) {
if ( mode === 0 ) {
var dt = ngModel.$modelValue ? new Date( ngModel.$modelValue ) : new Date(0, 0, 0, 0, 0, 0, 0);
dt.setFullYear( date.getFullYear(), date.getMonth(), date.getDate() );
ngModel.$setViewValue( dt );
refill( true );
} else {
selected = date;
setMode( mode - 1 );
}
};
scope.move = function(direction) {
var step = datepickerCtrl.modes[mode].step;
selected.setMonth( selected.getMonth() + direction * (step.months || 0) );
selected.setFullYear( selected.getFullYear() + direction * (step.years || 0) );
refill();
};
scope.toggleMode = function() {
setMode( (mode + 1) % datepickerCtrl.modes.length );
};
scope.getWeekNumber = function(row) {
return ( mode === 0 && scope.showWeekNumbers && row.length === 7 ) ? getISO8601WeekNumber(row[0].date) : null;
};
function getISO8601WeekNumber(date) {
var checkDate = new Date(date);
checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); // Thursday
var time = checkDate.getTime();
checkDate.setMonth(0); // Compare with Jan 1
checkDate.setDate(1);
return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
}
}
};
}])
.constant('datepickerPopupConfig', {
dateFormat: 'yyyy-MM-dd',
currentText: 'Today',
toggleWeeksText: 'Weeks',
clearText: 'Clear',
closeText: 'Done',
closeOnDateSelection: true,
appendToBody: false,
showButtonBar: true
})
.directive('datepickerPopup', ['$compile', '$parse', '$document', '$position', 'dateFilter', 'datepickerPopupConfig', 'datepickerConfig',
function ($compile, $parse, $document, $position, dateFilter, datepickerPopupConfig, datepickerConfig) {
return {
restrict: 'EA',
require: 'ngModel',
link: function(originalScope, element, attrs, ngModel) {
var scope = originalScope.$new(), // create a child scope so we are not polluting original one
dateFormat,
closeOnDateSelection = angular.isDefined(attrs.closeOnDateSelection) ? originalScope.$eval(attrs.closeOnDateSelection) : datepickerPopupConfig.closeOnDateSelection,
appendToBody = angular.isDefined(attrs.datepickerAppendToBody) ? originalScope.$eval(attrs.datepickerAppendToBody) : datepickerPopupConfig.appendToBody;
attrs.$observe('datepickerPopup', function(value) {
dateFormat = value || datepickerPopupConfig.dateFormat;
ngModel.$render();
});
scope.showButtonBar = angular.isDefined(attrs.showButtonBar) ? originalScope.$eval(attrs.showButtonBar) : datepickerPopupConfig.showButtonBar;
originalScope.$on('$destroy', function() {
$popup.remove();
scope.$destroy();
});
attrs.$observe('currentText', function(text) {
scope.currentText = angular.isDefined(text) ? text : datepickerPopupConfig.currentText;
});
attrs.$observe('toggleWeeksText', function(text) {
scope.toggleWeeksText = angular.isDefined(text) ? text : datepickerPopupConfig.toggleWeeksText;
});
attrs.$observe('clearText', function(text) {
scope.clearText = angular.isDefined(text) ? text : datepickerPopupConfig.clearText;
});
attrs.$observe('closeText', function(text) {
scope.closeText = angular.isDefined(text) ? text : datepickerPopupConfig.closeText;
});
var getIsOpen, setIsOpen;
if ( attrs.isOpen ) {
getIsOpen = $parse(attrs.isOpen);
setIsOpen = getIsOpen.assign;
originalScope.$watch(getIsOpen, function updateOpen(value) {
scope.isOpen = !! value;
});
}
scope.isOpen = getIsOpen ? getIsOpen(originalScope) : false; // Initial state
function setOpen( value ) {
if (setIsOpen) {
setIsOpen(originalScope, !!value);
} else {
scope.isOpen = !!value;
}
}
var documentClickBind = function(event) {
if (scope.isOpen && event.target !== element[0]) {
scope.$apply(function() {
setOpen(false);
});
}
};
var elementFocusBind = function() {
scope.$apply(function() {
setOpen( true );
});
};
// popup element used to display calendar
var popupEl = angular.element('<div datepicker-popup-wrap><div datepicker></div></div>');
popupEl.attr({
'ng-model': 'date',
'ng-change': 'dateSelection()'
});
var datepickerEl = angular.element(popupEl.children()[0]),
datepickerOptions = {};
if (attrs.datepickerOptions) {
datepickerOptions = originalScope.$eval(attrs.datepickerOptions);
datepickerEl.attr(angular.extend({}, datepickerOptions));
}
// TODO: reverse from dateFilter string to Date object
function parseDate(viewValue) {
if (!viewValue) {
ngModel.$setValidity('date', true);
return null;
} else if (angular.isDate(viewValue)) {
ngModel.$setValidity('date', true);
return viewValue;
} else if (angular.isString(viewValue)) {
var date = new Date(viewValue);
if (isNaN(date)) {
ngModel.$setValidity('date', false);
return undefined;
} else {
ngModel.$setValidity('date', true);
return date;
}
} else {
ngModel.$setValidity('date', false);
return undefined;
}
}
ngModel.$parsers.unshift(parseDate);
// Inner change
scope.dateSelection = function(dt) {
if (angular.isDefined(dt)) {
scope.date = dt;
}
ngModel.$setViewValue(scope.date);
ngModel.$render();
if (closeOnDateSelection) {
setOpen( false );
}
};
element.bind('input change keyup', function() {
scope.$apply(function() {
scope.date = ngModel.$modelValue;
});
});
// Outter change
ngModel.$render = function() {
var date = ngModel.$viewValue ? dateFilter(ngModel.$viewValue, dateFormat) : '';
element.val(date);
scope.date = ngModel.$modelValue;
};
function addWatchableAttribute(attribute, scopeProperty, datepickerAttribute) {
if (attribute) {
originalScope.$watch($parse(attribute), function(value){
scope[scopeProperty] = value;
});
datepickerEl.attr(datepickerAttribute || scopeProperty, scopeProperty);
}
}
addWatchableAttribute(attrs.min, 'min');
addWatchableAttribute(attrs.max, 'max');
if (attrs.showWeeks) {
addWatchableAttribute(attrs.showWeeks, 'showWeeks', 'show-weeks');
} else {
scope.showWeeks = 'show-weeks' in datepickerOptions ? datepickerOptions['show-weeks'] : datepickerConfig.showWeeks;
datepickerEl.attr('show-weeks', 'showWeeks');
}
if (attrs.dateDisabled) {
datepickerEl.attr('date-disabled', attrs.dateDisabled);
}
function updatePosition() {
scope.position = appendToBody ? $position.offset(element) : $position.position(element);
scope.position.top = scope.position.top + element.prop('offsetHeight');
}
var documentBindingInitialized = false, elementFocusInitialized = false;
scope.$watch('isOpen', function(value) {
if (value) {
updatePosition();
$document.bind('click', documentClickBind);
if(elementFocusInitialized) {
element.unbind('focus', elementFocusBind);
}
element[0].focus();
documentBindingInitialized = true;
} else {
if(documentBindingInitialized) {
$document.unbind('click', documentClickBind);
}
element.bind('focus', elementFocusBind);
elementFocusInitialized = true;
}
if ( setIsOpen ) {
setIsOpen(originalScope, value);
}
});
scope.today = function() {
scope.dateSelection(new Date());
};
scope.clear = function() {
scope.dateSelection(null);
};
var $popup = $compile(popupEl)(scope);
if ( appendToBody ) {
$document.find('body').append($popup);
} else {
element.after($popup);
}
}
};
}])
.directive('datepickerPopupWrap', function() {
return {
restrict:'EA',
replace: true,
transclude: true,
templateUrl: 'template/datepicker/popup.html',
link:function (scope, element, attrs) {
element.bind('click', function(event) {
event.preventDefault();
event.stopPropagation();
});
}
};
});
/*
* dropdownToggle - Provides dropdown menu functionality in place of bootstrap js
* @restrict class or attribute
* @example:
<li class="dropdown">
<a class="dropdown-toggle">My Dropdown Menu</a>
<ul class="dropdown-menu">
<li ng-repeat="choice in dropChoices">
<a ng-href="{{choice.href}}">{{choice.text}}</a>
</li>
</ul>
</li>
*/
angular.module('ui.bootstrap.dropdownToggle', []).directive('dropdownToggle', ['$document', '$location', function ($document, $location) {
var openElement = null,
closeMenu = angular.noop;
return {
restrict: 'CA',
link: function(scope, element, attrs) {
scope.$watch('$location.path', function() { closeMenu(); });
element.parent().bind('click', function() { closeMenu(); });
element.bind('click', function (event) {
var elementWasOpen = (element === openElement);
event.preventDefault();
event.stopPropagation();
if (!!openElement) {
closeMenu();
}
if (!elementWasOpen && !element.hasClass('disabled') && !element.prop('disabled')) {
element.parent().addClass('open');
openElement = element;
closeMenu = function (event) {
if (event) {
event.preventDefault();
event.stopPropagation();
}
$document.unbind('click', closeMenu);
element.parent().removeClass('open');
closeMenu = angular.noop;
openElement = null;
};
$document.bind('click', closeMenu);
}
});
}
};
}]);
angular.module('ui.bootstrap.modal', ['ui.bootstrap.transition'])
/**
* A helper, internal data structure that acts as a map but also allows getting / removing
* elements in the LIFO order
*/
.factory('$$stackedMap', function () {
return {
createNew: function () {
var stack = [];
return {
add: function (key, value) {
stack.push({
key: key,
value: value
});
},
get: function (key) {
for (var i = 0; i < stack.length; i++) {
if (key == stack[i].key) {
return stack[i];
}
}
},
keys: function() {
var keys = [];
for (var i = 0; i < stack.length; i++) {
keys.push(stack[i].key);
}
return keys;
},
top: function () {
return stack[stack.length - 1];
},
remove: function (key) {
var idx = -1;
for (var i = 0; i < stack.length; i++) {
if (key == stack[i].key) {
idx = i;
break;
}
}
return stack.splice(idx, 1)[0];
},
removeTop: function () {
return stack.splice(stack.length - 1, 1)[0];
},
length: function () {
return stack.length;
}
};
}
};
})
/**
* A helper directive for the $modal service. It creates a backdrop element.
*/
.directive('modalBackdrop', ['$timeout', function ($timeout) {
return {
restrict: 'EA',
replace: true,
templateUrl: 'template/modal/backdrop.html',
link: function (scope) {
scope.animate = false;
//trigger CSS transitions
$timeout(function () {
scope.animate = true;
});
}
};
}])
.directive('modalWindow', ['$modalStack', '$timeout', function ($modalStack, $timeout) {
return {
restrict: 'EA',
scope: {
index: '@',
animate: '='
},
replace: true,
transclude: true,
templateUrl: 'template/modal/window.html',
link: function (scope, element, attrs) {
scope.windowClass = attrs.windowClass || '';
$timeout(function () {
// trigger CSS transitions
scope.animate = true;
// focus a freshly-opened modal
element[0].focus();
});
scope.close = function (evt) {
var modal = $modalStack.getTop();
if (modal && modal.value.backdrop && modal.value.backdrop != 'static' && (evt.target === evt.currentTarget)) {
evt.preventDefault();
evt.stopPropagation();
$modalStack.dismiss(modal.key, 'backdrop click');
}
};
}
};
}])
.factory('$modalStack', ['$transition', '$timeout', '$document', '$compile', '$rootScope', '$$stackedMap',
function ($transition, $timeout, $document, $compile, $rootScope, $$stackedMap) {
var OPENED_MODAL_CLASS = 'modal-open';
var backdropDomEl, backdropScope;
var openedWindows = $$stackedMap.createNew();
var $modalStack = {};
function backdropIndex() {
var topBackdropIndex = -1;
var opened = openedWindows.keys();
for (var i = 0; i < opened.length; i++) {
if (openedWindows.get(opened[i]).value.backdrop) {
topBackdropIndex = i;
}
}
return topBackdropIndex;
}
$rootScope.$watch(backdropIndex, function(newBackdropIndex){
if (backdropScope) {
backdropScope.index = newBackdropIndex;
}
});
function removeModalWindow(modalInstance) {
var body = $document.find('body').eq(0);
var modalWindow = openedWindows.get(modalInstance).value;
//clean up the stack
openedWindows.remove(modalInstance);
//remove window DOM element
removeAfterAnimate(modalWindow.modalDomEl, modalWindow.modalScope, 300, checkRemoveBackdrop);
body.toggleClass(OPENED_MODAL_CLASS, openedWindows.length() > 0);
}
function checkRemoveBackdrop() {
//remove backdrop if no longer needed
if (backdropDomEl && backdropIndex() == -1) {
var backdropScopeRef = backdropScope;
removeAfterAnimate(backdropDomEl, backdropScope, 150, function () {
backdropScopeRef.$destroy();
backdropScopeRef = null;
});
backdropDomEl = undefined;
backdropScope = undefined;
}
}
function removeAfterAnimate(domEl, scope, emulateTime, done) {
// Closing animation
scope.animate = false;
var transitionEndEventName = $transition.transitionEndEventName;
if (transitionEndEventName) {
// transition out
var timeout = $timeout(afterAnimating, emulateTime);
domEl.bind(transitionEndEventName, function () {
$timeout.cancel(timeout);
afterAnimating();
scope.$apply();
});
} else {
// Ensure this call is async
$timeout(afterAnimating, 0);
}
function afterAnimating() {
if (afterAnimating.done) {
return;
}
afterAnimating.done = true;
domEl.remove();
if (done) {
done();
}
}
}
$document.bind('keydown', function (evt) {
var modal;
if (evt.which === 27) {
modal = openedWindows.top();
if (modal && modal.value.keyboard) {
$rootScope.$apply(function () {
$modalStack.dismiss(modal.key);
});
}
}
});
$modalStack.open = function (modalInstance, modal) {
openedWindows.add(modalInstance, {
deferred: modal.deferred,
modalScope: modal.scope,
backdrop: modal.backdrop,
keyboard: modal.keyboard
});
var body = $document.find('body').eq(0),
currBackdropIndex = backdropIndex();
if (currBackdropIndex >= 0 && !backdropDomEl) {
backdropScope = $rootScope.$new(true);
backdropScope.index = currBackdropIndex;
backdropDomEl = $compile('<div modal-backdrop></div>')(backdropScope);
body.append(backdropDomEl);
}
var angularDomEl = angular.element('<div modal-window></div>');
angularDomEl.attr('window-class', modal.windowClass);
angularDomEl.attr('index', openedWindows.length() - 1);
angularDomEl.attr('animate', 'animate');
angularDomEl.html(modal.content);
var modalDomEl = $compile(angularDomEl)(modal.scope);
openedWindows.top().value.modalDomEl = modalDomEl;
body.append(modalDomEl);
body.addClass(OPENED_MODAL_CLASS);
};
$modalStack.close = function (modalInstance, result) {
var modalWindow = openedWindows.get(modalInstance).value;
if (modalWindow) {
modalWindow.deferred.resolve(result);
removeModalWindow(modalInstance);
}
};
$modalStack.dismiss = function (modalInstance, reason) {
var modalWindow = openedWindows.get(modalInstance).value;
if (modalWindow) {
modalWindow.deferred.reject(reason);
removeModalWindow(modalInstance);
}
};
$modalStack.dismissAll = function (reason) {
var topModal = this.getTop();
while (topModal) {
this.dismiss(topModal.key, reason);
topModal = this.getTop();
}
};
$modalStack.getTop = function () {
return openedWindows.top();
};
return $modalStack;
}])
.provider('$modal', function () {
var $modalProvider = {
options: {
backdrop: true, //can be also false or 'static'
keyboard: true
},
$get: ['$injector', '$rootScope', '$q', '$http', '$templateCache', '$controller', '$modalStack',
function ($injector, $rootScope, $q, $http, $templateCache, $controller, $modalStack) {
var $modal = {};
function getTemplatePromise(options) {
return options.template ? $q.when(options.template) :
$http.get(options.templateUrl, {cache: $templateCache}).then(function (result) {
return result.data;
});
}
function getResolvePromises(resolves) {
var promisesArr = [];
angular.forEach(resolves, function (value, key) {
if (angular.isFunction(value) || angular.isArray(value)) {
promisesArr.push($q.when($injector.invoke(value)));
}
});
return promisesArr;
}
$modal.open = function (modalOptions) {
var modalResultDeferred = $q.defer();
var modalOpenedDeferred = $q.defer();
//prepare an instance of a modal to be injected into controllers and returned to a caller
var modalInstance = {
result: modalResultDeferred.promise,
opened: modalOpenedDeferred.promise,
close: function (result) {
$modalStack.close(modalInstance, result);
},
dismiss: function (reason) {
$modalStack.dismiss(modalInstance, reason);
}
};
//merge and clean up options
modalOptions = angular.extend({}, $modalProvider.options, modalOptions);
modalOptions.resolve = modalOptions.resolve || {};
//verify options
if (!modalOptions.template && !modalOptions.templateUrl) {
throw new Error('One of template or templateUrl options is required.');
}
var templateAndResolvePromise =
$q.all([getTemplatePromise(modalOptions)].concat(getResolvePromises(modalOptions.resolve)));
templateAndResolvePromise.then(function resolveSuccess(tplAndVars) {
var modalScope = (modalOptions.scope || $rootScope).$new();
modalScope.$close = modalInstance.close;
modalScope.$dismiss = modalInstance.dismiss;
var ctrlInstance, ctrlLocals = {};
var resolveIter = 1;
//controllers
if (modalOptions.controller) {
ctrlLocals.$scope = modalScope;
ctrlLocals.$modalInstance = modalInstance;
angular.forEach(modalOptions.resolve, function (value, key) {
ctrlLocals[key] = tplAndVars[resolveIter++];
});
ctrlInstance = $controller(modalOptions.controller, ctrlLocals);
}
$modalStack.open(modalInstance, {
scope: modalScope,
deferred: modalResultDeferred,
content: tplAndVars[0],
backdrop: modalOptions.backdrop,
keyboard: modalOptions.keyboard,
windowClass: modalOptions.windowClass
});
}, function resolveError(reason) {
modalResultDeferred.reject(reason);
});
templateAndResolvePromise.then(function () {
modalOpenedDeferred.resolve(true);
}, function () {
modalOpenedDeferred.reject(false);
});
return modalInstance;
};
return $modal;
}]
};
return $modalProvider;
});
angular.module('ui.bootstrap.pagination', [])
.controller('PaginationController', ['$scope', '$attrs', '$parse', '$interpolate', function ($scope, $attrs, $parse, $interpolate) {
var self = this,
setNumPages = $attrs.numPages ? $parse($attrs.numPages).assign : angular.noop;
this.init = function(defaultItemsPerPage) {
if ($attrs.itemsPerPage) {
$scope.$parent.$watch($parse($attrs.itemsPerPage), function(value) {
self.itemsPerPage = parseInt(value, 10);
$scope.totalPages = self.calculateTotalPages();
});
} else {
this.itemsPerPage = defaultItemsPerPage;
}
};
this.noPrevious = function() {
return this.page === 1;
};
this.noNext = function() {
return this.page === $scope.totalPages;
};
this.isActive = function(page) {
return this.page === page;
};
this.calculateTotalPages = function() {
var totalPages = this.itemsPerPage < 1 ? 1 : Math.ceil($scope.totalItems / this.itemsPerPage);
return Math.max(totalPages || 0, 1);
};
this.getAttributeValue = function(attribute, defaultValue, interpolate) {
return angular.isDefined(attribute) ? (interpolate ? $interpolate(attribute)($scope.$parent) : $scope.$parent.$eval(attribute)) : defaultValue;
};
this.render = function() {
this.page = parseInt($scope.page, 10) || 1;
if (this.page > 0 && this.page <= $scope.totalPages) {
$scope.pages = this.getPages(this.page, $scope.totalPages);
}
};
$scope.selectPage = function(page) {
if ( ! self.isActive(page) && page > 0 && page <= $scope.totalPages) {
$scope.page = page;
$scope.onSelectPage({ page: page });
}
};
$scope.$watch('page', function() {
self.render();
});
$scope.$watch('totalItems', function() {
$scope.totalPages = self.calculateTotalPages();
});
$scope.$watch('totalPages', function(value) {
setNumPages($scope.$parent, value); // Readonly variable
if ( self.page > value ) {
$scope.selectPage(value);
} else {
self.render();
}
});
}])
.constant('paginationConfig', {
itemsPerPage: 10,
boundaryLinks: false,
directionLinks: true,
firstText: 'First',
previousText: 'Previous',
nextText: 'Next',
lastText: 'Last',
rotate: true
})
.directive('pagination', ['$parse', 'paginationConfig', function($parse, config) {
return {
restrict: 'EA',
scope: {
page: '=',
totalItems: '=',
onSelectPage:' &'
},
controller: 'PaginationController',
templateUrl: 'template/pagination/pagination.html',
replace: true,
link: function(scope, element, attrs, paginationCtrl) {
// Setup configuration parameters
var maxSize,
boundaryLinks = paginationCtrl.getAttributeValue(attrs.boundaryLinks, config.boundaryLinks ),
directionLinks = paginationCtrl.getAttributeValue(attrs.directionLinks, config.directionLinks ),
firstText = paginationCtrl.getAttributeValue(attrs.firstText, config.firstText, true),
previousText = paginationCtrl.getAttributeValue(attrs.previousText, config.previousText, true),
nextText = paginationCtrl.getAttributeValue(attrs.nextText, config.nextText, true),
lastText = paginationCtrl.getAttributeValue(attrs.lastText, config.lastText, true),
rotate = paginationCtrl.getAttributeValue(attrs.rotate, config.rotate);
paginationCtrl.init(config.itemsPerPage);
if (attrs.maxSize) {
scope.$parent.$watch($parse(attrs.maxSize), function(value) {
maxSize = parseInt(value, 10);
paginationCtrl.render();
});
}
// Create page object used in template
function makePage(number, text, isActive, isDisabled) {
return {
number: number,
text: text,
active: isActive,
disabled: isDisabled
};
}
paginationCtrl.getPages = function(currentPage, totalPages) {
var pages = [];
// Default page limits
var startPage = 1, endPage = totalPages;
var isMaxSized = ( angular.isDefined(maxSize) && maxSize < totalPages );
// recompute if maxSize
if ( isMaxSized ) {
if ( rotate ) {
// Current page is displayed in the middle of the visible ones
startPage = Math.max(currentPage - Math.floor(maxSize/2), 1);
endPage = startPage + maxSize - 1;
// Adjust if limit is exceeded
if (endPage > totalPages) {
endPage = totalPages;
startPage = endPage - maxSize + 1;
}
} else {
// Visible pages are paginated with maxSize
startPage = ((Math.ceil(currentPage / maxSize) - 1) * maxSize) + 1;
// Adjust last page if limit is exceeded
endPage = Math.min(startPage + maxSize - 1, totalPages);
}
}
// Add page number links
for (var number = startPage; number <= endPage; number++) {
var page = makePage(number, number, paginationCtrl.isActive(number), false);
pages.push(page);
}
// Add links to move between page sets
if ( isMaxSized && ! rotate ) {
if ( startPage > 1 ) {
var previousPageSet = makePage(startPage - 1, '...', false, false);
pages.unshift(previousPageSet);
}
if ( endPage < totalPages ) {
var nextPageSet = makePage(endPage + 1, '...', false, false);
pages.push(nextPageSet);
}
}
// Add previous & next links
if (directionLinks) {
var previousPage = makePage(currentPage - 1, previousText, false, paginationCtrl.noPrevious());
pages.unshift(previousPage);
var nextPage = makePage(currentPage + 1, nextText, false, paginationCtrl.noNext());
pages.push(nextPage);
}
// Add first & last links
if (boundaryLinks) {
var firstPage = makePage(1, firstText, false, paginationCtrl.noPrevious());
pages.unshift(firstPage);
var lastPage = makePage(totalPages, lastText, false, paginationCtrl.noNext());
pages.push(lastPage);
}
return pages;
};
}
};
}])
.constant('pagerConfig', {
itemsPerPage: 10,
previousText: '« Previous',
nextText: 'Next »',
align: true
})
.directive('pager', ['pagerConfig', function(config) {
return {
restrict: 'EA',
scope: {
page: '=',
totalItems: '=',
onSelectPage:' &'
},
controller: 'PaginationController',
templateUrl: 'template/pagination/pager.html',
replace: true,
link: function(scope, element, attrs, paginationCtrl) {
// Setup configuration parameters
var previousText = paginationCtrl.getAttributeValue(attrs.previousText, config.previousText, true),
nextText = paginationCtrl.getAttributeValue(attrs.nextText, config.nextText, true),
align = paginationCtrl.getAttributeValue(attrs.align, config.align);
paginationCtrl.init(config.itemsPerPage);
// Create page object used in template
function makePage(number, text, isDisabled, isPrevious, isNext) {
return {
number: number,
text: text,
disabled: isDisabled,
previous: ( align && isPrevious ),
next: ( align && isNext )
};
}
paginationCtrl.getPages = function(currentPage) {
return [
makePage(currentPage - 1, previousText, paginationCtrl.noPrevious(), true, false),
makePage(currentPage + 1, nextText, paginationCtrl.noNext(), false, true)
];
};
}
};
}]);
/**
* The following features are still outstanding: animation as a
* function, placement as a function, inside, support for more triggers than
* just mouse enter/leave, html tooltips, and selector delegation.
*/
angular.module( 'ui.bootstrap.tooltip', [ 'ui.bootstrap.position', 'ui.bootstrap.bindHtml' ] )
/**
* The $tooltip service creates tooltip- and popover-like directives as well as
* houses global options for them.
*/
.provider( '$tooltip', function () {
// The default options tooltip and popover.
var defaultOptions = {
placement: 'top',
animation: true,
popupDelay: 0
};
// Default hide triggers for each show trigger
var triggerMap = {
'mouseenter': 'mouseleave',
'click': 'click',
'focus': 'blur'
};
// The options specified to the provider globally.
var globalOptions = {};
/**
* `options({})` allows global configuration of all tooltips in the
* application.
*
* var app = angular.module( 'App', ['ui.bootstrap.tooltip'], function( $tooltipProvider ) {
* // place tooltips left instead of top by default
* $tooltipProvider.options( { placement: 'left' } );
* });
*/
this.options = function( value ) {
angular.extend( globalOptions, value );
};
/**
* This allows you to extend the set of trigger mappings available. E.g.:
*
* $tooltipProvider.setTriggers( 'openTrigger': 'closeTrigger' );
*/
this.setTriggers = function setTriggers ( triggers ) {
angular.extend( triggerMap, triggers );
};
/**
* This is a helper function for translating camel-case to snake-case.
*/
function snake_case(name){
var regexp = /[A-Z]/g;
var separator = '-';
return name.replace(regexp, function(letter, pos) {
return (pos ? separator : '') + letter.toLowerCase();
});
}
/**
* Returns the actual instance of the $tooltip service.
* TODO support multiple triggers
*/
this.$get = [ '$window', '$compile', '$timeout', '$parse', '$document', '$position', '$interpolate', function ( $window, $compile, $timeout, $parse, $document, $position, $interpolate ) {
return function $tooltip ( type, prefix, defaultTriggerShow ) {
var options = angular.extend( {}, defaultOptions, globalOptions );
/**
* Returns an object of show and hide triggers.
*
* If a trigger is supplied,
* it is used to show the tooltip; otherwise, it will use the `trigger`
* option passed to the `$tooltipProvider.options` method; else it will
* default to the trigger supplied to this directive factory.
*
* The hide trigger is based on the show trigger. If the `trigger` option
* was passed to the `$tooltipProvider.options` method, it will use the
* mapped trigger from `triggerMap` or the passed trigger if the map is
* undefined; otherwise, it uses the `triggerMap` value of the show
* trigger; else it will just use the show trigger.
*/
function getTriggers ( trigger ) {
var show = trigger || options.trigger || defaultTriggerShow;
var hide = triggerMap[show] || show;
return {
show: show,
hide: hide
};
}
var directiveName = snake_case( type );
var startSym = $interpolate.startSymbol();
var endSym = $interpolate.endSymbol();
var template =
'<div '+ directiveName +'-popup '+
'title="'+startSym+'tt_title'+endSym+'" '+
'content="'+startSym+'tt_content'+endSym+'" '+
'placement="'+startSym+'tt_placement'+endSym+'" '+
'animation="tt_animation" '+
'is-open="tt_isOpen"'+
'>'+
'</div>';
return {
restrict: 'EA',
scope: true,
compile: function (tElem, tAttrs) {
var tooltipLinker = $compile( template );
return function link ( scope, element, attrs ) {
var tooltip;
var transitionTimeout;
var popupTimeout;
var appendToBody = angular.isDefined( options.appendToBody ) ? options.appendToBody : false;
var triggers = getTriggers( undefined );
var hasRegisteredTriggers = false;
var hasEnableExp = angular.isDefined(attrs[prefix+'Enable']);
var positionTooltip = function (){
var position,
ttWidth,
ttHeight,
ttPosition;
// Get the position of the directive element.
position = appendToBody ? $position.offset( element ) : $position.position( element );
// Get the height and width of the tooltip so we can center it.
ttWidth = tooltip.prop( 'offsetWidth' );
ttHeight = tooltip.prop( 'offsetHeight' );
// Calculate the tooltip's top and left coordinates to center it with
// this directive.
switch ( scope.tt_placement ) {
case 'right':
ttPosition = {
top: position.top + position.height / 2 - ttHeight / 2,
left: position.left + position.width
};
break;
case 'bottom':
ttPosition = {
top: position.top + position.height,
left: position.left + position.width / 2 - ttWidth / 2
};
break;
case 'left':
ttPosition = {
top: position.top + position.height / 2 - ttHeight / 2,
left: position.left - ttWidth
};
break;
default:
ttPosition = {
top: position.top - ttHeight,
left: position.left + position.width / 2 - ttWidth / 2
};
break;
}
ttPosition.top += 'px';
ttPosition.left += 'px';
// Now set the calculated positioning.
tooltip.css( ttPosition );
};
// By default, the tooltip is not open.
// TODO add ability to start tooltip opened
scope.tt_isOpen = false;
function toggleTooltipBind () {
if ( ! scope.tt_isOpen ) {
showTooltipBind();
} else {
hideTooltipBind();
}
}
// Show the tooltip with delay if specified, otherwise show it immediately
function showTooltipBind() {
if(hasEnableExp && !scope.$eval(attrs[prefix+'Enable'])) {
return;
}
if ( scope.tt_popupDelay ) {
popupTimeout = $timeout( show, scope.tt_popupDelay, false );
popupTimeout.then(function(reposition){reposition();});
} else {
show()();
}
}
function hideTooltipBind () {
scope.$apply(function () {
hide();
});
}
// Show the tooltip popup element.
function show() {
// Don't show empty tooltips.
if ( ! scope.tt_content ) {
return angular.noop;
}
createTooltip();
// If there is a pending remove transition, we must cancel it, lest the
// tooltip be mysteriously removed.
if ( transitionTimeout ) {
$timeout.cancel( transitionTimeout );
}
// Set the initial positioning.
tooltip.css({ top: 0, left: 0, display: 'block' });
// Now we add it to the DOM because need some info about it. But it's not
// visible yet anyway.
if ( appendToBody ) {
$document.find( 'body' ).append( tooltip );
} else {
element.after( tooltip );
}
positionTooltip();
// And show the tooltip.
scope.tt_isOpen = true;
scope.$digest(); // digest required as $apply is not called
// Return positioning function as promise callback for correct
// positioning after draw.
return positionTooltip;
}
// Hide the tooltip popup element.
function hide() {
// First things first: we don't show it anymore.
scope.tt_isOpen = false;
//if tooltip is going to be shown after delay, we must cancel this
$timeout.cancel( popupTimeout );
// And now we remove it from the DOM. However, if we have animation, we
// need to wait for it to expire beforehand.
// FIXME: this is a placeholder for a port of the transitions library.
if ( scope.tt_animation ) {
transitionTimeout = $timeout(removeTooltip, 500);
} else {
removeTooltip();
}
}
function createTooltip() {
// There can only be one tooltip element per directive shown at once.
if (tooltip) {
removeTooltip();
}
tooltip = tooltipLinker(scope, function () {});
// Get contents rendered into the tooltip
scope.$digest();
}
function removeTooltip() {
if (tooltip) {
tooltip.remove();
tooltip = null;
}
}
/**
* Observe the relevant attributes.
*/
attrs.$observe( type, function ( val ) {
scope.tt_content = val;
if (!val && scope.tt_isOpen ) {
hide();
}
});
attrs.$observe( prefix+'Title', function ( val ) {
scope.tt_title = val;
});
attrs.$observe( prefix+'Placement', function ( val ) {
scope.tt_placement = angular.isDefined( val ) ? val : options.placement;
});
attrs.$observe( prefix+'PopupDelay', function ( val ) {
var delay = parseInt( val, 10 );
scope.tt_popupDelay = ! isNaN(delay) ? delay : options.popupDelay;
});
var unregisterTriggers = function() {
if (hasRegisteredTriggers) {
element.unbind( triggers.show, showTooltipBind );
element.unbind( triggers.hide, hideTooltipBind );
}
};
attrs.$observe( prefix+'Trigger', function ( val ) {
unregisterTriggers();
triggers = getTriggers( val );
if ( triggers.show === triggers.hide ) {
element.bind( triggers.show, toggleTooltipBind );
} else {
element.bind( triggers.show, showTooltipBind );
element.bind( triggers.hide, hideTooltipBind );
}
hasRegisteredTriggers = true;
});
var animation = scope.$eval(attrs[prefix + 'Animation']);
scope.tt_animation = angular.isDefined(animation) ? !!animation : options.animation;
attrs.$observe( prefix+'AppendToBody', function ( val ) {
appendToBody = angular.isDefined( val ) ? $parse( val )( scope ) : appendToBody;
});
// if a tooltip is attached to <body> we need to remove it on
// location change as its parent scope will probably not be destroyed
// by the change.
if ( appendToBody ) {
scope.$on('$locationChangeSuccess', function closeTooltipOnLocationChangeSuccess () {
if ( scope.tt_isOpen ) {
hide();
}
});
}
// Make sure tooltip is destroyed and removed.
scope.$on('$destroy', function onDestroyTooltip() {
$timeout.cancel( transitionTimeout );
$timeout.cancel( popupTimeout );
unregisterTriggers();
removeTooltip();
});
};
}
};
};
}];
})
.directive( 'tooltipPopup', function () {
return {
restrict: 'EA',
replace: true,
scope: { content: '@', placement: '@', animation: '&', isOpen: '&' },
templateUrl: 'template/tooltip/tooltip-popup.html'
};
})
.directive( 'tooltip', [ '$tooltip', function ( $tooltip ) {
return $tooltip( 'tooltip', 'tooltip', 'mouseenter' );
}])
.directive( 'tooltipHtmlUnsafePopup', function () {
return {
restrict: 'EA',
replace: true,
scope: { content: '@', placement: '@', animation: '&', isOpen: '&' },
templateUrl: 'template/tooltip/tooltip-html-unsafe-popup.html'
};
})
.directive( 'tooltipHtmlUnsafe', [ '$tooltip', function ( $tooltip ) {
return $tooltip( 'tooltipHtmlUnsafe', 'tooltip', 'mouseenter' );
}]);
/**
* The following features are still outstanding: popup delay, animation as a
* function, placement as a function, inside, support for more triggers than
* just mouse enter/leave, html popovers, and selector delegatation.
*/
angular.module( 'ui.bootstrap.popover', [ 'ui.bootstrap.tooltip' ] )
.directive( 'popoverPopup', function () {
return {
restrict: 'EA',
replace: true,
scope: { title: '@', content: '@', placement: '@', animation: '&', isOpen: '&' },
templateUrl: 'template/popover/popover.html'
};
})
.directive( 'popover', [ '$tooltip', function ( $tooltip ) {
return $tooltip( 'popover', 'popover', 'click' );
}]);
angular.module('ui.bootstrap.progressbar', ['ui.bootstrap.transition'])
.constant('progressConfig', {
animate: true,
max: 100
})
.controller('ProgressController', ['$scope', '$attrs', 'progressConfig', '$transition', function($scope, $attrs, progressConfig, $transition) {
var self = this,
bars = [],
max = angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : progressConfig.max,
animate = angular.isDefined($attrs.animate) ? $scope.$parent.$eval($attrs.animate) : progressConfig.animate;
this.addBar = function(bar, element) {
var oldValue = 0, index = bar.$parent.$index;
if ( angular.isDefined(index) && bars[index] ) {
oldValue = bars[index].value;
}
bars.push(bar);
this.update(element, bar.value, oldValue);
bar.$watch('value', function(value, oldValue) {
if (value !== oldValue) {
self.update(element, value, oldValue);
}
});
bar.$on('$destroy', function() {
self.removeBar(bar);
});
};
// Update bar element width
this.update = function(element, newValue, oldValue) {
var percent = this.getPercentage(newValue);
if (animate) {
element.css('width', this.getPercentage(oldValue) + '%');
$transition(element, {width: percent + '%'});
} else {
element.css({'transition': 'none', 'width': percent + '%'});
}
};
this.removeBar = function(bar) {
bars.splice(bars.indexOf(bar), 1);
};
this.getPercentage = function(value) {
return Math.round(100 * value / max);
};
}])
.directive('progress', function() {
return {
restrict: 'EA',
replace: true,
transclude: true,
controller: 'ProgressController',
require: 'progress',
scope: {},
template: '<div class="progress" ng-transclude></div>'
//templateUrl: 'template/progressbar/progress.html' // Works in AngularJS 1.2
};
})
.directive('bar', function() {
return {
restrict: 'EA',
replace: true,
transclude: true,
require: '^progress',
scope: {
value: '=',
type: '@'
},
templateUrl: 'template/progressbar/bar.html',
link: function(scope, element, attrs, progressCtrl) {
progressCtrl.addBar(scope, element);
}
};
})
.directive('progressbar', function() {
return {
restrict: 'EA',
replace: true,
transclude: true,
controller: 'ProgressController',
scope: {
value: '=',
type: '@'
},
templateUrl: 'template/progressbar/progressbar.html',
link: function(scope, element, attrs, progressCtrl) {
progressCtrl.addBar(scope, angular.element(element.children()[0]));
}
};
});
angular.module('ui.bootstrap.rating', [])
.constant('ratingConfig', {
max: 5,
stateOn: null,
stateOff: null
})
.controller('RatingController', ['$scope', '$attrs', '$parse', 'ratingConfig', function($scope, $attrs, $parse, ratingConfig) {
this.maxRange = angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : ratingConfig.max;
this.stateOn = angular.isDefined($attrs.stateOn) ? $scope.$parent.$eval($attrs.stateOn) : ratingConfig.stateOn;
this.stateOff = angular.isDefined($attrs.stateOff) ? $scope.$parent.$eval($attrs.stateOff) : ratingConfig.stateOff;
this.createRateObjects = function(states) {
var defaultOptions = {
stateOn: this.stateOn,
stateOff: this.stateOff
};
for (var i = 0, n = states.length; i < n; i++) {
states[i] = angular.extend({ index: i }, defaultOptions, states[i]);
}
return states;
};
// Get objects used in template
$scope.range = angular.isDefined($attrs.ratingStates) ? this.createRateObjects(angular.copy($scope.$parent.$eval($attrs.ratingStates))): this.createRateObjects(new Array(this.maxRange));
$scope.rate = function(value) {
if ( $scope.value !== value && !$scope.readonly ) {
$scope.value = value;
}
};
$scope.enter = function(value) {
if ( ! $scope.readonly ) {
$scope.val = value;
}
$scope.onHover({value: value});
};
$scope.reset = function() {
$scope.val = angular.copy($scope.value);
$scope.onLeave();
};
$scope.$watch('value', function(value) {
$scope.val = value;
});
$scope.readonly = false;
if ($attrs.readonly) {
$scope.$parent.$watch($parse($attrs.readonly), function(value) {
$scope.readonly = !!value;
});
}
}])
.directive('rating', function() {
return {
restrict: 'EA',
scope: {
value: '=',
onHover: '&',
onLeave: '&'
},
controller: 'RatingController',
templateUrl: 'template/rating/rating.html',
replace: true
};
});
/**
* @ngdoc overview
* @name ui.bootstrap.tabs
*
* @description
* AngularJS version of the tabs directive.
*/
angular.module('ui.bootstrap.tabs', [])
.controller('TabsetController', ['$scope', function TabsetCtrl($scope) {
var ctrl = this,
tabs = ctrl.tabs = $scope.tabs = [];
ctrl.select = function(tab) {
angular.forEach(tabs, function(tab) {
tab.active = false;
});
tab.active = true;
};
ctrl.addTab = function addTab(tab) {
tabs.push(tab);
if (tabs.length === 1 || tab.active) {
ctrl.select(tab);
}
};
ctrl.removeTab = function removeTab(tab) {
var index = tabs.indexOf(tab);
//Select a new tab if the tab to be removed is selected
if (tab.active && tabs.length > 1) {
//If this is the last tab, select the previous tab. else, the next tab.
var newActiveIndex = index == tabs.length - 1 ? index - 1 : index + 1;
ctrl.select(tabs[newActiveIndex]);
}
tabs.splice(index, 1);
};
}])
/**
* @ngdoc directive
* @name ui.bootstrap.tabs.directive:tabset
* @restrict EA
*
* @description
* Tabset is the outer container for the tabs directive
*
* @param {boolean=} vertical Whether or not to use vertical styling for the tabs.
* @param {boolean=} justified Whether or not to use justified styling for the tabs.
*
* @example
<example module="ui.bootstrap">
<file name="index.html">
<tabset>
<tab heading="Tab 1"><b>First</b> Content!</tab>
<tab heading="Tab 2"><i>Second</i> Content!</tab>
</tabset>
<hr />
<tabset vertical="true">
<tab heading="Vertical Tab 1"><b>First</b> Vertical Content!</tab>
<tab heading="Vertical Tab 2"><i>Second</i> Vertical Content!</tab>
</tabset>
<tabset justified="true">
<tab heading="Justified Tab 1"><b>First</b> Justified Content!</tab>
<tab heading="Justified Tab 2"><i>Second</i> Justified Content!</tab>
</tabset>
</file>
</example>
*/
.directive('tabset', function() {
return {
restrict: 'EA',
transclude: true,
replace: true,
scope: {},
controller: 'TabsetController',
templateUrl: 'template/tabs/tabset.html',
link: function(scope, element, attrs) {
scope.vertical = angular.isDefined(attrs.vertical) ? scope.$parent.$eval(attrs.vertical) : false;
scope.justified = angular.isDefined(attrs.justified) ? scope.$parent.$eval(attrs.justified) : false;
scope.type = angular.isDefined(attrs.type) ? scope.$parent.$eval(attrs.type) : 'tabs';
}
};
})
/**
* @ngdoc directive
* @name ui.bootstrap.tabs.directive:tab
* @restrict EA
*
* @param {string=} heading The visible heading, or title, of the tab. Set HTML headings with {@link ui.bootstrap.tabs.directive:tabHeading tabHeading}.
* @param {string=} select An expression to evaluate when the tab is selected.
* @param {boolean=} active A binding, telling whether or not this tab is selected.
* @param {boolean=} disabled A binding, telling whether or not this tab is disabled.
*
* @description
* Creates a tab with a heading and content. Must be placed within a {@link ui.bootstrap.tabs.directive:tabset tabset}.
*
* @example
<example module="ui.bootstrap">
<file name="index.html">
<div ng-controller="TabsDemoCtrl">
<button class="btn btn-small" ng-click="items[0].active = true">
Select item 1, using active binding
</button>
<button class="btn btn-small" ng-click="items[1].disabled = !items[1].disabled">
Enable/disable item 2, using disabled binding
</button>
<br />
<tabset>
<tab heading="Tab 1">First Tab</tab>
<tab select="alertMe()">
<tab-heading><i class="icon-bell"></i> Alert me!</tab-heading>
Second Tab, with alert callback and html heading!
</tab>
<tab ng-repeat="item in items"
heading="{{item.title}}"
disabled="item.disabled"
active="item.active">
{{item.content}}
</tab>
</tabset>
</div>
</file>
<file name="script.js">
function TabsDemoCtrl($scope) {
$scope.items = [
{ title:"Dynamic Title 1", content:"Dynamic Item 0" },
{ title:"Dynamic Title 2", content:"Dynamic Item 1", disabled: true }
];
$scope.alertMe = function() {
setTimeout(function() {
alert("You've selected the alert tab!");
});
};
};
</file>
</example>
*/
/**
* @ngdoc directive
* @name ui.bootstrap.tabs.directive:tabHeading
* @restrict EA
*
* @description
* Creates an HTML heading for a {@link ui.bootstrap.tabs.directive:tab tab}. Must be placed as a child of a tab element.
*
* @example
<example module="ui.bootstrap">
<file name="index.html">
<tabset>
<tab>
<tab-heading><b>HTML</b> in my titles?!</tab-heading>
And some content, too!
</tab>
<tab>
<tab-heading><i class="icon-heart"></i> Icon heading?!?</tab-heading>
That's right.
</tab>
</tabset>
</file>
</example>
*/
.directive('tab', ['$parse', function($parse) {
return {
require: '^tabset',
restrict: 'EA',
replace: true,
templateUrl: 'template/tabs/tab.html',
transclude: true,
scope: {
heading: '@',
onSelect: '&select', //This callback is called in contentHeadingTransclude
//once it inserts the tab's content into the dom
onDeselect: '&deselect'
},
controller: function() {
//Empty controller so other directives can require being 'under' a tab
},
compile: function(elm, attrs, transclude) {
return function postLink(scope, elm, attrs, tabsetCtrl) {
var getActive, setActive;
if (attrs.active) {
getActive = $parse(attrs.active);
setActive = getActive.assign;
scope.$parent.$watch(getActive, function updateActive(value, oldVal) {
// Avoid re-initializing scope.active as it is already initialized
// below. (watcher is called async during init with value ===
// oldVal)
if (value !== oldVal) {
scope.active = !!value;
}
});
scope.active = getActive(scope.$parent);
} else {
setActive = getActive = angular.noop;
}
scope.$watch('active', function(active) {
// Note this watcher also initializes and assigns scope.active to the
// attrs.active expression.
setActive(scope.$parent, active);
if (active) {
tabsetCtrl.select(scope);
scope.onSelect();
} else {
scope.onDeselect();
}
});
scope.disabled = false;
if ( attrs.disabled ) {
scope.$parent.$watch($parse(attrs.disabled), function(value) {
scope.disabled = !! value;
});
}
scope.select = function() {
if ( ! scope.disabled ) {
scope.active = true;
}
};
tabsetCtrl.addTab(scope);
scope.$on('$destroy', function() {
tabsetCtrl.removeTab(scope);
});
//We need to transclude later, once the content container is ready.
//when this link happens, we're inside a tab heading.
scope.$transcludeFn = transclude;
};
}
};
}])
.directive('tabHeadingTransclude', [function() {
return {
restrict: 'A',
require: '^tab',
link: function(scope, elm, attrs, tabCtrl) {
scope.$watch('headingElement', function updateHeadingElement(heading) {
if (heading) {
elm.html('');
elm.append(heading);
}
});
}
};
}])
.directive('tabContentTransclude', function() {
return {
restrict: 'A',
require: '^tabset',
link: function(scope, elm, attrs) {
var tab = scope.$eval(attrs.tabContentTransclude);
//Now our tab is ready to be transcluded: both the tab heading area
//and the tab content area are loaded. Transclude 'em both.
tab.$transcludeFn(tab.$parent, function(contents) {
angular.forEach(contents, function(node) {
if (isTabHeading(node)) {
//Let tabHeadingTransclude know.
tab.headingElement = node;
} else {
elm.append(node);
}
});
});
}
};
function isTabHeading(node) {
return node.tagName && (
node.hasAttribute('tab-heading') ||
node.hasAttribute('data-tab-heading') ||
node.tagName.toLowerCase() === 'tab-heading' ||
node.tagName.toLowerCase() === 'data-tab-heading'
);
}
})
;
angular.module('ui.bootstrap.timepicker', [])
.constant('timepickerConfig', {
hourStep: 1,
minuteStep: 1,
showMeridian: true,
meridians: null,
readonlyInput: false,
mousewheel: true
})
.directive('timepicker', ['$parse', '$log', 'timepickerConfig', '$locale', function ($parse, $log, timepickerConfig, $locale) {
return {
restrict: 'EA',
require:'?^ngModel',
replace: true,
scope: {},
templateUrl: 'template/timepicker/timepicker.html',
link: function(scope, element, attrs, ngModel) {
if ( !ngModel ) {
return; // do nothing if no ng-model
}
var selected = new Date(),
meridians = angular.isDefined(attrs.meridians) ? scope.$parent.$eval(attrs.meridians) : timepickerConfig.meridians || $locale.DATETIME_FORMATS.AMPMS;
var hourStep = timepickerConfig.hourStep;
if (attrs.hourStep) {
scope.$parent.$watch($parse(attrs.hourStep), function(value) {
hourStep = parseInt(value, 10);
});
}
var minuteStep = timepickerConfig.minuteStep;
if (attrs.minuteStep) {
scope.$parent.$watch($parse(attrs.minuteStep), function(value) {
minuteStep = parseInt(value, 10);
});
}
// 12H / 24H mode
scope.showMeridian = timepickerConfig.showMeridian;
if (attrs.showMeridian) {
scope.$parent.$watch($parse(attrs.showMeridian), function(value) {
scope.showMeridian = !!value;
if ( ngModel.$error.time ) {
// Evaluate from template
var hours = getHoursFromTemplate(), minutes = getMinutesFromTemplate();
if (angular.isDefined( hours ) && angular.isDefined( minutes )) {
selected.setHours( hours );
refresh();
}
} else {
updateTemplate();
}
});
}
// Get scope.hours in 24H mode if valid
function getHoursFromTemplate ( ) {
var hours = parseInt( scope.hours, 10 );
var valid = ( scope.showMeridian ) ? (hours > 0 && hours < 13) : (hours >= 0 && hours < 24);
if ( !valid ) {
return undefined;
}
if ( scope.showMeridian ) {
if ( hours === 12 ) {
hours = 0;
}
if ( scope.meridian === meridians[1] ) {
hours = hours + 12;
}
}
return hours;
}
function getMinutesFromTemplate() {
var minutes = parseInt(scope.minutes, 10);
return ( minutes >= 0 && minutes < 60 ) ? minutes : undefined;
}
function pad( value ) {
return ( angular.isDefined(value) && value.toString().length < 2 ) ? '0' + value : value;
}
// Input elements
var inputs = element.find('input'), hoursInputEl = inputs.eq(0), minutesInputEl = inputs.eq(1);
// Respond on mousewheel spin
var mousewheel = (angular.isDefined(attrs.mousewheel)) ? scope.$eval(attrs.mousewheel) : timepickerConfig.mousewheel;
if ( mousewheel ) {
var isScrollingUp = function(e) {
if (e.originalEvent) {
e = e.originalEvent;
}
//pick correct delta variable depending on event
var delta = (e.wheelDelta) ? e.wheelDelta : -e.deltaY;
return (e.detail || delta > 0);
};
hoursInputEl.bind('mousewheel wheel', function(e) {
scope.$apply( (isScrollingUp(e)) ? scope.incrementHours() : scope.decrementHours() );
e.preventDefault();
});
minutesInputEl.bind('mousewheel wheel', function(e) {
scope.$apply( (isScrollingUp(e)) ? scope.incrementMinutes() : scope.decrementMinutes() );
e.preventDefault();
});
}
scope.readonlyInput = (angular.isDefined(attrs.readonlyInput)) ? scope.$eval(attrs.readonlyInput) : timepickerConfig.readonlyInput;
if ( ! scope.readonlyInput ) {
var invalidate = function(invalidHours, invalidMinutes) {
ngModel.$setViewValue( null );
ngModel.$setValidity('time', false);
if (angular.isDefined(invalidHours)) {
scope.invalidHours = invalidHours;
}
if (angular.isDefined(invalidMinutes)) {
scope.invalidMinutes = invalidMinutes;
}
};
scope.updateHours = function() {
var hours = getHoursFromTemplate();
if ( angular.isDefined(hours) ) {
selected.setHours( hours );
refresh( 'h' );
} else {
invalidate(true);
}
};
hoursInputEl.bind('blur', function(e) {
if ( !scope.validHours && scope.hours < 10) {
scope.$apply( function() {
scope.hours = pad( scope.hours );
});
}
});
scope.updateMinutes = function() {
var minutes = getMinutesFromTemplate();
if ( angular.isDefined(minutes) ) {
selected.setMinutes( minutes );
refresh( 'm' );
} else {
invalidate(undefined, true);
}
};
minutesInputEl.bind('blur', function(e) {
if ( !scope.invalidMinutes && scope.minutes < 10 ) {
scope.$apply( function() {
scope.minutes = pad( scope.minutes );
});
}
});
} else {
scope.updateHours = angular.noop;
scope.updateMinutes = angular.noop;
}
ngModel.$render = function() {
var date = ngModel.$modelValue ? new Date( ngModel.$modelValue ) : null;
if ( isNaN(date) ) {
ngModel.$setValidity('time', false);
$log.error('Timepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.');
} else {
if ( date ) {
selected = date;
}
makeValid();
updateTemplate();
}
};
// Call internally when we know that model is valid.
function refresh( keyboardChange ) {
makeValid();
ngModel.$setViewValue( new Date(selected) );
updateTemplate( keyboardChange );
}
function makeValid() {
ngModel.$setValidity('time', true);
scope.invalidHours = false;
scope.invalidMinutes = false;
}
function updateTemplate( keyboardChange ) {
var hours = selected.getHours(), minutes = selected.getMinutes();
if ( scope.showMeridian ) {
hours = ( hours === 0 || hours === 12 ) ? 12 : hours % 12; // Convert 24 to 12 hour system
}
scope.hours = keyboardChange === 'h' ? hours : pad(hours);
scope.minutes = keyboardChange === 'm' ? minutes : pad(minutes);
scope.meridian = selected.getHours() < 12 ? meridians[0] : meridians[1];
}
function addMinutes( minutes ) {
var dt = new Date( selected.getTime() + minutes * 60000 );
selected.setHours( dt.getHours(), dt.getMinutes() );
refresh();
}
scope.incrementHours = function() {
addMinutes( hourStep * 60 );
};
scope.decrementHours = function() {
addMinutes( - hourStep * 60 );
};
scope.incrementMinutes = function() {
addMinutes( minuteStep );
};
scope.decrementMinutes = function() {
addMinutes( - minuteStep );
};
scope.toggleMeridian = function() {
addMinutes( 12 * 60 * (( selected.getHours() < 12 ) ? 1 : -1) );
};
}
};
}]);
angular.module('ui.bootstrap.typeahead', ['ui.bootstrap.position', 'ui.bootstrap.bindHtml'])
/**
* A helper service that can parse typeahead's syntax (string provided by users)
* Extracted to a separate service for ease of unit testing
*/
.factory('typeaheadParser', ['$parse', function ($parse) {
// 00000111000000000000022200000000000000003333333333333330000000000044000
var TYPEAHEAD_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?\s+for\s+(?:([\$\w][\$\w\d]*))\s+in\s+(.*)$/;
return {
parse:function (input) {
var match = input.match(TYPEAHEAD_REGEXP), modelMapper, viewMapper, source;
if (!match) {
throw new Error(
"Expected typeahead specification in form of '_modelValue_ (as _label_)? for _item_ in _collection_'" +
" but got '" + input + "'.");
}
return {
itemName:match[3],
source:$parse(match[4]),
viewMapper:$parse(match[2] || match[1]),
modelMapper:$parse(match[1])
};
}
};
}])
.directive('typeahead', ['$compile', '$parse', '$q', '$timeout', '$document', '$position', 'typeaheadParser',
function ($compile, $parse, $q, $timeout, $document, $position, typeaheadParser) {
var HOT_KEYS = [9, 13, 27, 38, 40];
return {
require:'ngModel',
link:function (originalScope, element, attrs, modelCtrl) {
//SUPPORTED ATTRIBUTES (OPTIONS)
//minimal no of characters that needs to be entered before typeahead kicks-in
var minSearch = originalScope.$eval(attrs.typeaheadMinLength) || 1;
//minimal wait time after last character typed before typehead kicks-in
var waitTime = originalScope.$eval(attrs.typeaheadWaitMs) || 0;
//should it restrict model values to the ones selected from the popup only?
var isEditable = originalScope.$eval(attrs.typeaheadEditable) !== false;
//binding to a variable that indicates if matches are being retrieved asynchronously
var isLoadingSetter = $parse(attrs.typeaheadLoading).assign || angular.noop;
//a callback executed when a match is selected
var onSelectCallback = $parse(attrs.typeaheadOnSelect);
var inputFormatter = attrs.typeaheadInputFormatter ? $parse(attrs.typeaheadInputFormatter) : undefined;
var appendToBody = attrs.typeaheadAppendToBody ? $parse(attrs.typeaheadAppendToBody) : false;
//INTERNAL VARIABLES
//model setter executed upon match selection
var $setModelValue = $parse(attrs.ngModel).assign;
//expressions used by typeahead
var parserResult = typeaheadParser.parse(attrs.typeahead);
var hasFocus;
//pop-up element used to display matches
var popUpEl = angular.element('<div typeahead-popup></div>');
popUpEl.attr({
matches: 'matches',
active: 'activeIdx',
select: 'select(activeIdx)',
query: 'query',
position: 'position'
});
//custom item template
if (angular.isDefined(attrs.typeaheadTemplateUrl)) {
popUpEl.attr('template-url', attrs.typeaheadTemplateUrl);
}
//create a child scope for the typeahead directive so we are not polluting original scope
//with typeahead-specific data (matches, query etc.)
var scope = originalScope.$new();
originalScope.$on('$destroy', function(){
scope.$destroy();
});
var resetMatches = function() {
scope.matches = [];
scope.activeIdx = -1;
};
var getMatchesAsync = function(inputValue) {
var locals = {$viewValue: inputValue};
isLoadingSetter(originalScope, true);
$q.when(parserResult.source(originalScope, locals)).then(function(matches) {
//it might happen that several async queries were in progress if a user were typing fast
//but we are interested only in responses that correspond to the current view value
if (inputValue === modelCtrl.$viewValue && hasFocus) {
if (matches.length > 0) {
scope.activeIdx = 0;
scope.matches.length = 0;
//transform labels
for(var i=0; i<matches.length; i++) {
locals[parserResult.itemName] = matches[i];
scope.matches.push({
label: parserResult.viewMapper(scope, locals),
model: matches[i]
});
}
scope.query = inputValue;
//position pop-up with matches - we need to re-calculate its position each time we are opening a window
//with matches as a pop-up might be absolute-positioned and position of an input might have changed on a page
//due to other elements being rendered
scope.position = appendToBody ? $position.offset(element) : $position.position(element);
scope.position.top = scope.position.top + element.prop('offsetHeight');
} else {
resetMatches();
}
isLoadingSetter(originalScope, false);
}
}, function(){
resetMatches();
isLoadingSetter(originalScope, false);
});
};
resetMatches();
//we need to propagate user's query so we can higlight matches
scope.query = undefined;
//Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later
var timeoutPromise;
//plug into $parsers pipeline to open a typeahead on view changes initiated from DOM
//$parsers kick-in on all the changes coming from the view as well as manually triggered by $setViewValue
modelCtrl.$parsers.unshift(function (inputValue) {
hasFocus = true;
if (inputValue && inputValue.length >= minSearch) {
if (waitTime > 0) {
if (timeoutPromise) {
$timeout.cancel(timeoutPromise);//cancel previous timeout
}
timeoutPromise = $timeout(function () {
getMatchesAsync(inputValue);
}, waitTime);
} else {
getMatchesAsync(inputValue);
}
} else {
isLoadingSetter(originalScope, false);
resetMatches();
}
if (isEditable) {
return inputValue;
} else {
if (!inputValue) {
// Reset in case user had typed something previously.
modelCtrl.$setValidity('editable', true);
return inputValue;
} else {
modelCtrl.$setValidity('editable', false);
return undefined;
}
}
});
modelCtrl.$formatters.push(function (modelValue) {
var candidateViewValue, emptyViewValue;
var locals = {};
if (inputFormatter) {
locals['$model'] = modelValue;
return inputFormatter(originalScope, locals);
} else {
//it might happen that we don't have enough info to properly render input value
//we need to check for this situation and simply return model value if we can't apply custom formatting
locals[parserResult.itemName] = modelValue;
candidateViewValue = parserResult.viewMapper(originalScope, locals);
locals[parserResult.itemName] = undefined;
emptyViewValue = parserResult.viewMapper(originalScope, locals);
return candidateViewValue!== emptyViewValue ? candidateViewValue : modelValue;
}
});
scope.select = function (activeIdx) {
//called from within the $digest() cycle
var locals = {};
var model, item;
locals[parserResult.itemName] = item = scope.matches[activeIdx].model;
model = parserResult.modelMapper(originalScope, locals);
$setModelValue(originalScope, model);
modelCtrl.$setValidity('editable', true);
onSelectCallback(originalScope, {
$item: item,
$model: model,
$label: parserResult.viewMapper(originalScope, locals)
});
resetMatches();
//return focus to the input element if a mach was selected via a mouse click event
element[0].focus();
};
//bind keyboard events: arrows up(38) / down(40), enter(13) and tab(9), esc(27)
element.bind('keydown', function (evt) {
//typeahead is open and an "interesting" key was pressed
if (scope.matches.length === 0 || HOT_KEYS.indexOf(evt.which) === -1) {
return;
}
evt.preventDefault();
if (evt.which === 40) {
scope.activeIdx = (scope.activeIdx + 1) % scope.matches.length;
scope.$digest();
} else if (evt.which === 38) {
scope.activeIdx = (scope.activeIdx ? scope.activeIdx : scope.matches.length) - 1;
scope.$digest();
} else if (evt.which === 13 || evt.which === 9) {
scope.$apply(function () {
scope.select(scope.activeIdx);
});
} else if (evt.which === 27) {
evt.stopPropagation();
resetMatches();
scope.$digest();
}
});
element.bind('blur', function (evt) {
hasFocus = false;
});
// Keep reference to click handler to unbind it.
var dismissClickHandler = function (evt) {
if (element[0] !== evt.target) {
resetMatches();
scope.$digest();
}
};
$document.bind('click', dismissClickHandler);
originalScope.$on('$destroy', function(){
$document.unbind('click', dismissClickHandler);
});
var $popup = $compile(popUpEl)(scope);
if ( appendToBody ) {
$document.find('body').append($popup);
} else {
element.after($popup);
}
}
};
}])
.directive('typeaheadPopup', function () {
return {
restrict:'EA',
scope:{
matches:'=',
query:'=',
active:'=',
position:'=',
select:'&'
},
replace:true,
templateUrl:'template/typeahead/typeahead-popup.html',
link:function (scope, element, attrs) {
scope.templateUrl = attrs.templateUrl;
scope.isOpen = function () {
return scope.matches.length > 0;
};
scope.isActive = function (matchIdx) {
return scope.active == matchIdx;
};
scope.selectActive = function (matchIdx) {
scope.active = matchIdx;
};
scope.selectMatch = function (activeIdx) {
scope.select({activeIdx:activeIdx});
};
}
};
})
.directive('typeaheadMatch', ['$http', '$templateCache', '$compile', '$parse', function ($http, $templateCache, $compile, $parse) {
return {
restrict:'EA',
scope:{
index:'=',
match:'=',
query:'='
},
link:function (scope, element, attrs) {
var tplUrl = $parse(attrs.templateUrl)(scope.$parent) || 'template/typeahead/typeahead-match.html';
$http.get(tplUrl, {cache: $templateCache}).success(function(tplContent){
element.replaceWith($compile(tplContent.trim())(scope));
});
}
};
}])
.filter('typeaheadHighlight', function() {
function escapeRegexp(queryToEscape) {
return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
}
return function(matchItem, query) {
return query ? matchItem.replace(new RegExp(escapeRegexp(query), 'gi'), '<strong>$&</strong>') : matchItem;
};
});
angular.module("template/accordion/accordion-group.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/accordion/accordion-group.html",
"<div class=\"panel panel-default\">\n" +
" <div class=\"panel-heading\">\n" +
" <h4 class=\"panel-title\">\n" +
" <a class=\"accordion-toggle\" ng-click=\"isOpen = !isOpen\" accordion-transclude=\"heading\">{{heading}}</a>\n" +
" </h4>\n" +
" </div>\n" +
" <div class=\"panel-collapse\" collapse=\"!isOpen\">\n" +
" <div class=\"panel-body\" ng-transclude></div>\n" +
" </div>\n" +
"</div>");
}]);
angular.module("template/accordion/accordion.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/accordion/accordion.html",
"<div class=\"panel-group\" ng-transclude></div>");
}]);
angular.module("template/alert/alert.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/alert/alert.html",
"<div class='alert' ng-class='\"alert-\" + (type || \"warning\")'>\n" +
" <button ng-show='closeable' type='button' class='close' ng-click='close()'>×</button>\n" +
" <div ng-transclude></div>\n" +
"</div>\n" +
"");
}]);
angular.module("template/carousel/carousel.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/carousel/carousel.html",
"<div ng-mouseenter=\"pause()\" ng-mouseleave=\"play()\" class=\"carousel\">\n" +
" <ol class=\"carousel-indicators\" ng-show=\"slides().length > 1\">\n" +
" <li ng-repeat=\"slide in slides()\" ng-class=\"{active: isActive(slide)}\" ng-click=\"select(slide)\"></li>\n" +
" </ol>\n" +
" <div class=\"carousel-inner\" ng-transclude></div>\n" +
" <a class=\"left carousel-control\" ng-click=\"prev()\" ng-show=\"slides().length > 1\"><span class=\"icon-prev\"></span></a>\n" +
" <a class=\"right carousel-control\" ng-click=\"next()\" ng-show=\"slides().length > 1\"><span class=\"icon-next\"></span></a>\n" +
"</div>\n" +
"");
}]);
angular.module("template/carousel/slide.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/carousel/slide.html",
"<div ng-class=\"{\n" +
" 'active': leaving || (active && !entering),\n" +
" 'prev': (next || active) && direction=='prev',\n" +
" 'next': (next || active) && direction=='next',\n" +
" 'right': direction=='prev',\n" +
" 'left': direction=='next'\n" +
" }\" class=\"item text-center\" ng-transclude></div>\n" +
"");
}]);
angular.module("template/datepicker/datepicker.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/datepicker/datepicker.html",
"<table>\n" +
" <thead>\n" +
" <tr>\n" +
" <th><button type=\"button\" class=\"btn btn-default btn-sm pull-left\" ng-click=\"move(-1)\"><i class=\"glyphicon glyphicon-chevron-left\"></i></button></th>\n" +
" <th colspan=\"{{rows[0].length - 2 + showWeekNumbers}}\"><button type=\"button\" class=\"btn btn-default btn-sm btn-block\" ng-click=\"toggleMode()\"><strong>{{title}}</strong></button></th>\n" +
" <th><button type=\"button\" class=\"btn btn-default btn-sm pull-right\" ng-click=\"move(1)\"><i class=\"glyphicon glyphicon-chevron-right\"></i></button></th>\n" +
" </tr>\n" +
" <tr ng-show=\"labels.length > 0\" class=\"h6\">\n" +
" <th ng-show=\"showWeekNumbers\" class=\"text-center\">#</th>\n" +
" <th ng-repeat=\"label in labels\" class=\"text-center\">{{label}}</th>\n" +
" </tr>\n" +
" </thead>\n" +
" <tbody>\n" +
" <tr ng-repeat=\"row in rows\">\n" +
" <td ng-show=\"showWeekNumbers\" class=\"text-center\"><em>{{ getWeekNumber(row) }}</em></td>\n" +
" <td ng-repeat=\"dt in row\" class=\"text-center\">\n" +
" <button type=\"button\" style=\"width:100%;\" class=\"btn btn-default btn-sm\" ng-class=\"{'btn-info': dt.selected}\" ng-click=\"select(dt.date)\" ng-disabled=\"dt.disabled\"><span ng-class=\"{'text-muted': dt.secondary}\">{{dt.label}}</span></button>\n" +
" </td>\n" +
" </tr>\n" +
" </tbody>\n" +
"</table>\n" +
"");
}]);
angular.module("template/datepicker/popup.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/datepicker/popup.html",
"<ul class=\"dropdown-menu\" ng-style=\"{display: (isOpen && 'block') || 'none', top: position.top+'px', left: position.left+'px'}\">\n" +
" <li ng-transclude></li>\n" +
" <li ng-show=\"showButtonBar\" style=\"padding:10px 9px 2px\">\n" +
" <span class=\"btn-group\">\n" +
" <button type=\"button\" class=\"btn btn-sm btn-info\" ng-click=\"today()\">{{currentText}}</button>\n" +
" <button type=\"button\" class=\"btn btn-sm btn-default\" ng-click=\"showWeeks = ! showWeeks\" ng-class=\"{active: showWeeks}\">{{toggleWeeksText}}</button>\n" +
" <button type=\"button\" class=\"btn btn-sm btn-danger\" ng-click=\"clear()\">{{clearText}}</button>\n" +
" </span>\n" +
" <button type=\"button\" class=\"btn btn-sm btn-success pull-right\" ng-click=\"isOpen = false\">{{closeText}}</button>\n" +
" </li>\n" +
"</ul>\n" +
"");
}]);
angular.module("template/modal/backdrop.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/modal/backdrop.html",
"<div class=\"modal-backdrop fade\" ng-class=\"{in: animate}\" ng-style=\"{'z-index': 1040 + index*10}\"></div>");
}]);
angular.module("template/modal/window.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/modal/window.html",
"<div tabindex=\"-1\" class=\"modal fade {{ windowClass }}\" ng-class=\"{in: animate}\" ng-style=\"{'z-index': 1050 + index*10, display: 'block'}\" ng-click=\"close($event)\">\n" +
" <div class=\"modal-dialog\"><div class=\"modal-content\" ng-transclude></div></div>\n" +
"</div>");
}]);
angular.module("template/pagination/pager.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/pagination/pager.html",
"<ul class=\"pager\">\n" +
" <li ng-repeat=\"page in pages\" ng-class=\"{disabled: page.disabled, previous: page.previous, next: page.next}\"><a ng-click=\"selectPage(page.number)\">{{page.text}}</a></li>\n" +
"</ul>");
}]);
angular.module("template/pagination/pagination.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/pagination/pagination.html",
"<ul class=\"pagination\">\n" +
" <li ng-repeat=\"page in pages\" ng-class=\"{active: page.active, disabled: page.disabled}\"><a ng-click=\"selectPage(page.number)\">{{page.text}}</a></li>\n" +
"</ul>");
}]);
angular.module("template/tooltip/tooltip-html-unsafe-popup.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/tooltip/tooltip-html-unsafe-popup.html",
"<div class=\"tooltip {{placement}}\" ng-class=\"{ in: isOpen(), fade: animation() }\">\n" +
" <div class=\"tooltip-arrow\"></div>\n" +
" <div class=\"tooltip-inner\" bind-html-unsafe=\"content\"></div>\n" +
"</div>\n" +
"");
}]);
angular.module("template/tooltip/tooltip-popup.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/tooltip/tooltip-popup.html",
"<div class=\"tooltip {{placement}}\" ng-class=\"{ in: isOpen(), fade: animation() }\">\n" +
" <div class=\"tooltip-arrow\"></div>\n" +
" <div class=\"tooltip-inner\" ng-bind=\"content\"></div>\n" +
"</div>\n" +
"");
}]);
angular.module("template/popover/popover.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/popover/popover.html",
"<div class=\"popover {{placement}}\" ng-class=\"{ in: isOpen(), fade: animation() }\">\n" +
" <div class=\"arrow\"></div>\n" +
"\n" +
" <div class=\"popover-inner\">\n" +
" <h3 class=\"popover-title\" ng-bind=\"title\" ng-show=\"title\"></h3>\n" +
" <div class=\"popover-content\" ng-bind=\"content\"></div>\n" +
" </div>\n" +
"</div>\n" +
"");
}]);
angular.module("template/progressbar/bar.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/progressbar/bar.html",
"<div class=\"progress-bar\" ng-class=\"type && 'progress-bar-' + type\" ng-transclude></div>");
}]);
angular.module("template/progressbar/progress.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/progressbar/progress.html",
"<div class=\"progress\" ng-transclude></div>");
}]);
angular.module("template/progressbar/progressbar.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/progressbar/progressbar.html",
"<div class=\"progress\"><div class=\"progress-bar\" ng-class=\"type && 'progress-bar-' + type\" ng-transclude></div></div>");
}]);
angular.module("template/rating/rating.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/rating/rating.html",
"<span ng-mouseleave=\"reset()\">\n" +
" <i ng-repeat=\"r in range\" ng-mouseenter=\"enter($index + 1)\" ng-click=\"rate($index + 1)\" class=\"glyphicon\" ng-class=\"$index < val && (r.stateOn || 'glyphicon-star') || (r.stateOff || 'glyphicon-star-empty')\"></i>\n" +
"</span>");
}]);
angular.module("template/tabs/tab.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/tabs/tab.html",
"<li ng-class=\"{active: active, disabled: disabled}\">\n" +
" <a ng-click=\"select()\" tab-heading-transclude>{{heading}}</a>\n" +
"</li>\n" +
"");
}]);
angular.module("template/tabs/tabset-titles.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/tabs/tabset-titles.html",
"<ul class=\"nav {{type && 'nav-' + type}}\" ng-class=\"{'nav-stacked': vertical}\">\n" +
"</ul>\n" +
"");
}]);
angular.module("template/tabs/tabset.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/tabs/tabset.html",
"\n" +
"<div class=\"tabbable\">\n" +
" <ul class=\"nav {{type && 'nav-' + type}}\" ng-class=\"{'nav-stacked': vertical, 'nav-justified': justified}\" ng-transclude></ul>\n" +
" <div class=\"tab-content\">\n" +
" <div class=\"tab-pane\" \n" +
" ng-repeat=\"tab in tabs\" \n" +
" ng-class=\"{active: tab.active}\"\n" +
" tab-content-transclude=\"tab\">\n" +
" </div>\n" +
" </div>\n" +
"</div>\n" +
"");
}]);
angular.module("template/timepicker/timepicker.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/timepicker/timepicker.html",
"<table>\n" +
" <tbody>\n" +
" <tr class=\"text-center\">\n" +
" <td><a ng-click=\"incrementHours()\" class=\"btn btn-link\"><span class=\"glyphicon glyphicon-chevron-up\"></span></a></td>\n" +
" <td> </td>\n" +
" <td><a ng-click=\"incrementMinutes()\" class=\"btn btn-link\"><span class=\"glyphicon glyphicon-chevron-up\"></span></a></td>\n" +
" <td ng-show=\"showMeridian\"></td>\n" +
" </tr>\n" +
" <tr>\n" +
" <td style=\"width:50px;\" class=\"form-group\" ng-class=\"{'has-error': invalidHours}\">\n" +
" <input type=\"text\" ng-model=\"hours\" ng-change=\"updateHours()\" class=\"form-control text-center\" ng-mousewheel=\"incrementHours()\" ng-readonly=\"readonlyInput\" maxlength=\"2\">\n" +
" </td>\n" +
" <td>:</td>\n" +
" <td style=\"width:50px;\" class=\"form-group\" ng-class=\"{'has-error': invalidMinutes}\">\n" +
" <input type=\"text\" ng-model=\"minutes\" ng-change=\"updateMinutes()\" class=\"form-control text-center\" ng-readonly=\"readonlyInput\" maxlength=\"2\">\n" +
" </td>\n" +
" <td ng-show=\"showMeridian\"><button type=\"button\" class=\"btn btn-default text-center\" ng-click=\"toggleMeridian()\">{{meridian}}</button></td>\n" +
" </tr>\n" +
" <tr class=\"text-center\">\n" +
" <td><a ng-click=\"decrementHours()\" class=\"btn btn-link\"><span class=\"glyphicon glyphicon-chevron-down\"></span></a></td>\n" +
" <td> </td>\n" +
" <td><a ng-click=\"decrementMinutes()\" class=\"btn btn-link\"><span class=\"glyphicon glyphicon-chevron-down\"></span></a></td>\n" +
" <td ng-show=\"showMeridian\"></td>\n" +
" </tr>\n" +
" </tbody>\n" +
"</table>\n" +
"");
}]);
angular.module("template/typeahead/typeahead-match.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/typeahead/typeahead-match.html",
"<a tabindex=\"-1\" bind-html-unsafe=\"match.label | typeaheadHighlight:query\"></a>");
}]);
angular.module("template/typeahead/typeahead-popup.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/typeahead/typeahead-popup.html",
"<ul class=\"dropdown-menu\" ng-style=\"{display: isOpen()&&'block' || 'none', top: position.top+'px', left: position.left+'px'}\">\n" +
" <li ng-repeat=\"match in matches\" ng-class=\"{active: isActive($index) }\" ng-mouseenter=\"selectActive($index)\" ng-click=\"selectMatch($index)\">\n" +
" <div typeahead-match index=\"$index\" match=\"match\" query=\"query\" template-url=\"templateUrl\"></div>\n" +
" </li>\n" +
"</ul>");
}]);
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M20 6.54v10.91c-2.6-.77-5.28-1.16-8-1.16s-5.4.39-8 1.16V6.54c2.6.77 5.28 1.16 8 1.16 2.72.01 5.4-.38 8-1.16M21.43 4c-.1 0-.2.02-.31.06C18.18 5.16 15.09 5.7 12 5.7s-6.18-.55-9.12-1.64C2.77 4.02 2.66 4 2.57 4c-.34 0-.57.23-.57.63v14.75c0 .39.23.62.57.62.1 0 .2-.02.31-.06 2.94-1.1 6.03-1.64 9.12-1.64s6.18.55 9.12 1.64c.11.04.21.06.31.06.33 0 .57-.23.57-.63V4.63c0-.4-.24-.63-.57-.63z" /></g></React.Fragment>
, 'PanoramaHorizontalRounded');
|
(function ($) {
"use strict";
var skin = require('../lib/_skin')();
/**
* jQuery plugin wrapper for compatibility with Angular UI.Utils: jQuery Passthrough
*/
$.fn.tkEasyPie = function () {
if (! this.length) return;
if (!$.fn.easyPieChart) return;
var color = config.skins[ skin ][ 'primary-color' ];
if (this.is('.info')) color = colors[ 'info-color' ];
if (this.is('.danger')) color = colors[ 'danger-color' ];
if (this.is('.success')) color = colors[ 'success-color' ];
if (this.is('.warning')) color = colors[ 'warning-color' ];
if (this.is('.inverse')) color = colors[ 'inverse-color' ];
this.easyPieChart({
barColor: color,
animate: ($('html').is('.ie') ? false : 3000),
lineWidth: 4,
size: 50
});
};
$.each($('.easy-pie'), function (k, v) {
$(this).tkEasyPie();
});
})(jQuery); |
const Choice = Jymfony.Component.Validator.Constraints.Choice;
const ConstraintDefinitionException = Jymfony.Component.Validator.Exception.ConstraintDefinitionException;
const ConstraintValidator = Jymfony.Component.Validator.ConstraintValidator;
const UnexpectedTypeException = Jymfony.Component.Validator.Exception.UnexpectedTypeException;
/**
* Validates that a card number belongs to a specified scheme.
*
* @memberOf Jymfony.Component.Validator.Constraints
*/
export default class ChoiceValidator extends ConstraintValidator {
/**
* @inheritdoc
*/
validate(value, constraint) {
if (! (constraint instanceof Choice)) {
throw new UnexpectedTypeException(constraint, Choice);
}
if (! isArray(constraint.choices) && ! constraint.callback) {
throw new ConstraintDefinitionException('Either "choices" or "callback" must be specified on constraint Choice');
}
if (null === value || undefined === value) {
return;
}
if (constraint.multiple && ! isArray(value)) {
throw new UnexpectedTypeException(value, 'Array');
}
let choices;
if (constraint.callback) {
if (isCallableArray(constraint.callback)) {
choices = getCallableFromArray(constraint.callback);
} else if (isFunction(constraint.callback)) {
choices = constraint.callback;
} else {
try {
const reflClass = new ReflectionClass(this._context.object);
const method = reflClass.getMethod(constraint.callback);
choices = method.method;
} catch (e) {
// Do nothing.
}
}
if (! isFunction(choices)) {
throw new ConstraintDefinitionException('The Choice constraint expects a valid callback');
}
choices = choices();
} else {
choices = constraint.choices;
}
if (constraint.multiple) {
for (const _value of value) {
if (! choices.includes(_value)) {
this._context.buildViolation(constraint.multipleMessage)
.setParameter('{{ value }}', this._formatValue(_value))
.setCode(Choice.NO_SUCH_CHOICE_ERROR)
.setInvalidValue(_value)
.addViolation();
return;
}
}
const count = value.length;
if (undefined !== constraint.min && null !== constraint.min && count < constraint.min) {
this._context.buildViolation(constraint.minMessage)
.setParameter('{{ limit }}', constraint.min)
.setPlural(~~constraint.min)
.setCode(Choice.TOO_FEW_ERROR)
.addViolation();
return;
}
if (undefined !== constraint.max && null !== constraint.max && count > constraint.max) {
this._context.buildViolation(constraint.maxMessage)
.setParameter('{{ limit }}', constraint.max)
.setPlural(~~constraint.max)
.setCode(Choice.TOO_MANY_ERROR)
.addViolation();
}
} else if (! choices.includes(value)) {
this._context.buildViolation(constraint.message)
.setParameter('{{ value }}', this._formatValue(value))
.setParameter('{{ choices }}', this._formatValues(choices))
.setCode(Choice.NO_SUCH_CHOICE_ERROR)
.addViolation();
}
}
}
|
/************************************************
* REVOLUTION 5.4.6.4 EXTENSION - LAYER ANIMATION
* @version: 3.6.5 (08.03.2018)
* @requires jquery.themepunch.revolution.js
* @author ThemePunch
************************************************/
(function($) {
"use strict";
var _R = jQuery.fn.revolution,
_ISM = _R.is_mobile(),
_ANDROID = _R.is_android(),
extension = { alias:"LayerAnimation Min JS",
name:"revolution.extensions.layeranimation.min.js",
min_core: "5.4.6.4",
version:"3.6.5"
};
///////////////////////////////////////////
// EXTENDED FUNCTIONS AVAILABLE GLOBAL //
///////////////////////////////////////////
jQuery.extend(true,_R, {
updateMarkup : function(layer,o) {
var d = jQuery(layer).data();
if (d.start!==undefined && !d.frames_added && d.frames===undefined) {
var frames = new Array(),
oin = getAnimDatas(newAnimObject(),d.transform_in,undefined, false),
oout = getAnimDatas(newAnimObject(),d.transform_out,undefined, false),
oh = getAnimDatas(newAnimObject(),d.transform_hover,undefined, false);
if (jQuery.isNumeric(d.end) && jQuery.isNumeric(d.start) && jQuery.isNumeric(oin.speed)) {
d.end = (parseInt(d.end,0) - (parseInt(d.start,0)+parseFloat(oin.speed,0)));
}
frames.push({frame:"0", delay:d.start, from:d.transform_in, to:d.transform_idle, split:d.splitin, speed:oin.speed, ease:oin.anim.ease, mask:d.mask_in, splitdelay:d.elementdelay});
frames.push({frame:"5", delay:d.end, to:d.transform_out, split:d.splitout, speed:oout.speed, ease:oout.anim.ease, mask:d.mask_out, splitdelay:d.elementdelay});
if (d.transform_hover)
frames.push({frame:"hover", to:d.transform_hover, style:d.style_hover, speed:oh.speed, ease:oh.anim.ease, splitdelay:d.elementdelay});
d.frames = frames;
//layer.frames_added = true;
}
if (!d.frames_added) {
d.inframeindex = 0;
d.outframeindex = -1;
d.hoverframeindex = -1;
if (d.frames!==undefined) {
for (var i=0;i<d.frames.length;i++) {
// CHECK FOR BLOCK SFX ANIMATION
if (d.frames[i].sfx_effect!==undefined && d.frames[i].sfx_effect.indexOf('block')>=0) {
if (i===0) {
d.frames[i].from = "o:0";
d.frames[i].to = "o:1";
} else {
d.frames[i].to = "o:0";
}
d._sfx = "block";
}
if (d.frames[0].from===undefined) d.frames[0].from = "o:inherit";
if (d.frames[0].delay===0) d.frames[0].delay=20;
if (d.frames[i].frame==="hover")
d.hoverframeindex = i;
else
if (d.frames[i].frame==="frame_999" || d.frames[i].frame==="frame_out" || d.frames[i].frame==="last" || d.frames[i].frame==="end")
d.outframeindex = i;
if (d.frames[i].split!==undefined && d.frames[i].split.match(/chars|words|lines/g))
d.splittext = true;
}
}
d.outframeindex = d.outframeindex===-1 ? d.hoverframeindex === -1 ? d.frames.length-1 : d.frames.length -2 : d.outframeindex; // CHECK LATER !!!
d.frames_added = true;
}
},
// MAKE SURE THE ANIMATION ENDS WITH A CLEANING ON MOZ TRANSFORMS
animcompleted : function(_nc,opt) {
var _ = _nc.data(),
t = _.videotype,
ap = _.autoplay,
an = _.autoplayonlyfirsttime;
if (t!=undefined && t!="none")
if (ap==true || ap=="true" || ap=="on" || ap=="1sttime" || an) {
if (opt.sliderType!=="carousel" ||
(opt.sliderType==="carousel" && opt.carousel.showLayersAllTime==="on" && _nc.closest('li').hasClass("active-revslide")) ||
(opt.sliderType==="carousel" && opt.carousel.showLayersAllTime!=="on" && _nc.closest('li').hasClass("active-revslide"))
)
_R.playVideo(_nc,opt);
_R.toggleState(_nc.data('videotoggledby'));
if ( an || ap=="1sttime") {
_.autoplayonlyfirsttime = false;
_.autoplay = "off";
}
} else {
if (ap=="no1sttime")
_.datasetautoplay = 'on';
_R.unToggleState(_nc.data('videotoggledby'));
}
},
/********************************************************
- PREPARE AND DEFINE STATIC LAYER DIRECTIONS -
*********************************************************/
handleStaticLayers : function(_nc,opt) {
var s = parseInt(_nc.data('startslide'),0),
e = parseInt(_nc.data('endslide'),0);
if (s < 0)
s=0;
if (e <0 )
e = opt.realslideamount;
if (s===0 && e===opt.realslideamount-1)
e = opt.realslideamount+1;
_nc.data('startslide',s);
_nc.data('endslide',e);
},
/************************************
ANIMATE ALL CAPTIONS
*************************************/
animateTheCaptions : function(obj) {
if (_R.compare_version(extension).check==="stop") return false;
var opt = obj.opt,
nextli = obj.slide,
recall = obj.recall,
mtl = obj.maintimeline,
preset = obj.preset,
startSlideAnimAt = obj.startslideanimat,
base_offsetx = opt.sliderType==="carousel" ? 0 : opt.width/2 - (opt.gridwidth[opt.curWinRange]*opt.bw)/2,
base_offsety=0,
index = nextli.data('index');
// COLLECTION OF LAYERS
opt.layers = opt.layers || new Object();
opt.layers[index] = opt.layers[index] || nextli.find('.tp-caption');
opt.layers["static"] = opt.layers["static"] || opt.c.find('.tp-static-layers').find('.tp-caption');
if (opt.timelines === undefined) _R.createTimelineStructure(opt);
opt.conh = opt.c.height();
opt.conw = opt.c.width();
opt.ulw = opt.ul.width();
opt.ulh = opt.ul.height();
/* ENABLE DEBUG MODE */
if (opt.debugMode) {
nextli.addClass("indebugmode");
nextli.find('.helpgrid').remove();
opt.c.find('.hglayerinfo').remove();
nextli.append('<div class="helpgrid" style="width:'+(opt.gridwidth[opt.curWinRange]*opt.bw)+'px;height:'+(opt.gridheight[opt.curWinRange]*opt.bw)+'px;"></div>');
var hg = nextli.find('.helpgrid');
hg.append('<div class="hginfo">Zoom:'+(Math.round(opt.bw*100))+'% Device Level:'+opt.curWinRange+' Grid Preset:'+opt.gridwidth[opt.curWinRange]+'x'+opt.gridheight[opt.curWinRange]+'</div>')
opt.c.append('<div class="hglayerinfo"></div>')
hg.append('<div class="tlhg"></div>');
}
// PREPARE THE LAYERS
if (index!==undefined && opt.layers[index])
jQuery.each(opt.layers[index], function(i,a) {
var _t = jQuery(this);
_R.updateMarkup(this,opt);
_R.prepareSingleCaption({caption:_t, opt:opt, offsetx:base_offsetx, offsety:base_offsety, index:i, recall:recall, preset:preset});
if (!preset || startSlideAnimAt===0) _R.buildFullTimeLine({caption:_t, opt:opt, offsetx:base_offsetx, offsety:base_offsety, index:i, recall:recall, preset:preset, regenerate: startSlideAnimAt===0});
if (recall && opt.sliderType==="carousel" && opt.carousel.showLayersAllTime==="on") _R.animcompleted(_t,opt);
});
if (opt.layers["static"])
jQuery.each(opt.layers["static"], function(i,a) {
var _t = jQuery(this),
_ = _t.data();
if (_.hoveredstatus!==true && _.inhoveroutanimation!==true) {
_R.updateMarkup(this,opt);
_R.prepareSingleCaption({caption:_t, opt:opt, offsetx:base_offsetx, offsety:base_offsety, index:i, recall:recall, preset:preset});
if ((!preset || startSlideAnimAt===0) && _.veryfirstststic !==true) {
_R.buildFullTimeLine({caption:_t, opt:opt, offsetx:base_offsetx, offsety:base_offsety, index:i, recall:recall, preset:preset, regenerate: startSlideAnimAt===0});
_.veryfirstststic = true;
}
if (recall && opt.sliderType==="carousel" && opt.carousel.showLayersAllTime==="on") _R.animcompleted(_t,opt);
} else {
_R.prepareSingleCaption({caption:_t, opt:opt, offsetx:base_offsetx, offsety:base_offsety, index:i, recall:recall, preset:preset});
}
});
// RECALCULATE HEIGHTS OF SLIDE IF ROW EXIST
var _actli = opt.nextSlide === -1 || opt.nextSlide===undefined ? 0 : opt.nextSlide;
if (opt.rowzones!==undefined)
_actli = _actli>opt.rowzones.length ? opt.rowzones.length : _actli;
if (opt.rowzones!=undefined && opt.rowzones.length>0 && opt.rowzones[_actli]!=undefined && _actli>=0 && _actli<=opt.rowzones.length && opt.rowzones[_actli].length>0)
_R.setSize(opt);
// RESTART ANIMATION TIMELINES
if (!preset)
if (startSlideAnimAt!==undefined) {
if (index!==undefined)
jQuery.each(opt.timelines[index].layers,function(key,o) {
var _ = o.layer.data();
if (o.wrapper==="none" || o.wrapper===undefined) {
if (o.triggerstate=="keep" && _.triggerstate==="on")
_R.playAnimationFrame({caption:o.layer,opt:opt,frame:"frame_0", triggerdirection:"in", triggerframein:"frame_0", triggerframeout:"frame_999"});
else
o.timeline.restart();
}
});
if (opt.timelines.staticlayers)
jQuery.each(opt.timelines.staticlayers.layers,function(key,o) {
var _ = o.layer.data(),
in_v_range = _actli>=o.firstslide && _actli<=o.lastslide,
in_uv_range = _actli<o.firstslide || _actli>o.lastslide,
flt = o.timeline.getLabelTime("slide_"+o.firstslide),
elt = o.timeline.getLabelTime("slide_"+o.lastslide),
ct = _.static_layer_timeline_time,
isvisible = _.animdirection==="in" ? true : _.animdirection==="out" ? false : undefined,
triggered_in = _.frames[0].delay==="bytrigger",
triggered_out = _.frames[_.frames.length-1].delay==="bytrigger",
layer_start_status = _.triggered_startstatus,
triggerstate = _.lasttriggerstate;
if (_.hoveredstatus===true || _.inhoveroutanimation==true) return;
/*console.log("-----------------------")
console.log("Show Static Layer Start")
console.log("-----------------------")
console.log(ct);
console.log(isvisible)*/
// LAYER ALREADY VISIBLE, TIMER IS NOT UNKNOW ANY MORE
if (ct!==undefined && isvisible) {
if (triggerstate=="keep") {
_R.playAnimationFrame({caption:o.layer,opt:opt,frame:"frame_0", triggerdirection:"in", triggerframein:"frame_0", triggerframeout:"frame_999"});
_.triggeredtimeline.time(ct);
}
else {
if (_.hoveredstatus!==true)
o.timeline.time(ct);
}
}
// RESET STATUS ALWAYS TO HIDDEN
if (triggerstate==="reset" && layer_start_status==="hidden") {
//console.log("Pre Path X");
o.timeline.time(0);
_.animdirection = "out";
}
//console.log("in Range:"+in_v_range+" "+o.firstslide+" <= "+_actli+" <= "+o.lastslide);
// LAYER IS ON SLIDE TO SHOW, OR LAYER NEED TO DISAPPEAR
if (in_v_range) {
if (isvisible) {
//console.log("Path A");
if (_actli===o.lastslide) {
//console.log("Path A.1");
o.timeline.play(elt);
_.animdirection = "in";
}
} else {
//console.log("Path B");
//console.log(triggered_in+" "+_.animdirection)
if (!triggered_in && _.animdirection!=="in") {
//console.log("Path B.1")
o.timeline.play(flt);
}
if ((layer_start_status=="visible" && triggerstate!=="keep") || (triggerstate==="keep" && isvisible===true) || (layer_start_status=="visible" && isvisible===undefined)) {
//console.log("Path B.2");
o.timeline.play(flt+0.01);
_.animdirection = "in";
}
}
} else {
//console.log("Path C");
if (in_uv_range) {
//console.log("Path C.1");
if (isvisible) {
//console.log("Path C.1.1")
o.timeline.play("frame_999");
} else {
//console.log("Path C.1.2")
}
}
}
});
}
// RESUME THE MAIN TIMELINE NOW
if (mtl != undefined) setTimeout(function() {
mtl.resume();
},30);
},
/********************************************
PREPARE ALL LAYER SIZES, POSITION
********************************************/
prepareSingleCaption : function(obj) {
var _nc = obj.caption,
_ = _nc.data(),
opt = obj.opt,
recall = obj.recall,
internrecall = obj.recall,
preset = obj.preset,
rtl = jQuery('body').hasClass("rtl"),
datas
_._pw = _._pw===undefined ? _nc.closest('.tp-parallax-wrap') : _._pw;
_._lw = _._lw===undefined ? _nc.closest('.tp-loop-wrap') : _._lw;
_._mw = _._mw===undefined ? _nc.closest('.tp-mask-wrap') : _._mw;
_._responsive = _.responsive || "on";
_._respoffset = _.responsive_offset || "on";
_._ba = _.basealign || "grid";
_._gw = _._ba==="grid" ? opt.width : opt.ulw;
_._gh = _._ba==="grid" ? opt.height : opt.ulh;
_._lig = _._lig===undefined ? _nc.hasClass("rev_layer_in_group") ? _nc.closest('.rev_group') : _nc.hasClass("rev_layer_in_column") ?_nc.closest('.rev_column_inner') : _nc.hasClass("rev_column_inner") ? _nc.closest(".rev_row") : "none" : _._lig,
_._column = _._column===undefined ? _nc.hasClass("rev_column_inner") ? _nc.closest(".rev_column") : "none" : _._column,
_._row = _._row===undefined ? _nc.hasClass("rev_column_inner") ? _nc.closest(".rev_row") : "none" : _._row,
_._ingroup = _._ingroup===undefined ? !_nc.hasClass('rev_group') && _nc.closest('.rev_group') ? true : false :_._ingroup;
_._isgroup = _._isgroup===undefined ? _nc.hasClass("rev_group") ? true : false : _._isgroup;
_._nctype = _.type || "none";
_._cbgc_auto = _._cbgc_auto===undefined ? _._nctype==="column" ? _._pw.find('.rev_column_bg_auto_sized') : false : _._cbgc_auto;
_._cbgc_man = _._cbgc_man===undefined ? _._nctype==="column" ? _._pw.find('.rev_column_bg_man_sized') : false : _._cbgc_man;
_._slideid = _._slideid || _nc.closest('.tp-revslider-slidesli').data('index');
_._id = _._id===undefined ? _nc.data('id') || _nc.attr('id') : _._id;
_._slidelink = _._slidelink===undefined ? _nc.hasClass("slidelink")===undefined ? false : _nc.hasClass("slidelink") : _._slidelink;
if (_._li===undefined)
if (_nc.hasClass("tp-static-layer")) {
_._isstatic = true;
_._li = _nc.closest('.tp-static-layers');
_._slideid = "staticlayers";
} else {
_._li = _nc.closest('.tp-revslider-slidesli');
}
_._row = _._row===undefined ? _._nctype==="column" ? _._pw.closest('.rev_row') : false : _._row;
if (_._togglelisteners===undefined && _nc.find('.rs-toggled-content')) {
_._togglelisteners = true;
if (_.actions===undefined) _nc.click(function() {_R.swaptoggleState(_nc); })
} else {
_._togglelisteners = false;
}
if (opt.sliderLayout=="fullscreen")
obj.offsety = _._gh/2 - (opt.gridheight[opt.curWinRange]*opt.bh)/2;
if (opt.autoHeight=="on" || (opt.minHeight!=undefined && opt.minHeight>0))
obj.offsety = opt.conh/2 - (opt.gridheight[opt.curWinRange]*opt.bh)/2;;
if (obj.offsety<0) obj.offsety=0;
// LAYER GRID FOR DEBUGGING
if (opt.debugMode) {
_nc.closest('li').find('.helpgrid').css({top:obj.offsety+"px", left:obj.offsetx+"px"});
var linfo = opt.c.find('.hglayerinfo');
_nc.on("hover, mouseenter",function() {
var ltxt = "",
spa = 0;
if (_nc.data())
jQuery.each(_nc.data(),function(key,val) {
if (typeof val !== "object") {
ltxt = ltxt + '<span style="white-space:nowrap"><span style="color:#27ae60">'+key+":</span>"+val+"</span> ";
}
});
linfo.html(ltxt);
});
}
/* END OF DEBUGGING */
var handlecaption=0,
layervisible = _.visibility === undefined ? "oon" : makeArray(_.visibility,opt)[opt.forcedWinRange] || makeArray(_.visibility,opt) || "ooon";
// HIDE CAPTION IF RESOLUTION IS TOO LOW
if (layervisible==="off" || (_._gw<opt.hideCaptionAtLimit && _.captionhidden=="on") || (_._gw<opt.hideAllCaptionAtLimit))
_._pw.addClass("tp-hidden-caption");
else
_._pw.removeClass("tp-hidden-caption")
_.layertype = "html";
if (obj.offsetx<0) obj.offsetx=0;
// FALL BACK TO NORMAL IMAGES
if (_.thumbimage !=undefined && _.videoposter==undefined)
_.videoposter = _.thumbimage;
// IF IT IS AN IMAGE
if (_nc.find('img').length>0) {
var im = _nc.find('img');
_.layertype = "image";
if (im.width()==0) im.css({width:"auto"});
if (im.height()==0) im.css({height:"auto"});
if (im.data('ww') == undefined && im.width()>0) im.data('ww',im.width());
if (im.data('hh') == undefined && im.height()>0) im.data('hh',im.height());
var ww = im.data('ww'),
hh = im.data('hh'),
fuw = _._ba =="slide" ? opt.ulw : opt.gridwidth[opt.curWinRange],
fuh = _._ba =="slide" ? opt.ulh : opt.gridheight[opt.curWinRange];
ww = makeArray(im.data('ww'),opt)[opt.curWinRange] || makeArray(im.data('ww'),opt) || "auto",
hh = makeArray(im.data('hh'),opt)[opt.curWinRange] || makeArray(im.data('hh'),opt) || "auto";
var wful = ww==="full" || ww === "full-proportional",
hful = hh==="full" || hh === "full-proportional";
if (ww==="full-proportional") {
var ow = im.data('owidth'),
oh = im.data('oheight');
if (ow/fuw < oh/fuh) {
ww = fuw;
hh = oh*(fuw/ow);
} else {
hh = fuh;
ww = ow*(fuh/oh);
}
} else {
ww = wful ? fuw : !jQuery.isNumeric(ww) && ww.indexOf("%")>0 ? ww : parseFloat(ww);
hh = hful ? fuh : !jQuery.isNumeric(hh) && hh.indexOf("%")>0 ? hh : parseFloat(hh);
}
ww = ww===undefined ? 0 : ww;
hh = hh===undefined ? 0 : hh;
if (_._responsive!=="off") {
if (_._ba!="grid" && wful)
if (jQuery.isNumeric(ww))
im.css({width:ww+"px"});
else
im.css({width:ww});
else
if (jQuery.isNumeric(ww))
im.css({width:(ww*opt.bw)+"px"});
else
im.css({width:ww});
if (_._ba!="grid" && hful)
if (jQuery.isNumeric(hh))
im.css({height:hh+"px"});
else
im.css({height:hh});
else
if (jQuery.isNumeric(hh))
im.css({height:(hh*opt.bh)+"px"});
else
im.css({height:hh});
} else {
im.css({width:ww, height:hh});
}
if (_._ingroup && _._nctype!=="row") {
if (ww!==undefined && !jQuery.isNumeric(ww) && jQuery.type(ww)==="string" && ww.indexOf("%")>0)
punchgs.TweenLite.set([_._lw,_._pw,_._mw],{minWidth:ww});
if (hh!==undefined && !jQuery.isNumeric(hh) && jQuery.type(hh)==="string" && hh.indexOf("%")>0)
punchgs.TweenLite.set([_._lw,_._pw,_._mw],{minHeight:hh});
}
}
if (_._ba==="slide") {
obj.offsetx = 0;
obj.offsety=0;
} else {
if (_._isstatic && opt.carousel!==undefined && opt.carousel.horizontal_align!==undefined && opt.sliderType==="carousel") {
switch (opt.carousel.horizontal_align) {
case "center":
obj.offsetx = 0 + (opt.ulw - (opt.gridwidth[opt.curWinRange]*opt.bw))/2;
break;
case "left":
break;
case "right":
obj.offsetx = (opt.ulw - (opt.gridwidth[opt.curWinRange]*opt.bw));
break;
}
obj.offsetx = obj.offsetx<0 ? 0 : obj.offsetx;
}
}
var tag = _.audio=="html5" ? "audio" : "video";
// IF IT IS A VIDEO LAYER
if (_nc.hasClass("tp-videolayer") || _nc.hasClass("tp-audiolayer") || _nc.find('iframe').length>0 || _nc.find(tag).length>0) {
_.layertype = "video";
if (_R.manageVideoLayer) _R.manageVideoLayer(_nc,opt,recall,internrecall);
if (!recall && !internrecall) {
var t = _.videotype;
if (_R.resetVideo) _R.resetVideo(_nc,opt,obj.preset);
}
var asprat = _.aspectratio;
if (asprat!=undefined && asprat.split(":").length>1)
_R.prepareCoveredVideo(opt,_nc);
var im = _nc.find('iframe') ? _nc.find('iframe') : im = _nc.find(tag),
html5vid = _nc.find('iframe') ? false : true,
yvcover = _nc.hasClass('coverscreenvideo');
im.css({display:"block"});
// SET WIDTH / HEIGHT
if (_nc.data('videowidth') == undefined) {
_nc.data('videowidth',im.width());
_nc.data('videoheight',im.height());
}
var ww = makeArray(_nc.data('videowidth'),opt)[opt.curWinRange] || makeArray(_nc.data('videowidth'),opt) || "auto",
hh = makeArray(_nc.data('videoheight'),opt)[opt.curWinRange] || makeArray(_nc.data('videoheight'),opt) || "auto";
/*if (!jQuery.isNumeric(ww) && ww.indexOf("%")>0) {
hh = (parseFloat(hh)*opt.bh)+"px";
} else {
ww = (parseFloat(ww)*opt.bw)+"px";
hh = (parseFloat(hh)*opt.bh)+"px";
}*/
if (ww==="auto" || (!jQuery.isNumeric(ww) && ww.indexOf("%")>0)) {
ww = ww==="auto" ? "auto" : _._ba==="grid" ? opt.gridwidth[opt.curWinRange]*opt.bw : _._gw;
} else {
ww = (parseFloat(ww)*opt.bw)+"px";
}
if (hh==="auto" || (!jQuery.isNumeric(hh) && hh.indexOf("%")>0)) {
hh = hh==="auto" ? "auto" : _._ba==="grid" ? opt.gridheight[opt.curWinRange]*opt.bw : _._gh;
} else {
hh = (parseFloat(hh)*opt.bh)+"px";
}
// READ AND WRITE CSS SETTINGS OF IFRAME AND VIDEO FOR RESIZING ELEMENST ON DEMAND
_.cssobj = _.cssobj===undefined ? getcssParams(_nc,0) : _.cssobj;
var ncobj = setResponsiveCSSValues(_.cssobj,opt);
// IE8 FIX FOR AUTO LINEHEIGHT
if (ncobj.lineHeight=="auto") ncobj.lineHeight = ncobj.fontSize+4;
if (!_nc.hasClass('fullscreenvideo') && !yvcover) {
punchgs.TweenLite.set(_nc,{
paddingTop: Math.round((ncobj.paddingTop * opt.bh)) + "px",
paddingBottom: Math.round((ncobj.paddingBottom * opt.bh)) + "px",
paddingLeft: Math.round((ncobj.paddingLeft* opt.bw)) + "px",
paddingRight: Math.round((ncobj.paddingRight * opt.bw)) + "px",
marginTop: (ncobj.marginTop * opt.bh) + "px",
marginBottom: (ncobj.marginBottom * opt.bh) + "px",
marginLeft: (ncobj.marginLeft * opt.bw) + "px",
marginRight: (ncobj.marginRight * opt.bw) + "px",
borderTopWidth: Math.round(ncobj.borderTopWidth * opt.bh) + "px",
borderBottomWidth: Math.round(ncobj.borderBottomWidth * opt.bh) + "px",
borderLeftWidth: Math.round(ncobj.borderLeftWidth * opt.bw) + "px",
borderRightWidth: Math.round(ncobj.borderRightWidth * opt.bw) + "px",
width:ww,
height:hh
});
} else {
obj.offsetx=0; obj.offsety=0;
_nc.data('x',0)
_nc.data('y',0)
var ovhh = _._gh;
if (opt.autoHeight=="on") ovhh = opt.conh
_nc.css({'width':_._gw, 'height':ovhh });
}
if ((html5vid == false && !yvcover) || ((_.forcecover!=1 && !_nc.hasClass('fullscreenvideo') && !yvcover))) {
im.width(ww);
im.height(hh);
}
if (_._ingroup) {
if (_.videowidth!==null && _.videowidth!==undefined && !jQuery.isNumeric(_.videowidth) && _.videowidth.indexOf("%")>0)
punchgs.TweenLite.set([_._lw,_._pw,_._mw],{minWidth:_.videowidth});
}
} // END OF POSITION AND STYLE READ OUTS OF VIDEO
// RESPONIVE HANDLING OF CURRENT LAYER
calcCaptionResponsive(_nc,opt,0,_._responsive);
// ALL ELEMENTS IF THE MAIN ELEMENT IS REKURSIVE RESPONSIVE SHOULD BE REPONSIVE HANDLED
if (_nc.hasClass("tp-resizeme"))
_nc.find('*').each(function() {
calcCaptionResponsive(jQuery(this),opt,"rekursive",_._responsive);
});
// _nc FRONTCORNER CHANGES
var ncch = _nc.outerHeight(),
bgcol = _nc.css('backgroundColor');
sharpCorners(_nc,'.frontcorner','left','borderRight','borderTopColor',ncch,bgcol);
sharpCorners(_nc,'.frontcornertop','left','borderRight','borderBottomColor',ncch,bgcol);
sharpCorners(_nc,'.backcorner','right','borderLeft','borderBottomColor',ncch,bgcol);
sharpCorners(_nc,'.backcornertop','right','borderLeft','borderTopColor',ncch,bgcol);
if (opt.fullScreenAlignForce == "on") {
obj.offsetx=0;
obj.offsety=0;
}
// BLOCK ANIMATION ON LAYERS
if (_._sfx==="block")
if (_._bmask === undefined) {
_._bmask = jQuery('<div class="tp-blockmask"></div>');
_._mw.append(_._bmask);
}
_.arrobj = new Object();
_.arrobj.voa = makeArray(_.voffset,opt)[opt.curWinRange] || makeArray(_.voffset,opt)[0];
_.arrobj.hoa = makeArray(_.hoffset,opt)[opt.curWinRange] || makeArray(_.hoffset,opt)[0];
_.arrobj.elx = makeArray(_.x,opt)[opt.curWinRange] || makeArray(_.x,opt)[0];
_.arrobj.ely = makeArray(_.y,opt)[opt.curWinRange] || makeArray(_.y,opt)[0];
var voa = _.arrobj.voa.length==0 ? 0 : _.arrobj.voa,
hoa = _.arrobj.hoa.length==0 ? 0 : _.arrobj.hoa,
elx = _.arrobj.elx.length==0 ? 0 : _.arrobj.elx,
ely = _.arrobj.ely.length==0 ? 0 : _.arrobj.ely;
_.eow = _nc.outerWidth(true);
_.eoh = _nc.outerHeight(true);
// NEED CLASS FOR FULLWIDTH AND FULLHEIGHT LAYER SETTING !!
if (_.eow==0 && _.eoh==0) {
_.eow = opt.ulw;
_.eoh = opt.ulh;
}
var vofs= _._respoffset !=="off" ? parseInt(voa,0)*opt.bw : parseInt(voa,0),
hofs= _._respoffset !=="off" ? parseInt(hoa,0)*opt.bw : parseInt(hoa,0),
crw = _._ba==="grid" ? opt.gridwidth[opt.curWinRange]*opt.bw : _._gw,
crh = _._ba==="grid" ? opt.gridheight[opt.curWinRange]*opt.bw : _._gh;
if (opt.fullScreenAlignForce == "on") {
crw = opt.ulw;
crh = opt.ulh;
}
// ALIGN POSITIONED ELEMENTS
if (_._lig!=="none" && _._lig!=undefined) {
crw=_._lig.width();
crh=_._lig.height();
obj.offsetx =0;
obj.offsety = 0;
}
elx = elx==="center" || elx==="middle" ? (crw/2 - _.eow/2) + hofs : elx==="left" ? hofs : elx==="right" ? (crw - _.eow) - hofs : _._respoffset !=="off" ? elx * opt.bw : elx;
ely = ely=="center" || ely=="middle" ? (crh/2 - _.eoh/2) + vofs : ely =="top" ? vofs : ely=="bottom" ? (crh - _.eoh)-vofs : _._respoffset !=="off" ? ely*opt.bw : ely;
if (rtl && !_._slidelink)
elx = elx + _.eow;
if (_._slidelink) elx=0;
_.calcx = (parseInt(elx,0)+obj.offsetx);
_.calcy = (parseInt(ely,0)+obj.offsety);
var tpcapindex = _nc.css("z-Index");
// SET TOP/LEFT POSITION OF LAYER
if (_._nctype!=="row" && _._nctype!=="column")
punchgs.TweenLite.set(_._pw,{zIndex:tpcapindex, top:_.calcy,left:_.calcx,overwrite:"auto"});
else
if (_._nctype!=="row")
punchgs.TweenLite.set(_._pw,{zIndex:tpcapindex, width:_.columnwidth, top:0,left:0,overwrite:"auto"});
else
if (_._nctype==="row") {
var _roww = _._ba==="grid" ? crw+"px" : "100%";
punchgs.TweenLite.set(_._pw,{zIndex:tpcapindex, width:_roww, top:0,left:obj.offsetx,overwrite:"auto"});
}
if (_.blendmode!==undefined)
punchgs.TweenLite.set(_._pw,{mixBlendMode:_.blendmode});
/*if (_._nctype==="svg") {
_.svgcontainer = _.svgcontainer===undefined ? _nc.find('.tp-svg-innercontainer') : _.svgcontainer;
punchgs.TweenLite.set(_.svgcontainer,{ ... });
}*/
//SET ROW BROKEN / TABLE FORMED
if (_._nctype==="row") {
if (_.columnbreak<=opt.curWinRange) {
_nc.addClass("rev_break_columns");
} else {
_nc.removeClass("rev_break_columns");
}
}
// LOOP ANIMATION WIDTH/HEIGHT
if (_.loopanimation=="on") punchgs.TweenLite.set(_._lw,{minWidth:_.eow,minHeight:_.eoh});
//Preset Position of BG
if (_._nctype==="column") {
var tempy = _nc[0]._gsTransform !==undefined ? _nc[0]._gsTransform.y : 0,
pT = parseInt(_._column[0].style.paddingTop,0);
punchgs.TweenLite.set(_nc,{y:0});
punchgs.TweenLite.set(_._cbgc_man,{y:parseInt(( pT+_._column.offset().top-_nc.offset().top),0)});
punchgs.TweenLite.set(_nc,{y:tempy});
}
// ELEMENT IN GROUPS WITH % WIDTH AND HEIGHT SHOULD EXTEND PARRENT SIZES
if (_._ingroup && _._nctype!=="row") {
if (_._groupw!==undefined && !jQuery.isNumeric(_._groupw) && _._groupw.indexOf("%")>0)
punchgs.TweenLite.set([_._lw,_._pw,_._mw],{minWidth:_._groupw});
if (_._grouph!==undefined && !jQuery.isNumeric(_._grouph) && _._grouph.indexOf("%")>0)
punchgs.TweenLite.set([_._lw,_._pw,_._mw],{minHeight:_._grouph});
}
},
/********************************************
BUILD THE TIMELINE STRUCTURES
********************************************/
createTimelineStructure : function(opt) {
// COLLECTION OF TIMELINES
opt.timelines = opt.timelines || new Object();
function addTimeLineWithLabel(layer,opt,parentobject,slideid) {
var timeline = new punchgs.TimelineLite({paused:true}),
c;
parentobject = parentobject || new Object();
parentobject[layer.attr('id')] = parentobject[layer.attr('id')] || new Object();
if (slideid==="staticlayers") {
parentobject[layer.attr('id')].firstslide = layer.data('startslide');
parentobject[layer.attr('id')].lastslide = layer.data('endslide');
}
layer.data('slideid',slideid);
parentobject[layer.attr('id')].defclasses=c=layer[0].className;
parentobject[layer.attr('id')].wrapper = c.indexOf("rev_layer_in_column")>=0 ? layer.closest('.rev_column_inner') : c.indexOf("rev_column_inner")>=0 ? layer.closest(".rev_row") : c.indexOf("rev_layer_in_group")>=0 ? layer.closest(".rev_group") : "none";
parentobject[layer.attr('id')].timeline = timeline;
parentobject[layer.attr('id')].layer = layer;
parentobject[layer.attr('id')].triggerstate = layer.data('lasttriggerstate');
parentobject[layer.attr('id')].dchildren = c.indexOf("rev_row")>=0 ? layer[0].getElementsByClassName('rev_column_inner') : c.indexOf("rev_column_inner")>=0 ? layer[0].getElementsByClassName('tp-caption') : c.indexOf("rev_group")>=0 ? layer[0].getElementsByClassName('rev_layer_in_group') : "none";
layer.data('timeline',timeline);
}
//GO THROUGH ALL LI
opt.c.find('.tp-revslider-slidesli, .tp-static-layers').each(function() {
var slide = jQuery(this),
index = slide.data('index');
opt.timelines[index] = opt.timelines[index] || {};
opt.timelines[index].layers = opt.timelines[index].layers || new Object();
// COLLECT LAYERS
slide.find('.tp-caption').each(function(i) {
addTimeLineWithLabel(jQuery(this),opt,opt.timelines[index].layers,index);
});
});
},
/***************************************
- BUILD CAPTION FULL TIMELINES -
***************************************/
buildFullTimeLine : function(obj) {
//if (obj.recall) return;
var _nc = obj.caption,
_ = _nc.data(),
opt = obj.opt,
$svg = {},
_nc_tl_obj,
_nc_timeline,
$hover = newHoverAnimObject(),
timelineprog = 0;
_nc_tl_obj = opt.timelines[_._slideid]["layers"][_._id];
if (_nc_tl_obj.generated && obj.regenerate!==true) return;
_nc_timeline = _nc_tl_obj.timeline;
_nc_tl_obj.generated = true;
if (_.current_timeline!==undefined && obj.regenerate!==true) {
_.current_timeline_pause = _.current_timeline.paused();
_.current_timeline_time = _.current_timeline.time();
_.current_is_nc_timeline = _nc_timeline === _.current_timeline;
_.static_layer_timeline_time = _.current_timeline_time;
} else {
_.static_layer_timeline_time = _.current_timeline_time;
_.current_timeline_time = 0;
if (_.current_timeline) _.current_timeline.clear();
}
_nc_timeline.clear();
// PRESET SVG STYLE
$svg.svg = _.svg_src!=undefined ? _nc.find('svg') : false;
if ($svg.svg) {
_.idlesvg = setSVGAnimObject(_.svg_idle,newSVGHoverAnimObject());
punchgs.TweenLite.set($svg.svg,_.idlesvg.anim);
}
// HOVER ANIMATION
if (_.hoverframeindex!==-1 && _.hoverframeindex!==undefined) {
if (!_nc.hasClass("rs-hover-ready")) {
_nc.addClass("rs-hover-ready");
_.hovertimelines = {};
_.hoveranim = getAnimDatas($hover,_.frames[_.hoverframeindex].to);
_.hoveranim = convertHoverStyle(_.hoveranim,_.frames[_.hoverframeindex].style);
if ($svg.svg) {
var $svghover = setSVGAnimObject(_.svg_hover,newSVGHoverAnimObject());
if (_.hoveranim.anim.color!=undefined) {
$svghover.anim.fill = _.hoveranim.anim.color;
_.idlesvg.anim.css.fill = $svg.svg.css("fill");
}
_.hoversvg = $svghover;
}
_nc.hover(function(e) {
var obj = {caption:jQuery(e.currentTarget), opt:opt, firstframe : "frame_0", lastframe:"frame_999"},
tl = getTLInfos(obj),
nc = obj.caption,
_ = nc.data(),
frame = _.frames[_.hoverframeindex],
animended = true;
_.forcehover = frame.force;
if (animended) {
_.hovertimelines.item = punchgs.TweenLite.to(nc,frame.speed/1000,_.hoveranim.anim);
if (_.hoverzIndex || (_.hoveranim.anim && _.hoveranim.anim.zIndex)) {
_.basiczindex = _.basiczindex===undefined ? _.cssobj.zIndex : _.basiczindex;
_.hoverzIndex = _.hoverzIndex===undefined ? _.hoveranim.anim.zIndex : _.hoverzIndex;
_.inhoverinanimation = true;
if (frame.speed===0) _.inhoverinanimation= false;
_.hovertimelines.pwhoveranim = punchgs.TweenLite.to(_._pw,frame.speed/1000,{overwrite:"auto",zIndex:_.hoverzIndex});
_.hovertimelines.pwhoveranim.eventCallback("onComplete",function(_) {
_.inhoverinanimation=false;;
},[_])
}
if ($svg.svg)
_.hovertimelines.svghoveranim = punchgs.TweenLite.to([$svg.svg, $svg.svg.find('path')],frame.speed/1000,_.hoversvg.anim);
_.hoveredstatus = true;
}
},
function(e) {
var obj = {caption:jQuery(e.currentTarget), opt:opt, firstframe : "frame_0", lastframe:"frame_999"},
tl = getTLInfos(obj),
nc = obj.caption,
_ = nc.data(),
frame = _.frames[_.hoverframeindex],
animended = true;
if (animended) {
_.hoveredstatus = false;
_.inhoveroutanimation = true;
_.hovertimelines.item.pause();
_.hovertimelines.item = punchgs.TweenLite.to(nc,frame.speed/1000,jQuery.extend(true,{},_._gsTransformTo));
if (frame.speed==0) _.inhoveroutanimation= false;
_.hovertimelines.item.eventCallback("onComplete",function(_) {
_.inhoveroutanimation=false;;
},[_])
if (_.hovertimelines.pwhoveranim!==undefined) _.hovertimelines.pwhoveranim = punchgs.TweenLite.to(_._pw,frame.speed/1000,{overwrite:"auto",zIndex:_.basiczindex});
if ($svg.svg) punchgs.TweenLite.to([$svg.svg, $svg.svg.find('path')],frame.speed/1000,_.idlesvg.anim);
}
});
}
} // END IF HOVER ANIMATION
// LOOP TROUGH THE FRAMES AND CREATE FRAME TWEENS AND TL'S ON THE MAIN TIMELINE
for (var frame_index=0; frame_index<_.frames.length;frame_index++) {
if (frame_index !== _.hoverframeindex) {
// Create a new Timeline for each Frame
var frame_name = frame_index === _.inframeindex ? "frame_0" : frame_index===_.outframeindex || _.frames[frame_index].frame==="frame_999" ? "frame_999" : "frame_"+frame_index;
_.frames[frame_index].framename = frame_name;
_nc_tl_obj[frame_name] = {};
_nc_tl_obj[frame_name].timeline = new punchgs.TimelineLite({align:"normal"});
var $start = _.frames[frame_index].delay,
$start_status = _.triggered_startstatus,
mdelay = $start !== undefined ? jQuery.inArray($start,["slideenter","bytrigger","wait"])>=0 ? $start : parseInt($start,0)/1000 : "wait";
// ADD STARTLABEL FOR STATIC LAYERS
if (_nc_tl_obj.firstslide!==undefined && frame_name==="frame_0") {
_nc_timeline.addLabel("slide_"+_nc_tl_obj.firstslide+"_pause",0);
_nc_timeline.addPause("slide_"+_nc_tl_obj.firstslide+"_pause");
_nc_timeline.addLabel("slide_"+_nc_tl_obj.firstslide,"+=0.005");
}
// ADD ENDSLIDE LABEL FOR STATIC LAYERS
if (_nc_tl_obj.lastslide!==undefined && frame_name==="frame_999") {
_nc_timeline.addLabel("slide_"+_nc_tl_obj.lastslide+"_pause","+=0.01");
_nc_timeline.addPause("slide_"+_nc_tl_obj.lastslide+"_pause");
_nc_timeline.addLabel("slide_"+_nc_tl_obj.lastslide,"+=0.005");
}
if (!jQuery.isNumeric(mdelay)) {
_nc_timeline.addLabel("pause_"+frame_index,"+=0.01");
_nc_timeline.addPause("pause_"+frame_index);
_nc_timeline.addLabel(frame_name,"+=0.01");
} else {
_nc_timeline.addLabel(frame_name,"+="+mdelay);
}
_nc_timeline = _R.createFrameOnTimeline({caption:obj.caption, timeline : _nc_timeline, label:frame_name, frameindex : frame_index, opt:opt });
} //
} // END OF LOOP THROUGH FRAMES AND CREATING NEW TWEENS
//_nc_timeline.time(timelineprog);
if (!obj.regenerate) {
if (_.current_is_nc_timeline)
_.current_timeline = _nc_timeline;
if (_.current_timeline_pause)
_nc_timeline.pause(_.current_timeline_time);
else
_nc_timeline.time(_.current_timeline_time);
}
return;
},
/////////////////////////////////////
// BUILD A FRAME ON THE TIMELINE //
/////////////////////////////////////
createFrameOnTimeline : function(obj) {
var _nc = obj.caption,
_ = _nc.data(),
label = obj.label,
timeline = obj.timeline,
frame_index = obj.frameindex,
opt = obj.opt,
animobject = _nc,
tweens = {},
_nc_tl_obj = opt.timelines[_._slideid]["layers"][_._id],
verylastframe = _.frames.length-1,
$split = _.frames[frame_index].split,
$splitdir = _.frames[frame_index].split_direction,
$sfx = _.frames[frame_index].sfx_effect,
$splitnow = false;
$splitdir = $splitdir === undefined ? "forward" : $splitdir;
if (_.hoverframeindex!==-1 && _.hoverframeindex==verylastframe) verylastframe=verylastframe-1;
tweens.content = new punchgs.TimelineLite({align:"normal"});
tweens.mask = new punchgs.TimelineLite({align:"normal"});
if (timeline.vars.id===undefined)
timeline.vars.id=Math.round(Math.random()*100000);
if (_._nctype==="column") {
timeline.add(punchgs.TweenLite.set(_._cbgc_man,{visibility:"visible"}),label);
timeline.add(punchgs.TweenLite.set(_._cbgc_auto,{visibility:"hidden"}),label);
}
if (_.splittext && frame_index===0) {
if (_.mySplitText !== undefined) _.mySplitText.revert();
var splittarget = _nc.find('a').length>0 ? _nc.find('a') : _nc;
_.mySplitText = new punchgs.SplitText(splittarget,{type:"chars,words,lines",charsClass:"tp-splitted tp-charsplit",wordsClass:"tp-splitted tp-wordsplit",linesClass:"tp-splitted tp-linesplit"});
_nc.addClass("splitted");
}
if ( _.mySplitText !==undefined && $split && $split.match(/chars|words|lines/g)) {
animobject = _.mySplitText[$split];
$splitnow = true;
}
// ANIMATE THE FRAME
var $to = frame_index!==_.outframeindex ? getAnimDatas(newAnimObject(),_.frames[frame_index].to,undefined,$splitnow,animobject.length-1) : _.frames[frame_index].to !==undefined && _.frames[frame_index].to.match(/auto:auto/g)===null ? getAnimDatas(newEndAnimObject(),_.frames[frame_index].to,opt.sdir==1,$splitnow,(animobject.length-1)) : getAnimDatas(newEndAnimObject(),_.frames[_.inframeindex].from,opt.sdir==0,$splitnow,(animobject.length-1)),
$from = _.frames[frame_index].from !==undefined ? getAnimDatas($to,_.frames[_.inframeindex].from,opt.sdir==1,$splitnow,animobject.length-1) : undefined, // ANIMATE FROM THE VERY FIRST SETTING, OR FROM PREVIOUS SETTING
$elemdelay = _.frames[frame_index].splitdelay,
$mask_from,$mask_to;
if (frame_index===0 && !obj.fromcurrentstate)
$mask_from = getMaskDatas(_.frames[frame_index].mask);
else
$mask_to = getMaskDatas(_.frames[frame_index].mask);
$to.anim.ease = _.frames[frame_index].ease===undefined ? punchgs.Power1.easeInOut : _.frames[frame_index].ease;
if ($from!==undefined) {
$from.anim.ease = _.frames[frame_index].ease===undefined ? punchgs.Power1.easeInOut : _.frames[frame_index].ease;
$from.speed = _.frames[frame_index].speed === undefined ? $from.speed : _.frames[frame_index].speed;
$from.anim.x = $from.anim.x * opt.bw || getBorderDirections($from.anim.x,opt,_.eow,_.eoh,_.calcy,_.calcx, "horizontal" );
$from.anim.y = $from.anim.y * opt.bw || getBorderDirections($from.anim.y,opt,_.eow,_.eoh,_.calcy,_.calcx, "vertical" );
}
if ($to!==undefined) {
$to.anim.ease = _.frames[frame_index].ease===undefined ? punchgs.Power1.easeInOut : _.frames[frame_index].ease;
$to.speed = _.frames[frame_index].speed === undefined ? $to.speed : _.frames[frame_index].speed;
$to.anim.x = $to.anim.x * opt.bw || getBorderDirections($to.anim.x,opt,_.eow,_.eoh,_.calcy,_.calcx, "horizontal" );
$to.anim.y = $to.anim.y * opt.bw || getBorderDirections($to.anim.y,opt,_.eow,_.eoh,_.calcy,_.calcx, "vertical" );
}
// FIX VISIBLE IFRAME BUG IN SAFARI
if (_nc.data('iframes')) timeline.add(punchgs.TweenLite.set(_nc.find('iframe'),{autoAlpha:1}),label+"+=0.001");
// IN CASE LAST FRAME REACHED, AND ANIMATION IS SET TO AUTO (REVERSE PLAYING)
if (frame_index===_.outframeindex) {
if (_.frames[frame_index].to && _.frames[frame_index].to.match(/auto:auto/g)) {
//
}
$to.speed = _.frames[frame_index].speed === undefined || _.frames[frame_index].speed==="inherit" ? _.frames[_.inframeindex].speed : _.frames[frame_index].speed;
$to.anim.ease = _.frames[frame_index].ease === undefined || _.frames[frame_index].ease==="inherit" ? _.frames[_.inframeindex].ease : _.frames[frame_index].ease;
$to.anim.overwrite ="auto";
}
// IN CASE FIRST FRAME REACHED
if (frame_index===0 && !obj.fromcurrentstate) {
if (animobject != _nc) {
var old = jQuery.extend({},$to.anim,true);
timeline.add(punchgs.TweenLite.set(_nc, $to.anim),label);
$to = newAnimObject();
$to.ease = old.ease;
if (old.filter!==undefined) $to.anim.filter = old.filter;
if (old["-webkit-filter"]!==undefined) $to.anim["-webkit-filter"] = old["-webkit-filter"];
}
$from.anim.visibility = "hidden";
$from.anim.immediateRender = true;
$to.anim.visibility = "visible";
//_nc.data('speed',$from.speed);
//_nc.data('ease',$to.anim.ease);
} else
if (frame_index===0 && obj.fromcurrentstate) {
$to.speed = $from.speed;
}
if (obj.fromcurrentstate) {
$to.anim.immediateRender = true;
}
// SPECIAL EFFECT LAYER ANIMATIONS
var $sfx_blockdelay = -1;
//Boxed Mask Animation 0 or 999 Frame
if ((frame_index===0 && !obj.fromcurrentstate && _._bmask!==undefined && $sfx!==undefined && $sfx.indexOf("block")>=0) ||
(frame_index===_.outframeindex && !obj.fromcurrentstate && _._bmask!==undefined && $sfx!==undefined && $sfx.indexOf("block")>=0)) {
var $sfx_speed = frame_index===0 ? ($from.speed/1000)/2 : ($to.speed/1000)/2,
$sfx_ft = [{scaleY:1,scaleX:0,transformOrigin:"0% 50%"},{scaleY:1,scaleX:1,ease:$to.anim.ease}],
$sfx_t = {scaleY:1,scaleX:0,transformOrigin:"100% 50%",ease:$to.anim.ease};
$sfx_blockdelay = $elemdelay === undefined ? $sfx_speed : $elemdelay + $sfx_speed;
switch ($sfx) {
case "blocktoleft":
case "blockfromright":
$sfx_ft[0].transformOrigin = "100% 50%";
$sfx_t.transformOrigin = "0% 50%";
break;
case "blockfromtop":
case "blocktobottom":
$sfx_ft = [{scaleX:1,scaleY:0,transformOrigin:"50% 0%"},{scaleX:1,scaleY:1,ease:$to.anim.ease}];
$sfx_t = {scaleX:1,scaleY:0,transformOrigin:"50% 100%",ease:$to.anim.ease};
break;
case "blocktotop":
case "blockfrombottom":
$sfx_ft = [{scaleX:1,scaleY:0,transformOrigin:"50% 100%"},{scaleX:1,scaleY:1,ease:$to.anim.ease}];
$sfx_t = {scaleX:1,scaleY:0,transformOrigin:"50% 0%",ease:$to.anim.ease};
break;
}
$sfx_ft[0].background = _.frames[frame_index].sfxcolor;
timeline.add(tweens.mask.fromTo(_._bmask,$sfx_speed, $sfx_ft[0], $sfx_ft[1],$elemdelay),label);
timeline.add(tweens.mask.to(_._bmask,$sfx_speed,$sfx_t,$sfx_blockdelay),label);
}
if ($splitnow)
var ri = getSplitTextDirs(animobject.length-1, $splitdir);
if (frame_index===0 && !obj.fromcurrentstate) {
if (_._sfx_in==="block")
timeline.add(tweens.content.staggerFromTo(animobject,0.05,{x:0,y:0,autoAlpha:0},{x:0,y:0,autoAlpha:1,delay:$sfx_blockdelay}),label);
else {
if ($splitnow && ri!==undefined) {
var cycles = {from:getCycles($from.anim), to:getCycles($to.anim)};
for (var si in animobject) {
var $fanim = jQuery.extend({},$from.anim),
$tanim = jQuery.extend({},$to.anim);
for (var k in cycles.from) {
$fanim[k] = parseInt(cycles.from[k].values[cycles.from[k].index],0);
cycles.from[k].index = cycles.from[k].index < cycles.from[k].len ? cycles.from[k].index+1 : 0;
}
$tanim.ease = $fanim.ease;
if (_.frames[frame_index].color!==undefined) {
$fanim.color = _.frames[frame_index].color;
$tanim.color = _.cssobj.styleProps.color;
}
if (_.frames[frame_index].bgcolor!==undefined) {
$fanim.backgroundColor = _.frames[frame_index].bgcolor;
$tanim.backgroundColor = _.cssobj.styleProps["background-color"];
}
timeline.add(tweens.content.fromTo(animobject[ri[si]],$from.speed/1000,$fanim,$tanim,$elemdelay*si),label);
}
} else {
if (_.frames[frame_index].color!==undefined) {
$from.anim.color = _.frames[frame_index].color;
$to.anim.color = _.cssobj.styleProps.color;
}
if (_.frames[frame_index].bgcolor!==undefined) {
$from.anim.backgroundColor = _.frames[frame_index].bgcolor;
$to.anim.backgroundColor = _.cssobj.styleProps["background-color"];
}
timeline.add(tweens.content.staggerFromTo(animobject,$from.speed/1000,$from.anim,$to.anim,$elemdelay),label);
}
}
} else {
if (_._sfx_out==="block" && frame_index===_.outframeindex) {
timeline.add(tweens.content.staggerTo(animobject,0.001,{autoAlpha:0,delay:$sfx_blockdelay}),label);
timeline.add(tweens.content.staggerTo(animobject,((($to.speed/1000)/2)-0.001),{x:0,delay:$sfx_blockdelay}),label+"+=0.001");
} else
if ($splitnow && ri!==undefined) {
var cycles = {to:getCycles($to.anim)};
for (var si in animobject) {
var $tanim = jQuery.extend({},$to.anim);
for (var k in cycles.to) {
$tanim[k] = parseInt(cycles.to[k].values[cycles.to[k].index],0);
cycles.to[k].index = cycles.to[k].index < cycles.to[k].len ? cycles.to[k].index+1 : 0;
}
if (_.frames[frame_index].color!==undefined)
$tanim.color = _.frames[frame_index].color;
if (_.frames[frame_index].bgcolor!==undefined)
$tanim.backgroundColor = _.frames[frame_index].bgcolor;
timeline.add(tweens.content.to(animobject[ri[si]],$to.speed/1000,$tanim,$elemdelay*si),label);
}
} else {
if (_.frames[frame_index].color!==undefined)
$to.anim.color = _.frames[frame_index].color;
if (_.frames[frame_index].bgcolor!==undefined)
$to.anim.backgroundColor = _.frames[frame_index].bgcolor;
timeline.add(tweens.content.staggerTo(animobject,$to.speed/1000,$to.anim,$elemdelay),label);
}
}
if ($mask_to!==undefined && $mask_to!==false && (frame_index!==0 || !obj.ignorefirstframe)) {
$mask_to.anim.ease = $mask_to.anim.ease === undefined || $mask_to.anim.ease==="inherit" ? _.frames[0].ease : $mask_to.anim.ease;
$mask_to.anim.overflow = "hidden";
$mask_to.anim.x = $mask_to.anim.x * opt.bw || getBorderDirections($mask_to.anim.x,opt,_.eow,_.eoh,_.calcy,_.calcx,"horizontal");
$mask_to.anim.y = $mask_to.anim.y * opt.bw || getBorderDirections($mask_to.anim.y,opt,_.eow,_.eoh,_.calcy,_.calcx,"vertical");
}
if ((frame_index===0 && $mask_from && $mask_from!==false && !obj.fromcurrentstate) || (frame_index===0 && obj.ignorefirstframe)) {
$mask_to = new Object();
$mask_to.anim = new Object();
$mask_to.anim.overwrite = "auto";
$mask_to.anim.ease = $to.anim.ease;
$mask_to.anim.x = $mask_to.anim.y = 0;
if ($mask_from && $mask_from!==false) {
$mask_from.anim.x = $mask_from.anim.x * opt.bw || getBorderDirections($mask_from.anim.x,opt,_.eow,_.eoh,_.calcy,_.calcx,"horizontal");
$mask_from.anim.y = $mask_from.anim.y * opt.bw || getBorderDirections($mask_from.anim.y,opt,_.eow,_.eoh,_.calcy,_.calcx,"vertical");
$mask_from.anim.overflow ="hidden";
}
} else
if (frame_index===0)
timeline.add(tweens.mask.set(_._mw,{overflow:"visible"}),label);
if ($mask_from!==undefined && $mask_to!==undefined && $mask_from!==false && $mask_to!==false)
timeline.add(tweens.mask.fromTo(_._mw,$from.speed/1000,$mask_from.anim,$mask_to.anim,$elemdelay),label);
else
if ($mask_to!==undefined && $mask_to!==false)
timeline.add(tweens.mask.to(_._mw,$to.speed/1000,$mask_to.anim,$elemdelay),label);
timeline.addLabel(label+"_end");
// Reset Hover Effect when Last Frame (Out Animation) ordered
if (_._gsTransformTo && frame_index===verylastframe && _.hoveredstatus)
_.hovertimelines.item = punchgs.TweenLite.to(_nc,0,_._gsTransformTo);
_._gsTransformTo = false;
// ON START
tweens.content.eventCallback("onStart",tweenOnStart,[frame_index,_nc_tl_obj,_._pw,_,timeline,$to.anim,_nc,obj.updateStaticTimeline,opt]);
// ON UPDATE
tweens.content.eventCallback("onUpdate",tweenOnUpdate,[label,_._id,_._pw,_,timeline,frame_index,jQuery.extend(true,{},$to.anim),obj.updateStaticTimeline,_nc,opt]);
// ON COMPLETE
tweens.content.eventCallback("onComplete",tweenOnComplete,[frame_index,_.frames.length,verylastframe,_._pw,_,timeline,obj.updateStaticTimeline,_nc,opt]);
return timeline;
},
//////////////////////////////
// MOVE OUT THE CAPTIONS //
////////////////////////////
endMoveCaption : function(obj) {
obj.firstframe="frame_0";
obj.lastframe="frame_999";
var nc = getTLInfos(obj),
_ = obj.caption.data();
if (obj.frame!==undefined)
nc.timeline.play(obj.frame);
else
if (!nc.static || (obj.currentslide>=nc.removeonslide) || (obj.currentslide<nc.showonslide)) {
nc.outnow = new punchgs.TimelineLite;
nc.timeline.pause();
if (_.visibleelement===true)
_R.createFrameOnTimeline({caption:obj.caption, timeline : nc.outnow, label:"outnow", frameindex : obj.caption.data("outframeindex"), opt:obj.opt, fromcurrentstate:true}).play();
}
if (obj.checkchildrens)
if (nc.timeline_obj && nc.timeline_obj.dchildren && nc.timeline_obj.dchildren!=="none" && nc.timeline_obj.dchildren.length>0)
for (var q = 0; q<nc.timeline_obj.dchildren.length;q++) {
_R.endMoveCaption({caption:jQuery(nc.timeline_obj.dchildren[q]), opt:obj.opt});
}
},
//////////////////////////////////
// MOVE CAPTIONS TO xx FRAME //
/////////////////////////////////
playAnimationFrame : function(obj) {
obj.firstframe = obj.triggerframein;
obj.lastframe = obj.triggerframeout;
var nc = getTLInfos(obj),
_ = obj.caption.data(),
frameindex,
i=0;
for (var k in _.frames) {
if (_.frames[k].framename === obj.frame) frameindex = i;
i++;
}
if (_.triggeredtimeline!==undefined) _.triggeredtimeline.pause();
_.triggeredtimeline = new punchgs.TimelineLite;
nc.timeline.pause();
var fcs = _.visibleelement===true ? true : false;
_.triggeredtimeline = _R.createFrameOnTimeline({caption:obj.caption, timeline : _.triggeredtimeline, label:"triggered", frameindex : frameindex, updateStaticTimeline:true, opt:obj.opt, ignorefirstframe:true, fromcurrentstate:fcs}).play();
//nc.timeline.play(obj.frame);
},
//////////////////////////
// REMOVE THE CAPTIONS //
/////////////////////////
removeTheCaptions : function(actli,opt) {
if (_R.compare_version(extension).check==="stop") return false;
var removetime = 0,
index = actli.data('index'),
allcaptions = new Array;
// COLLECT ALL CAPTIONS
if (opt.layers[index])
jQuery.each(opt.layers[index], function(i,a) { allcaptions.push(a); });
/*if (opt.layers["static"])
jQuery.each(opt.layers["static"], function(i,a) { allcaptions.push(a); });*/
var slideindex = _R.currentSlideIndex(opt);
// GO THROUGH ALL CAPTIONS, AND MANAGE THEM
if (allcaptions)
jQuery.each(allcaptions,function(i) {
var _nc=jQuery(this);
if (opt.sliderType==="carousel" && opt.carousel.showLayersAllTime==="on") {
clearTimeout(_nc.data('videoplaywait'));
if (_R.stopVideo) _R.stopVideo(_nc,opt);
if (_R.removeMediaFromList) _R.removeMediaFromList(_nc,opt);
opt.lastplayedvideos = [];
} else {
killCaptionLoops(_nc);
clearTimeout(_nc.data('videoplaywait'));
_R.endMoveCaption({caption:_nc,opt:opt, currentslide:slideindex});
if (_R.removeMediaFromList) _R.removeMediaFromList(_nc,opt);
opt.lastplayedvideos = [];
}
});
}
});
/**********************************************************************************************
- HELPER FUNCTIONS FOR LAYER TRANSFORMS -
**********************************************************************************************/
var tweenOnStart = function(frame_index,ncobj,pw,_,tl,toanim,_nc,ust,opt){
var data={};
data.layer = _nc;
data.eventtype = frame_index===0 ? "enterstage" : frame_index===_.outframeindex ? "leavestage" : "framestarted";
data.layertype = _nc.data('layertype');
_.active = true;
//_nc.data('active',true);
//_.idleanimadded = false;
data.frame_index = frame_index;
data.layersettings = _nc.data();
opt.c.trigger("revolution.layeraction",[data]);
if (_.loopanimation=="on") callCaptionLoops(_._lw,opt.bw);
if (data.eventtype==="enterstage") {
_.animdirection="in";
_.visibleelement=true;
_R.toggleState(_.layertoggledby);
}
if (ncobj.dchildren!=="none" && ncobj.dchildren!==undefined && ncobj.dchildren.length>0) {
if (frame_index===0)
for (var q=0;q<ncobj.dchildren.length;q++) {
jQuery(ncobj.dchildren[q]).data('timeline').play(0);
}
else
if (frame_index===_.outframeindex)
for (var q=0;q<ncobj.dchildren.length;q++) {
_R.endMoveCaption({caption:jQuery(ncobj.dchildren[q]), opt:opt, checkchildrens:true});
}
}
punchgs.TweenLite.set(pw,{visibility:"visible"});
_.current_frame = frame_index;
_.current_timeline = tl;
_.current_timeline_time = tl.time();
if (ust) _.static_layer_timeline_time = _.current_timeline_time;
_.last_frame_started = frame_index;
}
var tweenOnUpdate = function(label,id,pw,_,tl,frame_index,toanim,ust,_nc,opt) {
if (_._nctype==="column") setColumnBgDimension(_nc,opt);
punchgs.TweenLite.set(pw,{visibility:"visible"});
_.current_frame = frame_index;
_.current_timeline = tl;
_.current_timeline_time = tl.time();
if (ust) _.static_layer_timeline_time = _.current_timeline_time;
if (_.hoveranim !== undefined && _._gsTransformTo===false) {
_._gsTransformTo = toanim;
if (_._gsTransformTo && _._gsTransformTo.startAt) delete _._gsTransformTo.startAt;
if (_.cssobj.styleProps.css===undefined)
_._gsTransformTo = jQuery.extend(true,{},_.cssobj.styleProps,_._gsTransformTo);
else
_._gsTransformTo = jQuery.extend(true,{},_.cssobj.styleProps.css,_._gsTransformTo);
}
_.visibleelement=true;
}
var tweenOnComplete = function(frame_index,frame_max,verylastframe,pw,_,tl,ust,_nc,opt) {
var data={};
data.layer = _nc;
data.eventtype = frame_index===0 ? "enteredstage" : frame_index===frame_max-1 || frame_index===verylastframe ? "leftstage" : "frameended";
data.layertype = _nc.data('layertype');
data.layersettings = _nc.data();
opt.c.trigger("revolution.layeraction",[data]);
if (data.eventtype!=="leftstage") _R.animcompleted(_nc,opt);
if (data.eventtype==="leftstage")
if (_R.stopVideo) _R.stopVideo(_nc,opt);
if (_._nctype==="column") {
punchgs.TweenLite.to(_._cbgc_man,0.01,{visibility:"hidden"});
punchgs.TweenLite.to(_._cbgc_auto,0.01,{visibility:"visible"});
}
if (data.eventtype === "leftstage") {
_.active = false;
punchgs.TweenLite.set(pw,{visibility:"hidden",overwrite:"auto"});
_.animdirection="out";
_.visibleelement=false;
_R.unToggleState(_.layertoggledby);
//RESET VIDEO AFTER REMOVING LAYER
if (_._nctype==="video" && _R.resetVideo) setTimeout(function() {
_R.resetVideo(_nc,opt);
},100);
}
_.current_frame = frame_index;
_.current_timeline = tl;
_.current_timeline_time = tl.time();
if (ust) _.static_layer_timeline_time = _.current_timeline_time;
}
//////////////////////////////////////////////
// - GET TIMELINE INFOS FROM CAPTION - //
/////////////////////////////////////////////
var getTLInfos = function(obj) {
var _ = {};
obj.firstframe=obj.firstframe===undefined ? "frame_0" : obj.firstframe;
obj.lastframe=obj.lastframe===undefined ? "frame_999" : obj.lastframe;
_.id = obj.caption.data('id') || obj.caption.attr('id');
_.slideid = obj.caption.data('slideid') || obj.caption.closest('.tp-revslider-slidesli').data('index');
_.timeline_obj = obj.opt.timelines[_.slideid]["layers"][_.id];
_.timeline = _.timeline_obj.timeline;
_.ffs = _.timeline.getLabelTime(obj.firstframe);
_.ffe = _.timeline.getLabelTime(obj.firstframe+"_end");
_.lfs = _.timeline.getLabelTime(obj.lastframe);
_.lfe = _.timeline.getLabelTime(obj.lastframe+"_end");
_.ct = _.timeline.time();
_.static = _.timeline_obj.firstslide!=undefined || _.timeline_obj.lastslide!=undefined;
if (_.static) {
_.showonslide = _.timeline_obj.firstslide;
_.removeonslide = _.timeline_obj.lastslide;
}
return _;
}
//////////////////////////////////////////////
// - GET SPLITTEXT DIRECTION ARRAY - //
/////////////////////////////////////////////
var shuffleArray = function(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
var getSplitTextDirs = function(alen,d) {
var ri = new Array();
switch (d) {
case "forward":
case "random":
for (var si=0;si<=alen;si++) { ri.push(si);}
if (d==="random") ri = shuffleArray(ri);
break;
case "backward":
for (var si=0;si<=alen;si++) { ri.push(alen-si); }
break;
case "middletoedge":
var cc = Math.ceil(alen/2),
mm = cc-1,
pp = cc+1;
ri.push(cc);
for (var si=0;si<cc;si++) {
if (mm>=0) ri.push(mm);
if (pp<=alen) ri.push(pp);
mm--;
pp++;
}
break;
case "edgetomiddle":
var mm = alen,
pp = 0;
for (var si=0;si<=Math.floor(alen/2);si++) {
ri.push(mm);
if (pp<mm) ri.push(pp);
mm--;
pp++;
}
break;
}
return ri;
}
//////////////////////////////////////////////
// - GET SPLITTEXT CYCLES ANIMATION - //
/////////////////////////////////////////////
var getCycles = function(anim) {
var _ = {};
for (var a in anim) {
if (typeof anim[a] === "string" && anim[a].indexOf("|")>=0) {
if (_[a]===undefined) _[a] = {index:0};
_[a].values = ((anim[a].replace("[","")).replace("]","")).split("|");
_[a].len = _[a].values.length-1;
}
}
return _;
}
/////////////////////////////////////
// - CREATE ANIMATION OBJECT - //
/////////////////////////////////////
var newAnimObject = function(a) {
a = a===undefined ? new Object() : a;
a.anim = a.anim===undefined ? new Object() : a.anim;
a.anim.x = a.anim.x===undefined ? 0 : a.anim.x;
a.anim.y = a.anim.y===undefined ? 0 : a.anim.y;
a.anim.z = a.anim.z===undefined ? 0 : a.anim.z;
a.anim.rotationX = a.anim.rotationX===undefined ? 0 : a.anim.rotationX;
a.anim.rotationY = a.anim.rotationY===undefined ? 0 : a.anim.rotationY;
a.anim.rotationZ = a.anim.rotationZ===undefined ? 0 : a.anim.rotationZ;
a.anim.scaleX = a.anim.scaleX===undefined ? 1 : a.anim.scaleX;
a.anim.scaleY = a.anim.scaleY===undefined ? 1 : a.anim.scaleY;
a.anim.skewX = a.anim.skewX===undefined ? 0 : a.anim.skewX;
a.anim.skewY = a.anim.skewY===undefined ? 0 : a.anim.skewY;
a.anim.opacity = a.anim.opacity===undefined ? 1 : a.anim.opacity;
a.anim.transformOrigin = a.anim.transformOrigin===undefined ? "50% 50%" : a.anim.transformOrigin;
a.anim.transformPerspective = a.anim.transformPerspective===undefined ? 600 : a.anim.transformPerspective;
a.anim.rotation = a.anim.rotation===undefined ? 0 : a.anim.rotation;
//a.anim.ease = a.anim.ease===undefined ? punchgs.Power3.easeOut : a.anim.ease;
a.anim.force3D = a.anim.force3D===undefined ? "auto" : a.anim.force3D;
a.anim.autoAlpha = a.anim.autoAlpha===undefined ? 1 : a.anim.autoAlpha;
a.anim.visibility = a.anim.visibility===undefined ? "visible" : a.anim.visibility;
a.anim.overwrite = a.anim.overwrite===undefined ? "auto" : a.anim.overwrite;
a.speed = a.speed===undefined ? 0.3 : a.speed;
a.filter = a.filter===undefined ? "blur(0px) grayscale(0%) brightness(100%)" : a.filter;
a["-webkit-filter"] = a["-webkit-filter"]===undefined ? "blur(0px) grayscale(0%) brightness(100%)" : a["-webkit-filter"];
return a;
}
var newSVGHoverAnimObject = function() {
var a = new Object();
a.anim = new Object();
a.anim.stroke="none";
a.anim.strokeWidth=0;
a.anim.strokeDasharray="none";
a.anim.strokeDashoffset="0";
return a;
}
var setSVGAnimObject = function(data,a) {
var customarray = data.split(';');
if (customarray)
jQuery.each(customarray,function(index,pa) {
var p = pa.split(":")
var w = p[0],
v = p[1];
if (w=="sc") a.anim.stroke=v;
if (w=="sw") a.anim.strokeWidth=v;
if (w=="sda") a.anim.strokeDasharray=v;
if (w=="sdo") a.anim.strokeDashoffset=v;
});
return a;
}
var newEndAnimObject = function() {
var a = new Object();
a.anim = new Object();
a.anim.x=0;
a.anim.y=0;
a.anim.z=0;
return a;
}
var newHoverAnimObject = function() {
var a = new Object();
a.anim = new Object();
a.speed = 0.2;
return a;
}
var animDataTranslator = function(val,defval,$split,$splitamount,ext) {
ext = ext===undefined ? "" : ext;
if (jQuery.isNumeric(parseFloat(val))) {
return parseFloat(val)+ext;
} else
if (val===undefined || val==="inherit") {
return defval+"ext";
} else
if (val.split("{").length>1) {
var min = val.split(","),
max = parseFloat(min[1].split("}")[0]);
min = parseFloat(min[0].split("{")[1]);
if ($split!==undefined && $splitamount!==undefined) {
val=="["+(parseInt(Math.random()*(max-min),0) + parseInt(min,0))+"ext";
for (var i=0;i<$splitamount;i++) {
val = val+"|"+(parseInt(Math.random()*(max-min),0) + parseInt(min,0))+ext;
}
val = val+"]";
} else {
val = Math.random()*(max-min) + min;
}
}
return val;
}
var getBorderDirections = function (x,o,w,h,top,left,direction) {
if (!jQuery.isNumeric(x) && x.match(/%]/g)) {
x = x.split("[")[1].split("]")[0];
if (direction=="horizontal")
x = (w+2)*parseInt(x,0)/100;
else
if (direction=="vertical")
x = (h+2)*parseInt(x,0)/100;
} else {
x = x === "layer_left" ? (0-w) : x === "layer_right" ? w : x;
x = x === "layer_top" ? (0-h) : x==="layer_bottom" ? h : x;
x = x === "left" || x==="stage_left" ? (0-w-left) : x === "right" || x==="stage_right" ? o.conw-left : x === "center" || x === "stage_center" ? (o.conw/2 - w/2)-left : x;
x = x === "top" || x==="stage_top" ? (0-h-top) : x==="bottom" || x==="stage_bottom" ? o.conh-top : x === "middle" || x === "stage_middle" ? (o.conh/2 - h/2)-top : x;
}
return x;
}
///////////////////////////////////////////////////
// ANALYSE AND READ OUT DATAS FROM HTML CAPTIONS //
///////////////////////////////////////////////////
var getAnimDatas = function(frm,data,reversed,$split,$splitamount) {
var o = new Object();
o = jQuery.extend(true,{},o, frm);
if (data === undefined)
return o;
var customarray = data.split(';'),
tmpf="";
if (customarray)
jQuery.each(customarray,function(index,pa) {
var p = pa.split(":")
var w = p[0],
v = p[1];
if (reversed && reversed!=="none" && v!=undefined && v.length>0 && v.match(/\(R\)/)) {
v = v.replace("(R)","");
v = v==="right" ? "left" : v==="left" ? "right" : v==="top" ? "bottom" : v==="bottom" ? "top" : v;
if (v[0]==="[" && v[1]==="-") v = v.replace("[-","[");
else
if (v[0]==="[" && v[1]!=="-") v = v.replace("[","[-");
else
if (v[0]==="-") v = v.replace("-","");
else
if (v[0].match(/[1-9]/)) v="-"+v;
}
if (v!=undefined) {
v = v.replace(/\(R\)/,'');
if (w=="rotationX" || w=="rX") o.anim.rotationX = animDataTranslator(v,o.anim.rotationX,$split,$splitamount,"deg");
if (w=="rotationY" || w=="rY") o.anim.rotationY = animDataTranslator(v,o.anim.rotationY,$split,$splitamount,"deg");
if (w=="rotationZ" || w=="rZ") o.anim.rotation = animDataTranslator(v,o.anim.rotationZ,$split,$splitamount,"deg");
if (w=="scaleX" || w=="sX") o.anim.scaleX = animDataTranslator(v,o.anim.scaleX,$split,$splitamount);
if (w=="scaleY" || w=="sY") o.anim.scaleY = animDataTranslator(v,o.anim.scaleY,$split,$splitamount);
if (w=="opacity" || w=="o") o.anim.opacity = animDataTranslator(v,o.anim.opacity,$split,$splitamount);
//if (w=="letterspacing" || w=="ls") o.anim.letterSpacing = animDataTranslator(v,o.anim.letterSpacing);
if (w=="fb") tmpf = tmpf==="" ? 'blur('+parseInt(v,0)+'px)' : tmpf+" "+'blur('+parseInt(v,0)+'px)';
if (w=="fg") tmpf = tmpf==="" ? 'grayscale('+parseInt(v,0)+'%)' : tmpf+" "+'grayscale('+parseInt(v,0)+'%)';
if (w=="fbr") tmpf = tmpf==="" ? 'brightness('+parseInt(v,0)+'%)' : tmpf+" "+'brightness('+parseInt(v,0)+'%)';
if (o.anim.opacity===0) o.anim.autoAlpha = 0;
o.anim.opacity = o.anim.opacity == 0 ? 0.0001 : o.anim.opacity;
if (w=="skewX" || w=="skX") o.anim.skewX = animDataTranslator(v,o.anim.skewX,$split,$splitamount);
if (w=="skewY" || w=="skY") o.anim.skewY = animDataTranslator(v,o.anim.skewY,$split,$splitamount);
if (w=="x") o.anim.x = animDataTranslator(v,o.anim.x,$split,$splitamount);
if (w=="y") o.anim.y = animDataTranslator(v,o.anim.y,$split,$splitamount);
if (w=="z") o.anim.z = animDataTranslator(v,o.anim.z,$split,$splitamount);
if (w=="transformOrigin" || w=="tO") o.anim.transformOrigin = v.toString();
if (w=="transformPerspective" || w=="tP") o.anim.transformPerspective=parseInt(v,0);
if (w=="speed" || w=="s") o.speed = parseFloat(v);
//if (w=="ease" || w=="e") o.anim.ease = v;
}
})
if (tmpf!=="") {
o.anim['-webkit-filter'] = tmpf;
o.anim['filter'] = tmpf;
}
return o;
}
/////////////////////////////////
// BUILD MASK ANIMATION OBJECT //
/////////////////////////////////
var getMaskDatas = function(d) {
if (d === undefined)
return false;
var o = new Object();
o.anim = new Object();
var s = d.split(';')
if (s)
jQuery.each(s,function(index,param) {
param = param.split(":")
var w = param[0],
v = param[1];
if (w=="x") o.anim.x = v;
if (w=="y") o.anim.y = v;
if (w=="s") o.speed = parseFloat(v);
if (w=="e" || w=="ease") o.anim.ease = v;
});
return o;
}
////////////////////////
// SHOW THE CAPTION //
///////////////////////
var makeArray = function(obj,opt,show) {
if (obj==undefined) obj = 0;
if (!jQuery.isArray(obj) && jQuery.type(obj)==="string" && (obj.split(",").length>1 || obj.split("[").length>1)) {
obj = obj.replace("[","");
obj = obj.replace("]","");
var newobj = obj.match(/'/g) ? obj.split("',") : obj.split(",");
obj = new Array();
if (newobj)
jQuery.each(newobj,function(index,element) {
element = element.replace("'","");
element = element.replace("'","");
obj.push(element);
})
} else {
var tempw = obj;
if (!jQuery.isArray(obj) ) {
obj = new Array();
obj.push(tempw);
}
}
var tempw = obj[obj.length-1];
if (obj.length<opt.rle) {
for (var i=1;i<=opt.curWinRange;i++) {
obj.push(tempw);
}
}
return obj;
}
/* CREATE SHARP CORNERS */
function sharpCorners(nc,$class, $side,$borderh,$borderv,ncch,bgcol) {
var a = nc.find($class);
a.css('borderWidth',ncch+"px");
a.css($side,(0-ncch)+'px');
a.css($borderh,'0px solid transparent');
a.css($borderv,bgcol);
}
var convertHoverStyle = function(t,s) {
if (s===undefined) return t;
s = s.replace("c:","color:");
s = s.replace("bg:","background-color:");
s = s.replace("bw:","border-width:");
s = s.replace("bc:","border-color:");
s = s.replace("br:","borderRadius:");
s = s.replace("bs:","border-style:");
s = s.replace("td:","text-decoration:");
s = s.replace("zi:","zIndex:");
var sp = s.split(";");
if (sp)
jQuery.each(sp,function(key,cont){
var attr = cont.split(":");
if (attr[0].length>0) {
if (attr[0]==="background-color" && attr[1].indexOf("gradient")>=0) attr[0]="background";
t.anim[attr[0]] = attr[1];
}
})
return t;
}
////////////////////////////////////////////////
// - GET CSS ATTRIBUTES OF ELEMENT - //
////////////////////////////////////////////////
var getcssParams = function(nc,level) {
var obj = new Object(),
gp = false,
pc;
// CHECK IF CURRENT ELEMENT SHOULD RESPECT REKURSICVE RESIZES, AND SHOULD OWN THE SAME ATTRIBUTES FROM PARRENT ELEMENT
if (level=="rekursive") {
pc = nc.closest('.tp-caption');
if (pc && (
(nc.css("fontSize") === pc.css("fontSize")) &&
(nc.css("fontWeight") === pc.css("fontWeight")) &&
(nc.css("lineHeight") === pc.css("lineHeight"))
))
gp = true;
}
obj.basealign = nc.data('basealign') || "grid";
obj.fontSize = gp ? pc.data('fontsize')===undefined ? parseInt(pc.css('fontSize'),0) || 0 : pc.data('fontsize') : nc.data('fontsize')===undefined ? parseInt(nc.css('fontSize'),0) || 0 : nc.data('fontsize');
obj.fontWeight = gp ? pc.data('fontweight')===undefined ? parseInt(pc.css('fontWeight'),0) || 0 : pc.data('fontweight') : nc.data('fontweight')===undefined ? parseInt(nc.css('fontWeight'),0) || 0 : nc.data('fontweight');
obj.whiteSpace = gp ? pc.data('whitespace')===undefined ? pc.css('whitespace') || "normal" : pc.data('whitespace') : nc.data('whitespace')===undefined ? nc.css('whitespace') || "normal" : nc.data('whitespace');
obj.textAlign = gp ? pc.data('textalign')===undefined ? pc.css('textalign') || "inherit" : pc.data('textalign') : nc.data('textalign')===undefined ? nc.css('textalign') || "inherit" : nc.data('textalign');
obj.zIndex = gp ? pc.data('zIndex')===undefined ? pc.css('zIndex') || "inherit" : pc.data('zIndex') : nc.data('zIndex')===undefined ? nc.css('zIndex') || "inherit" : nc.data('zIndex');
if (jQuery.inArray(nc.data('layertype'),["video","image","audio"])===-1 && !nc.is("img"))
obj.lineHeight = gp ? pc.data('lineheight')===undefined ? parseInt(pc.css('lineHeight'),0) || 0 : pc.data('lineheight') : nc.data('lineheight')===undefined ? parseInt(nc.css('lineHeight'),0) || 0 : nc.data('lineheight');
else
obj.lineHeight = 0;
obj.letterSpacing = gp ? pc.data('letterspacing')===undefined ? parseFloat(pc.css('letterSpacing'),0) || 0 : pc.data('letterspacing') : nc.data('letterspacing')===undefined ? parseFloat(nc.css('letterSpacing')) || 0 : nc.data('letterspacing');
obj.paddingTop = nc.data('paddingtop')===undefined ? parseInt(nc.css('paddingTop'),0) || 0 : nc.data('paddingtop');
obj.paddingBottom = nc.data('paddingbottom')===undefined ? parseInt(nc.css('paddingBottom'),0) || 0 : nc.data('paddingbottom');
obj.paddingLeft = nc.data('paddingleft')===undefined ? parseInt(nc.css('paddingLeft'),0) || 0 : nc.data('paddingleft');
obj.paddingRight = nc.data('paddingright')===undefined ? parseInt(nc.css('paddingRight'),0) || 0 : nc.data('paddingright');
obj.marginTop = nc.data('margintop')===undefined ? parseInt(nc.css('marginTop'),0) || 0 : nc.data('margintop');
obj.marginBottom = nc.data('marginbottom')===undefined ? parseInt(nc.css('marginBottom'),0) || 0 : nc.data('marginbottom');
obj.marginLeft = nc.data('marginleft')===undefined ? parseInt(nc.css('marginLeft'),0) || 0 : nc.data('marginleft');
obj.marginRight = nc.data('marginright')===undefined ? parseInt(nc.css('marginRight'),0) || 0 : nc.data('marginright');
obj.borderTopWidth = nc.data('bordertopwidth')===undefined ? parseInt(nc.css('borderTopWidth'),0) || 0 : nc.data('bordertopwidth');
obj.borderBottomWidth = nc.data('borderbottomwidth')===undefined ? parseInt(nc.css('borderBottomWidth'),0) || 0 : nc.data('borderbottomwidth');
obj.borderLeftWidth = nc.data('borderleftwidth')===undefined ? parseInt(nc.css('borderLeftWidth'),0) || 0 : nc.data('borderleftwidth');
obj.borderRightWidth = nc.data('borderrightwidth')===undefined ? parseInt(nc.css('borderRightWidth'),0) || 0 : nc.data('borderrightwidth');
if (level!="rekursive") {
obj.color = nc.data('color')===undefined ? "nopredefinedcolor" : nc.data('color');
obj.whiteSpace = gp ? pc.data('whitespace')===undefined ? pc.css('whiteSpace') || "nowrap" : pc.data('whitespace') : nc.data('whitespace')===undefined ? nc.css('whiteSpace') || "nowrap" : nc.data('whitespace');
obj.textAlign = gp ? pc.data('textalign')===undefined ? pc.css('textalign') || "inherit" : pc.data('textalign') : nc.data('textalign')===undefined ? nc.css('textalign') || "inherit" : nc.data('textalign');
obj.fontWeight = gp ? pc.data('fontweight')===undefined ? parseInt(pc.css('fontWeight'),0) || 0 : pc.data('fontweight') : nc.data('fontweight')===undefined ? parseInt(nc.css('fontWeight'),0) || 0 : nc.data('fontweight');
obj.minWidth = nc.data('width')===undefined ? parseInt(nc.css('minWidth'),0) || 0 : nc.data('width');
obj.minHeight = nc.data('height')===undefined ? parseInt(nc.css('minHeight'),0) || 0 : nc.data('height');
if (nc.data('videowidth')!=undefined && nc.data('videoheight')!=undefined) {
var vwid = nc.data('videowidth'),
vhei = nc.data('videoheight');
vwid = vwid==="100%" ? "none" : vwid;
vhei = vhei==="100%" ? "none" : vhei;
nc.data('width',vwid);
nc.data('height',vhei);
}
obj.maxWidth = nc.data('width')===undefined ? parseInt(nc.css('maxWidth'),0) || "none" : nc.data('width');
obj.maxHeight = jQuery.inArray(nc.data('type'),["column","row"])!==-1 ? "none" : nc.data('height')===undefined ? parseInt(nc.css('maxHeight'),0) || "none" : nc.data('height');
obj.wan = nc.data('wan')===undefined ? parseInt(nc.css('-webkit-transition'),0) || "none" : nc.data('wan');
obj.moan = nc.data('moan')===undefined ? parseInt(nc.css('-moz-animation-transition'),0) || "none" : nc.data('moan');
obj.man = nc.data('man')===undefined ? parseInt(nc.css('-ms-animation-transition'),0) || "none" : nc.data('man');
obj.ani = nc.data('ani')===undefined ? parseInt(nc.css('transition'),0) || "none" : nc.data('ani');
}
obj.styleProps = { borderTopLeftRadius : nc[0].style.borderTopLeftRadius,
borderTopRightRadius : nc[0].style.borderTopRightRadius,
borderBottomRightRadius : nc[0].style.borderBottomRightRadius,
borderBottomLeftRadius : nc[0].style.borderBottomLeftRadius,
"background" : nc[0].style["background"],
"boxShadow" : nc[0].style["boxShadow"],
"background-color" : nc[0].style["background-color"],
"border-top-color" : nc[0].style["border-top-color"],
"border-bottom-color" : nc[0].style["border-bottom-color"],
"border-right-color" : nc[0].style["border-right-color"],
"border-left-color" : nc[0].style["border-left-color"],
"border-top-style" : nc[0].style["border-top-style"],
"border-bottom-style" : nc[0].style["border-bottom-style"],
"border-left-style" : nc[0].style["border-left-style"],
"border-right-style" : nc[0].style["border-right-style"],
"border-left-width" : nc[0].style["border-left-width"],
"border-right-width" : nc[0].style["border-right-width"],
"border-bottom-width" : nc[0].style["border-bottom-width"],
"border-top-width" : nc[0].style["border-top-width"],
"color" : nc[0].style["color"],
"text-decoration" : nc[0].style["text-decoration"],
"font-style" : nc[0].style["font-style"]
};
if (obj.styleProps.background==="" || obj.styleProps.background===undefined || obj.styleProps.background === obj.styleProps["background-color"])
delete obj.styleProps.background;
if (obj.styleProps.color=="")
obj.styleProps.color = nc.css("color");
return obj;
}
// READ SINGLE OR ARRAY VALUES OF OBJ CSS ELEMENTS
var setResponsiveCSSValues = function(obj,opt) {
var newobj = new Object();
if (obj)
jQuery.each(obj,function(key,val){
var res_a = makeArray(val,opt)[opt.curWinRange];
newobj[key] = res_a!==undefined ? res_a : obj[key];
});
return newobj;
}
var minmaxconvert = function(a,m,r,fr) {
a = jQuery.isNumeric(a) ? (a * m)+"px" : a;
a = a==="full" ? fr : a==="auto" || a==="none" ? r : a;
return a;
}
/////////////////////////////////////////////////////////////////
// - CALCULATE THE RESPONSIVE SIZES OF THE CAPTIONS - //
/////////////////////////////////////////////////////////////////
var calcCaptionResponsive = function(nc,opt,level,responsive) {
var _=nc.data();
_ = _===undefined ? {} : _;
try{
if (nc[0].nodeName=="BR" || nc[0].tagName=="br"
/*|| nc[0].nodeName=="b" || nc[0].tagName=="b" ||
nc[0].nodeName=="strong" || nc[0].tagName=="STRONG"*/
)
return false;
} catch(e) {
}
_.cssobj = _.cssobj===undefined ? getcssParams(nc,level) : _.cssobj;
var obj = setResponsiveCSSValues(_.cssobj,opt),
bw=opt.bw,
bh=opt.bh;
if (responsive==="off") {
bw=1;
bh=1;
}
// IE8 FIX FOR AUTO LINEHEIGHT
if (obj.lineHeight=="auto") obj.lineHeight = obj.fontSize+4;
var objmargins = { Top: obj.marginTop,
Bottom: obj.marginBottom,
Left: obj.marginLeft,
Right: obj.marginRight
}
if (_._nctype==="column") {
punchgs.TweenLite.set(_._column,{
paddingTop: Math.round((obj.marginTop * bh)) + "px",
paddingBottom: Math.round((obj.marginBottom * bh)) + "px",
paddingLeft: Math.round((obj.marginLeft* bw)) + "px",
paddingRight: Math.round((obj.marginRight * bw)) + "px"});
objmargins = { Top: 0,
Bottom: 0,
Left: 0,
Right: 0
}
}
if (!nc.hasClass("tp-splitted")) {
nc.css("-webkit-transition", "none");
nc.css("-moz-transition", "none");
nc.css("-ms-transition", "none");
nc.css("transition", "none");
var hashover = nc.data('transform_hover')!==undefined || nc.data('style_hover')!==undefined;
if (hashover) punchgs.TweenLite.set(nc,obj.styleProps);
punchgs.TweenLite.set(nc,{
fontSize: Math.round((obj.fontSize * bw))+"px",
fontWeight: obj.fontWeight,
letterSpacing:Math.floor((obj.letterSpacing * bw))+"px",
paddingTop: Math.round((obj.paddingTop * bh)) + "px",
paddingBottom: Math.round((obj.paddingBottom * bh)) + "px",
paddingLeft: Math.round((obj.paddingLeft* bw)) + "px",
paddingRight: Math.round((obj.paddingRight * bw)) + "px",
marginTop: (objmargins.Top * bh) + "px",
marginBottom: (objmargins.Bottom * bh) + "px",
marginLeft: (objmargins.Left * bw) + "px",
marginRight: (objmargins.Right * bw) + "px",
borderTopWidth: Math.round(obj.borderTopWidth * bh) + "px",
borderBottomWidth: Math.round(obj.borderBottomWidth * bh) + "px",
borderLeftWidth: Math.round(obj.borderLeftWidth * bw) + "px",
borderRightWidth: Math.round(obj.borderRightWidth * bw) + "px",
lineHeight: Math.round(obj.lineHeight * bh) + "px",
textAlign:(obj.textAlign),
overwrite:"auto"});
if (level!="rekursive") {
var winw = obj.basealign =="slide" ? opt.ulw : opt.gridwidth[opt.curWinRange],
winh = obj.basealign =="slide" ? opt.ulh : opt.gridheight[opt.curWinRange],
maxw = minmaxconvert(obj.maxWidth,bw,"none",winw),
maxh = minmaxconvert(obj.maxHeight,bh,"none",winh),
minw = minmaxconvert(obj.minWidth,bw,"0px",winw),
minh = minmaxconvert(obj.minHeight,bh,"0px",winh);
// TWEEN FIX ISSUES
minw=minw===undefined ? 0 : minw;
minh=minh===undefined ? 0 : minh;
maxw=maxw===undefined ? "none" : maxw;
maxh=maxh===undefined ? "none" : maxh;
if (_._isgroup) {
if (minw==="#1/1#") minw = maxw = winw;
if (minw==="#1/2#") minw = maxw = winw / 2;
if (minw==="#1/3#") minw = maxw = winw/3;
if (minw==="#1/4#") minw = maxw = winw / 4;
if (minw==="#1/5#") minw = maxw = winw / 5;
if (minw==="#1/6#") minw = maxw = winw / 6;
if (minw==="#2/3#") minw = maxw = (winw / 3) * 2;
if (minw==="#3/4#") minw = maxw = (winw / 4) * 3;
if (minw==="#2/5#") minw = maxw = (winw / 5) * 2;
if (minw==="#3/5#") minw = maxw = (winw / 5) * 3;
if (minw==="#4/5#") minw = maxw = (winw / 5) * 4;
if (minw==="#3/6#") minw = maxw = (winw / 6) * 3;
if (minw==="#4/6#") minw = maxw = (winw / 6) * 4;
if (minw==="#5/6#") minw = maxw = (winw / 6) * 5;
}
if (_._ingroup) {
_._groupw = minw;
_._grouph = minh;
}
punchgs.TweenLite.set(nc,{
maxWidth:maxw,
maxHeight:maxh,
minWidth:minw,
minHeight:minh,
whiteSpace:obj.whiteSpace,
textAlign:(obj.textAlign),
overwrite:"auto"
});
if (obj.color!="nopredefinedcolor")
punchgs.TweenLite.set(nc,{color:obj.color,overwrite:"auto"});
if (_.svg_src!=undefined) {
var scolto = obj.color!="nopredefinedcolor" && obj.color!=undefined ? obj.color : obj.css!=undefined && obj.css.color!="nopredefinedcolor" && obj.css.color!=undefined ? obj.css.color : obj.styleProps.color!=undefined ? obj.styleProps.color : obj.styleProps.css!=undefined && obj.styleProps.css.color!=undefined ? obj.styleProps.css.color : false;
if (scolto!=false) {
punchgs.TweenLite.set(nc.find('svg'),{fill:scolto,overwrite:"auto"});
punchgs.TweenLite.set(nc.find('svg path'),{fill:scolto,overwrite:"auto"});
}
}
}
if (_._nctype==="column") {
if (_._column_bg_set===undefined) {
_._column_bg_set = nc.css('backgroundColor');
_._column_bg_image = nc.css('backgroundImage');
_._column_bg_image_repeat =nc.css('backgroundRepeat');
_._column_bg_image_position =nc.css('backgroundPosition');
_._column_bg_image_size =nc.css('backgroundSize');
_._column_bg_opacity = nc.data('bgopacity');
_._column_bg_opacity = _._column_bg_opacity===undefined ? 1 : _._column_bg_opacity;
punchgs.TweenLite.set(nc,{
backgroundColor:"transparent",
backgroundImage:""
});
}
setTimeout(function() {
setColumnBgDimension(nc,opt);
},1);
// DYNAMIC HEIGHT AUTO CALCULATED BY BROWSER
if (_._cbgc_auto && _._cbgc_auto.length>0) {
_._cbgc_auto[0].style.backgroundSize = _._column_bg_image_size;
if (jQuery.isArray(obj.marginLeft)) {
punchgs.TweenLite.set(_._cbgc_auto,{
borderTopWidth: (obj.marginTop[opt.curWinRange] * bh) + "px",
borderLeftWidth: (obj.marginLeft[opt.curWinRange] * bw) + "px",
borderRightWidth: (obj.marginRight[opt.curWinRange] * bw) + "px",
borderBottomWidth:(obj.marginBottom[opt.curWinRange] * bh) + "px",
backgroundColor:_._column_bg_set,
backgroundImage:_._column_bg_image,
backgroundRepeat:_._column_bg_image_repeat,
backgroundPosition:_._column_bg_image_position,
opacity:_._column_bg_opacity
});
} else {
punchgs.TweenLite.set(_._cbgc_auto,{
borderTopWidth: (obj.marginTop * bh) + "px",
borderLeftWidth: (obj.marginLeft * bw) + "px",
borderRightWidth: (obj.marginRight * bw) + "px",
borderBottomWidth:(obj.marginBottom * bh) + "px",
backgroundColor:_._column_bg_set,
backgroundImage:_._column_bg_image,
backgroundRepeat:_._column_bg_image_repeat,
backgroundPosition:_._column_bg_image_position,
opacity:_._column_bg_opacity
});
}
}
}
setTimeout(function() {
nc.css("-webkit-transition", nc.data('wan'));
nc.css("-moz-transition", nc.data('moan'));
nc.css("-ms-transition", nc.data('man'));
nc.css("transition", nc.data('ani'));
},30);
}
}
var setColumnBgDimension = function(nc,opt) {
// DYNAMIC HEIGHT BASED ON ROW HEIGHT
var _ = nc.data();
if (_._cbgc_man && _._cbgc_man.length>0) {
var _l,_t,_b,_r,_h,_o;
if (!jQuery.isArray(_.cssobj.marginLeft)) {
_l = (_.cssobj.marginLeft * opt.bw);
_t = (_.cssobj.marginTop * opt.bh);
_b = (_.cssobj.marginBottom * opt.bh);
_r = (_.cssobj.marginRight * opt.bw);
} else {
_l = (_.cssobj.marginLeft[opt.curWinRange] * opt.bw);
_t = (_.cssobj.marginTop[opt.curWinRange] * opt.bh);
_b = (_.cssobj.marginBottom[opt.curWinRange] * opt.bh);
_r = (_.cssobj.marginRight[opt.curWinRange] * opt.bw);
}
_h = _._row.hasClass("rev_break_columns") ? "100%" : (_._row.height() - (_t+_b))+"px";
_._cbgc_man[0].style.backgroundSize = _._column_bg_image_size;
punchgs.TweenLite.set(_._cbgc_man,{
width:"100%",
height:_h,
backgroundColor:_._column_bg_set,
backgroundImage:_._column_bg_image,
backgroundRepeat:_._column_bg_image_repeat,
backgroundPosition:_._column_bg_image_position,
overwrite:"auto",
opacity:_._column_bg_opacity
});
}
}
//////////////////////
// CAPTION LOOPS //
//////////////////////
var callCaptionLoops = function(el,factor) {
var _ = el.data();
// SOME LOOPING ANIMATION ON INTERNAL ELEMENTS
if (el.hasClass("rs-pendulum")) {
if (_._loop_timeline==undefined) {
_._loop_timeline = new punchgs.TimelineLite;
var startdeg = el.data('startdeg')==undefined ? -20 : el.data('startdeg'),
enddeg = el.data('enddeg')==undefined ? 20 : el.data('enddeg'),
speed = el.data('speed')==undefined ? 2 : el.data('speed'),
origin = el.data('origin')==undefined ? "50% 50%" : el.data('origin'),
easing = el.data('easing')==undefined ? punchgs.Power2.easeInOut : el.data('easing');
startdeg = startdeg * factor;
enddeg = enddeg * factor;
_._loop_timeline.append(new punchgs.TweenLite.fromTo(el,speed,{force3D:"auto",rotation:startdeg,transformOrigin:origin},{rotation:enddeg,ease:easing}));
_._loop_timeline.append(new punchgs.TweenLite.fromTo(el,speed,{force3D:"auto",rotation:enddeg,transformOrigin:origin},{rotation:startdeg,ease:easing,onComplete:function() {
_._loop_timeline.restart();
}}));
}
}
// SOME LOOPING ANIMATION ON INTERNAL ELEMENTS
if (el.hasClass("rs-rotate")) {
if (_._loop_timeline==undefined) {
_._loop_timeline = new punchgs.TimelineLite;
var startdeg = el.data('startdeg')==undefined ? 0 : el.data('startdeg'),
enddeg = el.data('enddeg')==undefined ? 360 : el.data('enddeg'),
speed = el.data('speed')==undefined ? 2 : el.data('speed'),
origin = el.data('origin')==undefined ? "50% 50%" : el.data('origin'),
easing = el.data('easing')==undefined ? punchgs.Power2.easeInOut : el.data('easing');
startdeg = startdeg * factor;
enddeg = enddeg * factor;
_._loop_timeline.append(new punchgs.TweenLite.fromTo(el,speed,{force3D:"auto",rotation:startdeg,transformOrigin:origin},{rotation:enddeg,ease:easing,onComplete:function() {
_._loop_timeline.restart();
}}));
}
}
// SOME LOOPING ANIMATION ON INTERNAL ELEMENTS
if (el.hasClass("rs-slideloop")) {
if (_._loop_timeline==undefined) {
_._loop_timeline = new punchgs.TimelineLite;
var xs = el.data('xs')==undefined ? 0 : el.data('xs'),
ys = el.data('ys')==undefined ? 0 : el.data('ys'),
xe = el.data('xe')==undefined ? 0 : el.data('xe'),
ye = el.data('ye')==undefined ? 0 : el.data('ye'),
speed = el.data('speed')==undefined ? 2 : el.data('speed'),
easing = el.data('easing')==undefined ? punchgs.Power2.easeInOut : el.data('easing');
xs = xs * factor;
ys = ys * factor;
xe = xe * factor;
ye = ye * factor;
_._loop_timeline.append(new punchgs.TweenLite.fromTo(el,speed,{force3D:"auto",x:xs,y:ys},{x:xe,y:ye,ease:easing}));
_._loop_timeline.append(new punchgs.TweenLite.fromTo(el,speed,{force3D:"auto",x:xe,y:ye},{x:xs,y:ys,onComplete:function() {
_._loop_timeline.restart();
}}));
}
}
// SOME LOOPING ANIMATION ON INTERNAL ELEMENTS
if (el.hasClass("rs-pulse")) {
if (_._loop_timeline==undefined) {
_._loop_timeline = new punchgs.TimelineLite;
var zoomstart = el.data('zoomstart')==undefined ? 0 : el.data('zoomstart'),
zoomend = el.data('zoomend')==undefined ? 0 : el.data('zoomend'),
speed = el.data('speed')==undefined ? 2 : el.data('speed'),
easing = el.data('easing')==undefined ? punchgs.Power2.easeInOut : el.data('easing');
_._loop_timeline.append(new punchgs.TweenLite.fromTo(el,speed,{force3D:"auto",scale:zoomstart},{scale:zoomend,ease:easing}));
_._loop_timeline.append(new punchgs.TweenLite.fromTo(el,speed,{force3D:"auto",scale:zoomend},{scale:zoomstart,onComplete:function() {
_._loop_timeline.restart();
}}));
}
}
if (el.hasClass("rs-wave")) {
if (_._loop_timeline==undefined) {
_._loop_timeline = new punchgs.TimelineLite;
var angle= el.data('angle')==undefined ? 10 : parseInt(el.data('angle'),0),
radius = el.data('radius')==undefined ? 10 : parseInt(el.data('radius'),0),
speed = el.data('speed')==undefined ? -20 : el.data('speed'),
origin = el.data('origin')==undefined ? "50% 50%" : el.data('origin'),
ors = origin.split(" "),
oo = new Object();
if (ors.length>=1) {
oo.x = ors[0];
oo.y = ors[1];
} else {
oo.x = "50%";
oo.y = "50%";
}
radius = radius * factor;
var _ox = ((parseInt(oo.x,0)/100)-0.5) * el.width(),
_oy = ((parseInt(oo.y,0)/100)-0.5) * el.height(),
yo = (-1*radius) + _oy,
xo = 0 + _ox,
angobj= {a:0, ang : angle, element:el, unit:radius, xoffset:xo, yoffset:yo},
ang = parseInt(angle,0),
waveanim = new punchgs.TweenLite.fromTo(angobj,speed,{ a:(0+ang) },{ a:(360+ang),force3D:"auto",ease:punchgs.Linear.easeNone});
waveanim.eventCallback("onUpdate",function(angobj) {
var rad = angobj.a * (Math.PI / 180),
yy = angobj.yoffset+(angobj.unit * (1 - Math.sin(rad))),
xx = angobj.xoffset+Math.cos(rad) * angobj.unit;
punchgs.TweenLite.to(angobj.element,0.1,{force3D:"auto",x:xx, y:yy});
},[angobj]);
waveanim.eventCallback("onComplete",function(_) {
_._loop_timeline.restart();
},[_]);
_._loop_timeline.append(waveanim);
}
}
}
var killCaptionLoops = function(nextcaption) {
// SOME LOOPING ANIMATION ON INTERNAL ELEMENTS
nextcaption.closest('.rs-pendulum, .rs-slideloop, .rs-pulse, .rs-wave').each(function() {
var _ = this;
if (_._loop_timeline!=undefined) {
_._loop_timeline.pause();
_._loop_timeline = null;
}
});
}
})(jQuery); |
/*Solved by Alexander Black Jr. on 01/25/15. Have the function LetterChanges(str) take the str parameter being passed and modify it using the following algorithm.
Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a).
Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string. */
function LetterChanges(str) {
var alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
var vowel = ['a','e','i','o','u'];
var separate = str.split("");
var reconnect = [];;
for(var x = 0; x < separate.length; x++){
if(separate[x] == " "){
reconnect.push(' ');
}
for(var j = 0; j < alphabet.length; j++){
if(separate[x] == alphabet[j]){
reconnect.push(alphabet[j+1]);
for(var a = 0; a < reconnect.length; a++){
for(var b = 0; b < vowel.length; b++){
if(reconnect[a] == vowel[b]){
reconnect[a] = vowel[b].toUpperCase();
}//if
}//for
}//for
}//if
}
}str = reconnect.join('');
return str;
}
LetterChanges();
|
import FunctionTree from 'function-tree'
import {ContextProvider, DebuggerProvider} from 'function-tree/providers'
import axios from 'axios'
import store from './store'
export default FunctionTree([
DebuggerProvider({
colors: {
axios: '#7ea732'
}
}),
ContextProvider({
axios,
data: store.data,
view: store.view
})
])
|
var moment = require('moment');
var PATH_TO_DISPFORM = window.webAbsoluteUrl + "/Lists/Tasks/DispForm.aspx";
var TASK_LIST = "Tasks";
var COLORS = ['#466365', '#B49A67', '#93B7BE', '#E07A5F', '#849483', '#084C61', '#DB3A34'];
displayTasks();
function displayTasks() {
$('#calendar').fullCalendar('destroy');
$('#calendar').fullCalendar({
weekends: false,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
displayEventTime: false,
// open up the display form when a user clicks on an event
eventClick: function (calEvent, jsEvent, view) {
window.location = PATH_TO_DISPFORM + "?ID=" + calEvent.id;
},
editable: true,
timezone: "UTC",
droppable: true, // this allows things to be dropped onto the calendar
// update the end date when a user drags and drops an event
eventDrop: function (event, delta, revertFunc) {
updateTask(event.id, event.start, event.end);
},
// put the events on the calendar
events: function (start, end, timezone, callback) {
var startDate = start.format('YYYY-MM-DD');
var endDate = end.format('YYYY-MM-DD');
var restQuery = "/_api/Web/Lists/GetByTitle('" + TASK_LIST + "')/items?$select=ID,Title,\
Status,StartDate,DueDate,AssignedTo/Title&$expand=AssignedTo&\
$filter=((DueDate ge '" + startDate + "' and DueDate le '" + endDate + "')or(StartDate ge '" + startDate + "' and StartDate le '" + endDate + "'))";
$.ajax({
url: window.webAbsoluteUrl + restQuery,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=nometadata"
}
})
.done(function (data, textStatus, jqXHR) {
var personColors = {};
var colorNo = 0;
var events = data.value.map(function (task) {
var assignedTo = task.AssignedTo.map(function (person) {
return person.Title;
}).join(', ');
var color = personColors[assignedTo];
if (!color) {
color = COLORS[colorNo++];
personColors[assignedTo] = color;
}
if (colorNo >= COLORS.length) {
colorNo = 0;
}
return {
title: task.Title + " - " + assignedTo,
id: task.ID,
color: color, // specify the background color and border color can also create a class and use className paramter.
start: moment.utc(task.StartDate).add("1", "days"),
end: moment.utc(task.DueDate).add("1", "days") // add one day to end date so that calendar properly shows event ending on that day
};
});
callback(events);
});
}
});
}
function updateTask(id, startDate, dueDate) {
// subtract the previously added day to the date to store correct date
var sDate = moment.utc(startDate).add("-1", "days").format('YYYY-MM-DD') + "T" +
startDate.format("hh:mm") + ":00Z";
if (!dueDate) {
dueDate = startDate;
}
var dDate = moment.utc(dueDate).add("-1", "days").format('YYYY-MM-DD') + "T" +
dueDate.format("hh:mm") + ":00Z";
$.ajax({
url: window.webAbsoluteUrl + '/_api/contextinfo',
type: 'POST',
headers: {
'Accept': 'application/json;odata=nometadata'
}
})
.then(function (data, textStatus, jqXHR) {
return $.ajax({
url: window.webAbsoluteUrl +
"/_api/Web/Lists/getByTitle('" + TASK_LIST + "')/Items(" + id + ")",
type: 'POST',
data: JSON.stringify({
StartDate: sDate,
DueDate: dDate,
}),
headers: {
Accept: "application/json;odata=nometadata",
"Content-Type": "application/json;odata=nometadata",
"X-RequestDigest": data.FormDigestValue,
"IF-MATCH": "*",
"X-Http-Method": "PATCH"
}
});
})
.done(function (data, textStatus, jqXHR) {
alert("Update Successful");
})
.fail(function (jqXHR, textStatus, errorThrown) {
alert("Update Failed");
})
.always(function () {
displayTasks();
});
} |
describe("Array Extensions", function() {
it("should test for emptiness with is_empty and not_empty", function() {
expect([].is_empty()).toBeTruthy();
expect(['one', 'two', 'three'].is_empty()).toBeFalsy();
expect(['one', 'two', 'three'].not_empty()).toBeTruthy();
expect([].not_empty()).toBeFalsy();
});
it("should iterate over each element with each", function() {
var iteration_count = 0,
test_array_values = [],
test_array_indices = [];
['one', 'two', 'three'].each(function(value, index) {
iteration_count++;
test_array_values.push(value);
test_array_indices.push(index);
});
expect(test_array_values[0]).toEqual('one');
expect(test_array_values[1]).toEqual('two');
expect(test_array_values[2]).toEqual('three');
expect(test_array_indices[0]).toEqual(0);
expect(test_array_indices[1]).toEqual(1);
expect(test_array_indices[2]).toEqual(2);
expect(iteration_count).toEqual(3);
});
it("should test if an array contains an element", function() {
var array = ['one', 'two', 'three'],
string = 'hello',
object = {
name: 'some object'
},
number = 45,
date = new Date(),
test_array = [array, string, object, number, date];
expect(test_array.contains(array)).toBeTruthy();
expect(test_array.contains(string)).toBeTruthy();
expect(test_array.contains(object)).toBeTruthy();
expect(test_array.contains(number)).toBeTruthy();
expect(test_array.contains(date)).toBeTruthy();
expect(test_array.contains('not in there')).toBeFalsy();
});
}); |
import React, { Component, PropTypes } from 'react';
import classNames from 'classnames';
import { Scrollbars } from 'react-custom-scrollbars';
import MultiSelectorListItem from '../MultiSelectorListItem';
class MultiSelectorList extends Component {
render() {
const { options, isSelectorOpen, handleCheckItem, visibleItems } = this.props;
const elementSizePx = 39;
const borderSizePx = 1;
const scrollHeight = (options.length > visibleItems) ?
(visibleItems * elementSizePx - borderSizePx) :
(options.length * elementSizePx - borderSizePx);
return(
<div
className={classNames({
'multi-selector__list': true,
'multi-selector__list_active': isSelectorOpen && options.length != 0
})}
>
<Scrollbars style={{ height: scrollHeight }}>
{
options.map((option, index) =>
<MultiSelectorListItem key={index} option={option} handleCheckItem={handleCheckItem} />
)
}
</Scrollbars>
</div>
);
}
}
MultiSelectorList.propTypes = {
options: PropTypes.array.isRequired,
isSelectorOpen: PropTypes.bool,
scrollHeight: PropTypes.number,
handleCheckItem: PropTypes.func,
};
export default MultiSelectorList;
|
import Vue from 'vue';
import issuePlaceholderNote from '~/vue_shared/components/notes/placeholder_note.vue';
import createStore from '~/notes/stores';
import { userDataMock } from '../../../../javascripts/notes/mock_data';
describe('issue placeholder system note component', () => {
let store;
let vm;
beforeEach(() => {
const Component = Vue.extend(issuePlaceholderNote);
store = createStore();
store.dispatch('setUserData', userDataMock);
vm = new Component({
store,
propsData: { note: { body: 'Foo' } },
}).$mount();
});
afterEach(() => {
vm.$destroy();
});
describe('user information', () => {
it('should render user avatar with link', () => {
expect(vm.$el.querySelector('.user-avatar-link').getAttribute('href')).toEqual(
userDataMock.path,
);
expect(vm.$el.querySelector('.user-avatar-link img').getAttribute('src')).toEqual(
`${userDataMock.avatar_url}?width=40`,
);
});
});
describe('note content', () => {
it('should render note header information', () => {
expect(vm.$el.querySelector('.note-header-info a').getAttribute('href')).toEqual(
userDataMock.path,
);
expect(
vm.$el.querySelector('.note-header-info .note-headline-light').textContent.trim(),
).toEqual(`@${userDataMock.username}`);
});
it('should render note body', () => {
expect(vm.$el.querySelector('.note-text p').textContent.trim()).toEqual('Foo');
});
});
});
|
'use strict';
var concat = require('concat-stream');
var tap = require('tap');
var tape = require('../');
// Exploratory test to ascertain proper output when no t.comment() call
// is made.
tap.test('no comment', function (assert) {
assert.plan(1);
var verify = function (output) {
assert.deepEqual(output.toString('utf8').split('\n'), [
'TAP version 13',
'# no comment',
'',
'1..0',
'# tests 0',
'# pass 0',
'',
'# ok',
''
]);
};
var test = tape.createHarness();
test.createStream().pipe(concat(verify));
test('no comment', function (t) {
t.end();
});
});
// Exploratory test, can we call t.comment() passing nothing?
tap.test('missing argument', function (assert) {
assert.plan(1);
var test = tape.createHarness();
test.createStream();
test('missing argument', function (t) {
try {
t.comment();
t.end();
} catch (err) {
assert.equal(err.constructor, TypeError);
} finally {
assert.end();
}
});
});
// Exploratory test, can we call t.comment() passing nothing?
tap.test('null argument', function (assert) {
assert.plan(1);
var test = tape.createHarness();
test.createStream();
test('null argument', function (t) {
try {
t.comment(null);
t.end();
} catch (err) {
assert.equal(err.constructor, TypeError);
} finally {
assert.end();
}
});
});
// Exploratory test, how is whitespace treated?
tap.test('whitespace', function (assert) {
assert.plan(1);
var verify = function (output) {
assert.equal(output.toString('utf8'), [
'TAP version 13',
'# whitespace',
'# ',
'# a',
'# a',
'# a',
'',
'1..0',
'# tests 0',
'# pass 0',
'',
'# ok',
''
].join('\n'));
};
var test = tape.createHarness();
test.createStream().pipe(concat(verify));
test('whitespace', function (t) {
t.comment(' ');
t.comment(' a');
t.comment('a ');
t.comment(' a ');
t.end();
});
});
// Exploratory test, how about passing types other than strings?
tap.test('non-string types', function (assert) {
assert.plan(1);
var verify = function (output) {
assert.equal(output.toString('utf8'), [
'TAP version 13',
'# non-string types',
'# true',
'# false',
'# 42',
'# 6.66',
'# [object Object]',
'# [object Object]',
'# [object Object]',
'# function ConstructorFunction() {}',
'',
'1..0',
'# tests 0',
'# pass 0',
'',
'# ok',
''
].join('\n'));
};
var test = tape.createHarness();
test.createStream().pipe(concat(verify));
test('non-string types', function (t) {
t.comment(true);
t.comment(false);
t.comment(42);
t.comment(6.66);
t.comment({});
t.comment({ answer: 42 });
function ConstructorFunction() {}
t.comment(new ConstructorFunction());
t.comment(ConstructorFunction);
t.end();
});
});
tap.test('multiline string', function (assert) {
assert.plan(1);
var verify = function (output) {
assert.equal(output.toString('utf8'), [
'TAP version 13',
'# multiline strings',
'# a',
'# b',
'# c',
'# d',
'',
'1..0',
'# tests 0',
'# pass 0',
'',
'# ok',
''
].join('\n'));
};
var test = tape.createHarness();
test.createStream().pipe(concat(verify));
test('multiline strings', function (t) {
t.comment([
'a',
'b'
].join('\n'));
t.comment([
'c',
'd'
].join('\r\n'));
t.end();
});
});
tap.test('comment with createStream/objectMode', function (assert) {
assert.plan(1);
var test = tape.createHarness();
test.createStream({ objectMode: true }).on('data', function (row) {
if (typeof row === 'string') {
assert.equal(row, 'comment message');
}
});
test('t.comment', function (t) {
t.comment('comment message');
t.end();
});
});
|
var searchData=
[
['z',['z',['../struct_leap_1_1_vector.html#aa44971ce01ce035e78ea557bc1e983a4',1,'Leap::Vector']]],
['zbasis',['zBasis',['../struct_leap_1_1_matrix.html#a62c45d9b2370027de27781fadcfc13d8',1,'Leap::Matrix']]]
];
|
import {Member, errors} from 'src/server/services/dataService'
import {LGNotAuthorizedError, LGForbiddenError} from 'src/server/util/error'
export default function assertUserIsMember(userId) {
return Member.get(userId)
.then(member => {
if (!member.chapterId) {
throw new LGForbiddenError('Members must be assigned to a chapter')
}
return member
})
.catch(errors.DocumentNotFound, () => {
throw new LGNotAuthorizedError('Must be a member of a chapter')
})
}
|
System.import('lib/edl'); |
import { __decorate, __metadata } from 'tslib';
import { ɵɵdefineInjectable, ɵɵinject, Injectable } from '@angular/core';
import { Angulartics2 } from 'angulartics2';
let Angulartics2Piwik = class Angulartics2Piwik {
constructor(angulartics2) {
this.angulartics2 = angulartics2;
if (typeof (_paq) === 'undefined') {
console.warn('Piwik not found');
}
this.angulartics2.setUsername
.subscribe((x) => this.setUsername(x));
this.angulartics2.setUserProperties
.subscribe((x) => this.setUserProperties(x));
}
startTracking() {
this.angulartics2.pageTrack
.pipe(this.angulartics2.filterDeveloperMode())
.subscribe((x) => this.pageTrack(x.path));
this.angulartics2.eventTrack
.pipe(this.angulartics2.filterDeveloperMode())
.subscribe((x) => this.eventTrack(x.action, x.properties));
}
pageTrack(path, location) {
try {
if (!window.location.origin) {
window.location.origin = window.location.protocol + '//'
+ window.location.hostname
+ (window.location.port ? ':' + window.location.port : '');
}
_paq.push(['setDocumentTitle', window.document.title]);
_paq.push(['setCustomUrl', window.location.origin + path]);
_paq.push(['trackPageView']);
}
catch (e) {
if (!(e instanceof ReferenceError)) {
throw e;
}
}
}
/**
* Track a basic event in Piwik, or send an ecommerce event.
*
* @param action A string corresponding to the type of event that needs to be tracked.
* @param properties The properties that need to be logged with the event.
*/
eventTrack(action, properties = {}) {
let params = [];
switch (action) {
/**
* @description Sets the current page view as a product or category page view. When you call
* setEcommerceView it must be followed by a call to trackPageView to record the product or
* category page view.
*
* @link https://piwik.org/docs/ecommerce-analytics/#tracking-product-page-views-category-page-views-optional
* @link https://developer.piwik.org/api-reference/tracking-javascript#ecommerce
*
* @property productSKU (required) SKU: Product unique identifier
* @property productName (optional) Product name
* @property categoryName (optional) Product category, or array of up to 5 categories
* @property price (optional) Product Price as displayed on the page
*/
case 'setEcommerceView':
params = ['setEcommerceView',
properties.productSKU,
properties.productName,
properties.categoryName,
properties.price,
];
break;
/**
* @description Adds a product into the ecommerce order. Must be called for each product in
* the order.
*
* @link https://piwik.org/docs/ecommerce-analytics/#tracking-ecommerce-orders-items-purchased-required
* @link https://developer.piwik.org/api-reference/tracking-javascript#ecommerce
*
* @property productSKU (required) SKU: Product unique identifier
* @property productName (optional) Product name
* @property categoryName (optional) Product category, or array of up to 5 categories
* @property price (recommended) Product price
* @property quantity (optional, default to 1) Product quantity
*/
case 'addEcommerceItem':
params = [
'addEcommerceItem',
properties.productSKU,
properties.productName,
properties.productCategory,
properties.price,
properties.quantity,
];
break;
/**
* @description Tracks a shopping cart. Call this javascript function every time a user is
* adding, updating or deleting a product from the cart.
*
* @link https://piwik.org/docs/ecommerce-analytics/#tracking-add-to-cart-items-added-to-the-cart-optional
* @link https://developer.piwik.org/api-reference/tracking-javascript#ecommerce
*
* @property grandTotal (required) Cart amount
*/
case 'trackEcommerceCartUpdate':
params = ['trackEcommerceCartUpdate', properties.grandTotal];
break;
/**
* @description Tracks an Ecommerce order, including any ecommerce item previously added to
* the order. orderId and grandTotal (ie. revenue) are required parameters.
*
* @link https://piwik.org/docs/ecommerce-analytics/#tracking-ecommerce-orders-items-purchased-required
* @link https://developer.piwik.org/api-reference/tracking-javascript#ecommerce
*
* @property orderId (required) Unique Order ID
* @property grandTotal (required) Order Revenue grand total (includes tax, shipping, and subtracted discount)
* @property subTotal (optional) Order sub total (excludes shipping)
* @property tax (optional) Tax amount
* @property shipping (optional) Shipping amount
* @property discount (optional) Discount offered (set to false for unspecified parameter)
*/
case 'trackEcommerceOrder':
params = [
'trackEcommerceOrder',
properties.orderId,
properties.grandTotal,
properties.subTotal,
properties.tax,
properties.shipping,
properties.discount,
];
break;
/**
* @description Tracks an Ecommerce goal
*
* @link https://piwik.org/docs/tracking-goals-web-analytics/
* @link https://developer.piwik.org/guides/tracking-javascript-guide#manually-trigger-goal-conversions
*
* @property goalId (required) Unique Goal ID
* @property value (optional) passed to goal tracking
*/
case 'trackGoal':
params = [
'trackGoal',
properties.goalId,
properties.value,
];
break;
/**
* @description Tracks a site search
*
* @link https://piwik.org/docs/site-search/
* @link https://developer.piwik.org/guides/tracking-javascript-guide#internal-search-tracking
*
* @property keyword (required) Keyword searched for
* @property category (optional) Search category
* @property searchCount (optional) Number of results
*/
case 'trackSiteSearch':
params = [
'trackSiteSearch',
properties.keyword,
properties.category,
properties.searchCount,
];
break;
/**
* @description Logs an event with an event category (Videos, Music, Games...), an event
* action (Play, Pause, Duration, Add Playlist, Downloaded, Clicked...), and an optional
* event name and optional numeric value.
*
* @link https://piwik.org/docs/event-tracking/
* @link https://developer.piwik.org/api-reference/tracking-javascript#using-the-tracker-object
*
* @property category
* @property action
* @property name (optional, recommended)
* @property value (optional)
*/
default:
// PAQ requires that eventValue be an integer, see: http://piwik.org/docs/event-tracking
if (properties.value) {
const parsed = parseInt(properties.value, 10);
properties.value = isNaN(parsed) ? 0 : parsed;
}
params = [
'trackEvent',
properties.category,
action,
properties.name || properties.label,
properties.value,
];
}
try {
_paq.push(params);
}
catch (e) {
if (!(e instanceof ReferenceError)) {
throw e;
}
}
}
setUsername(userId) {
try {
_paq.push(['setUserId', userId]);
}
catch (e) {
if (!(e instanceof ReferenceError)) {
throw e;
}
}
}
/**
* Sets custom dimensions if at least one property has the key "dimension<n>",
* e.g. dimension10. If there are custom dimensions, any other property is ignored.
*
* If there are no custom dimensions in the given properties object, the properties
* object is saved as a custom variable.
*
* If in doubt, prefer custom dimensions.
* @link https://piwik.org/docs/custom-variables/
*/
setUserProperties(properties) {
const dimensions = this.setCustomDimensions(properties);
try {
if (dimensions.length === 0) {
_paq.push(['setCustomVariable', properties.index, properties.name, properties.value, properties.scope]);
}
}
catch (e) {
if (!(e instanceof ReferenceError)) {
throw e;
}
}
}
setCustomDimensions(properties) {
const dimensionRegex = /dimension[1-9]\d*/;
const dimensions = Object.keys(properties)
.filter(key => dimensionRegex.exec(key));
dimensions.forEach(dimension => {
const number = Number(dimension.substr(9));
_paq.push(['setCustomDimension', number, properties[dimension]]);
});
return dimensions;
}
};
Angulartics2Piwik.ngInjectableDef = ɵɵdefineInjectable({ factory: function Angulartics2Piwik_Factory() { return new Angulartics2Piwik(ɵɵinject(Angulartics2)); }, token: Angulartics2Piwik, providedIn: "root" });
Angulartics2Piwik = __decorate([
Injectable({ providedIn: 'root' }),
__metadata("design:paramtypes", [Angulartics2])
], Angulartics2Piwik);
export { Angulartics2Piwik };
//# sourceMappingURL=angulartics2-piwik.js.map
|
/**
* @license Highmaps JS v8.0.0 (2019-12-10)
* @module highcharts/modules/heatmap
* @requires highcharts
*
* (c) 2009-2019 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
import '../../parts-map/ColorAxis.js';
import '../../parts-map/ColorMapSeriesMixin.js';
import '../../parts-map/HeatmapSeries.js';
|
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var globals_1 = require("../../globals");
var graph_util = require("../graph_util");
var op_1 = require("./op");
var LinearCombination = (function (_super) {
__extends(LinearCombination, _super);
function LinearCombination(x1Tensor, x2Tensor, c1Tensor, c2Tensor, outTensor) {
var _this = _super.call(this) || this;
_this.x1Tensor = x1Tensor;
_this.x2Tensor = x2Tensor;
_this.c1Tensor = c1Tensor;
_this.c2Tensor = c2Tensor;
_this.outTensor = outTensor;
return _this;
}
LinearCombination.prototype.feedForward = function (math, inferenceArrays) {
var _this = this;
var x1 = inferenceArrays.get(this.x1Tensor);
var x2 = inferenceArrays.get(this.x2Tensor);
var c1 = inferenceArrays.get(this.c1Tensor).asScalar();
var c2 = inferenceArrays.get(this.c2Tensor).asScalar();
globals_1.tidy(function () {
inferenceArrays.set(_this.outTensor, globals_1.keep(math.scaledArrayAdd(c1, x1, c2, x2)));
});
};
LinearCombination.prototype.backProp = function (math, inferenceArrays, gradientArrays) {
var _this = this;
var x1 = inferenceArrays.get(this.x1Tensor);
var x2 = inferenceArrays.get(this.x2Tensor);
var c1 = inferenceArrays.get(this.c1Tensor);
var c2 = inferenceArrays.get(this.c2Tensor);
var dy = gradientArrays.get(this.outTensor);
globals_1.tidy(function () {
if (graph_util.shouldBackProp(_this.x1Tensor)) {
gradientArrays.add(_this.x1Tensor, math.scalarTimesArray(c1, dy));
}
if (graph_util.shouldBackProp(_this.x2Tensor)) {
gradientArrays.add(_this.x2Tensor, math.scalarTimesArray(c2, dy));
}
if (graph_util.shouldBackProp(_this.c1Tensor)) {
var dotProduct1 = math.elementWiseMul(x1, dy);
gradientArrays.add(_this.c1Tensor, math.sum(dotProduct1));
}
if (graph_util.shouldBackProp(_this.c2Tensor)) {
var dotProduct2 = math.elementWiseMul(x2, dy);
gradientArrays.add(_this.c2Tensor, math.sum(dotProduct2));
}
});
};
return LinearCombination;
}(op_1.Operation));
exports.LinearCombination = LinearCombination;
|
module.exports = createTest;
var assert = require('assert');
function createTest(linter, fixturesPath) {
var fixturePath = fixturesPath + 'validate-attribute-separator.pug';
describe('validateAttributeSeparator', function () {
describe('space', function () {
before(function () {
linter.configure({validateAttributeSeparator: ' '});
});
it('should report invalid attribute separator', function () {
assert.equal(linter.checkString('input(type=\'text\' name=\'name\' value=\'value\')').length, 2);
});
it('should not report valid attribute separator', function () {
assert.equal(linter.checkString('input(type=\'text\' name=\'name\' value=\'value\')').length, 0);
});
it('should report multiple errors found in file', function () {
var result = linter.checkFile(fixturePath);
assert.equal(result.length, 31);
assert.equal(result[0].code, 'PUG:LINT_VALIDATEATTRIBUTESEPARATOR');
assert.equal(result[0].line, 3);
assert.equal(result[0].column, 18);
assert.equal(result[1].line, 3);
assert.equal(result[1].column, 30);
});
it('should not raise error on attribute having asterisk mark in name', function () {
assert.doesNotThrow(function () {
linter.checkString('input(*ngIf=\'editing\' type=\'text\' name=\'name\' value=\'value\')');
}, /Invalid regular expression/);
});
describe('with ellipsis mark in name', () => {
it('reports invalid attribute separator', () => {
const result = linter.checkString('input(type=\'text\' ...props name=\'name\')');
assert.equal(result.length, 1);
assert.equal(result[0].code, 'PUG:LINT_VALIDATEATTRIBUTESEPARATOR');
assert.equal(result[0].line, 1);
assert.equal(result[0].column, 18);
});
it('does not report with valid separator', function () {
const result = linter.checkString('input(...props type=\'text\' ...props name=\'name\' value=\'value\' ...props)');
assert.equal(result.length, 0);
});
});
});
describe('comma', function () {
before(function () {
linter.configure({validateAttributeSeparator: ','});
});
it('should report invalid attribute separator', function () {
assert.equal(linter.checkString('input(type=\'text\' name=\'name\' value=\'value\')').length, 2);
});
it('should not report valid attribute separator', function () {
assert.equal(linter.checkString('input(type=\'text\',name=\'name\',value=\'value\')').length, 0);
});
it('should report multiple errors found in file', function () {
var result = linter.checkFile(fixturePath);
assert.equal(result.length, 32);
assert.equal(result[0].code, 'PUG:LINT_VALIDATEATTRIBUTESEPARATOR');
assert.equal(result[0].line, 2);
assert.equal(result[0].column, 18);
});
});
describe('comma-space', function () {
before(function () {
linter.configure({validateAttributeSeparator: ', '});
});
it('should report invalid attribute separator', function () {
assert.equal(linter.checkString('input(type=\'text\' name=\'name\' value=\'value\')').length, 2);
});
it('should not report valid attribute separator', function () {
assert.equal(linter.checkString('input(type=\'text\', name=\'name\', value=\'value\')').length, 0);
});
it('should report multiple errors found in file', function () {
var result = linter.checkFile(fixturePath);
assert.equal(result.length, 31);
assert.equal(result[0].code, 'PUG:LINT_VALIDATEATTRIBUTESEPARATOR');
assert.equal(result[0].line, 2);
assert.equal(result[0].column, 18);
});
});
describe('space-comma', function () {
before(function () {
linter.configure({validateAttributeSeparator: ' ,'});
});
it('should report invalid attribute separator', function () {
assert.equal(linter.checkString('input(type=\'text\', name=\'name\', value=\'value\')').length, 2);
});
it('should not report valid attribute separator', function () {
assert.equal(linter.checkString('input(type=\'text\' ,name=\'name\' ,value=\'value\')').length, 0);
});
it('should report multiple errors found in file', function () {
var result = linter.checkFile(fixturePath);
assert.equal(result.length, 32);
assert.equal(result[0].code, 'PUG:LINT_VALIDATEATTRIBUTESEPARATOR');
assert.equal(result[0].line, 2);
assert.equal(result[0].column, 18);
});
});
describe('space-comma-space', function () {
before(function () {
linter.configure({validateAttributeSeparator: ' , '});
});
it('should report invalid attribute separator', function () {
assert.equal(linter.checkString('input(type=\'text\' name=\'name\' value=\'value\')').length, 2);
});
it('should not report valid attribute separator', function () {
assert.equal(linter.checkString('input(type=\'text\' , name=\'name\' , value=\'value\')').length, 0);
});
it('should report multiple errors found in file', function () {
var result = linter.checkFile(fixturePath);
assert.equal(result.length, 33);
assert.equal(result[0].code, 'PUG:LINT_VALIDATEATTRIBUTESEPARATOR');
assert.equal(result[0].line, 2);
assert.equal(result[0].column, 18);
});
});
describe('indentation - spaces', function () {
before(function () {
linter.configure({
validateAttributeSeparator: {
separator: ' ',
multiLineSeparator: '\n '
}
});
});
it('should report invalid attribute separator', function () {
assert.equal(linter.checkString('input(type=\'text\', name=\'name\', value=\'value\')').length, 2);
});
it('should not report valid attribute separator', function () {
assert.equal(linter.checkString('input(type=\'text\' name=\'name\' value=\'value\')').length, 0);
});
it('should report multiple errors found in file', function () {
var result = linter.checkFile(fixturePath);
assert.equal(result.length, 27);
assert.equal(result[0].code, 'PUG:LINT_VALIDATEATTRIBUTESEPARATOR');
assert.equal(result[25].line, 42);
assert.equal(result[25].column, 1);
assert.equal(result[26].line, 44);
assert.equal(result[26].column, 1);
});
});
describe('indentation, comma-spaces', function () {
before(function () {
linter.configure({
validateAttributeSeparator: {
separator: ', ',
multiLineSeparator: ',\n '
}
});
});
it('should not report valid attribute separator', function () {
var result = linter.checkString('div(foo="1",\n bar="{hello:\' world\',\\n 666: true}",\n batz="2")');
assert.equal(result.length, 0);
result = linter.checkFile(fixturesPath + 'validate-attribute-separator--multiline.pug');
assert.equal(result.length, 0);
});
});
});
}
|
import $ from 'jquery';
import Qti from './qti';
import { AssessmentFormats } from '../assessment';
export default class Parser{
static parse(assessmentId, assessmentXml, xml){
var assessment = {
id : assessmentXml.attr('ident'),
title : assessmentXml.attr('title'),
standard : AssessmentFormats.Qti1,
assessmentId : assessmentId,
};
assessment.objectives = xml.find('assessment > objectives matref').map((index, item) => {
return $(item).attr('linkrefid');
});
assessment.sections = this.parseSections(xml);
return assessment;
}
static parseSections(xml){
var fromXml = (xml) => {
xml = $(xml);
return {
id : xml.attr('ident'),
standard : AssessmentFormats.Qti1,
xml : xml,
outcome : this.parseOutcome(xml),
items : this.parseItems(xml)
};
};
// Not all QTI files have sections. If we don't find one we build a default one to contain the items from the QTI file.
var buildDefault = (xml) => {
return {
id : 'default',
standard : AssessmentFormats.Qti1,
xml : xml,
items : this.parseItems(xml)
};
};
return this.listFromXml(xml, 'section', fromXml, buildDefault);
}
static parseOutcome(xml){
xml = $(xml);
if(xml.attr("ident") == "root_section"){
return "root section";
}
var item = xml.find("item")[0];
var fields = $(item).find("qtimetadatafield");
var outcome = {
shortOutcome: "",
longOutcome: "",
outcomeGuid: "",
};
for (var i = fields.length - 1; i >= 0; i--) {
if($(fields[i]).find("fieldlabel").text() == "outcome_guid"){
outcome.outcomeGuid = $(fields[i]).find("fieldentry").text();
}
if($(fields[i]).find("fieldlabel").text() == "outcome_long_title"){
outcome.longOutcome = $(fields[i]).find("fieldentry").text();
}
if($(fields[i]).find("fieldlabel").text() == "outcome_short_title"){
outcome.shortOutcome = $(fields[i]).find("fieldentry").text();
}
};
return outcome;
}
static parseItems(xml){
var fromXml = (xml) => {
xml = $(xml);
var objectives = xml.find('objectives matref').map((index, item) => {
return $(item).attr('linkrefid');
});
var outcomes = {
shortOutcome: "",
longOutcome: ""
};
xml.find("fieldentry").map((index, outcome)=>{
if(index == 2){
outcomes.shortOutcome = outcome.textContent;
}
if(index == 3){
outcomes.longOutcome = outcome.textContent;
}
});
var item = {
id : xml.attr('ident'),
title : xml.attr('title'),
objectives : objectives,
outcomes : outcomes,
xml : xml,
material : this.material(xml),
answers : this.parseAnswers(xml),
correct : this.parseCorrect(xml),
timeSpent : 0
};
$.each(xml.find('itemmetadata > qtimetadata > qtimetadatafield'), function(i, x){
item[$(x).find('fieldlabel').text()] = $(x).find('fieldentry').text();
});
if(xml.find('itemmetadata > qmd_itemtype').text() === 'Multiple Choice'){
item.question_type = 'multiple_choice_question';
}
var response_grp = xml.find('response_grp');
if(response_grp){
if(response_grp.attr('rcardinality') === 'Multiple'){
item.question_type = 'drag_and_drop';
}
}
return item;
};
// Only grab the items at the current level of the tree
return this.listFromXml(xml, '> item', fromXml);
}
static parseCorrect(xml){
var respconditions = xml.find("respcondition");
var correctAnswers = [];
for (var i=0; i<respconditions.length; i++){
var condition = $(respconditions[i]);
if(condition.find('setvar').text() != '0'){
var answer = {
id: condition.find('conditionvar > varequal').text(),
value: condition.find('setvar').text()
};
if(answer.id == ""){
answer.id = condition.find('conditionvar > and > varequal').map((index, condition) => {
condition = $(condition);
return condition.text();
});
answer.id = answer.id.toArray();
}
correctAnswers.push(answer);
}
}
return correctAnswers;
}
static parseAnswers(xml){
var fromXml = (xml) => {
xml = $(xml);
var matchMaterial = xml.parent().parent().find('material')[0].textContent.trim();
var answer = {
id : xml.attr('ident'),
material : this.buildMaterial(xml.find('material').children()),
matchMaterial : matchMaterial,
xml : xml,
feedback : this.parseFeedback(xml)
};
return answer;
};
return this.listFromXml(xml, 'response_lid > render_choice > response_label', fromXml);
}
// Process nodes based on QTI spec here:
// http://www.imsglobal.org/question/qtiv1p2/imsqti_litev1p2.html#1404782
static buildMaterial(nodes){
var result = '';
$.each(nodes, function(i, item){
var parsedItem = $(item);
switch(item.nodeName.toLowerCase()){
case 'mattext':
// TODO both mattext and matemtext have a number of attributes that can be used to display the contents
result += parsedItem.text();
break;
case 'matemtext':
// TODO figure out how to 'emphasize' text
result += parsedItem.text();
break;
case 'matimage':
result += '<img src="' + parsedItem.attr('uri') + '"';
if(parsedItem.attr('label')) { result += 'alt="' + parsedItem.attr('label') + '"'; }
if(parsedItem.attr('width')) { result += 'width="' + parsedItem.attr('width') + '"'; }
if(parsedItem.attr('height')){ result += 'height="' + parsedItem.attr('height') + '"'; }
result += ' />';
break;
case 'matref':
var linkrefid = $(item).attr('linkrefid');
// TODO figure out how to look up material based on linkrefid
break;
}
});
return result;
}
static listFromXml(xml, selector, fromXml, buildDefault){
xml = $(xml);
var list = xml.find(selector).map((i, x) => {
return fromXml(x);
}).toArray(); // Make sure we have a normal javascript array not a jquery array.
if(list.length <= 0 && buildDefault){
list = [buildDefault(xml)];
}
return list;
}
// //////////////////////////////////////////////////////////
// Item related functionality
//
static buildResponseGroup(node){
// TODO this is an incomplete attempt to build a drag and drop
// question type based on the drag_and_drop.xml in seeds/qti
return this.buildMaterial($(node).find('material').children());
}
static material(xml){
var material = xml.find('presentation > material').children();
if(material.length > 0){
return this.buildMaterial(material);
}
var flow = xml.find('presentation > flow');
if(flow.length > 0){
return this.reduceFlow(flow);
}
}
static reduceFlow(flow){
var result = '';
$.each(flow.children(), function(i, node){
if(node.nodeName.toLowerCase() === 'flow'){
result += Qti.buildMaterial($(node).find('material').children());
} else if(node.nodeName.toLowerCase() === 'response_grp'){
result += Qti.buildResponseGroup(node);
}
});
return result;
}
static parseFeedback(xml){
return {
// See code below and drupal.xml for an example
};
}
}
// var score = 0; // TODO we should get var names and types from the QTI. For now we just use the default 'score'
// var feedbacks = [];
// var correct = false;
// var respconditions = xml.find('respcondition');
// for (var i =0; i<respconditions.length; i++){
// var condition = respconditions[i];
// condition = $(condition);
// var conditionMet = false;
// if(condition.find('conditionvar > varequal').length){
// var varequal = condition.find('conditionvar > varequal');
// if(varequal.text() === selectedAnswerId){
// conditionMet = true;
// }
// } else if(condition.find('conditionvar > unanswered').length){
// if(selectedAnswerId === null){
// conditionMet = true;
// }
// } else if(condition.find('conditionvar > not').length){
// if(condition.find('conditionvar > not > varequal').length){
// if(selectedAnswerId !== condition.find('conditionvar > not > varequal').text()){
// conditionMet = true;
// }
// } else if(condition.find('conditionvar > not > unanswered').length) {
// if(selectedAnswerId !== null){
// conditionMet = true;
// }
// }
// }
// if(conditionMet){
// var setvar = condition.find('setvar');
// if(setvar.length > 0){
// var setvarVal = parseFloat(setvar.text(), 10);
// if(setvarVal > 0){
// correct = true;
// var action = setvar.attr('action');
// if(action === 'Add'){
// score += setvarVal;
// } else if(action === 'Set'){
// score = setvarVal;
// }
// }
// }
// var feedbackId = condition.find('displayfeedback').attr('linkrefid');
// if(feedbackId){
// var feedback = xml.find('itemfeedback[ident="' + feedbackId + '"]');
// if(feedback && feedback.attr('view') && feedback.attr('view').length === 0 ||
// feedback.attr('view') === 'All' ||
// feedback.attr('view') === 'Candidate' ){ //All, Administrator, AdminAuthority, Assessor, Author, Candidate, InvigilatorProctor, Psychometrician, Scorer, Tutor
// var result = Qti.buildMaterial(feedback.find('material').children());
// if(feedbacks.indexOf(result) === -1){
// feedbacks.push(result);
// }
// }
// }
// }
// if(correct){
// return {
// feedbacks: feedbacks,
// score: score,
// correct: correct
// };
// }
// //if(condition.attr('continue') === 'No'){ return false; }
// }
|
// @flow
import { combineReducers } from 'redux'
import type { Store } from 'redux'
import location from './location'
import counter from './modules/counter'
import githubRepos from './modules/githubRepos'
import { storeHelper } from './createStore'
type AsyncReducers = { [key: string]: any }
type AsyncReducer = { key: string, reducer: any }
export type Action = { type: string, payload?: any }
export const makeRootReducer = (asyncReducers: AsyncReducers = {}) => {
return combineReducers({
location,
counter,
githubRepos,
...asyncReducers
})
}
export const injectReducer = (store: Store<*, *>, { key, reducer }: AsyncReducer) => {
if (Object.hasOwnProperty.call(storeHelper.asyncReducers, key)) return
storeHelper.asyncReducers[key] = reducer
store.replaceReducer(makeRootReducer(storeHelper.asyncReducers))
}
export default makeRootReducer
|
// I would like to lazy load json2, but I'm worried we're trying to access
// JSON very early in the code
//= require <json2>
var requiresCookies = (function () {
var ua = navigator.userAgent.toLowerCase(),
id = null;
if (/mozilla/.test(ua) && !/compatible/.test(ua)) {
id = new Date().getTime();
document.cookie = '__cprobe=' + id + ';path=/';
if (document.cookie.indexOf(id,0) === -1) {
return true;
}
}
return false;
})();
// Firefox with Cookies disabled triggers a security error when we probe window.sessionStorage
// currently we're just disabling all the session features if that's the case.
var sessionStorage = window.sessionStorage;
var localStorage = window.localStorage;
if (!requiresCookies && window.sessionStorage) {
sessionStorage = window.sessionStorage;
}
if (!sessionStorage) {
sessionStorage = (function () {
var data = window.top.name ? JSON.parse(window.top.name) : {};
return {
clear: function () {
data = {};
window.top.name = '';
},
getItem: function (key) {
return data[key] || null;
},
removeItem: function (key) {
delete data[key];
window.top.name = JSON.stringify(data);
},
setItem: function (key, value) {
data[key] = value;
window.top.name = JSON.stringify(data);
}
};
})();
}
if ((!requiresCookies && !window.localStorage) || requiresCookies) {
// dirty, but will do for our purposes
localStorage = sessionStorage;
} else if (!requiresCookies) {
localStorage = window.localStorage;
} else if (!localStorage) {
localStorage = sessionStorage;
} |
export default {
name: 'test label text',
color: 'c3c3c3',
};
|
///////////////////////////////////////////////////////////////////////////
// Copyright © Esri. 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.
///////////////////////////////////////////////////////////////////////////
define(['dojo/_base/declare',
'esri/geometry/Extent'
],
function (declare, Extent) {
var instance = null, clazz;
clazz = declare(null, {
map: null,
setMap: function(map){
this.map = map;
},
handleMapChangeEvent: function(evtInfo){
switch(evtInfo.evtName){
case 'sync/map/extent-change':
return this._onExtentChange(evtInfo.evt);
default:
console.error('Unknown event name:', evtInfo.evtName);
}
},
_onExtentChange: function(extent){
this.map.setExtent(new Extent(extent));
}
});
clazz.getInstance = function() {
if(instance === null) {
instance = new clazz();
}
return instance;
};
return clazz;
}); |
define({
"_widgetLabel": "Добавить данные",
"noOptionsConfigured": "Отсутствуют настроенные опции",
"tabs": {
"search": "Поиск",
"url": "URL-адрес",
"file": "Файл"
},
"search": {
"featureLayerTitlePattern": "{serviceName} - {layerName}",
"layerInaccessible": "Слой не доступен.",
"loadError": "AddData, не удалось загрузить:",
"searchBox": {
"search": "Поиск",
"placeholder": "Поиск..."
},
"bboxOption": {
"bbox": "В карте"
},
"scopeOptions": {
"anonymousContent": "Ресурсы",
"myContent": "Мои ресурсы",
"myOrganization": "Моя организация",
"curated": "Куратор",
"ArcGISOnline": "ArcGIS Online"
},
"sortOptions": {
"prompt": "Сортировать по:",
"relevance": "Актуальность",
"title": "Заголовок",
"owner": "Владелец",
"rating": "Рейтинг",
"views": "Просмотры",
"date": "Дата",
"switchOrder": "Переключиться"
},
"typeOptions": {
"prompt": "Тип",
"mapService": "Картографический сервис",
"featureService": "Сервис пространственных объектов",
"imageService": "Сервис изображений",
"vectorTileService": "Сервис векторных листов",
"kml": "KML",
"wms": "WMS"
},
"resultsPane": {
"noMatch": "Результаты не найдены."
},
"paging": {
"first": "<<",
"firstTip": "Первый",
"previous": "<",
"previousTip": "Предыдущий",
"next": ">",
"nextTip": "Следующий",
"pagePattern": "{page}"
},
"resultCount": {
"countPattern": "{count} {type}",
"itemSingular": "Элемент",
"itemPlural": "Элементы"
},
"item": {
"actions": {
"add": "Добавить",
"close": "Закрыть",
"remove": "Удалить",
"details": "Детали",
"done": "Готово",
"editName": "Редактировать имя"
},
"messages": {
"adding": "Добавление...",
"removing": "Удаление...",
"added": "Добавлено",
"addFailed": "Не удалось добавить",
"unsupported": "Не поддерживается"
},
"typeByOwnerPattern": "{type} принадлежит {owner}",
"dateFormat": "MMMM d, yyyy",
"datePattern": "{date}",
"ratingsCommentsViewsPattern": "{ratings} {ratingsIcon} {comments} {commentsIcon} {views} {viewsIcon}",
"ratingsCommentsViewsLabels": {
"ratings": "ratings\", \"comments\": \"comments\", \"views\": \"views"
},
"types": {
"Map Service": "Картографический сервис",
"Feature Service": "Сервис пространственных объектов",
"Image Service": "Сервис изображений",
"Vector Tile Service": "Сервис векторных листов",
"WMS": "WMS",
"KML": "KML"
}
}
},
"addFromUrl": {
"type": "Тип",
"url": "URL-адрес",
"types": {
"ArcGIS": "Веб-сервис ArcGIS Server",
"WMS": "Веб-сервис WMS OGC",
"WMTS": "Веб-сервис WMTS OGC",
"WFS": "Веб-сервис WFS OGC",
"KML": "Файл KML",
"GeoRSS": "Файл GeoRSS",
"CSV": "Файл CSV"
},
"samplesHint": "URL образца"
},
"addFromFile": {
"intro": "Вы можете перетащить или просмотреть один из следующих типов:",
"types": {
"Shapefile": "Шейп-файл (.zip, ZIP-архив, содержащий все файлы шейп-файла)",
"CSV": "Файл CSV (.csv, с адресами или координатами широты и долготы (с разделителями: запятой, точкой с запятой или табуляцией))",
"KML": "Файл KML (.kml)",
"GPX": "Файл GPX (.gpx, обменный формат GPS)",
"GeoJSON": "Файл GeoJSON (.geo.json или .geojson)"
},
"generalizeOn": "Генерализовать объекты для веб-отображения",
"dropOrBrowse": "Перетаскивание или просмотр",
"browse": "Просмотр",
"invalidType": "Этот тип файлов не поддерживается.",
"addingPattern": "{filename}: добавление...",
"addFailedPattern": "{filename}: добавление не удалось",
"featureCountPattern": "{filename}: {count} объектов",
"invalidTypePattern": "{filename}: этот тип не поддерживается",
"maxFeaturesAllowedPattern": "Допустимо использовать не более {count} объектов",
"layerNamePattern": "{filename} – {name}",
"generalIssue": "Имеется проблема.",
"kmlProjectionMismatch": "Пространственная привязка карты и слоя KML не совпадают, конвертация на клиенте не может быть выполнена."
},
"layerList": {
"caption": "Слои",
"noLayersAdded": "Слои не были добавлены.",
"removeLayer": "Удалить слой",
"back": "Назад"
}
}); |
version https://git-lfs.github.com/spec/v1
oid sha256:34540ed0f65c00f78c1f40f26ebf00af8cbbf57bbe9ddda8095151730f3916c0
size 1347
|
angular.module('bolt.controller', [])
.controller('BoltController', function ($scope, $location, $window) {
$scope.session = $window.localStorage;
$scope.startRun = function () {
// Check which radio button is selected
if (document.getElementById("switch_3_left").checked) {
// Solo run
$location.path('/run');
} else if (document.getElementById("switch_3_center").checked) {
// Running with friends has not been implemented yet, this is a
// placeholder for when this functionality has been developed.
// For now redirect runners to solo run.
$location.path('/run');
} else {
// Public run
$location.path('/multiLoad');
}
};
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:284de388de4cc188513a9b77a18f8457b4dc2bc01d915bee8b98c7ba5221c12f
size 274
|
"use strict";
function fact(_x2) {
var _arguments = arguments;
var _again = true;
_function: while (_again) {
_again = false;
var n = _x2;
acc = undefined;
var acc = _arguments[1] === undefined ? 1 : _arguments[1];
if (n > 1) {
_arguments = [_x2 = n - 1, acc * n];
_again = true;
continue _function;
} else {
return acc;
}
}
} |
/*
* Swipe 2.0
*
* Brad Birdsall
* Copyright 2013, MIT License
*
*/
module.exports = function Swipe(container, options) {
"use strict";
// utilities
var noop = function() {}; // simple no operation function
var offloadFn = function(fn) { setTimeout(fn || noop, 0) }; // offload a functions execution
// check browser capabilities
var browser = {
addEventListener: !!window.addEventListener,
touch: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch,
transitions: (function(temp) {
var props = ['transitionProperty', 'WebkitTransition', 'MozTransition', 'OTransition', 'msTransition'];
for ( var i in props ) if (temp.style[ props[i] ] !== undefined) return true;
return false;
})(document.createElement('swipe'))
};
// quit if no root element
if (!container) return;
var element = container.children[0];
var slides, slidePos, width, length;
options = options || {};
var index = parseInt(options.startSlide, 10) || 0;
var speed = options.speed || 300;
options.continuous = options.continuous !== undefined ? options.continuous : true;
function setup() {
// cache slides
slides = element.children;
length = slides.length;
// set continuous to false if only one slide
if (slides.length < 2) options.continuous = false;
//special case if two slides
if (browser.transitions && options.continuous && slides.length < 3) {
element.appendChild(slides[0].cloneNode(true));
element.appendChild(element.children[1].cloneNode(true));
slides = element.children;
}
// create an array to store current positions of each slide
slidePos = new Array(slides.length);
// determine width of each slide
width = container.getBoundingClientRect().width || container.offsetWidth;
element.style.width = (slides.length * width) + 'px';
// stack elements
var pos = slides.length;
while(pos--) {
var slide = slides[pos];
slide.style.width = width + 'px';
slide.setAttribute('data-index', pos);
if (browser.transitions) {
slide.style.left = (pos * -width) + 'px';
move(pos, index > pos ? -width : (index < pos ? width : 0), 0);
}
}
// reposition elements before and after index
if (options.continuous && browser.transitions) {
move(circle(index-1), -width, 0);
move(circle(index+1), width, 0);
}
if (!browser.transitions) element.style.left = (index * -width) + 'px';
container.style.visibility = 'visible';
}
function prev() {
if (options.continuous) slide(index-1);
else if (index) slide(index-1);
}
function next() {
if (options.continuous) slide(index+1);
else if (index < slides.length - 1) slide(index+1);
}
function circle(index) {
// a simple positive modulo using slides.length
return (slides.length + (index % slides.length)) % slides.length;
}
function slide(to, slideSpeed) {
// do nothing if already on requested slide
if (index == to) return;
if (browser.transitions) {
var direction = Math.abs(index-to) / (index-to); // 1: backward, -1: forward
// get the actual position of the slide
if (options.continuous) {
var natural_direction = direction;
direction = -slidePos[circle(to)] / width;
// if going forward but to < index, use to = slides.length + to
// if going backward but to > index, use to = -slides.length + to
if (direction !== natural_direction) to = -direction * slides.length + to;
}
var diff = Math.abs(index-to) - 1;
// move all the slides between index and to in the right direction
while (diff--) move( circle((to > index ? to : index) - diff - 1), width * direction, 0);
to = circle(to);
move(index, width * direction, slideSpeed || speed);
move(to, 0, slideSpeed || speed);
if (options.continuous) move(circle(to - direction), -(width * direction), 0); // we need to get the next in place
} else {
to = circle(to);
animate(index * -width, to * -width, slideSpeed || speed);
//no fallback for a circular continuous if the browser does not accept transitions
}
index = to;
offloadFn(options.callback && options.callback(index, slides[index]));
}
function move(index, dist, speed) {
translate(index, dist, speed);
slidePos[index] = dist;
}
function translate(index, dist, speed) {
var slide = slides[index];
var style = slide && slide.style;
if (!style) return;
style.webkitTransitionDuration =
style.MozTransitionDuration =
style.msTransitionDuration =
style.OTransitionDuration =
style.transitionDuration = speed + 'ms';
style.webkitTransform = 'translate(' + dist + 'px,0)' + 'translateZ(0)';
style.msTransform =
style.MozTransform =
style.OTransform = 'translateX(' + dist + 'px)';
}
function animate(from, to, speed) {
// if not an animation, just reposition
if (!speed) {
element.style.left = to + 'px';
return;
}
var start = +new Date;
var timer = setInterval(function() {
var timeElap = +new Date - start;
if (timeElap > speed) {
element.style.left = to + 'px';
if (delay) begin();
options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);
clearInterval(timer);
return;
}
element.style.left = (( (to - from) * (Math.floor((timeElap / speed) * 100) / 100) ) + from) + 'px';
}, 4);
}
// setup auto slideshow
var delay = options.auto || 0;
var interval;
function begin() {
interval = setTimeout(next, delay);
}
function stop() {
delay = 0;
clearTimeout(interval);
}
// setup initial vars
var start = {};
var delta = {};
var isScrolling;
// setup event capturing
var events = {
handleEvent: function(event) {
switch (event.type) {
case 'touchstart': this.start(event); break;
case 'touchmove': this.move(event); break;
case 'touchend': offloadFn(this.end(event)); break;
case 'webkitTransitionEnd':
case 'msTransitionEnd':
case 'oTransitionEnd':
case 'otransitionend':
case 'transitionend': offloadFn(this.transitionEnd(event)); break;
case 'resize': offloadFn(setup); break;
}
if (options.stopPropagation) event.stopPropagation();
},
start: function(event) {
var touches = event.touches[0];
// measure start values
start = {
// get initial touch coords
x: touches.pageX,
y: touches.pageY,
// store time to determine touch duration
time: +new Date
};
// used for testing first move event
isScrolling = undefined;
// reset delta and end measurements
delta = {};
// attach touchmove and touchend listeners
element.addEventListener('touchmove', this, false);
element.addEventListener('touchend', this, false);
},
move: function(event) {
// ensure swiping with one touch and not pinching
if ( event.touches.length > 1 || event.scale && event.scale !== 1) return
if (options.disableScroll) event.preventDefault();
var touches = event.touches[0];
// measure change in x and y
delta = {
x: touches.pageX - start.x,
y: touches.pageY - start.y
}
// determine if scrolling test has run - one time test
if ( typeof isScrolling == 'undefined') {
isScrolling = !!( isScrolling || Math.abs(delta.x) < Math.abs(delta.y) );
}
// if user is not trying to scroll vertically
if (!isScrolling) {
// prevent native scrolling
event.preventDefault();
// stop slideshow
stop();
// increase resistance if first or last slide
if (options.continuous) { // we don't add resistance at the end
translate(circle(index-1), delta.x + slidePos[circle(index-1)], 0);
translate(index, delta.x + slidePos[index], 0);
translate(circle(index+1), delta.x + slidePos[circle(index+1)], 0);
} else {
delta.x =
delta.x /
( (!index && delta.x > 0 // if first slide and sliding left
|| index == slides.length - 1 // or if last slide and sliding right
&& delta.x < 0 // and if sliding at all
) ?
( Math.abs(delta.x) / width + 1 ) // determine resistance level
: 1 ); // no resistance if false
// translate 1:1
translate(index-1, delta.x + slidePos[index-1], 0);
translate(index, delta.x + slidePos[index], 0);
translate(index+1, delta.x + slidePos[index+1], 0);
}
}
},
end: function(event) {
// measure duration
var duration = +new Date - start.time;
// determine if slide attempt triggers next/prev slide
var isValidSlide =
Number(duration) < 250 // if slide duration is less than 250ms
&& Math.abs(delta.x) > 20 // and if slide amt is greater than 20px
|| Math.abs(delta.x) > width/2; // or if slide amt is greater than half the width
// determine if slide attempt is past start and end
var isPastBounds =
!index && delta.x > 0 // if first slide and slide amt is greater than 0
|| index == slides.length - 1 && delta.x < 0; // or if last slide and slide amt is less than 0
if (options.continuous) isPastBounds = false;
// determine direction of swipe (true:right, false:left)
var direction = delta.x < 0;
// if not scrolling vertically
if (!isScrolling) {
if (isValidSlide && !isPastBounds) {
if (direction) {
if (options.continuous) { // we need to get the next in this direction in place
move(circle(index-1), -width, 0);
move(circle(index+2), width, 0);
} else {
move(index-1, -width, 0);
}
move(index, slidePos[index]-width, speed);
move(circle(index+1), slidePos[circle(index+1)]-width, speed);
index = circle(index+1);
} else {
if (options.continuous) { // we need to get the next in this direction in place
move(circle(index+1), width, 0);
move(circle(index-2), -width, 0);
} else {
move(index+1, width, 0);
}
move(index, slidePos[index]+width, speed);
move(circle(index-1), slidePos[circle(index-1)]+width, speed);
index = circle(index-1);
}
options.callback && options.callback(index, slides[index]);
} else {
if (options.continuous) {
move(circle(index-1), -width, speed);
move(index, 0, speed);
move(circle(index+1), width, speed);
} else {
move(index-1, -width, speed);
move(index, 0, speed);
move(index+1, width, speed);
}
}
}
// kill touchmove and touchend event listeners until touchstart called again
element.removeEventListener('touchmove', events, false)
element.removeEventListener('touchend', events, false)
},
transitionEnd: function(event) {
if (parseInt(event.target.getAttribute('data-index'), 10) == index) {
if (delay) begin();
options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);
}
}
}
// trigger setup
setup();
// start auto slideshow if applicable
if (delay) begin();
// add event listeners
if (browser.addEventListener) {
// set touchstart event on element
if (browser.touch) element.addEventListener('touchstart', events, false);
if (browser.transitions) {
element.addEventListener('webkitTransitionEnd', events, false);
element.addEventListener('msTransitionEnd', events, false);
element.addEventListener('oTransitionEnd', events, false);
element.addEventListener('otransitionend', events, false);
element.addEventListener('transitionend', events, false);
}
// set resize event on window
window.addEventListener('resize', events, false);
} else {
window.onresize = function () { setup() }; // to play nice with old IE
}
// expose the Swipe API
return {
setup: function() {
setup();
},
slide: function(to, speed) {
// cancel slideshow
stop();
slide(to, speed);
},
prev: function() {
// cancel slideshow
stop();
prev();
},
next: function() {
// cancel slideshow
stop();
next();
},
stop: function() {
// cancel slideshow
stop();
},
getPos: function() {
// return current index position
return index;
},
getNumSlides: function() {
// return total number of slides
return length;
},
kill: function() {
// cancel slideshow
stop();
// reset element
element.style.width = '';
element.style.left = '';
// reset slides
var pos = slides.length;
while(pos--) {
var slide = slides[pos];
slide.style.width = '';
slide.style.left = '';
if (browser.transitions) translate(pos, 0, 0);
}
// removed event listeners
if (browser.addEventListener) {
// remove current event listeners
element.removeEventListener('touchstart', events, false);
element.removeEventListener('webkitTransitionEnd', events, false);
element.removeEventListener('msTransitionEnd', events, false);
element.removeEventListener('oTransitionEnd', events, false);
element.removeEventListener('otransitionend', events, false);
element.removeEventListener('transitionend', events, false);
window.removeEventListener('resize', events, false);
}
else {
window.onresize = null;
}
}
}
}
|
/*jslint nomen: true, vars: true*/
/*global define*/
define(['jquery', 'underscore', 'backbone'], function ($, _, Backbone) {
'use strict';
/**
* @export oro/sidebar/widget/hello-world
*/
var helloWorld = {};
helloWorld.ContentView = Backbone.View.extend({
template: _.template('<span><%= settings.content %></span>'),
initialize: function () {
var view = this;
view.listenTo(view.model, 'change', view.render);
},
render: function () {
var view = this;
view.$el.html(view.template(view.model.toJSON()));
return view;
}
});
helloWorld.SetupView = Backbone.View.extend({
template: _.template('<h3>Hello world settings</h3><textarea style="width: 400px; height: 150px;"><%= settings.content %></textarea>'),
events: {
'keyup textarea': 'onKeyup'
},
render: function () {
var view = this;
view.$el.html(view.template(view.model.toJSON()));
return view;
},
onKeyup: function (e) {
var view = this;
var model = view.model;
var content = view.$el.find('textarea').val();
var settings = model.get('settings');
settings.content = content;
model.set({ settings: settings }, { silent: true });
model.trigger('change');
}
});
return helloWorld;
});
|
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const _ = require("underscore")
const Backbone = require("backbone")
const benv = require("benv")
let sd = require("sharify").data
const Profile = require("../../../../models/profile.coffee")
const Fair = require("../../../../models/fair.coffee")
const { resolve } = require("path")
const sinon = require("sinon")
import { mediator } from "lib/mediator"
const CurrentUser = require("../../../../models/current_user")
const { fabricate } = require("@artsy/antigravity")
describe("HeaderView", function () {
before(done =>
benv.setup(function () {
benv.expose({
$: benv.require("jquery"),
jQuery: benv.require("jquery"),
})
Backbone.$ = $
return done()
})
)
after(() => benv.teardown())
describe("user is signed out", function () {
beforeEach(function (done) {
sinon.stub(Backbone, "sync")
sinon.stub($, "ajax")
this.mediatorSpy = sinon.spy(mediator, "trigger")
this.fair = new Fair(fabricate("fair"))
this.profile = new Profile(fabricate("fair_profile"))
return benv.render(
resolve(__dirname, "../../templates/header.jade"),
{ sd: {}, _ },
() => {
const FairHeaderView = benv.require(
resolve(__dirname, "../../client/header")
)
this.view = new FairHeaderView({
el: $(".fair-layout-header-right"),
model: this.profile,
fair: this.fair,
})
this.$template = $("body")
return done()
}
)
})
afterEach(function () {
Backbone.sync.restore()
this.mediatorSpy.restore()
return $.ajax.restore()
})
describe("#login", () =>
it("triggers the mediator", function () {
this.view.$(".mlh-login").click()
this.mediatorSpy.args[0][0].should.equal("open:auth")
return this.mediatorSpy.args[0][1].mode.should.equal("login")
}))
return describe("#signup", () =>
it("triggers the mediator", function () {
this.view.$(".mlh-signup").click()
this.mediatorSpy.args[0][0].should.equal("open:auth")
return this.mediatorSpy.args[0][1].mode.should.equal("signup")
}))
})
return describe("user signed in", function () {
beforeEach(function (done) {
sinon.stub(Backbone, "sync")
sinon.stub($, "ajax")
this.fair = new Fair(fabricate("fair"))
this.profile = new Profile(fabricate("fair_profile"))
this.user = new CurrentUser(fabricate("user"))
sd = { CURRENT_USER: this.user }
return benv.render(
resolve(__dirname, "../../templates/header.jade"),
{ sd, _, user: this.user },
() => {
const FairHeaderView = benv.require(
resolve(__dirname, "../../client/header")
)
this.view = new FairHeaderView({
el: $(".fair-layout-header-right"),
model: this.profile,
fair: this.fair,
})
this.$template = $("body")
return done()
}
)
})
afterEach(function () {
Backbone.sync.restore()
return $.ajax.restore()
})
return describe("#logout", () =>
it("signs out user with ajax", function () {
this.view.$(".mlh-logout").click()
$.ajax.args[0][0].type.should.equal("DELETE")
return $.ajax.args[0][0].url.should.equal("/users/sign_out")
}))
})
})
|
/**
* @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'language', 'sl', {
button: 'Nastavi jezik',
remove: 'Odstrani jezik'
} );
|
import { Meteor } from 'meteor/meteor';
import { HTTP } from 'meteor/http';
import { SyncedCron } from 'meteor/littledata:synced-cron';
import { Logger } from '../../app/logger';
import { getWorkspaceAccessToken } from '../../app/cloud/server';
import { statistics } from '../../app/statistics';
import { settings } from '../../app/settings';
const logger = new Logger('SyncedCron');
SyncedCron.config({
logger(opts) {
return logger[opts.level].call(logger, opts.message);
},
collectionName: 'rocketchat_cron_history',
});
function generateStatistics() {
const cronStatistics = statistics.save();
cronStatistics.host = Meteor.absoluteUrl();
if (settings.get('Statistics_reporting')) {
try {
const headers = {};
const token = getWorkspaceAccessToken();
if (token) {
headers.Authorization = `Bearer ${ token }`;
}
HTTP.post('https://collector.rocket.chat/', {
data: cronStatistics,
headers,
});
} catch (error) {
/* error*/
logger.warn('Failed to send usage report');
}
}
}
function cleanupOEmbedCache() {
return Meteor.call('OEmbedCacheCleanup');
}
const name = 'Generate and save statistics';
Meteor.startup(function() {
return Meteor.defer(function() {
let TroubleshootDisableStatisticsGenerator;
settings.get('Troubleshoot_Disable_Statistics_Generator', (key, value) => {
if (TroubleshootDisableStatisticsGenerator === value) { return; }
TroubleshootDisableStatisticsGenerator = value;
if (value) {
return SyncedCron.remove(name);
}
generateStatistics();
SyncedCron.add({
name,
schedule(parser) {
return parser.cron('12 * * * *');
},
job: generateStatistics,
});
});
SyncedCron.add({
name: 'Cleanup OEmbed cache',
schedule(parser) {
return parser.cron('24 2 * * *');
},
job: cleanupOEmbedCache,
});
return SyncedCron.start();
});
});
|
import StoreInitMixin from './ember-sync/store-initialization-mixin';
import Queue from './ember-sync/queue';
import Query from './ember-sync/query';
import Persistence from './ember-sync/persistence';
import QueueModel from './ember-sync/ember-sync-queue-model';
export default Ember.Object.extend(
StoreInitMixin, {
onError: function() { },
/**
*
* This is called when a record is added from an online or offline store and
* pushed to the results array. This will be triggered when using the find or
* findQuery methods
*
* @method onRecordAddded
*/
onRecordAdded: function(record, type) {
this.embedThisIntoRecord(record, type);
},
queueModel: QueueModel,
/**
* Pushes pending record to the server.
*
* Whenever you create, updates or deletes a record, a `job` is create in a
* `queue` in the offline database. Once the internet is available, this queue
* will be processed and those records will be synchronized with the remote
* server.
*
* This should be called from the ApplicationRoute, e.g.
*
* App.ApplicationRoute = Ember.Route.extend({
* init: function() {
* this._super();
*
* var emberSync = EmberSync.API.create({container: this});
* emberSync.synchronizeOnline();
* }
* });
*
* It will keep running forever (unless otherwise commanded).
*
* @method synchronizeOnline
*/
synchronizeOnline: function() {
Queue.create({
offlineStore: this.offlineStore,
onlineStore: this.onlineStore,
onError: this.get('onError')
}).process();
},
/**
* Finds a record both offline and online, returning the first to be found.
* If an online record is found, it is then pushed into the offline store,
* which should automatically update the references to the original record
* (if this was changed).
*
* Use this just like regular store's `find()`.
*
* @method find
* @param {string} type
* @param {object} query
* @return {Promise}
*/
find: function(type, query) {
var _this = this;
var syncQuery = Query.create({
onlineStore: this.onlineStore,
offlineStore: this.offlineStore,
onError: this.get('onError'),
onRecordAdded: function(record) {
_this.onRecordAdded(record, type);
}
});
return syncQuery.find(type, query);
},
/**
* Queries both online and offline stores simultaneously, returning values
* asynchronously into a stream of results (Ember.A()).
*
* The records found online are stored into the offline store.
*
* Use this just like regular store's `findQuery()`. Remember, though, it
* doesn't return a Promise, but you can use `.then()` even so.
*
* @method findQuery
* @param {string} type
* @param {object} query
* @return {Ember.A}
*/
findQuery: function(type, query) {
var _this = this;
var syncQuery = Query.create({
onlineStore: this.onlineStore,
offlineStore: this.offlineStore,
onError: this.get('onError'),
onRecordAdded: function(record) {
_this.onRecordAdded(record, type);
}
});
return syncQuery.findQuery(type, query);
},
createRecord: function(type, properties) {
var _this = this,
record;
if (properties) {
record = this.offlineStore.createRecord(type, properties);
} else {
record = this.offlineStore.createRecord(type);
}
this.embedThisIntoRecord(record, type, properties);
return record;
},
deleteRecord: function(type, record) {
record.deleteRecord();
this.embedThisIntoRecord(record, type);
return record;
},
embedThisIntoRecord: function(record, type, properties) {
var _this = this;
record.emberSync = Ember.Object.create({
init: function() {
this.set('emberSync', _this);
this.set('record', record);
this.set('recordType', type);
},
save: function() {
var persistence = Persistence.create({
onlineStore: this.get('emberSync.onlineStore'),
offlineStore: this.get('emberSync.offlineStore'),
onError: _this.get('onError')
});
return persistence.save(this.get('record'));
}
});
}
});
|
// Copyright 2015 Yahoo! Inc.
// Copyrights licensed under the Mit License. See the accompanying LICENSE file for terms.
var Compressor = require('../processor/compressor');
var iconv = require('iconv-lite');
var os = require('os');
/**
* @class zTXt
* @module PNG
* @submodule PNGChunks
*/
module.exports = {
/**
* Gets the sequence
*
* @method getSequence
* @return {int}
*/
getSequence: function () {
return 110;
},
/**
* Gets the keyword
*
* @method getKeyword
* @return {string}
*/
getKeyword: function () {
return this._keyword || 'Title';
},
/**
* Sets the keyword
*
* @method setKeyword
* @param {string} text
*/
setKeyword: function (text) {
text = text.trim();
if (text.length > 79) {
throw new Error('Keyword cannot be longer than 79 characters.');
}
if (text.length === 0) {
throw new Error('Keyword needs to have a least one character.');
}
this._keyword = text;
},
/**
* Gets the text
*
* @method getText
* @return {string}
*/
getText: function () {
return this._text || '';
},
/**
* Sets the text
*
* @method setText
* @param {string} text
*/
setText: function (text) {
this._text = text;
},
/**
* Parsing of chunk data
*
* Phase 1
*
* @method parse
* @param {BufferedStream} stream Data stream
* @param {int} length Length of chunk data
* @param {boolean} strict Should parsing be strict?
* @param {object} options Decoding options
*/
parse: function (stream, length, strict, options) {
var i, len,
foundIndex = null,
buffer, string,
compressor,
compressionMethod;
// See where the null-character is
buffer = stream.peekBuffer(length);
for(i = 0, len = buffer.length; i < len; i++) {
if (buffer.readUInt8(i) === 0) {
foundIndex = i;
break;
}
}
// Found a null-character?
if (foundIndex === null) {
throw new Error('Cannot find separator in ' + this.getType() + ' chunk.');
}
// Convert keyword from latin1
buffer = stream.readBuffer(foundIndex);
string = iconv.decode(buffer, 'latin1');
this.setKeyword(string.replace(/\n/g, os.EOL));
// Skip null
stream.skip(1);
// Load compression method
compressionMethod = stream.readUInt8();
if (compressionMethod !== 0) {
throw new Error('Unknown compression method for chunk ' + this.getType() + '.');
}
// Load text content
buffer = stream.readBuffer(length - foundIndex - 1);
// Decompress
compressor = new Compressor(options);
buffer = compressor.decode(buffer);
// Convert text content from latin1
string = iconv.decode(buffer, 'latin1');
this.setText(string.replace(/\n/g, os.EOL));
},
/**
* Gathers chunk-data from decoded chunks
*
* Phase 5
*
* @static
* @method decodeData
* @param {object} data Data-object that will be used to export values
* @param {boolean} strict Should parsing be strict?
* @param {object} options Decoding options
*/
decodeData: function (data, strict, options) {
var chunks = this.getChunksByType(this.getType());
if (!chunks) {
return ;
}
data.compressedTexts = [];
chunks.forEach(function (chunk) {
data.compressedTexts.push({
keyword: chunk.getKeyword(),
content: chunk.getText()
});
});
},
/**
* Returns a list of chunks to be added to the data-stream
*
* Phase 1
*
* @static
* @method encodeData
* @param {Buffer} image Image data
* @param {object} options Encoding options
* @return {Chunk[]} List of chunks to encode
*/
encodeData: function (image, options) {
if (options.compressedTexts) {
var chunk,
result = [],
type = this.getType(),
chunks = this.getChunks();
options.compressedTexts.forEach(function (text) {
chunk = this.createChunk(type, chunks);
if (text.keyword !== undefined) {
chunk.setKeyword(text.keyword);
}
if (text.content !== undefined) {
chunk.setText(text.content);
}
result.push(chunk);
}.bind(this));
return result;
} else {
return [];
}
},
/**
* Composing of chunk data
*
* Phase 4
*
* @method compose
* @param {BufferedStream} stream Data stream
* @param {object} options Encoding options
*/
compose: function (stream, options) {
var string, buffer, compressor;
// Write title to stream
string = this.getKeyword();
string = string.replace(new RegExp(os.EOL, 'g'), "\n");
buffer = iconv.encode(string, 'latin1');
stream.writeBuffer(buffer);
// Write null-character and compression method (0)
stream.writeUInt8(0);
stream.writeUInt8(0);
// Convert text content
string = this.getText();
string = string.replace(new RegExp(os.EOL, 'g'), "\n");
buffer = iconv.encode(string, 'latin1');
// Compress
compressor = new Compressor(options);
buffer = compressor.encode(buffer);
// Write compressed data to stream
stream.writeBuffer(buffer);
}
};
|
/*
This shows a line chart of the data given. It is assumed that the default transform is already set by the default state (transform property).
*/
import React, { Component } from "react";
import createClass from "create-react-class";
import PropTypes from "prop-types";
import BarChart, { getBarChartIcons } from "./BarChart";
import DropDownMenu from "material-ui/DropDownMenu";
import MenuItem from "material-ui/MenuItem";
import dropdownTransformDisplay from "./dropdownTransformDisplay";
class DropdownBarChart extends Component {
static propTypes = {
data: PropTypes.arrayOf(PropTypes.object).isRequired,
state: PropTypes.object.isRequired,
setState: PropTypes.func.isRequired,
options: PropTypes.arrayOf(
PropTypes.shape({
description: PropTypes.string,
transform: PropTypes.string.isRequired,
name: PropTypes.string.isRequired
})
)
};
render() {
const { data, state, setState, options } = this.props;
return (
<div
style={{
textAlign: "center"
}}
>
<DropDownMenu
value={state.currentOption}
onChange={(e, i, v) =>
setState({
transform: v.transform,
currentOption: v,
description: v.description
})}
>
{options.map(function(o) {
return (
<MenuItem key={o.transform} value={o} primaryText={o.name} />
);
})}
</DropDownMenu>
<BarChart {...this.props} transform={state.transform} />
</div>
);
}
}
export default DropdownBarChart;
// generate creates a new view that shows the dropdown bar chart, and auto-updates
export function generateDropdownBarChart(
description,
options,
defaultOptionIndex
) {
return {
initialState: {
currentOption: options[defaultOptionIndex],
transform: options[defaultOptionIndex].transform,
description: options[defaultOptionIndex].description
},
width: "expandable-half",
dropdown: dropdownTransformDisplay(description, ""),
icons: getBarChartIcons,
component: createClass({
render: function() {
return <DropdownBarChart {...this.props} options={options} />;
}
})
};
}
|
module.exports = {
point: {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [
-76.29215240478516,
36.85067669846314
]
}
},
shape: {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"crs": {
"type":"name",
"properties":{
"name":"EPSG:4326"
}
},
"coordinates": [
[
[
-76.2956714630127,
36.85943312934033
],
[
-76.3020658493042,
36.859467466310285
],
[
-76.29648685455322,
36.8519473016299
],
[
-76.29069328308105,
36.854625801280235
],
[
-76.29137992858887,
36.858437350500914
],
[
-76.2956714630127,
36.85943312934033
]
]
]
}
},
line: {
"type": "Feature",
"properties": {},
"geometry": {
"type": "LineString",
"crs": {
"type":"name",
"properties":{
"name":"EPSG:4326"
}
},
"coordinates": [
[
-76.3046407699585,
36.85438542694001
],
[
-76.28833293914795,
36.846555678014376
],
[
-76.28687381744385,
36.85325222344018
]
]
}
}
};
|
angular.module('service.weatherinfo', [])
.factory('WeatherInfo', function ($rootScope, WeatherUtil, TwStorage, Util) {
var cities = [];
var cityIndex = -1;
var loadingWeatherPhotos = false;
var obj = {};
var createCity = function (item) {
var city = {};
if (item === undefined) {
city.currentPosition = true;
city.address = null;
city.location = null;
city.currentWeather = null;
city.timeTable = null;
city.timeChart = null;
city.dayTable = null;
city.dayChart = null;
city.disable = true; // 현재 위치 off
city.photo = null;
} else {
city = item;
city.disable = item.disable === undefined ? false : item.disable;
city.photo = item.photo === undefined ? null : item.photo;
}
city.loadTime = null;
cities.push(city);
};
//region APIs
obj.getIndexOfCity = function (city) {
for (var i = 0; i < cities.length; i += 1) {
if (cities[i].currentPosition === true) {
if (city.currentPosition === true) {
return i;
}
}
else {
if (cities[i].address === city.address) {
if (city.name || cities[i].name) {
if (city.name === cities[i].name) {
return i;
}
}
else {
return i;
}
}
}
}
return -1;
};
obj.getCityOfIndex = function (index) {
if (index < 0 || index >= cities.length) {
return null;
}
return cities[index];
};
obj.getCityCount = function () {
return cities.length;
};
obj.getEnabledCityCount = function () {
var count = cities.length;
for (var i = 0; i < cities.length; i += 1) {
if (cities[i].disable === true) {
count -= 1;
}
}
return count;
};
obj.getCityIndex = function () {
return cityIndex;
};
/**
*
* @param {number} index
*/
obj.setCityIndex = function (index) {
if (index >= 0 && index < cities.length) {
cityIndex = index;
// save current cityIndex
TwStorage.set("cityIndex", cityIndex);
console.log("cityIndex = " + cityIndex);
Util.ga.trackEvent('city', 'set', 'index', index);
}
else {
Util.ga.trackEvent('city', 'error', 'Invalid set index', index);
}
};
obj.setFirstCityIndex = function () {
var that = this;
var city = cities[0];
if (city.disable === true) {
if (cities.length === 1) {
that.setCityIndex(-1);
} else {
that.setCityIndex(1);
}
} else {
that.setCityIndex(0);
}
};
obj.setPrevCityIndex = function () {
var that = this;
var city = cities[0];
if (cityIndex === 0 || (cityIndex === 1 && city.disable === true)) {
that.setCityIndex(cities.length - 1);
}
else {
that.setCityIndex(cityIndex - 1);
}
};
obj.setNextCityIndex = function () {
var that = this;
if (cityIndex === cities.length - 1) {
that.setFirstCityIndex();
}
else {
that.setCityIndex(cityIndex + 1);
}
};
obj.canLoadCity = function (index) {
if (index >= 0 && index < cities.length) {
var city = cities[index];
if (city.disable === true) {
return false;
}
var time = new Date();
return !!(city.loadTime === null || time.getTime() - city.loadTime.getTime() > (10 * 60 * 1000));
}
Util.ga.trackException(new Error('invalid city index='+index), false);
return false;
};
obj.addCity = function (city) {
var that = this;
if (that.getIndexOfCity(city) === -1) {
city.disable = false;
city.loadTime = new Date();
city.photo = that._getPhoto(city.currentWeather);
cities.push(city);
that.saveCities();
return true;
}
return false;
};
obj.removeCity = function (index) {
var that = this;
if (index !== -1) {
cities.splice(index, 1);
that.saveCities();
if (cityIndex === that.getCityCount()) {
that.setFirstCityIndex();
}
return true;
}
return false;
};
obj.disableCity = function (disable) {
var that = this;
cities[0].disable = disable;
that.saveCities();
if (cityIndex <= 0) {
that.setFirstCityIndex();
}
};
obj.reloadCity = function (index) {
var city;
try {
city = cities[index];
city.loadTime = null;
}
catch (err) {
Util.ga.trackEvent('city', 'error', 'fail to reload index='+index);
Util.ga.trackException(err, false);
}
};
obj.updateCity = function (index, newCityInfo) {
var that = this;
var city = cities[index];
if (city == undefined) {
Util.ga.trackException(new Error('invalid cityIndex:'+index+' length:'+cities.length), false);
return;
}
if (newCityInfo.currentWeather) {
city.currentWeather = newCityInfo.currentWeather;
}
if (newCityInfo.timeTable) {
city.timeTable = newCityInfo.timeTable;
}
if (newCityInfo.timeChart) {
city.timeChart = newCityInfo.timeChart;
}
if (newCityInfo.dayTable) {
city.dayTable = newCityInfo.dayTable;
}
if (newCityInfo.dayChart) {
city.dayChart = newCityInfo.dayChart;
}
if (newCityInfo.source) {
city.source = newCityInfo.source;
}
if (newCityInfo.airInfo) {
city.airInfo = newCityInfo.airInfo;
}
if (newCityInfo.airInfoList) {
city.airInfoList = newCityInfo.airInfoList;
}
if (city.currentPosition == true) {
if (newCityInfo.name) {
city.name = newCityInfo.name;
}
if (newCityInfo.country) {
city.country = newCityInfo.country;
}
if (newCityInfo.address) {
city.address = newCityInfo.address;
}
if (newCityInfo.location) {
city.location = newCityInfo.location;
}
}
else {
//구버전에 저장된 도시정보에는 location이 없는 경우가 있음. #1971
//v000901/kma/addr 에서 추가해주어야 함. TW-402 TW-365 TW-340
if ((!city.location || !city.location.lat) &&
(newCityInfo.location && newCityInfo.location.lat))
{
city.location = newCityInfo.location;
console.log('update location ', city);
}
}
if (window.updateCityInfo) {
console.log('try to update city info for push');
window.updateCityInfo(index);
}
else {
if (clientConfig && clientConfig.debug === false) {
Util.ga.trackException(new Error("updateCityInfo is undefined"), false);
}
}
city.loadTime = new Date();
city.photo = that._getPhoto(city.currentWeather);
that.saveCities();
};
obj.loadWeatherPhotos = function () {
var that = this;
if (loadingWeatherPhotos === true || window.weatherPhotos != undefined) {
return;
}
loadingWeatherPhotos = true;
WeatherUtil.loadWeatherPhotos().then(function () {
for (var i = 0; i < cities.length; i += 1) {
if (cities[i].photo === null) {
cities[i].photo = WeatherUtil.findWeatherPhoto(cities[i].currentWeather);
}
}
that.saveCities();
$rootScope.$broadcast('loadWeatherPhotosEvent');
}).finally(function () {
loadingWeatherPhotos = false;
});
};
obj.loadCities = function() {
var that = this;
var items = TwStorage.get("cities");
if (items === null) {
createCity();
Util.ga.trackEvent('app', 'user', 'new');
} else {
items.forEach(function (item) {
createCity(item);
});
that._loadCitiesPreference(function (err) {
if (err) {
//restore cities
that._saveCitiesPreference(items);
}
});
Util.ga.trackEvent('app', 'user', 'returning', that.getCityCount());
}
// load last cityIndex
cityIndex = TwStorage.get("cityIndex");
if (cityIndex === null) {
Util.ga.trackEvent('city', 'error', 'loadIndexNull');
that.setFirstCityIndex();
}
else if (cityIndex >= cities.length) {
Util.ga.trackEvent('city', 'error', 'loadIndexOver');
that.setFirstCityIndex();
}
else {
Util.ga.trackEvent('city', 'load', 'index', cityIndex);
}
// load weather photos
that.loadWeatherPhotos();
};
obj._saveCitiesPreference = function (cities) {
var pList = {cityList: []};
cities.forEach(function (city, index) {
if (!city.disable) {
var simpleInfo = {};
if (city.name) {
simpleInfo.name = city.name;
}
simpleInfo.currentPosition = city.currentPosition;
simpleInfo.address = city.address;
simpleInfo.location = city.location;
simpleInfo.country = city.country;
simpleInfo.index = index;
pList.cityList.push(simpleInfo);
}
});
console.log('save preference plist='+JSON.stringify(pList));
TwStorage.set("cityList", pList);
};
obj._loadCitiesPreference = function (callback) {
var cityList = TwStorage.get("cityList");
if (cityList == undefined) {
callback(new Error("Can not find cityList"));
} else {
callback(undefined, cityList);
}
};
obj._getPhoto = function (currentWeather) {
var that = this;
if (window.weatherPhotos == undefined) {
that.loadWeatherPhotos();
return null;
}
return WeatherUtil.findWeatherPhoto(currentWeather);
};
obj.saveCities = function() {
TwStorage.set("cities", cities);
this._saveCitiesPreference(cities);
};
//endregion
return obj;
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.