code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
/** * @license * Copyright 2020 Google LLC * SPDX-License-Identifier: Apache-2.0 */ goog.module('Blockly.test.connectionChecker'); const {ConnectionType} = goog.require('Blockly.ConnectionType'); const {sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers'); suite('Connection checker', function() { setup(function() { sharedTestSetup.call(this); }); teardown(function() { sharedTestTeardown.call(this); }); suiteSetup(function() { this.checker = new Blockly.ConnectionChecker(); }); suite('Safety checks', function() { function assertReasonHelper(checker, one, two, reason) { chai.assert.equal(checker.canConnectWithReason(one, two), reason); // Order should not matter. chai.assert.equal(checker.canConnectWithReason(two, one), reason); } test('Target Null', function() { const connection = new Blockly.Connection({}, ConnectionType.INPUT_VALUE); assertReasonHelper( this.checker, connection, null, Blockly.Connection.REASON_TARGET_NULL); }); test('Target Self', function() { const block = {workspace: 1}; const connection1 = new Blockly.Connection(block, ConnectionType.INPUT_VALUE); const connection2 = new Blockly.Connection(block, ConnectionType.OUTPUT_VALUE); assertReasonHelper( this.checker, connection1, connection2, Blockly.Connection.REASON_SELF_CONNECTION); }); test('Different Workspaces', function() { const connection1 = new Blockly.Connection( {workspace: 1}, ConnectionType.INPUT_VALUE); const connection2 = new Blockly.Connection( {workspace: 2}, ConnectionType.OUTPUT_VALUE); assertReasonHelper( this.checker, connection1, connection2, Blockly.Connection.REASON_DIFFERENT_WORKSPACES); }); suite('Types', function() { setup(function() { // We have to declare each separately so that the connections belong // on different blocks. const prevBlock = {isShadow: function() {}}; const nextBlock = {isShadow: function() {}}; const outBlock = {isShadow: function() {}}; const inBlock = {isShadow: function() {}}; this.previous = new Blockly.Connection( prevBlock, ConnectionType.PREVIOUS_STATEMENT); this.next = new Blockly.Connection( nextBlock, ConnectionType.NEXT_STATEMENT); this.output = new Blockly.Connection( outBlock, ConnectionType.OUTPUT_VALUE); this.input = new Blockly.Connection( inBlock, ConnectionType.INPUT_VALUE); }); test('Previous, Next', function() { assertReasonHelper( this.checker, this.previous, this.next, Blockly.Connection.CAN_CONNECT); }); test('Previous, Output', function() { assertReasonHelper( this.checker, this.previous, this.output, Blockly.Connection.REASON_WRONG_TYPE); }); test('Previous, Input', function() { assertReasonHelper( this.checker, this.previous, this.input, Blockly.Connection.REASON_WRONG_TYPE); }); test('Next, Previous', function() { assertReasonHelper( this.checker, this.next, this.previous, Blockly.Connection.CAN_CONNECT); }); test('Next, Output', function() { assertReasonHelper( this.checker, this.next, this.output, Blockly.Connection.REASON_WRONG_TYPE); }); test('Next, Input', function() { assertReasonHelper( this.checker, this.next, this.input, Blockly.Connection.REASON_WRONG_TYPE); }); test('Output, Previous', function() { assertReasonHelper( this.checker, this.previous, this.output, Blockly.Connection.REASON_WRONG_TYPE); }); test('Output, Next', function() { assertReasonHelper( this.checker, this.output, this.next, Blockly.Connection.REASON_WRONG_TYPE); }); test('Output, Input', function() { assertReasonHelper( this.checker, this.output, this.input, Blockly.Connection.CAN_CONNECT); }); test('Input, Previous', function() { assertReasonHelper( this.checker, this.previous, this.input, Blockly.Connection.REASON_WRONG_TYPE); }); test('Input, Next', function() { assertReasonHelper( this.checker, this.input, this.next, Blockly.Connection.REASON_WRONG_TYPE); }); test('Input, Output', function() { assertReasonHelper( this.checker, this.input, this.output, Blockly.Connection.CAN_CONNECT); }); }); suite('Shadows', function() { test('Previous Shadow', function() { const prevBlock = {isShadow: function() {return true;}}; const nextBlock = {isShadow: function() {return false;}}; const prev = new Blockly.Connection(prevBlock, ConnectionType.PREVIOUS_STATEMENT); const next = new Blockly.Connection(nextBlock, ConnectionType.NEXT_STATEMENT); assertReasonHelper( this.checker, prev, next, Blockly.Connection.CAN_CONNECT); }); test('Next Shadow', function() { const prevBlock = {isShadow: function() {return false;}}; const nextBlock = {isShadow: function() {return true;}}; const prev = new Blockly.Connection(prevBlock, ConnectionType.PREVIOUS_STATEMENT); const next = new Blockly.Connection(nextBlock, ConnectionType.NEXT_STATEMENT); assertReasonHelper( this.checker, prev, next, Blockly.Connection.REASON_SHADOW_PARENT); }); test('Prev and Next Shadow', function() { const prevBlock = {isShadow: function() {return true;}}; const nextBlock = {isShadow: function() {return true;}}; const prev = new Blockly.Connection(prevBlock, ConnectionType.PREVIOUS_STATEMENT); const next = new Blockly.Connection(nextBlock, ConnectionType.NEXT_STATEMENT); assertReasonHelper( this.checker, prev, next, Blockly.Connection.CAN_CONNECT); }); test('Output Shadow', function() { const outBlock = {isShadow: function() {return true;}}; const inBlock = {isShadow: function() {return false;}}; const outCon = new Blockly.Connection(outBlock, ConnectionType.OUTPUT_VALUE); const inCon = new Blockly.Connection(inBlock, ConnectionType.INPUT_VALUE); assertReasonHelper( this.checker, outCon, inCon, Blockly.Connection.CAN_CONNECT); }); test('Input Shadow', function() { const outBlock = {isShadow: function() {return false;}}; const inBlock = {isShadow: function() {return true;}}; const outCon = new Blockly.Connection(outBlock, ConnectionType.OUTPUT_VALUE); const inCon = new Blockly.Connection(inBlock, ConnectionType.INPUT_VALUE); assertReasonHelper( this.checker, outCon, inCon, Blockly.Connection.REASON_SHADOW_PARENT); }); test('Output and Input Shadow', function() { const outBlock = {isShadow: function() {return true;}}; const inBlock = {isShadow: function() {return true;}}; const outCon = new Blockly.Connection(outBlock, ConnectionType.OUTPUT_VALUE); const inCon = new Blockly.Connection(inBlock, ConnectionType.INPUT_VALUE); assertReasonHelper( this.checker, outCon, inCon, Blockly.Connection.CAN_CONNECT); }); }); suite('Output and Previous', function() { /** * Update two connections to target each other. * @param {Connection} first The first connection to update. * @param {Connection} second The second connection to update. */ const connectReciprocally = function(first, second) { if (!first || !second) { throw Error('Cannot connect null connections.'); } first.targetConnection = second; second.targetConnection = first; }; test('Output connected, adding previous', function() { const outBlock = { isShadow: function() { }, }; const inBlock = { isShadow: function() { }, }; const outCon = new Blockly.Connection(outBlock, ConnectionType.OUTPUT_VALUE); const inCon = new Blockly.Connection(inBlock, ConnectionType.INPUT_VALUE); outBlock.outputConnection = outCon; inBlock.inputConnection = inCon; connectReciprocally(inCon, outCon); const prevCon = new Blockly.Connection(outBlock, ConnectionType.PREVIOUS_STATEMENT); const nextBlock = { isShadow: function() { }, }; const nextCon = new Blockly.Connection(nextBlock, ConnectionType.NEXT_STATEMENT); assertReasonHelper( this.checker, prevCon, nextCon, Blockly.Connection.REASON_PREVIOUS_AND_OUTPUT); }); test('Previous connected, adding output', function() { const prevBlock = { isShadow: function() { }, }; const nextBlock = { isShadow: function() { }, }; const prevCon = new Blockly.Connection(prevBlock, ConnectionType.PREVIOUS_STATEMENT); const nextCon = new Blockly.Connection(nextBlock, ConnectionType.NEXT_STATEMENT); prevBlock.previousConnection = prevCon; nextBlock.nextConnection = nextCon; connectReciprocally(prevCon, nextCon); const outCon = new Blockly.Connection(prevBlock, ConnectionType.OUTPUT_VALUE); const inBlock = { isShadow: function() { }, }; const inCon = new Blockly.Connection(inBlock, ConnectionType.INPUT_VALUE); assertReasonHelper( this.checker, outCon, inCon, Blockly.Connection.REASON_PREVIOUS_AND_OUTPUT); }); }); }); suite('Check Types', function() { setup(function() { this.con1 = new Blockly.Connection({}, ConnectionType.PREVIOUS_STATEMENT); this.con2 = new Blockly.Connection({}, ConnectionType.NEXT_STATEMENT); }); function assertCheckTypes(checker, one, two) { chai.assert.isTrue(checker.doTypeChecks(one, two)); // Order should not matter. chai.assert.isTrue(checker.doTypeChecks(one, two)); } test('No Types', function() { assertCheckTypes(this.checker, this.con1, this.con2); }); test('Same Type', function() { this.con1.setCheck('type1'); this.con2.setCheck('type1'); assertCheckTypes(this.checker, this.con1, this.con2); }); test('Same Types', function() { this.con1.setCheck(['type1', 'type2']); this.con2.setCheck(['type1', 'type2']); assertCheckTypes(this.checker, this.con1, this.con2); }); test('Single Same Type', function() { this.con1.setCheck(['type1', 'type2']); this.con2.setCheck(['type1', 'type3']); assertCheckTypes(this.checker, this.con1, this.con2); }); test('One Typed, One Promiscuous', function() { this.con1.setCheck('type1'); assertCheckTypes(this.checker, this.con1, this.con2); }); test('No Compatible Types', function() { this.con1.setCheck('type1'); this.con2.setCheck('type2'); chai.assert.isFalse(this.checker.doTypeChecks(this.con1, this.con2)); }); }); });
google/blockly
tests/mocha/connection_checker_test.js
JavaScript
apache-2.0
12,098
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var stylus = require('stylus'); var nib = require('nib'); var passport = require('passport'); var HttpStrategy = require('passport-http'); var LocalStrategy = require('passport-local').Strategy; var expressSession = require('express-session'); var md5 = require('md5'); var sql = require('mssql') var flash = require('connect-flash'); var routes = require('./routes/index'); var templates = require('./routes/templates'); var publicApisRoutes = require('./routes/publicApis'); var authedApisRoutes = require('./routes/authedApis'); var app = express(); var db = require('mongoskin').db('mongodb://192.168.0.56/TestDB', { native_parser: true }) // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); //-------------------------------------------------------------------------------------------------------------- app.use(expressSession({ secret: 'mySecretKey' })); app.use(passport.initialize()); app.use(passport.session()); app.use(flash()); function compile(str, path) { return stylus(str) .set('filename', path) .use(nib()); } app.use(stylus.middleware({ src: __dirname + '/public/', compile: compile })); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use(express.static(path.join(__dirname, 'bower_components'))); var sqlconfig = { user: 'Nodejs', password: 'Nodejs', server: 'frosh', database: 'UM', } app.use(function (req, res, next) { req.db = db req.sqlconfig = sqlconfig; next(); }); passport.serializeUser(function (user, done) { done(null, user.UserId); }); passport.deserializeUser(function (id, done) { var sqlconnection = new sql.Connection(sqlconfig, function (err) { var request = new sql.Request(sqlconnection); request.query('SELECT TOP 1 * FROM dbo.Users WHERE UserId = ' + id, function (err, recordset) { if (recordset) return done(err, recordset[0]); }); }); }); passport.use('local', new LocalStrategy({ passReqToCallback: true }, function (req, username, password, done) { var sqlconnection = new sql.Connection(sqlconfig, function (err) { var request = new sql.Request(sqlconnection); request.query('SELECT TOP 1 * FROM dbo.Users WHERE UserId = ' + username, function (err, recordset) { if (recordset.length == 1) { var userRec = recordset[0]; var hashPass = md5(password); if (userRec.PasswordText.toLowerCase() == hashPass.toLowerCase()) { //success var request2 = new sql.Request(sqlconnection); request2.input('ID', sql.NVarChar(50), username) request2.execute('dbo.spTest', function (err, records) { req.session.user = recordset[0]; req.session.employee = records[0][0]; return done(null, recordset[0]); }) } else return done(null, false, req.flash('loginMessage', 'کلمه عبور صحیح نیست.')); } else return done(err, false, req.flash('loginMessage', 'کد پرسنلی صحیح نیست یا در مرکز سعیدآباد مشغول نیست.')); }); }); })); //-------------------------------------------------------------------------------------------------------------- app.use('/tmpl', templates); app.use('/papi', publicApisRoutes); app.use('/api', authedApisRoutes(passport)); app.all('/*', routes(passport)); passport.authenticate('local', function (req, res, next) { }) // catch 404 and forward to error handler app.use(function (req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
Hamcker/PersonalExit
app.js
JavaScript
apache-2.0
4,622
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.m.InputListItem. sap.ui.define(['jquery.sap.global', './ListItemBase', './library'], function(jQuery, ListItemBase, library) { "use strict"; /** * Constructor for a new InputListItem. * * @param {string} [sId] id for the new control, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new control * * @class * List item should be used for a label and an input field. * @extends sap.m.ListItemBase * * @author SAP SE * @version 1.38.7 * * @constructor * @public * @alias sap.m.InputListItem * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var InputListItem = ListItemBase.extend("sap.m.InputListItem", /** @lends sap.m.InputListItem.prototype */ { metadata : { library : "sap.m", properties : { /** * Label of the list item */ label : {type : "string", group : "Misc", defaultValue : null}, /** * This property specifies the label text directionality with enumerated options. By default, the label inherits text direction from the DOM. * @since 1.30.0 */ labelTextDirection : {type : "sap.ui.core.TextDirection", group : "Appearance", defaultValue : sap.ui.core.TextDirection.Inherit} }, defaultAggregation : "content", aggregations : { /** * Content controls can be added */ content : {type : "sap.ui.core.Control", multiple : true, singularName : "content", bindable : "bindable"} }, designtime : true }}); return InputListItem; }, /* bExport= */ true);
SuicidePreventionSquad/SeniorProject
resources/sap/m/InputListItem-dbg.js
JavaScript
apache-2.0
1,780
$(function(){$("li.animated").mouseover(function(){$(this).stop().animate({height:'50px'},{queue:false,duration:600,easing:'easeOutBounce'})});$("li.animated").mouseout(function(){$(this).stop().animate({height:'40px'},{queue:false,duration:600,easing:'easeOutBounce'})});});
lanesawyer/island
static/homepage/scripts/animated-menu.js
JavaScript
apache-2.0
275
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var factory = require( './factory.js' ); // MAIN // /** * Tests whether a collection contains at least `n` elements which pass a test implemented by a predicate function. * * ## Notes * * - If a predicate function calls the provided callback with a truthy error argument, the function suspends execution and immediately calls the `done` callback for subsequent error handling. * - This function does **not** guarantee that execution is asynchronous. To do so, wrap the `done` callback in a function which either executes at the end of the current stack (e.g., `nextTick`) or during a subsequent turn of the event loop (e.g., `setImmediate`, `setTimeout`). * * * @param {Collection} collection - input collection * @param {PositiveInteger} n - number of elements * @param {Options} [options] - function options * @param {*} [options.thisArg] - execution context * @param {PositiveInteger} [options.limit] - maximum number of pending invocations at any one time * @param {boolean} [options.series=false] - boolean indicating whether to wait for a previous invocation to complete before invoking a provided function for the next element in a collection * @param {Function} predicate - predicate function to invoke for each element in a collection * @param {Callback} done - function to invoke upon completion * @throws {TypeError} first argument must be a collection * @throws {TypeError} second argument must be a positive integer * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @throws {TypeError} second-to-last argument must be a function * @throws {TypeError} last argument must be a function * @returns {void} * * @example * var readFile = require( '@stdlib/fs/read-file' ); * * function done( error, bool ) { * if ( error ) { * throw error; * } * if ( bool ) { * console.log( 'Successfully read some files.' ); * } else { * console.log( 'Unable to read some files.' ); * } * } * * function predicate( file, next ) { * var opts = { * 'encoding': 'utf8' * }; * readFile( file, opts, onFile ); * * function onFile( error ) { * if ( error ) { * return next( null, false ); * } * next( null, true ); * } * } * * var files = [ * './beep.js', * './boop.js' * ]; * * someByAsync( files, 2, predicate, done ); */ function someByAsync( collection, n, options, predicate, done ) { if ( arguments.length < 5 ) { return factory( options )( collection, n, predicate ); } factory( options, predicate )( collection, n, done ); } // EXPORTS // module.exports = someByAsync;
stdlib-js/stdlib
lib/node_modules/@stdlib/utils/async/some-by/lib/some_by.js
JavaScript
apache-2.0
3,300
//MongoDB script to Update the Wing Directors list. //The list includes Wing Directors and Assistants only. // //History: // 15Nov21 MEG Clean spaces from email addresses. // 07Mar21 MEG Exclude assistants // 27Jan21 MEG Created. var DEBUG = false; var db = db.getSiblingDB( 'NHWG'); // Google Group of interest var baseGroupName = 'nh-wing-directors'; var googleGroup = baseGroupName + '@nhwg.cap.gov'; // Mongo collection that holds all wing groups var groupsCollection = 'GoogleGroups'; // Aggregation pipeline find all wing staff members as var memberPipeline = [ // Stage 1 - find ALL directors and assistants { $match: { Duty:/director/i, Asst: 0, } }, // Stage 2 { $lookup: // join Google account record { from: "Google", localField: "CAPID", foreignField: "customSchemas.Member.CAPID", as: "member" } }, // Stage 3 { // flatten array $unwind: { path : "$member", preserveNullAndEmptyArrays : false // optional } }, // Stage 4 { $project: { CAPID:1, Duty:1, Asst:1, Director: "$member.name.fullName", Email: "$member.primaryEmail", } }, ]; // Aggregate a list of all emails for the Google group of interest // Exlcuding MANAGER & OWNER roles, no group aristocrats var groupMemberPipeline = [ { "$match" : { "group" : googleGroup, "role" : 'MEMBER', } }, { "$project" : { "email" : "$email" } } ]; // pipeline options var options = { "allowDiskUse" : false }; function isActiveMember( capid ) { // Check to see if member is active. // This function needs to be changed for each group depending // on what constitutes "active". var m = db.getCollection( "Member").findOne( { "CAPID": capid, "MbrStatus": "ACTIVE" } ); if ( m == null ) { return false; } return true; } function isGroupMember( group, email ) { // Check if email is already in the group var email = email.toLowerCase(); var rx = new RegExp( email, 'i' ); return db.getCollection( groupsCollection ).findOne( { 'group': group, 'email': rx } ); } function addMembers( collection, pipeline, options, group ) { // Scans looking for active members // if member is not currently on the mailing list generate gam command to add member. // returns a list of members qualified to be on the list regardless of inclusion. var list = []; // the set of possible group members // Get the list of all qualified potential members for the list var cursor = db.getCollection( collection ).aggregate( pipeline, options ); while ( cursor.hasNext() ) { var m = cursor.next(); var email = m.Email.toLowerCase().replace( / /g, "" ); if ( ! isActiveMember( m.CAPID ) ) { continue; } if ( ! list.includes( email ) ) { list.push( email ); } if ( isGroupMember( googleGroup, m.Email ) ) { continue; } // Print gam command to add new member print("gam update group", googleGroup, "add member", email ); } return list; } function removeMembers( collection, pipeline, options, group, authMembers ) { // compare each member of the group against the authList // check active status, if not generate a gam command to remove member. // collection - name of collection holding all Google Group info // pipeline - array containing the pipeline to extract members of the target group // options - options for aggregations pipeline var m = db.getCollection( collection ).aggregate( pipeline, options ); while ( m.hasNext() ) { var e = m.next().email.toLowerCase().replace( / /g, "" ); DEBUG && print("DEBUG::removeMembers::email",e); var rgx = new RegExp( e, "i" ); if ( authMembers.includes( e ) ) { continue; } var r = db.getCollection( 'MbrContact' ).findOne( { Type: 'EMAIL', Priority: 'PRIMARY', Contact: rgx } ); if ( r ) { var a = db.getCollection( 'Member' ).findOne( { CAPID: r.CAPID } ); DEBUG && print("DEBUG::removeMembers::Member.CAPID",a.CAPID,"NameLast:",a.NameLast,"NameFirst:",a.NameFirst); if ( a ) { print( '#INFO:', a.CAPID, a.NameLast, a.NameFirst, a.NameSuffix ); print( 'gam update group', googleGroup, 'delete member', e ); } } } } // Main here print("# Update group:", googleGroup ); print("# Add new members"); var theAuthList = addMembers( "DutyPosition", memberPipeline, options, googleGroup ); DEBUG == true && print("DEBUG::theAuthList:", theAuthList); print( "# Remove inactive members") ; removeMembers( "GoogleGroups", groupMemberPipeline, options, googleGroup, theAuthList );
ifrguy/NHWG-MIMS
src/Groups/wing_directors.js
JavaScript
apache-2.0
4,806
/*! * ${copyright} */ // Provides control sap.ui.commons.HorizontalDivider. sap.ui.define([ './library', 'sap/ui/core/Control', './HorizontalDividerRenderer' ], function(library, Control, HorizontalDividerRenderer) { "use strict"; // shortcut for sap.ui.commons.HorizontalDividerHeight var HorizontalDividerHeight = library.HorizontalDividerHeight; // shortcut for sap.ui.commons.HorizontalDividerType var HorizontalDividerType = library.HorizontalDividerType; /** * Constructor for a new HorizontalDivider. * * @param {string} [sId] id for the new control, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new control * * @class * Divides the screen in visual areas. * @extends sap.ui.core.Control * @version ${version} * * @constructor * @public * @deprecated Since version 1.38. * @alias sap.ui.commons.HorizontalDivider * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var HorizontalDivider = Control.extend("sap.ui.commons.HorizontalDivider", /** @lends sap.ui.commons.HorizontalDivider.prototype */ { metadata : { library : "sap.ui.commons", deprecated: true, properties : { /** * Defines the width of the divider. */ width : {type : "sap.ui.core.CSSSize", group : "Appearance", defaultValue : '100%'}, /** * Defines the type of the divider. */ type : {type : "sap.ui.commons.HorizontalDividerType", group : "Appearance", defaultValue : HorizontalDividerType.Area}, /** * Defines the height of the divider. */ height : {type : "sap.ui.commons.HorizontalDividerHeight", group : "Appearance", defaultValue : HorizontalDividerHeight.Medium} } }}); // No Behaviour return HorizontalDivider; });
SAP/openui5
src/sap.ui.commons/src/sap/ui/commons/HorizontalDivider.js
JavaScript
apache-2.0
1,812
// This file was automatically generated. Do not modify. 'use strict'; goog.provide('Blockly.Msg.fr'); goog.require('Blockly.Msg'); Blockly.Msg.ADD_COMMENT = "Ajouter un commentaire"; Blockly.Msg.AUTH = "Veuillez autoriser cette application à permettre la sauvegarde de votre travail et à l’autoriser d'être partagé par vous."; Blockly.Msg.CHANGE_VALUE_TITLE = "Modifier la valeur :"; Blockly.Msg.CHAT = "Discutez avec votre collaborateur en tapant dans cette zone !"; Blockly.Msg.CLEAN_UP = "Nettoyer les blocs"; Blockly.Msg.COLLAPSE_ALL = "Réduire les blocs"; Blockly.Msg.COLLAPSE_BLOCK = "Réduire le bloc"; Blockly.Msg.COLOUR_BLEND_COLOUR1 = "couleur 1"; Blockly.Msg.COLOUR_BLEND_COLOUR2 = "couleur 2"; Blockly.Msg.COLOUR_BLEND_HELPURL = "http://meyerweb.com/eric/tools/color-blend/"; Blockly.Msg.COLOUR_BLEND_RATIO = "taux"; Blockly.Msg.COLOUR_BLEND_TITLE = "mélanger"; Blockly.Msg.COLOUR_BLEND_TOOLTIP = "Mélange deux couleurs dans une proportion donnée (de 0.0 à 1.0)."; Blockly.Msg.COLOUR_PICKER_HELPURL = "https://fr.wikipedia.org/wiki/Couleur"; Blockly.Msg.COLOUR_PICKER_TOOLTIP = "Choisir une couleur dans la palette."; Blockly.Msg.COLOUR_RANDOM_HELPURL = "http://randomcolour.com"; Blockly.Msg.COLOUR_RANDOM_TITLE = "couleur aléatoire"; Blockly.Msg.COLOUR_RANDOM_TOOLTIP = "Choisir une couleur au hasard."; Blockly.Msg.COLOUR_RGB_BLUE = "bleu"; Blockly.Msg.COLOUR_RGB_GREEN = "vert"; Blockly.Msg.COLOUR_RGB_HELPURL = "http://www.december.com/html/spec/colorper.html"; Blockly.Msg.COLOUR_RGB_RED = "rouge"; Blockly.Msg.COLOUR_RGB_TITLE = "colorier avec"; Blockly.Msg.COLOUR_RGB_TOOLTIP = "Créer une couleur avec la quantité spécifiée de rouge, vert et bleu. Les valeurs doivent être comprises entre 0 et 100."; Blockly.Msg.CONTROLS_FLOW_STATEMENTS_HELPURL = "https://github.com/google/blockly/wiki/Loops#loop-termination-blocks"; Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK = "quitter la boucle"; Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE = "passer à l’itération de boucle suivante"; Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK = "Sortir de la boucle englobante."; Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE = "Sauter le reste de cette boucle, et poursuivre avec l’itération suivante."; Blockly.Msg.CONTROLS_FLOW_STATEMENTS_WARNING = "Attention : Ce bloc ne devrait être utilisé que dans une boucle."; Blockly.Msg.CONTROLS_FOREACH_HELPURL = "https://github.com/google/blockly/wiki/Loops#for-each"; Blockly.Msg.CONTROLS_FOREACH_TITLE = "pour chaque élément %1 dans la liste %2"; Blockly.Msg.CONTROLS_FOREACH_TOOLTIP = "Pour chaque élément d’une liste, assigner la valeur de l’élément à la variable '%1', puis exécuter des instructions."; Blockly.Msg.CONTROLS_FOR_HELPURL = "https://github.com/google/blockly/wiki/Loops#count-with"; Blockly.Msg.CONTROLS_FOR_TITLE = "compter avec %1 de %2 à %3 par %4"; Blockly.Msg.CONTROLS_FOR_TOOLTIP = "Faire prendre à la variable « %1 » les valeurs depuis le nombre de début jusqu’au nombre de fin, en s’incrémentant du pas spécifié, et exécuter les instructions spécifiées."; Blockly.Msg.CONTROLS_IF_ELSEIF_TOOLTIP = "Ajouter une condition au bloc si."; Blockly.Msg.CONTROLS_IF_ELSE_TOOLTIP = "Ajouter une condition finale fourre-tout au bloc si."; Blockly.Msg.CONTROLS_IF_HELPURL = "https://github.com/google/blockly/wiki/IfElse"; Blockly.Msg.CONTROLS_IF_IF_TOOLTIP = "Ajouter, supprimer ou réordonner les sections pour reconfigurer ce bloc si."; Blockly.Msg.CONTROLS_IF_MSG_ELSE = "sinon"; Blockly.Msg.CONTROLS_IF_MSG_ELSEIF = "sinon si"; Blockly.Msg.CONTROLS_IF_MSG_IF = "si"; Blockly.Msg.CONTROLS_IF_TOOLTIP_1 = "Si une valeur est vraie, alors exécuter certains ordres."; Blockly.Msg.CONTROLS_IF_TOOLTIP_2 = "Si une valeur est vraie, alors exécuter le premier bloc d’ordres. Sinon, exécuter le second bloc d’ordres."; Blockly.Msg.CONTROLS_IF_TOOLTIP_3 = "Si la première valeur est vraie, alors exécuter le premier bloc d’ordres. Sinon, si la seconde valeur est vraie, exécuter le second bloc d’ordres."; Blockly.Msg.CONTROLS_IF_TOOLTIP_4 = "Si la première valeur est vraie, alors exécuter le premier bloc d’ordres. Sinon, si la seconde valeur est vraie, exécuter le second bloc d’ordres. Si aucune des valeurs n’est vraie, exécuter le dernier bloc d’ordres."; Blockly.Msg.CONTROLS_REPEAT_HELPURL = "http://fr.wikipedia.org/wiki/Boucle_for"; Blockly.Msg.CONTROLS_REPEAT_INPUT_DO = "faire"; Blockly.Msg.CONTROLS_REPEAT_TITLE = "répéter %1 fois"; Blockly.Msg.CONTROLS_REPEAT_TOOLTIP = "Exécuter des instructions plusieurs fois."; Blockly.Msg.CONTROLS_WHILEUNTIL_HELPURL = "https://github.com/google/blockly/wiki/Loops#repeat"; Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_UNTIL = "répéter jusqu’à"; Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_WHILE = "répéter tant que"; Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL = "Tant qu’une valeur est fausse, alors exécuter des instructions."; Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_WHILE = "Tant qu’une valeur est vraie, alors exécuter des instructions."; Blockly.Msg.DELETE_ALL_BLOCKS = "Supprimer ces %1 blocs ?"; Blockly.Msg.DELETE_BLOCK = "Supprimer le bloc"; Blockly.Msg.DELETE_X_BLOCKS = "Supprimer %1 blocs"; Blockly.Msg.DISABLE_BLOCK = "Désactiver le bloc"; Blockly.Msg.DUPLICATE_BLOCK = "Dupliquer"; Blockly.Msg.ENABLE_BLOCK = "Activer le bloc"; Blockly.Msg.EXPAND_ALL = "Développer les blocs"; Blockly.Msg.EXPAND_BLOCK = "Développer le bloc"; Blockly.Msg.EXTERNAL_INPUTS = "Entrées externes"; Blockly.Msg.HELP = "Aide"; Blockly.Msg.INLINE_INPUTS = "Entrées en ligne"; Blockly.Msg.LISTS_CREATE_EMPTY_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-empty-list"; Blockly.Msg.LISTS_CREATE_EMPTY_TITLE = "créer une liste vide"; Blockly.Msg.LISTS_CREATE_EMPTY_TOOLTIP = "Renvoyer une liste, de longueur 0, ne contenant aucun enregistrement"; Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD = "liste"; Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP = "Ajouter, supprimer, ou réordonner les sections pour reconfigurer ce bloc de liste."; Blockly.Msg.LISTS_CREATE_WITH_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-list-with"; Blockly.Msg.LISTS_CREATE_WITH_INPUT_WITH = "créer une liste avec"; Blockly.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP = "Ajouter un élément à la liste."; Blockly.Msg.LISTS_CREATE_WITH_TOOLTIP = "Créer une liste avec un nombre quelconque d’éléments."; Blockly.Msg.LISTS_GET_INDEX_FIRST = "premier"; Blockly.Msg.LISTS_GET_INDEX_FROM_END = "# depuis la fin"; Blockly.Msg.LISTS_GET_INDEX_FROM_START = "#"; Blockly.Msg.LISTS_GET_INDEX_GET = "obtenir"; Blockly.Msg.LISTS_GET_INDEX_GET_REMOVE = "obtenir et supprimer"; Blockly.Msg.LISTS_GET_INDEX_LAST = "dernier"; Blockly.Msg.LISTS_GET_INDEX_RANDOM = "aléatoire"; Blockly.Msg.LISTS_GET_INDEX_REMOVE = "supprimer"; Blockly.Msg.LISTS_GET_INDEX_TAIL = ""; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST = "Renvoie le premier élément dans une liste."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM_END = "Renvoie l’élément à la position indiquée dans une liste. #1 est le dernier élément."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM_START = "Renvoie l’élément à la position indiquée dans une liste. #1 est le premier élément."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST = "Renvoie le dernier élément dans une liste."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM = "Renvoie un élément au hasard dans une liste."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST = "Supprime et renvoie le premier élément dans une liste."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM_END = "Supprime et renvoie l’élément à la position indiquée dans une liste. #1 est le dernier élément."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM_START = "Supprime et renvoie l’élément à la position indiquée dans une liste. #1 est le premier élément."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST = "Supprime et renvoie le dernier élément dans une liste."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM = "Supprime et renvoie un élément au hasard dans une liste."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST = "Supprime le premier élément dans une liste."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM_END = "Supprime l’élément à la position indiquée dans une liste. #1 est le dernier élément."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM_START = "Supprime l’élément à la position indiquée dans une liste. #1 est le premier élément."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST = "Supprime le dernier élément dans une liste."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM = "Supprime un élément au hasard dans une liste."; Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_END = "jusqu’à # depuis la fin"; Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_START = "jusqu’à #"; Blockly.Msg.LISTS_GET_SUBLIST_END_LAST = "jusqu’à la fin"; Blockly.Msg.LISTS_GET_SUBLIST_HELPURL = "https://github.com/google/blockly/wiki/Lists#getting-a-sublist"; Blockly.Msg.LISTS_GET_SUBLIST_START_FIRST = "obtenir la sous-liste depuis le début"; Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_END = "obtenir la sous-liste depuis # depuis la fin"; Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_START = "obtenir la sous-liste depuis #"; Blockly.Msg.LISTS_GET_SUBLIST_TAIL = ""; Blockly.Msg.LISTS_GET_SUBLIST_TOOLTIP = "Crée une copie de la partie spécifiée d’une liste."; Blockly.Msg.LISTS_INDEX_OF_FIRST = "trouver la première occurrence de l’élément"; Blockly.Msg.LISTS_INDEX_OF_HELPURL = "https://github.com/google/blockly/wiki/Lists#getting-items-from-a-list"; Blockly.Msg.LISTS_INDEX_OF_LAST = "trouver la dernière occurrence de l’élément"; Blockly.Msg.LISTS_INDEX_OF_TOOLTIP = "Renvoie l’index de la première/dernière occurrence de l’élément dans la liste. Renvoie 0 si l'élément n'est pas trouvé."; Blockly.Msg.LISTS_INLIST = "dans la liste"; Blockly.Msg.LISTS_ISEMPTY_HELPURL = "https://github.com/google/blockly/wiki/Lists#is-empty"; Blockly.Msg.LISTS_ISEMPTY_TITLE = "%1 est vide"; Blockly.Msg.LISTS_ISEMPTY_TOOLTIP = "Renvoie vrai si la liste est vide."; Blockly.Msg.LISTS_LENGTH_HELPURL = "https://github.com/google/blockly/wiki/Lists#length-of"; Blockly.Msg.LISTS_LENGTH_TITLE = "longueur de %1"; Blockly.Msg.LISTS_LENGTH_TOOLTIP = "Renvoie la longueur d’une liste."; Blockly.Msg.LISTS_REPEAT_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-list-with"; Blockly.Msg.LISTS_REPEAT_TITLE = "créer une liste avec l’élément %1 répété %2 fois"; Blockly.Msg.LISTS_REPEAT_TOOLTIP = "Crée une liste consistant en la valeur fournie répétée le nombre de fois indiqué."; Blockly.Msg.LISTS_SET_INDEX_HELPURL = "https://github.com/google/blockly/wiki/Lists#in-list--set"; Blockly.Msg.LISTS_SET_INDEX_INPUT_TO = "comme"; Blockly.Msg.LISTS_SET_INDEX_INSERT = "insérer en"; Blockly.Msg.LISTS_SET_INDEX_SET = "mettre"; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST = "Insère l’élément au début d’une liste."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM_END = "Insère l’élément à la position indiquée dans une liste. #1 est le dernier élément."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM_START = "Insère l’élément à la position indiquée dans une liste. #1 est le premier élément."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST = "Ajouter l’élément à la fin d’une liste."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM = "Insère l’élément au hasard dans une liste."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST = "Fixe le premier élément dans une liste."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM_END = "Fixe l’élément à la position indiquée dans une liste. #1 est le dernier élément."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM_START = "Fixe l’élément à la position indiquée dans une liste. #1 est le premier élément."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST = "Fixe le dernier élément dans une liste."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM = "Fixe un élément au hasard dans une liste."; Blockly.Msg.LISTS_SORT_HELPURL = "https://github.com/google/blockly/wiki/Lists#sorting-a-list"; Blockly.Msg.LISTS_SORT_ORDER_ASCENDING = "croissant"; Blockly.Msg.LISTS_SORT_ORDER_DESCENDING = "décroissant"; Blockly.Msg.LISTS_SORT_TITLE = "trier %1 %2 %3"; Blockly.Msg.LISTS_SORT_TOOLTIP = "Trier une copie d’une liste."; Blockly.Msg.LISTS_SORT_TYPE_IGNORECASE = "alphabétique, en ignorant la casse"; Blockly.Msg.LISTS_SORT_TYPE_NUMERIC = "numérique"; Blockly.Msg.LISTS_SORT_TYPE_TEXT = "alphabétique"; Blockly.Msg.LISTS_SPLIT_HELPURL = "https://github.com/google/blockly/wiki/Lists#splitting-strings-and-joining-lists"; Blockly.Msg.LISTS_SPLIT_LIST_FROM_TEXT = "créer une liste depuis le texte"; Blockly.Msg.LISTS_SPLIT_TEXT_FROM_LIST = "créer un texte depuis la liste"; Blockly.Msg.LISTS_SPLIT_TOOLTIP_JOIN = "Réunir une liste de textes en un seul, en les séparant par un séparateur."; Blockly.Msg.LISTS_SPLIT_TOOLTIP_SPLIT = "Couper un texte en une liste de textes, en coupant à chaque séparateur."; Blockly.Msg.LISTS_SPLIT_WITH_DELIMITER = "avec le séparateur"; Blockly.Msg.LOGIC_BOOLEAN_FALSE = "faux"; Blockly.Msg.LOGIC_BOOLEAN_HELPURL = "https://github.com/google/blockly/wiki/Logic#values"; Blockly.Msg.LOGIC_BOOLEAN_TOOLTIP = "Renvoie soit vrai soit faux."; Blockly.Msg.LOGIC_BOOLEAN_TRUE = "vrai"; Blockly.Msg.LOGIC_COMPARE_HELPURL = "https://fr.wikipedia.org/wiki/Inegalite_(mathematiques)"; Blockly.Msg.LOGIC_COMPARE_TOOLTIP_EQ = "Renvoyer vrai si les deux entrées sont égales."; Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GT = "Renvoyer vrai si la première entrée est plus grande que la seconde."; Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GTE = "Renvoyer vrai si la première entrée est plus grande ou égale à la seconde."; Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LT = "Renvoyer vrai si la première entrée est plus petite que la seconde."; Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LTE = "Renvoyer vrai si la première entrée est plus petite ou égale à la seconde."; Blockly.Msg.LOGIC_COMPARE_TOOLTIP_NEQ = "Renvoyer vrai si les deux entrées sont différentes."; Blockly.Msg.LOGIC_NEGATE_HELPURL = "https://github.com/google/blockly/wiki/Logic#not"; Blockly.Msg.LOGIC_NEGATE_TITLE = "pas %1"; Blockly.Msg.LOGIC_NEGATE_TOOLTIP = "Renvoie vrai si l’entrée est fausse. Renvoie faux si l’entrée est vraie."; Blockly.Msg.LOGIC_NULL = "nul"; Blockly.Msg.LOGIC_NULL_HELPURL = "https://en.wikipedia.org/wiki/Nullable_type"; Blockly.Msg.LOGIC_NULL_TOOLTIP = "Renvoie nul."; Blockly.Msg.LOGIC_OPERATION_AND = "et"; Blockly.Msg.LOGIC_OPERATION_HELPURL = "https://github.com/google/blockly/wiki/Logic#logical-operations"; Blockly.Msg.LOGIC_OPERATION_OR = "ou"; Blockly.Msg.LOGIC_OPERATION_TOOLTIP_AND = "Renvoyer vrai si les deux entrées sont vraies."; Blockly.Msg.LOGIC_OPERATION_TOOLTIP_OR = "Renvoyer vrai si au moins une des entrées est vraie."; Blockly.Msg.LOGIC_TERNARY_CONDITION = "test"; Blockly.Msg.LOGIC_TERNARY_HELPURL = "https://en.wikipedia.org/wiki/%3F:"; Blockly.Msg.LOGIC_TERNARY_IF_FALSE = "si faux"; Blockly.Msg.LOGIC_TERNARY_IF_TRUE = "si vrai"; Blockly.Msg.LOGIC_TERNARY_TOOLTIP = "Vérifier la condition dans 'test'. Si elle est vraie, renvoie la valeur 'si vrai' ; sinon renvoie la valeur 'si faux'."; Blockly.Msg.MATH_ADDITION_SYMBOL = "+"; Blockly.Msg.MATH_ARITHMETIC_HELPURL = "https://fr.wikipedia.org/wiki/Arithmetique"; Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_ADD = "Renvoie la somme des deux nombres."; Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE = "Renvoie le quotient des deux nombres."; Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS = "Renvoie la différence des deux nombres."; Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY = "Renvoie le produit des deux nombres."; Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_POWER = "Renvoie le premier nombre élevé à la puissance du second."; Blockly.Msg.MATH_CHANGE_HELPURL = "https://en.wikipedia.org/wiki/Programming_idiom#Incrementing_a_counter"; Blockly.Msg.MATH_CHANGE_TITLE = "incrémenter %1 de %2"; Blockly.Msg.MATH_CHANGE_TOOLTIP = "Ajouter un nombre à la variable '%1'."; Blockly.Msg.MATH_CONSTANT_HELPURL = "https://en.wikipedia.org/wiki/Mathematical_constant"; Blockly.Msg.MATH_CONSTANT_TOOLTIP = "Renvoie une des constantes courantes : π (3.141…), e (2.718…), φ (1.618…), sqrt(2) (1.414…), sqrt(½) (0.707…), ou ∞ (infini)."; Blockly.Msg.MATH_CONSTRAIN_HELPURL = "https://en.wikipedia.org/wiki/Clamping_%28graphics%29"; Blockly.Msg.MATH_CONSTRAIN_TITLE = "contraindre %1 entre %2 et %3"; Blockly.Msg.MATH_CONSTRAIN_TOOLTIP = "Contraindre un nombre à être entre les limites spécifiées (incluses)."; Blockly.Msg.MATH_DIVISION_SYMBOL = "÷"; Blockly.Msg.MATH_IS_DIVISIBLE_BY = "est divisible par"; Blockly.Msg.MATH_IS_EVEN = "est pair"; Blockly.Msg.MATH_IS_NEGATIVE = "est négatif"; Blockly.Msg.MATH_IS_ODD = "est impair"; Blockly.Msg.MATH_IS_POSITIVE = "est positif"; Blockly.Msg.MATH_IS_PRIME = "est premier"; Blockly.Msg.MATH_IS_TOOLTIP = "Vérifier si un nombre est pair, impair, premier, entier, positif, négatif, ou s’il est divisible par un certain nombre. Renvoie vrai ou faux."; Blockly.Msg.MATH_IS_WHOLE = "est entier"; Blockly.Msg.MATH_MODULO_HELPURL = "https://en.wikipedia.org/wiki/Modulo_operation"; Blockly.Msg.MATH_MODULO_TITLE = "reste de %1 ÷ %2"; Blockly.Msg.MATH_MODULO_TOOLTIP = "Renvoyer le reste de la division euclidienne des deux nombres."; Blockly.Msg.MATH_MULTIPLICATION_SYMBOL = "×"; Blockly.Msg.MATH_NUMBER_HELPURL = "https://fr.wikipedia.org/wiki/Nombre"; Blockly.Msg.MATH_NUMBER_TOOLTIP = "Un nombre."; Blockly.Msg.MATH_ONLIST_HELPURL = ""; Blockly.Msg.MATH_ONLIST_OPERATOR_AVERAGE = "moyenne de la liste"; Blockly.Msg.MATH_ONLIST_OPERATOR_MAX = "maximum de la liste"; Blockly.Msg.MATH_ONLIST_OPERATOR_MEDIAN = "médiane de la liste"; Blockly.Msg.MATH_ONLIST_OPERATOR_MIN = "minimum de la liste"; Blockly.Msg.MATH_ONLIST_OPERATOR_MODE = "majoritaires de la liste"; Blockly.Msg.MATH_ONLIST_OPERATOR_RANDOM = "élément aléatoire de la liste"; Blockly.Msg.MATH_ONLIST_OPERATOR_STD_DEV = "écart-type de la liste"; Blockly.Msg.MATH_ONLIST_OPERATOR_SUM = "somme de la liste"; Blockly.Msg.MATH_ONLIST_TOOLTIP_AVERAGE = "Renvoyer la moyenne (arithmétique) des valeurs numériques dans la liste."; Blockly.Msg.MATH_ONLIST_TOOLTIP_MAX = "Renvoyer le plus grand nombre dans la liste."; Blockly.Msg.MATH_ONLIST_TOOLTIP_MEDIAN = "Renvoyer le nombre médian de la liste."; Blockly.Msg.MATH_ONLIST_TOOLTIP_MIN = "Renvoyer le plus petit nombre dans la liste."; Blockly.Msg.MATH_ONLIST_TOOLTIP_MODE = "Renvoyer une liste des élément(s) le(s) plus courant(s) dans la liste."; Blockly.Msg.MATH_ONLIST_TOOLTIP_RANDOM = "Renvoyer un élément dans la liste au hasard."; Blockly.Msg.MATH_ONLIST_TOOLTIP_STD_DEV = "Renvoyer l’écart-type de la liste."; Blockly.Msg.MATH_ONLIST_TOOLTIP_SUM = "Renvoyer la somme de tous les nombres dans la liste."; Blockly.Msg.MATH_POWER_SYMBOL = "^"; Blockly.Msg.MATH_RANDOM_FLOAT_HELPURL = "https://en.wikipedia.org/wiki/Random_number_generation"; Blockly.Msg.MATH_RANDOM_FLOAT_TITLE_RANDOM = "fraction aléatoire"; Blockly.Msg.MATH_RANDOM_FLOAT_TOOLTIP = "Renvoyer une fraction aléatoire entre 0.0 (inclus) et 1.0 (exclus)."; Blockly.Msg.MATH_RANDOM_INT_HELPURL = "https://en.wikipedia.org/wiki/Random_number_generation"; Blockly.Msg.MATH_RANDOM_INT_TITLE = "entier aléatoire entre %1 et %2"; Blockly.Msg.MATH_RANDOM_INT_TOOLTIP = "Renvoyer un entier aléatoire entre les deux limites spécifiées, incluses."; Blockly.Msg.MATH_ROUND_HELPURL = "https://en.wikipedia.org/wiki/Rounding"; Blockly.Msg.MATH_ROUND_OPERATOR_ROUND = "arrondir"; Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDDOWN = "arrondir par défaut"; Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDUP = "arrondir par excès"; Blockly.Msg.MATH_ROUND_TOOLTIP = "Arrondir un nombre au-dessus ou au-dessous."; Blockly.Msg.MATH_SINGLE_HELPURL = "https://fr.wikipedia.org/wiki/Racine_carree"; Blockly.Msg.MATH_SINGLE_OP_ABSOLUTE = "valeur absolue"; Blockly.Msg.MATH_SINGLE_OP_ROOT = "racine carrée"; Blockly.Msg.MATH_SINGLE_TOOLTIP_ABS = "Renvoie la valeur absolue d’un nombre."; Blockly.Msg.MATH_SINGLE_TOOLTIP_EXP = "Renvoie e à la puissance d’un nombre."; Blockly.Msg.MATH_SINGLE_TOOLTIP_LN = "Renvoie le logarithme naturel d’un nombre."; Blockly.Msg.MATH_SINGLE_TOOLTIP_LOG10 = "Renvoie le logarithme base 10 d’un nombre."; Blockly.Msg.MATH_SINGLE_TOOLTIP_NEG = "Renvoie l’opposé d’un nombre"; Blockly.Msg.MATH_SINGLE_TOOLTIP_POW10 = "Renvoie 10 à la puissance d’un nombre."; Blockly.Msg.MATH_SINGLE_TOOLTIP_ROOT = "Renvoie la racine carrée d’un nombre."; Blockly.Msg.MATH_SUBTRACTION_SYMBOL = "-"; Blockly.Msg.MATH_TRIG_ACOS = "acos"; Blockly.Msg.MATH_TRIG_ASIN = "asin"; Blockly.Msg.MATH_TRIG_ATAN = "atan"; Blockly.Msg.MATH_TRIG_COS = "cos"; Blockly.Msg.MATH_TRIG_HELPURL = "https://en.wikipedia.org/wiki/Trigonometric_functions"; Blockly.Msg.MATH_TRIG_SIN = "sin"; Blockly.Msg.MATH_TRIG_TAN = "tan"; Blockly.Msg.MATH_TRIG_TOOLTIP_ACOS = "Renvoie l’arccosinus d’un nombre."; Blockly.Msg.MATH_TRIG_TOOLTIP_ASIN = "Renvoie l’arcsinus d’un nombre."; Blockly.Msg.MATH_TRIG_TOOLTIP_ATAN = "Renvoie l’arctangente d’un nombre."; Blockly.Msg.MATH_TRIG_TOOLTIP_COS = "Renvoie le cosinus d’un angle en degrés (pas en radians)."; Blockly.Msg.MATH_TRIG_TOOLTIP_SIN = "Renvoie le sinus d’un angle en degrés (pas en radians)."; Blockly.Msg.MATH_TRIG_TOOLTIP_TAN = "Renvoie la tangente d’un angle en degrés (pas en radians)."; Blockly.Msg.ME = "Moi"; Blockly.Msg.NEW_VARIABLE = "Nouvelle variable…"; Blockly.Msg.NEW_VARIABLE_TITLE = "Nouveau nom de la variable :"; Blockly.Msg.ORDINAL_NUMBER_SUFFIX = ""; Blockly.Msg.PROCEDURES_ALLOW_STATEMENTS = "autoriser les ordres"; Blockly.Msg.PROCEDURES_BEFORE_PARAMS = "avec :"; Blockly.Msg.PROCEDURES_CALLNORETURN_HELPURL = "http://fr.wikipedia.org/wiki/Proc%C3%A9dure_%28informatique%29"; Blockly.Msg.PROCEDURES_CALLNORETURN_TOOLTIP = "Exécuter la fonction '%1' définie par l’utilisateur."; Blockly.Msg.PROCEDURES_CALLRETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; Blockly.Msg.PROCEDURES_CALLRETURN_TOOLTIP = "Exécuter la fonction '%1' définie par l’utilisateur et utiliser son résultat."; Blockly.Msg.PROCEDURES_CALL_BEFORE_PARAMS = "avec :"; Blockly.Msg.PROCEDURES_CREATE_DO = "Créer '%1'"; Blockly.Msg.PROCEDURES_DEFNORETURN_COMMENT = "Décrire cette fonction…"; Blockly.Msg.PROCEDURES_DEFNORETURN_DO = ""; Blockly.Msg.PROCEDURES_DEFNORETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE = "faire quelque chose"; Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE = "pour"; Blockly.Msg.PROCEDURES_DEFNORETURN_TOOLTIP = "Crée une fonction sans sortie."; Blockly.Msg.PROCEDURES_DEFRETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; Blockly.Msg.PROCEDURES_DEFRETURN_RETURN = "retour"; Blockly.Msg.PROCEDURES_DEFRETURN_TOOLTIP = "Crée une fonction avec une sortie."; Blockly.Msg.PROCEDURES_DEF_DUPLICATE_WARNING = "Attention : Cette fonction a des paramètres en double."; Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF = "Surligner la définition de la fonction"; Blockly.Msg.PROCEDURES_IFRETURN_HELPURL = "http://c2.com/cgi/wiki?GuardClause"; Blockly.Msg.PROCEDURES_IFRETURN_TOOLTIP = "Si une valeur est vraie, alors renvoyer une seconde valeur."; Blockly.Msg.PROCEDURES_IFRETURN_WARNING = "Attention : Ce bloc pourrait n’être utilisé que dans une définition de fonction."; Blockly.Msg.PROCEDURES_MUTATORARG_TITLE = "nom de l’entrée :"; Blockly.Msg.PROCEDURES_MUTATORARG_TOOLTIP = "Ajouter une entrée à la fonction."; Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TITLE = "entrées"; Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP = "Ajouter, supprimer, ou réarranger les entrées de cette fonction."; Blockly.Msg.REDO = "Refaire"; Blockly.Msg.REMOVE_COMMENT = "Supprimer un commentaire"; Blockly.Msg.RENAME_VARIABLE = "Renommer la variable…"; Blockly.Msg.RENAME_VARIABLE_TITLE = "Renommer toutes les variables « %1 » en :"; Blockly.Msg.TEXT_APPEND_APPENDTEXT = "ajouter le texte"; Blockly.Msg.TEXT_APPEND_HELPURL = "https://github.com/google/blockly/wiki/Text#text-modification"; Blockly.Msg.TEXT_APPEND_TO = "à"; Blockly.Msg.TEXT_APPEND_TOOLTIP = "Ajouter du texte à la variable '%1'."; Blockly.Msg.TEXT_CHANGECASE_HELPURL = "https://github.com/google/blockly/wiki/Text#adjusting-text-case"; Blockly.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE = "en minuscules"; Blockly.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE = "en Majuscule Au Début De Chaque Mot"; Blockly.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE = "en MAJUSCULES"; Blockly.Msg.TEXT_CHANGECASE_TOOLTIP = "Renvoyer une copie du texte dans une autre casse."; Blockly.Msg.TEXT_CHARAT_FIRST = "obtenir la première lettre"; Blockly.Msg.TEXT_CHARAT_FROM_END = "obtenir la lettre # depuis la fin"; Blockly.Msg.TEXT_CHARAT_FROM_START = "obtenir la lettre #"; Blockly.Msg.TEXT_CHARAT_HELPURL = "https://github.com/google/blockly/wiki/Text#extracting-text"; Blockly.Msg.TEXT_CHARAT_INPUT_INTEXT = "dans le texte"; Blockly.Msg.TEXT_CHARAT_LAST = "obtenir la dernière lettre"; Blockly.Msg.TEXT_CHARAT_RANDOM = "obtenir une lettre au hasard"; Blockly.Msg.TEXT_CHARAT_TAIL = ""; Blockly.Msg.TEXT_CHARAT_TOOLTIP = "Renvoie la lettre à la position indiquée."; Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TOOLTIP = "Ajouter un élément au texte."; Blockly.Msg.TEXT_CREATE_JOIN_TITLE_JOIN = "joindre"; Blockly.Msg.TEXT_CREATE_JOIN_TOOLTIP = "Ajouter, supprimer, ou réordonner des sections pour reconfigurer ce bloc de texte."; Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_END = "jusqu’à la lettre # depuis la fin"; Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_START = "jusqu’à la lettre #"; Blockly.Msg.TEXT_GET_SUBSTRING_END_LAST = "jusqu’à la dernière lettre"; Blockly.Msg.TEXT_GET_SUBSTRING_HELPURL = "https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text"; Blockly.Msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT = "dans le texte"; Blockly.Msg.TEXT_GET_SUBSTRING_START_FIRST = "obtenir la sous-chaîne depuis la première lettre"; Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_END = "obtenir la sous-chaîne depuis la lettre # depuis la fin"; Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_START = "obtenir la sous-chaîne depuis la lettre #"; Blockly.Msg.TEXT_GET_SUBSTRING_TAIL = ""; Blockly.Msg.TEXT_GET_SUBSTRING_TOOLTIP = "Renvoie une partie indiquée du texte."; Blockly.Msg.TEXT_INDEXOF_HELPURL = "https://github.com/google/blockly/wiki/Text#finding-text"; Blockly.Msg.TEXT_INDEXOF_INPUT_INTEXT = "dans le texte"; Blockly.Msg.TEXT_INDEXOF_OPERATOR_FIRST = "trouver la première occurrence de la chaîne"; Blockly.Msg.TEXT_INDEXOF_OPERATOR_LAST = "trouver la dernière occurrence de la chaîne"; Blockly.Msg.TEXT_INDEXOF_TAIL = ""; Blockly.Msg.TEXT_INDEXOF_TOOLTIP = "Renvoie l’index de la première/dernière occurrence de la première chaîne dans la seconde. Renvoie 0 si la chaîne n’est pas trouvée."; Blockly.Msg.TEXT_ISEMPTY_HELPURL = "https://github.com/google/blockly/wiki/Text#checking-for-empty-text"; Blockly.Msg.TEXT_ISEMPTY_TITLE = "%1 est vide"; Blockly.Msg.TEXT_ISEMPTY_TOOLTIP = "Renvoie vrai si le texte fourni est vide."; Blockly.Msg.TEXT_JOIN_HELPURL = "https://github.com/google/blockly/wiki/Text#text-creation"; Blockly.Msg.TEXT_JOIN_TITLE_CREATEWITH = "créer un texte avec"; Blockly.Msg.TEXT_JOIN_TOOLTIP = "Créer un morceau de texte en agrégeant un nombre quelconque d’éléments."; Blockly.Msg.TEXT_LENGTH_HELPURL = "https://github.com/google/blockly/wiki/Text#text-modification"; Blockly.Msg.TEXT_LENGTH_TITLE = "longueur de %1"; Blockly.Msg.TEXT_LENGTH_TOOLTIP = "Renvoie le nombre de lettres (espaces compris) dans le texte fourni."; Blockly.Msg.TEXT_PRINT_HELPURL = "https://github.com/google/blockly/wiki/Text#printing-text"; Blockly.Msg.TEXT_PRINT_TITLE = "afficher %1"; Blockly.Msg.TEXT_PRINT_TOOLTIP = "Afficher le texte, le nombre ou une autre valeur spécifié."; Blockly.Msg.TEXT_PROMPT_HELPURL = "https://github.com/google/blockly/wiki/Text#getting-input-from-the-user"; Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER = "Demander un nombre à l’utilisateur."; Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT = "Demander un texte à l’utilisateur."; Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER = "invite pour un nombre avec un message"; Blockly.Msg.TEXT_PROMPT_TYPE_TEXT = "invite pour un texte avec un message"; Blockly.Msg.TEXT_TEXT_HELPURL = "https://en.wikipedia.org/wiki/String_(computer_science)"; Blockly.Msg.TEXT_TEXT_TOOLTIP = "Une lettre, un mot ou une ligne de texte."; Blockly.Msg.TEXT_TRIM_HELPURL = "https://github.com/google/blockly/wiki/Text#trimming-removing-spaces"; Blockly.Msg.TEXT_TRIM_OPERATOR_BOTH = "supprimer les espaces des deux côtés"; Blockly.Msg.TEXT_TRIM_OPERATOR_LEFT = "supprimer les espaces du côté gauche"; Blockly.Msg.TEXT_TRIM_OPERATOR_RIGHT = "supprimer les espaces du côté droit"; Blockly.Msg.TEXT_TRIM_TOOLTIP = "Renvoyer une copie du texte avec les espaces supprimés d’un bout ou des deux."; Blockly.Msg.TODAY = "Aujourd'hui"; Blockly.Msg.UNDO = "Annuler"; Blockly.Msg.VARIABLES_DEFAULT_NAME = "élément"; Blockly.Msg.VARIABLES_GET_CREATE_SET = "Créer 'fixer %1'"; Blockly.Msg.VARIABLES_GET_HELPURL = "https://github.com/google/blockly/wiki/Variables#get"; Blockly.Msg.VARIABLES_GET_TOOLTIP = "Renvoie la valeur de cette variable."; Blockly.Msg.VARIABLES_SET = "fixer %1 à %2"; Blockly.Msg.VARIABLES_SET_CREATE_GET = "Créer 'obtenir %1'"; Blockly.Msg.VARIABLES_SET_HELPURL = "https://github.com/google/blockly/wiki/Variables#set"; Blockly.Msg.VARIABLES_SET_TOOLTIP = "Fixe cette variable pour qu’elle soit égale à la valeur de l’entrée."; Blockly.Msg.MATH_CHANGE_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME; Blockly.Msg.PROCEDURES_DEFRETURN_TITLE = Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE; Blockly.Msg.CONTROLS_IF_IF_TITLE_IF = Blockly.Msg.CONTROLS_IF_MSG_IF; Blockly.Msg.CONTROLS_WHILEUNTIL_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO; Blockly.Msg.CONTROLS_IF_MSG_THEN = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO; Blockly.Msg.CONTROLS_IF_ELSE_TITLE_ELSE = Blockly.Msg.CONTROLS_IF_MSG_ELSE; Blockly.Msg.PROCEDURES_DEFRETURN_PROCEDURE = Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE; Blockly.Msg.LISTS_GET_SUBLIST_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST; Blockly.Msg.LISTS_GET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST; Blockly.Msg.PROCEDURES_DEFRETURN_DO = Blockly.Msg.PROCEDURES_DEFNORETURN_DO; Blockly.Msg.CONTROLS_IF_ELSEIF_TITLE_ELSEIF = Blockly.Msg.CONTROLS_IF_MSG_ELSEIF; Blockly.Msg.LISTS_GET_INDEX_HELPURL = Blockly.Msg.LISTS_INDEX_OF_HELPURL; Blockly.Msg.CONTROLS_FOREACH_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO; Blockly.Msg.LISTS_SET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST; Blockly.Msg.CONTROLS_FOR_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO; Blockly.Msg.LISTS_CREATE_WITH_ITEM_TITLE = Blockly.Msg.VARIABLES_DEFAULT_NAME; Blockly.Msg.TEXT_APPEND_VARIABLE = Blockly.Msg.VARIABLES_DEFAULT_NAME; Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME; Blockly.Msg.LISTS_INDEX_OF_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST; Blockly.Msg.PROCEDURES_DEFRETURN_COMMENT = Blockly.Msg.PROCEDURES_DEFNORETURN_COMMENT; // Ardublockly strings Blockly.Msg.ARD_ANALOGREAD = "Lecture du signal analogique #"; Blockly.Msg.ARD_ANALOGREAD_TIP = "Valeur de retour entre 0 et 1024"; Blockly.Msg.ARD_ANALOGWRITE = "Ecriture du signal analogique #"; Blockly.Msg.ARD_ANALOGWRITE_TIP = "Ecrit une valeur analogique comprise entre 0 et 255 sur un port PWM spécifique"; Blockly.Msg.ARD_BUILTIN_LED = "Configurer la DEL"; Blockly.Msg.ARD_BUILTIN_LED_TIP = "Allumer ou éteindre la DEL de la carte"; Blockly.Msg.ARD_COMPONENT_WARN1 = "A %1 configuration block with the same %2 name must be added to use this block!"; // untranslated Blockly.Msg.ARD_DEFINE = "Définir"; Blockly.Msg.ARD_DIGITALREAD = "Lecture du signal numérique #"; Blockly.Msg.ARD_DIGITALREAD_TIP = "Lecture de la valeur d'un signal numérique: HAUT ou BAS"; Blockly.Msg.ARD_DIGITALWRITE = "Configuration du signal numérique #"; Blockly.Msg.ARD_DIGITALWRITE_TIP = " Ecriture de la valeur HAUT ou BAS du signal numérique #"; Blockly.Msg.ARD_FUN_RUN_LOOP = "Arduino boucle infinie:"; Blockly.Msg.ARD_FUN_RUN_SETUP = "Arduino exécute en premier:"; Blockly.Msg.ARD_FUN_RUN_TIP = "Definition de la configuration de l'Arduino: fonctions setup() et loop()."; Blockly.Msg.ARD_HIGH = "HAUT"; Blockly.Msg.ARD_HIGHLOW_TIP = " Configuration d'un signal à l'état HAUT ou BAS"; Blockly.Msg.ARD_LOW = "BAS"; Blockly.Msg.ARD_MAP = "Converti"; Blockly.Msg.ARD_MAP_TIP = "Converti un nombre de la plage [0-1024]."; Blockly.Msg.ARD_MAP_VAL = "valeur de [0-"; Blockly.Msg.ARD_NOTONE = "Eteindre la tonalité du signal #"; Blockly.Msg.ARD_NOTONE_PIN = "PAS de Signal de tonalité #"; Blockly.Msg.ARD_NOTONE_PIN_TIP = "Arret de la génération de tonalité (son)sur un signal"; Blockly.Msg.ARD_NOTONE_TIP = "Eteindre / Activer la tonalité du signal selectioné"; Blockly.Msg.ARD_PIN_WARN1 = "Signal %1 est utilisé pour %2 alors que signal %3. Déjà utilisé en tant que %4."; Blockly.Msg.ARD_PULSETIMEOUT_TIP = "Mesure la durée d'une pulsation sur le signal selectioné, dans le delai imparti"; Blockly.Msg.ARD_PULSE_READ = "mesure %1 impulsion sur le signal #%2"; Blockly.Msg.ARD_PULSE_READ_TIMEOUT = "mesure %1 impulsion sur le signal #%2 (délai de retard %3 μs)"; Blockly.Msg.ARD_PULSE_TIP = "Mesure la durée d'une pulsation sur le signal selectioné."; Blockly.Msg.ARD_SERIAL_BPS = "bps"; Blockly.Msg.ARD_SERIAL_PRINT = "imprimer"; Blockly.Msg.ARD_SERIAL_PRINT_NEWLINE = "ajouter une nouvelle ligne"; Blockly.Msg.ARD_SERIAL_PRINT_TIP = "Imprime les données sur la console série en texte lisible ASCII."; Blockly.Msg.ARD_SERIAL_PRINT_WARN = "Un bloc de configuration pour %1 doit être ajouté à l'espace de travail afin d'utiliser ce bloc!"; Blockly.Msg.ARD_SERIAL_SETUP = "Configuration"; Blockly.Msg.ARD_SERIAL_SETUP_TIP = "Choisir la vitesse d'un périphérique série"; Blockly.Msg.ARD_SERIAL_SPEED = ": vitesse"; Blockly.Msg.ARD_SERVO_READ = "Lecture du signal# du SERVO"; Blockly.Msg.ARD_SERVO_READ_TIP = "Lecture d'un angle du SERVO"; Blockly.Msg.ARD_SERVO_WRITE = "Configurer SERVO sur Patte"; Blockly.Msg.ARD_SERVO_WRITE_DEG_180 = "Degrés (0~180)"; Blockly.Msg.ARD_SERVO_WRITE_TIP = "Configurer un SERVO à un angle donné"; Blockly.Msg.ARD_SERVO_WRITE_TO = "vers"; Blockly.Msg.ARD_SETTONE = "Définir une tonalité sur le signal #"; Blockly.Msg.ARD_SPI_SETUP = "Configuration"; Blockly.Msg.ARD_SPI_SETUP_CONF = "configuration:"; Blockly.Msg.ARD_SPI_SETUP_DIVIDE = "Division de fréquence"; Blockly.Msg.ARD_SPI_SETUP_LSBFIRST = "LSBFIRST"; Blockly.Msg.ARD_SPI_SETUP_MODE = "mode SPI (idle - edge)"; Blockly.Msg.ARD_SPI_SETUP_MODE0 = "0 (Bas - Descendant)"; Blockly.Msg.ARD_SPI_SETUP_MODE1 = "1 (Bas - Montant)"; Blockly.Msg.ARD_SPI_SETUP_MODE2 = "2 (Haut - Descendant)"; Blockly.Msg.ARD_SPI_SETUP_MODE3 = "3 (Haut - Montant)"; Blockly.Msg.ARD_SPI_SETUP_MSBFIRST = "MSBFIRST"; Blockly.Msg.ARD_SPI_SETUP_SHIFT = "décalage de données"; Blockly.Msg.ARD_SPI_SETUP_TIP = "Configuration du périphérique SPI."; Blockly.Msg.ARD_SPI_TRANSRETURN_TIP = "Envoie d'un message SPI à un esclave précis et recuperation de la donnée."; Blockly.Msg.ARD_SPI_TRANS_NONE = "vide"; Blockly.Msg.ARD_SPI_TRANS_SLAVE = "vers le signal esclave"; Blockly.Msg.ARD_SPI_TRANS_TIP = "Envoie d'un message SPI à un esclave précis."; Blockly.Msg.ARD_SPI_TRANS_VAL = "transfert"; Blockly.Msg.ARD_SPI_TRANS_WARN1 = "Un bloc de configuration pour %1 doit être ajouté à l'espace de travail afin d'utiliser ce bloc!"; Blockly.Msg.ARD_SPI_TRANS_WARN2 = "L'ancienne valeur du signal %1 n'est plus disponible."; Blockly.Msg.ARD_STEPPER_COMPONENT = "stepper"; // untranslated Blockly.Msg.ARD_STEPPER_DEFAULT_NAME = "MyStepper"; // untranslated Blockly.Msg.ARD_STEPPER_FOUR_PINS = "4"; Blockly.Msg.ARD_STEPPER_MOTOR = "Moteur pas-à-pas:"; Blockly.Msg.ARD_STEPPER_NUMBER_OF_PINS = "Number of pins"; // untranslated Blockly.Msg.ARD_STEPPER_PIN1 = "signal1 #"; Blockly.Msg.ARD_STEPPER_PIN2 = "signal2 #"; Blockly.Msg.ARD_STEPPER_PIN3 = "signal3 #"; Blockly.Msg.ARD_STEPPER_PIN4 = "signal4 #"; Blockly.Msg.ARD_STEPPER_REVOLVS = "Combien de pas par tour"; Blockly.Msg.ARD_STEPPER_SETUP = "Configuration"; Blockly.Msg.ARD_STEPPER_SETUP_TIP = "Configuration d'un moteur pas-à-pas: signaux et autres paramètres."; Blockly.Msg.ARD_STEPPER_SPEED = "Configuration de la vitesse(rpm) à"; Blockly.Msg.ARD_STEPPER_STEP = "Déplacement grace au moteur pas-à-pas"; Blockly.Msg.ARD_STEPPER_STEPS = "pas"; Blockly.Msg.ARD_STEPPER_STEP_TIP = "Configurer le moteur pas-à-pas avec un nombre précis de pas."; Blockly.Msg.ARD_STEPPER_TWO_PINS = "2"; Blockly.Msg.ARD_TIME_DELAY = "Délai d'attente de"; Blockly.Msg.ARD_TIME_DELAY_MICROS = "microsecondes"; Blockly.Msg.ARD_TIME_DELAY_MICRO_TIP = "Attendre un délai précis en microsecondes"; Blockly.Msg.ARD_TIME_DELAY_TIP = "Attendre un délai précis en millisecondes"; Blockly.Msg.ARD_TIME_INF = "Attente sans fin (fin du programme)"; Blockly.Msg.ARD_TIME_INF_TIP = "Attente indéfinie, arrêt du programme."; Blockly.Msg.ARD_TIME_MICROS = "Temps écoulé (microsecondes)"; Blockly.Msg.ARD_TIME_MICROS_TIP = "Renvoie le temps en microseconds depuis le lancement de ce programme sur la carte Arduino. Doit être stocké dans un Entier long positif"; Blockly.Msg.ARD_TIME_MILLIS = "Temps écoulé (millisecondes)"; Blockly.Msg.ARD_TIME_MILLIS_TIP = "Renvoie le temps en milliseconds depuis le lancement de ce programme sur la carte Arduino. Doit être stocké dans un Entier long positif"; Blockly.Msg.ARD_TIME_MS = "millisecondes"; Blockly.Msg.ARD_TONEFREQ = "à la frequence"; Blockly.Msg.ARD_TONE_FREQ = "frequence"; Blockly.Msg.ARD_TONE_PIN = "Signal de tonalité #"; Blockly.Msg.ARD_TONE_PIN_TIP = "Génération de tonalité (son)sur un signal"; Blockly.Msg.ARD_TONE_TIP = " Configurer le signal de tonalité dans la plage: 31 - 65535"; Blockly.Msg.ARD_TONE_WARNING = "La fréquence doit être dans la plage 31 - 65535"; Blockly.Msg.ARD_TYPE_ARRAY = "Tableau"; Blockly.Msg.ARD_TYPE_BOOL = "Booléen"; Blockly.Msg.ARD_TYPE_CHAR = "Charactère"; Blockly.Msg.ARD_TYPE_CHILDBLOCKMISSING = "Dépendance manquante"; Blockly.Msg.ARD_TYPE_DECIMAL = "Décimal"; Blockly.Msg.ARD_TYPE_LONG = "Entier long"; Blockly.Msg.ARD_TYPE_NULL = "Null"; Blockly.Msg.ARD_TYPE_NUMBER = "Entier"; Blockly.Msg.ARD_TYPE_SHORT = "Entier court"; Blockly.Msg.ARD_TYPE_TEXT = "Texte"; Blockly.Msg.ARD_TYPE_UNDEF = "Non défini"; Blockly.Msg.ARD_VAR_AS = "comme"; Blockly.Msg.ARD_VAR_AS_TIP = "Configure une valeur à un type précis"; Blockly.Msg.ARD_WRITE_TO = "à"; Blockly.Msg.NEW_INSTANCE = "New instance..."; // untranslated Blockly.Msg.NEW_INSTANCE_TITLE = "New instance name:"; // untranslated Blockly.Msg.RENAME_INSTANCE = "Rename instance..."; // untranslated Blockly.Msg.RENAME_INSTANCE_TITLE = "Rename all '%1' instances to:"; // untranslated
carlosperate/ardublockly
blockly/msg/js/fr.js
JavaScript
apache-2.0
39,135
import path from 'path' import chromedriver from 'chromedriver' import webdriver from 'selenium-webdriver' import electronPath from 'electron-prebuilt' import homeStyles from '../app/components/Home.css' import counterStyles from '../app/components/Counter.css' chromedriver.start() // on port 9515 process.on('exit', chromedriver.stop) const delay = time => new Promise(resolve => setTimeout(resolve, time)) describe('main window', function spec() { this.timeout(5000) before(async () => { await delay(1000) // wait chromedriver start time this.driver = new webdriver.Builder() .usingServer('http://localhost:9515') .withCapabilities({ chromeOptions: { binary: electronPath, args: ['app=' + path.resolve()], }, }) .forBrowser('electron') .build() }) after(async () => { await this.driver.quit() }) const findCounter = () => { return this.driver.findElement(webdriver.By.className(counterStyles.counter)) } const findButtons = () => { return this.driver.findElements(webdriver.By.className(counterStyles.btn)) } it('should open window', async () => { const title = await this.driver.getTitle() expect(title).to.equal('Hello Electron React!') }) it('should to Counter with click "to Counter" link', async () => { const link = await this.driver.findElement(webdriver.By.css(`.${homeStyles.container} > a`)) link.click() const counter = await findCounter() expect(await counter.getText()).to.equal('0') }) it('should display updated count after increment button click', async () => { const buttons = await findButtons() buttons[0].click() const counter = await findCounter() expect(await counter.getText()).to.equal('1') }) it('should display updated count after descrement button click', async () => { const buttons = await findButtons() const counter = await findCounter() buttons[1].click() // - expect(await counter.getText()).to.equal('0') }) it('shouldnt change if even and if odd button clicked', async () => { const buttons = await findButtons() const counter = await findCounter() buttons[2].click() // odd expect(await counter.getText()).to.equal('0') }) it('should change if odd and if odd button clicked', async () => { const buttons = await findButtons() const counter = await findCounter() buttons[0].click() // + buttons[2].click() // odd expect(await counter.getText()).to.equal('2') }) it('should change if async button clicked and a second later', async () => { const buttons = await findButtons() const counter = await findCounter() buttons[3].click() // async expect(await counter.getText()).to.equal('2') await this.driver.wait(() => counter.getText().then(text => text === '3') , 1000, 'count not as expected') }) it('should back to home if back button clicked', async () => { const link = await this.driver.findElement(webdriver.By.css(`.${counterStyles.backButton} > a`)) link.click() await this.driver.findElement(webdriver.By.className(homeStyles.container)) }) })
3-strand-code/3sc-desktop
test/e2e.js
JavaScript
apache-2.0
3,188
'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 _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); exports.getMatchedParams = getMatchedParams; exports.getQueryParams = getQueryParams; exports.createRoute = createRoute; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var parametersPattern = /(:[^\/]+)/g; // Some utility functions. Exported just to be able to test them easily function getMatchedParams(route, path) { var matches = path.match(route.matcher); if (!matches) { return false; } return route.params.reduce(function (acc, param, idx) { acc[param] = decodeURIComponent(matches[idx + 1]); return acc; }, {}); }; function getQueryParams(query) { return query.split('&').filter(function (p) { return p.length; }).reduce(function (acc, part) { var _part$split = part.split('='); var _part$split2 = _slicedToArray(_part$split, 2); var key = _part$split2[0]; var value = _part$split2[1]; acc[decodeURIComponent(key)] = decodeURIComponent(value); return acc; }, {}); }; function createRoute(name, path, handler) { var matcher = new RegExp(path.replace(parametersPattern, '([^\/]+)') + '$'); var params = (path.match(parametersPattern) || []).map(function (x) { return x.substring(1); }); return { name: name, path: path, handler: handler, matcher: matcher, params: params }; }; var findRouteParams = function findRouteParams(routes, path) { var params = void 0; var route = routes.find(function (r) { return params = getMatchedParams(r, path); }); return { route: route, params: params }; }; var parseUrl = function parseUrl(url) { var _url$split = url.split('?'); var _url$split2 = _slicedToArray(_url$split, 2); var path = _url$split2[0]; var queryString = _url$split2[1]; return { path: path, queryString: queryString }; }; var stripPrefix = function stripPrefix(url, prefix) { return url.replace(new RegExp('^' + prefix), ''); }; // The actual Router as the default export of the module var Router = function () { function Router() { _classCallCheck(this, Router); this.routes = []; this.prefix = ''; } // Adds a route with an _optional_ name, a path and a handler function _createClass(Router, [{ key: 'add', value: function add(name, path, handler) { if (arguments.length == 2) { this.add.apply(this, [''].concat(Array.prototype.slice.call(arguments))); } else { this.routes.push(createRoute(name, path, handler)); } return this; } }, { key: 'setPrefix', value: function setPrefix(prefix) { this.prefix = prefix; return this; } }, { key: 'dispatch', value: function dispatch(url) { var _parseUrl = parseUrl(stripPrefix(url, this.prefix)); var path = _parseUrl.path; var queryString = _parseUrl.queryString; var query = getQueryParams(queryString || ''); var _findRouteParams = findRouteParams(this.routes, path); var route = _findRouteParams.route; var params = _findRouteParams.params; if (route) { route.handler({ params: params, query: query }); return route; } return false; } }, { key: 'getCurrentRoute', value: function getCurrentRoute(url) { var _parseUrl2 = parseUrl(stripPrefix(url, this.prefix)); var path = _parseUrl2.path; var queryString = _parseUrl2.queryString; var rp = findRouteParams(this.routes, path); return rp && rp.route; } }, { key: 'formatUrl', value: function formatUrl(routeName) { var params = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var query = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; var route = this.routes.find(function (r) { return r.name === routeName; }); if (!route) { return ''; } var queryString = Object.keys(query).map(function (k) { return [k, query[k]]; }).map(function (_ref) { var _ref2 = _slicedToArray(_ref, 2); var k = _ref2[0]; var v = _ref2[1]; return encodeURIComponent(k) + '=' + encodeURIComponent(v); }).join('&'); var path = this.prefix + route.path.replace(parametersPattern, function (match) { return params[match.substring(1)]; }); return queryString.length ? path + '?' + queryString : path; } }]); return Router; }(); exports.default = Router; ;
jmhdez/minimal-router
lib/Router.js
JavaScript
apache-2.0
5,579
/** * 预存费用 */ AcctFeeGrid = Ext.extend(Ext.ux.Grid, { border : false, acctFeeStore : null, region : 'center', pageSize : 10, constructor : function() { this.acctFeeStore = new Ext.data.JsonStore({ url:Constant.ROOT_PATH+ "/commons/x/QueryCust!queryAcctPayFee.action", totalProperty:'totalProperty', root:'records', fields : ['acct_type_text', 'acct_type', 'fee_text','is_logoff','is_doc','is_doc_text', 'fee_type', 'fee_type_text', {name : 'real_pay',type : 'float'}, 'create_time','acct_date','device_code','invoice_mode','invoice_book_id','finance_status', 'invoice_code', 'invoice_id', 'pay_type_text','begin_date','prod_invalid_date', 'pay_type', 'status_text', 'status', 'dept_id','dept_name', 'user_id','user_name', 'user_type_text','fee_sn','optr_id','optr_name', 'OPERATE','busi_code','busi_name','create_done_code','data_right', 'busi_optr_id','busi_optr_name','prod_sn','invoice_fee',"doc_type","doc_type_text","invoice_mode_text","allow_done_code",'count_text'] }); this.acctFeeStore.on("load",this.doOperate); var lc = langUtils.main("pay.payfee.columns"); var cm = new Ext.ux.grid.LockingColumnModel({ columns : [ {header:lc[0],dataIndex:'create_done_code',width:80}, {header:lc[1],dataIndex:'busi_name', width:150,renderer:App.qtipValue}, {header:lc[2],dataIndex:'acct_type_text',width:105,renderer:App.qtipValue}, {header:lc[3],dataIndex:'fee_text',width:150,renderer:App.qtipValue}, {header:lc[4],dataIndex:'user_type_text',width:70}, {header:lc[5],dataIndex:'user_name',width:130,renderer:App.qtipValue}, {header:lc[6],dataIndex:'device_code',width:130,renderer:App.qtipValue}, {header:lc[7],dataIndex:'status_text',width:70,renderer:Ext.util.Format.statusShow}, {header:lc[8],dataIndex:'real_pay',width:60,renderer:Ext.util.Format.formatFee}, {header:lc[9],dataIndex:'begin_date',width:125,renderer:Ext.util.Format.dateFormat}, {header:lc[10],dataIndex:'prod_invalid_date',width:125,renderer:Ext.util.Format.dateFormat}, {header:lc[11],dataIndex:'is_doc_text',width:75,renderer:Ext.util.Format.statusShow}, {header:lc[12],dataIndex:'pay_type_text',width:75, renderer:App.qtipValue}, {header:lc[13],dataIndex:'create_time',width:125}, {header:lc[14],dataIndex:'acct_date',width:125}, {header:lc[15],dataIndex:'optr_name',width:90, renderer:App.qtipValue}, {header:lc[16],dataIndex:'dept_name',width:100, renderer:App.qtipValue}, {header:lc[17],dataIndex:'invoice_id',width:80, renderer:App.qtipValue}, // {header:lc[18],dataIndex:'invoice_mode_text',width:80}, {header:lc[19],dataIndex:'doc_type_text',width:90, renderer:App.qtipValue}, {header:lc[20],dataIndex:'busi_optr_name',width:100, renderer:App.qtipValue} ] }); var pageTbar = new Ext.PagingToolbar({store: this.acctFeeStore ,pageSize : this.pageSize}); AcctFeeGrid.superclass.constructor.call(this, { id:'P_ACCT', title : langUtils.main("pay.payfee._title"), loadMask : true, store : this.acctFeeStore, border : false, bbar: pageTbar, disableSelection:true, view: new Ext.ux.grid.ColumnLockBufferView(), sm : new Ext.grid.RowSelectionModel(), cm : cm, tools:[{id:'search',qtip:'查询',cls:'tip-target',scope:this,handler:function(){ var comp = this.tools.search; if(this.acctFeeStore.getCount()>0){ if(win)win.close(); win = FilterWindow.addComp(this,[ {text:'智能卡号',field:'device_code',type:'textfield'}, {text:'状态',field:'status',showField:'status_text', data:[ {'text':'所有','value':''}, {'text':'已支付','value':'PAY'}, {'text':'失效','value':'INVALID'} ] }, {text:'受理日期',field:'create_time',type:'datefield'}, {text:'受理人',field:'optr_name',type:'textfield'}, {text:'发票号',field:'invoice_id',type:'textfield'} ],700,null,true,"queryFeeInfo"); if(win){ win.setPosition(comp.getX()-win.width, comp.getY()-50);//弹出框右对齐 win.show(); } }else{ Alert('请先查询数据!'); } } }] }); }, initEvents :function(){ this.on("afterrender",function(){ this.swapViews(); },this,{delay:10}); AcctFeeGrid.superclass.initEvents.call(this); }, doOperate:function(){ //不是当前登录人的不能进行“冲正”操作(去掉不符合条件行的“冲正”操作按钮) this.each(function(record){ if(record.get('optr_name') != App.getData().optr['optr_name']){ record.set('OPERATE','F'); } }); this.commitChanges(); }, remoteRefresh : function() { this.refresh(); }, localRefresh : function() { unitRecords = this.getSelectionModel().getSelections(); for (var i in unitRecords) { this.acctFeeStore.remove(unitRecords[i]); } }, refresh:function(){ this.acctFeeStore.baseParams = { residentCustId: App.getData().custFullInfo.cust.cust_id, custStatus : App.data.custFullInfo.cust.status }; // this.acctFeeStore.baseParams['residentCustId'] = App.getData().custFullInfo.cust.cust_id; // this.acctFeeStore.baseParams['custStatus'] = App.data.custFullInfo.cust.status; // this.acctFeeStore.load({params:{start: 0,limit: this.pageSize}}); this.reloadCurrentPage(); } }); /** * 业务费用 */ BusiFeeGrid = Ext.extend(Ext.ux.Grid, { border : false, busiFeeStore : null, region : 'center', pageSize : 10, constructor : function() { this.busiFeeStore = new Ext.data.JsonStore({ url : Constant.ROOT_PATH+ "/commons/x/QueryCust!queryBusiPayFee.action", totalProperty:'totalProperty', root:'records', fields : ['create_done_code','fee_text', 'device_type', 'device_type_text', 'device_code', {name : 'should_pay',type : 'int'},'is_doc','is_doc_text', 'pay_type_text', 'pay_type', 'status_text','dept_name','dept_id', 'status', 'invoice_code', 'invoice_id','invoice_mode', 'optr_id','optr_name', {name : 'real_pay',type : 'int'},'fee_sn','create_time','acct_date','deposit', 'data_right','finance_status','invoice_book_id','is_busi_fee', 'busi_optr_id','busi_optr_name','invoice_fee',"doc_type","doc_type_text", "invoice_mode_text",'buy_num','device_model','device_model_name', 'count_text'] }); var lc = langUtils.main("pay.busifee.columns"); var cm = new Ext.ux.grid.LockingColumnModel({ columns : [ {header:lc[0],dataIndex:'create_done_code',width:80}, {header:lc[1],dataIndex:'fee_text',width:110, renderer:App.qtipValue}, {header:lc[2],dataIndex:'device_type_text',width:80}, {header:lc[16],dataIndex:'device_model_name',width:120, renderer:App.qtipValue}, {header:lc[3],dataIndex:'device_code',width:130, renderer:App.qtipValue}, {header:lc[4],dataIndex:'status_text',width:70,renderer:Ext.util.Format.statusShow}, {header:lc[5],dataIndex:'is_doc_text',width:80,renderer:Ext.util.Format.statusShow}, {header:lc[6],dataIndex:'should_pay',width:60,renderer:Ext.util.Format.formatFee}, {header:lc[7],dataIndex:'real_pay',width:60,renderer:Ext.util.Format.formatFee}, {header:lc[17],dataIndex:'count_text',width:120,renderer:App.qtipValue}, {header:lc[15],dataIndex:'buy_num',width:80}, {header:lc[8],dataIndex:'pay_type_text',width:90, renderer:App.qtipValue}, {header:lc[9],dataIndex:'create_time',width:125}, {header:lc[19],dataIndex:'acct_date',width:125}, {header:lc[10],dataIndex:'optr_name',width:90, renderer:App.qtipValue}, {header:lc[11],dataIndex:'dept_name',width:100, renderer:App.qtipValue}, {header:lc[12],dataIndex:'invoice_id',width:90, renderer:App.qtipValue}, // {header:lc[13],dataIndex:'invoice_mode_text',width:80}, {header:lc[14],dataIndex:'doc_type_text',width:90, renderer:App.qtipValue}, {header:lc[18],dataIndex:'busi_optr_name',width:100, renderer:App.qtipValue} ] }); BusiFeeGrid.superclass.constructor.call(this, { id:'P_BUSI', title : langUtils.main("pay.busifee._title"), loadMask : true, store : this.busiFeeStore, border : false, bbar: new Ext.PagingToolbar({store: this.busiFeeStore ,pageSize : this.pageSize}), sm : new Ext.grid.RowSelectionModel(), view: new Ext.ux.grid.ColumnLockBufferView(), cm : cm, listeners:{ scope:this, delay:10, rowdblclick: this.doDblClickRecord, afterrender: this.swapViews }, tools:[{id:'search',qtip:'查询',cls:'tip-target',scope:this,handler:function(){ var comp = this.tools.search; if(this.busiFeeStore.getCount()>0){ if(win)win.close(); win = FilterWindow.addComp(this,[ {text:'设备类型',field:'device_type',showField:'device_type_text', data:[ {'text':'设备类型','value':''}, {'text':'机顶盒','value':'STB'}, {'text':'智能卡','value':'CARD'}, {'text':'MODEM','value':'MODEM'} ] }, {text:'设备编号',field:'device_code',type:'textfield'}, {text:'受理日期',field:'create_time',type:'datefield'}, {text:'状态',field:'status',showField:'status_text', data:[ {'text':'所有','value':''}, {'text':'已支付','value':'PAY'}, {'text':'失效','value':'INVALID'} ] }, {text:'受理人',field:'optr_name',type:'textfield'}, {text:'发票号',field:'invoice_id',type:'textfield'} ],800,null,true,"queryFeeInfo"); if(win){ win.setPosition(comp.getX()-win.width, comp.getY()-50);//弹出框右对齐 win.show(); } }else{ Alert('请先查询数据!'); } } }] }); }, doDblClickRecord : function(grid, rowIndex, e) { var record = grid.getStore().getAt(rowIndex); }, remoteRefresh : function() { this.refresh(); }, refresh:function(){ /*Ext.Ajax.request({ url : Constant.ROOT_PATH+ "/commons/x/QueryCust!queryBusiPayFee.action", scope:this, params:{ residentCustId:App.getData().custFullInfo.cust.cust_id, custStatus : App.data.custFullInfo.cust.status }, success:function(res,opt){ var data = Ext.decode(res.responseText); //PagingMemoryProxy() 一次性读取数据 this.busiFeeStore.proxy = new Ext.data.PagingMemoryProxy(data), //本地分页 this.busiFeeStore.load({params:{start:0,limit:this.pageSize}}); } });*/ // this.busiFeeStore.baseParams['residentCustId'] = App.getData().custFullInfo.cust.cust_id; this.busiFeeStore.baseParams = { residentCustId: App.getData().custFullInfo.cust.cust_id }; // this.busiFeeStore.load({params:{start: 0,limit: this.pageSize}}); this.reloadCurrentPage(); }, localRefresh : function() { unitRecords = this.getSelectionModel().getSelections(); for (var i in unitRecords) { this.busiFeeStore.remove(unitRecords[i]); } } }); /** * 订单金额明细 */ CfeePayWindow = Ext.extend(Ext.Window, { feeStore:null, constructor: function(){ this.feeStore = new Ext.data.JsonStore({ url : Constant.ROOT_PATH+ "/commons/x/QueryCust!queryFeePayDetail.action", fields: ["real_pay","fee_text","invoice_id","create_done_code"] }) var lc = langUtils.main("pay.feePayDetail.columns"); var columns = [ {header: lc[0], width: 80,sortable:true, dataIndex: 'create_done_code',renderer:App.qtipValue}, {header: lc[1],sortable:true, dataIndex: 'fee_text',renderer:App.qtipValue}, {header: lc[2], width: 70, sortable:true, dataIndex: 'real_pay',renderer:Ext.util.Format.formatFee}, {header: lc[3], width: 80,sortable:true, dataIndex: 'invoice_id',renderer:App.qtipValue} ]; return CfeePayWindow.superclass.constructor.call(this, { layout:"fit", title: langUtils.main("pay.feePayDetail._title"), width: 600, height: 300, resizable: false, maximizable: false, closeAction: 'hide', minimizable: false, items: [{ xtype: 'grid', stripeRows: true, border: false, store: this.feeStore, columns: columns, viewConfig:{forceFit:true}, stateful: true }] }); }, show: function(sn){ this.feeStore.baseParams = { paySn: sn }; this.feeStore.load(); return CfeePayWindow.superclass.show.call(this); } }); FeePayGrid = Ext.extend(Ext.ux.Grid, { feePayStore : null, pageSize : 20, cfeePayWindow:null, feePayData: [], constructor : function() { this.feePayStore = new Ext.data.JsonStore({ url : Constant.ROOT_PATH+ "/commons/x/QueryCust!queryFeePay.action", totalProperty:'totalProperty', root:'records', fields : ['pay_sn','reverse_done_code', 'pay_type', 'pay_type_text', 'done_code', {name : 'usd',type : 'int'},'receipt_id','is_valid_text', 'is_valid', 'payer', 'acct_date','dept_name','dept_id', 'invoice_mode', 'invoice_mode_text', 'remark',{name : 'exchange',type : 'int'}, {name : 'cos',type : 'int'}, 'optr_id','optr_name', {name : 'khr',type : 'int'},'create_time','data_right'] }); var lc = langUtils.main("pay.detail.columns"); var cm = new Ext.ux.grid.LockingColumnModel({ columns : [ {header:lc[0],dataIndex:'pay_sn',width:85,renderer:function(value,metaData,record){ that = this; if(value != ''){ return '<div style="text-decoration:underline;font-weight:bold" onclick="Ext.getCmp(\'P_FEE_PAY\').doTransferFeeShow();" ext:qtitle="" ext:qtip="' + value + '">' + value +'</div>'; }else{ return '<div ext:qtitle="" ext:qtip="' + value + '">' + value +'</div>'; } }}, {header:lc[1],dataIndex:'usd',width:50,renderer:Ext.util.Format.formatFee}, {header:lc[5],dataIndex:'is_valid_text',width:70,renderer:Ext.util.Format.statusShow}, {header:lc[2],dataIndex:'khr',width:50,renderer:Ext.util.Format.formatFee}, {header:lc[3],dataIndex:'exchange',width:70}, {header:lc[4],dataIndex:'cos',width:100,renderer:Ext.util.Format.formatFee}, {header:lc[6],dataIndex:'pay_type_text',width:100}, {header:lc[7],dataIndex:'payer',width:70}, {header:lc[8],dataIndex:'done_code',width:80}, {header:lc[9],dataIndex:'receipt_id',width:100}, // {header:lc[10],dataIndex:'invoice_mode_text',width:80}, {header:lc[11],dataIndex:'create_time',width:125}, {header:lc[12],dataIndex:'optr_name',width:100}, {header:lc[13],dataIndex:'dept_name',width:100} ] }); FeePayGrid.superclass.constructor.call(this, { id:'P_FEE_PAY', title : langUtils.main("pay.detail._title"), region:"east", width:"30%", split:true, loadMask : true, store : this.feePayStore, // border : false, bbar: new Ext.PagingToolbar({store: this.feePayStore ,pageSize : this.pageSize}), sm : new Ext.grid.RowSelectionModel(), view: new Ext.ux.grid.ColumnLockBufferView(), cm : cm, listeners:{ scope:this, delay:10, rowdblclick: this.doDblClickRecord, afterrender: this.swapViews }, tools:[{id:'search',qtip:'查询',cls:'tip-target',scope:this,handler:function(){ var comp = this.tools.search; if(this.feePayStore.getCount()>0){ if(win)win.close(); win = FilterWindow.addComp(this,[ {text:'状态',field:'status',showField:'is_valid_text', data:[ {'text':'所有','value':''}, {'text':'有效','value':'T'}, {'text':'失效','value':'F'} ] }, {text:'受理日期',field:'create_time',type:'datefield'}, {text:'受理人',field:'optr_name',type:'textfield'}, {text:'发票号',field:'invoice_id',type:'textfield'} ],580,null,true,"queryFeeInfo"); if(win){ win.setPosition(comp.getX()-win.width, comp.getY()-50);//弹出框右对齐 win.show(); } }else{ Alert('请先查询数据!'); } } }] }); }, doDblClickRecord : function(grid, rowIndex, e) { var record = grid.getStore().getAt(rowIndex); }, remoteRefresh : function() { this.refresh(); }, refresh:function(){ this.feePayStore.baseParams = { residentCustId: App.getData().custFullInfo.cust.cust_id }; // this.busiFeeStore.load({params:{start: 0,limit: this.pageSize}}); this.reloadCurrentPage(); }, localRefresh : function() { unitRecords = this.getSelectionModel().getSelections(); for (var i in unitRecords) { this.feePayStore.remove(unitRecords[i]); } }, doTransferFeeShow:function(){ if(!App.getApp().getCustId()){ Alert('请查询客户之后再做操作.'); return false; } var recs = this.selModel.getSelections(); if(!recs || recs.length !=1){ Alert('请选择且仅选择一条记录!'); return false; } var rec = recs[0]; if(!this.cfeePayWindow){ this.cfeePayWindow = new CfeePayWindow(); } this.cfeePayWindow.show(rec.get('pay_sn')); } }); /** */ PayfeePanel = Ext.extend(BaseInfoPanel, { // 面板属性定义 acctFeeGrid : null, busiFeeGrid : null, feePayGrid : null, // other property mask : null, constructor : function() { // 子面板实例化 this.acctFeeGrid = new AcctFeeGrid(); this.busiFeeGrid = new BusiFeeGrid(); this.feePayGrid = new FeePayGrid(); PayfeePanel.superclass.constructor.call(this, { layout:"border", border:false, items:[{ region:"center", layout:"anchor", // border: false, items : [{ layout : 'fit', border : false, anchor : "100% 60%", bodyStyle: 'border-bottom-width: 1px;', items : [this.acctFeeGrid] }, { layout : 'fit', border : false, anchor : "100% 40%", items : [this.busiFeeGrid] }] },this.feePayGrid // { // region:"west", // split:true, // width:"30%", // border: false, // items:[this.feePayGrid] // } ] }); }, refresh : function() { this.acctFeeGrid.remoteRefresh(); this.busiFeeGrid.remoteRefresh(); this.feePayGrid.remoteRefresh(); } }); Ext.reg("payfeepanel", PayfeePanel);
leopardoooo/cambodia
boss-core/src/main/webapp/pages/index/center/PayfeePanel.js
JavaScript
apache-2.0
18,342
/* * Copyright (C) 2017-2019 Dremio Corporation * * 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. */ // todo: should have a way to auto-register these (instead of manually maintaining a list) export default [ 'version', 'setting', 'home', 'historyItem', 'space', 'spaces', 'source', 'sources', 'dataset', 'fullDataset', 'datasetUI', 'datasetContext', 'physicalDataset', 'datasetConfig', 'file', 'fileFormat', 'folder', 'jobDetails', 'tableData', 'previewTable', 'user', 'datasetAccelerationSettings', 'provision' ];
dremio/dremio-oss
dac/ui/src/reducers/resources/entityTypes.js
JavaScript
apache-2.0
1,073
'use strict' // ** Constants const DEFAULT_HOST = 'localhost'; const DEFAULT_PORT = 8080; // ** Dependencies const WebSocket = require('ws'); // ** Libraries const Service = require('../../lib/Service'); // ** Platform const logger = require('nodus-framework').logging.createLogger(); function logEvents() { var socket = new WebSocket('ws://localhost:3333/'); socket.on('open', function open() { console.log('connected'); socket.send(Date.now().toString(), {mask: true}); }); socket.on('close', function close() { console.log('disconnected'); }); socket.on('message', function message(data, flags) { console.log('Roundtrip time: ' + (Date.now() - parseInt(data)) + 'ms', flags); setTimeout(function timeout() { socket.send(Date.now().toString(), {mask: true}); }, 500); }); return socket; } // ** Exports module.exports = logEvents;
bradserbu/nodus-server
examples/console/console.js
JavaScript
apache-2.0
935
import Ember from 'ember'; /** * @module ember-osf * @submodule mixins */ /** * Controller mixin that implements common actions performed on nodes. * @class NodeActionsMixin * @extends Ember.Mixin */ export default Ember.Mixin.create({ /** * The node to perform these actions on. If not specified, defaults to the model hook. * @property node * @type DS.Model */ node: null, model: null, _node: Ember.computed.or('node', 'model'), /** * Helper method that affiliates an institution with a node. * * @method _affiliateNode * @private * @param {DS.Model} node Node record * @param {Object} institution Institution record * @return {Promise} Returns a promise that resolves to the updated node with the newly created institution relationship */ _affiliateNode(node, institution) { node.get('affiliatedInstitutions').pushObject(institution); return node.save(); }, actions: { /** * Update a node * * @method updateNode * @param {String} title New title of the node * @param {String} description New Description of the node * @param {String} category New node category * @param {Boolean} isPublic Should this node be publicly-visible? * @return {Promise} Returns a promise that resolves to the updated node */ updateNode(title, description, category, isPublic) { var node = this.get('_node'); if (title) { node.set('title', title); } if (category) { node.set('category', category); } if (description) { node.set('description', description); } if (isPublic !== null) { node.set('public', isPublic); } return node.save(); }, /** * Delete a node * * @method deleteNode * @return {Promise} Returns a promise that resolves after the deletion of the node. */ deleteNode() { var node = this.get('_node'); return node.destroyRecord(); }, /** * Affiliate a node with an institution * * @method affiliateNode * @param {String} institutionId ID of the institutution to be affiliated * @return {Promise} Returns a promise that resolves to the updated node * with the newly affiliated institution relationship */ affiliateNode(institutionId) { var node = this.get('_node'); return this.store.findRecord('institution', institutionId) .then(institution => this._affiliateNode(node, institution)); }, /** * Unaffiliate a node with an institution * * @method unaffiliateNode * @param {Object} institution Institution relationship to be removed from node * @return {Promise} Returns a promise that resolves to the updated node * with the affiliated institution relationship removed. */ unaffiliateNode(institution) { var node = this.get('_node'); node.get('affiliatedInstitutions').removeObject(institution); return node.save(); }, /** * Add a contributor to a node * * @method addContributor * @param {String} userId ID of user that will be a contributor on the node * @param {String} permission User permission level. One of "read", "write", or "admin". Default: "write". * @param {Boolean} isBibliographic Whether user will be included in citations for the node. "default: true" * @param {Boolean} sendEmail Whether user will receive an email when added. "default: true" * @return {Promise} Returns a promise that resolves to the newly created contributor object. */ addContributor(userId, permission, isBibliographic, sendEmail) { // jshint ignore:line return this.get('_node').addContributor(...arguments); }, /** * Bulk add contributors to a node * * @method addContributors * @param {Array} contributors Array of objects containing contributor permission, bibliographic, and userId keys * @param {Boolean} sendEmail Whether user will receive an email when added. "default: true" * @return {Promise} Returns a promise that resolves to an array of added contributors */ addContributors(contributors, sendEmail) { // jshint ignore:line return this.get('_node').addContributors(...arguments); }, /** * Remove a contributor from a node * * @method removeContributor * @param {Object} contributor Contributor relationship that will be removed from node * @return {Promise} Returns a promise that will resolve upon contributor deletion. * User itself will not be removed. */ removeContributor(contributor) { var node = this.get('_node'); return node.removeContributor(contributor); }, /** * Update contributors of a node. Makes a bulk request to the APIv2. * * @method updateContributors * @param {Contributor[]} contributors Contributor relationships on the node. * @param {Object} permissionsChanges Dictionary mapping contributor ids to desired permissions. * @param {Object} bibliographicChanges Dictionary mapping contributor ids to desired bibliographic statuses * @return {Promise} Returns a promise that resolves to the updated node * with edited contributor relationships. */ updateContributors(contributors, permissionsChanges, bibliographicChanges) { // jshint ignore:line return this.get('_node').updateContributors(...arguments); }, /** * Update contributors of a node. Makes a bulk request to the APIv2. * * @method updateContributor * @param {Contributor} contributor relationship on the node. * @param {string} permissions desired permissions. * @param {boolean} bibliographic desired bibliographic statuses * @return {Promise} Returns a promise that resolves to the updated node * with edited contributor relationships. */ updateContributor(contributor, permissions, bibliographic) { // jshint ignore:line return this.get('_node').updateContributor(...arguments); }, /** * Reorder contributors on a node, and manually updates store. * * @method reorderContributors * @param {Object} contributor Contributor record to be modified * @param {Integer} newIndex Contributor's new position in the list * @param {Array} contributors New contributor list in correct order * @return {Promise} Returns a promise that resolves to the updated contributor. */ reorderContributors(contributor, newIndex, contributors) { contributor.set('index', newIndex); return contributor.save().then(() => { contributors.forEach((contrib, index) => { if (contrib.id !== contributor.id) { var payload = contrib.serialize(); payload.data.attributes = { permission: contrib.get('permission'), bibliographic: contrib.get('bibliographic'), index: index }; payload.data.id = contrib.get('id'); this.store.pushPayload(payload); } }); }); }, /** * Add a child (component) to a node. * * @method addChild * @param {String} title Title for the child * @param {String} description Description for the child * @param {String} category Category for the child * @return {Promise} Returns a promise that resolves to the newly created child node. */ addChild(title, description, category) { return this.get('_node').addChild(title, description, category); }, /** * Add a node link (pointer) to another node * * @method addNodeLink * @param {String} targetNodeId ID of the node for which you wish to create a pointer * @return {Promise} Returns a promise that resolves to model for the newly created NodeLink */ addNodeLink(targetNodeId) { var node = this.get('_node'); var nodeLink = this.store.createRecord('node-link', { target: targetNodeId }); node.get('nodeLinks').pushObject(nodeLink); return node.save().then(() => nodeLink); }, /** * Remove a node link (pointer) to another node * * @method removeNodeLink * @param {Object} nodeLink nodeLink record to be destroyed. * @return {Promise} Returns a promise that resolves after the node link has been removed. This does not delete * the target node itself. */ removeNodeLink(nodeLink) { return nodeLink.destroyRecord(); } } });
pattisdr/ember-osf
addon/mixins/node-actions.js
JavaScript
apache-2.0
9,519
phoxy.internal = { ChangeURL : function (url) { url = phoxy.ConstructURL(url); phoxy.Log(4, "History push", url); if (url[0] !== '/') url = '/' + url; history.pushState({}, document.title, url); return false; } , Reset : function (url) { if ((url || true) === true) return location.reload(); location = url; } , Config : function() { return phoxy._.config; } , Log : function(level) { if (phoxy.state.verbose < level) return; var error_names = phoxy._.internal.error_names; var errorname = error_names[level < error_names.length ? level : error_names.length - 1]; var args = []; for (var v in arguments) args.push(arguments[v]); args[0] = errorname; var error_methods = phoxy._.internal.error_methods; var method = error_methods[level < error_methods.length ? level : error_methods.length - 1]; console[method].apply(console, args); if (level === 0) throw "Break execution on fatal log"; } , Override: function(method_name, new_method) { return phoxy._.internal.Override(phoxy, method_name, new_method); } }; phoxy._.internal = { Load : function( ) { phoxy.state.loaded = true; phoxy._.click.InitClickHook(); } , GenerateUniqueID : function() { var ret = ""; var dictonary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (var i = 0; i < 10; i++) ret += dictonary.charAt(Math.floor(Math.random() * dictonary.length)); return "phoxy_" + ret; } , DispatchEvent : function(dom_element_id, event_name) { var that = phoxy._.render.Div(dom_element_id); if (document.createEvent) { var event = document.createEvent("HTMLEvents"); event.initEvent(event_name, true, true); event.eventName = event_name; that.dispatchEvent(event); } else { var event = document.createEventObject(); event.eventType = event_name; event.eventName = event_name; that.fireEvent("on" + event.eventType, event); } } , HookEvent : function(dom_element_id, event_name, callback) { var that = phoxy._.render.Div(dom_element_id); that.addEventListener(event_name, callback); } , Override : function(object, method_name, new_method) { var origin = object[method_name]; object[method_name] = new_method; object[method_name].origin = origin; } , error_names : [ "FATAL", "ERROR", "WARNING", "INFO", "DEBUG" ], error_methods : [ "error", "error", "warn", "info", "log", "debug" ] };
phoxy/phoxy
subsystem/internal.js
JavaScript
apache-2.0
2,785
/** * Main framework */ var http = require('http'); var fs = require('fs'); var url = require('url'); var querystring = require('querystring'); var mime = require('mime'); var engineMod = require('./engine.js') var WebApp = function(path,config){ console.log('Starting PanzerParty at '+path); var basepath = path; function checkConfig(config){ if (typeof(config.port)==='undefined') config.port = 8090; if (typeof(config.path)==='undefined') config.path = {}; if (typeof(config.path.statics==='undefined')) config.path.statics = '/static'; if (typeof(config.path.modules==='undefined')) config.path.modules = '/modules'; if (typeof(config.path.controllers)==='undefined') config.path.controllers = '/controllers'; if (typeof(config.path.views)==='undefined') config.path.views='/views'; if (typeof(config.path.layouts)==='undefined') config.path.layuots='/layouts'; if (typeof(config.path.l10n)==='undefined') config.path.l10n='/l10n'; if (typeof(config.controllers)==='undefined') config.controllers = []; } config.root = basepath; checkConfig(config); var engine = new engineMod.Engine(config); this.start = function(){ engine.start(); }; }; exports.WebApp = WebApp;
theoddbeard/PanzerParty
core/app.js
JavaScript
apache-2.0
1,246
import Router from 'viewModels/router' import read from './read' const router = new Router; router.get('token/read', '/', read); export default router
lian-yue/lianyue-server
app/viewModels/token/routes.js
JavaScript
apache-2.0
155
import 'style!../sass/spinner.scss'; const backdrop = ` <div class="js-blocking" id="lightbox-blocking"> <span class="lightbox-spinner"></span> </div> `; const prevControl = ` <div class="lightbox-extra control prev js-control js-prev"> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" x="0" y="0" width="60" height="60" viewBox="0 0 60 60" xml:space="preserve"> <circle class="lightbox-icon-bg" cx="30" cy="30" r="30"/> <path class="lightbox-icon-arrow" d="M36.8,36.4L30.3,30l6.5-6.4l-3.5-3.4l-10,9.8l10,9.8L36.8,36.4z"/> </svg> </div> `; const nextControl = ` <div class="lightbox-extra control next js-control js-next"> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" x="0" y="0" width="60" height="60" viewBox="0 0 60 60" xml:space="preserve"> <circle class="lightbox-icon-bg" cx="30" cy="30" r="30"/> <path class="lightbox-icon-arrow" d="M24.2,23.5l6.6,6.5l-6.6,6.5l3.6,3.5L37.8,30l-10.1-9.9L24.2,23.5z"/> </svg> </div> `; const closeControl = ` <div class="lightbox-extra control close js-control js-close"> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" x="0" y="0" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet"> <circle class="lightbox-icon-bg" cx="50" cy="50" r="47.5"/> <polygon class="lightbox-icon-close" points="64.5,39.8 60.2,35.5 50,45.7 39.8,35.5 35.5,39.8 45.7,50 35.5,60.2 39.8,64.5 50,54.3 60.2,64.5 64.5,60.2 54.3,50"/> </svg> </div> `; export const lightbox = ` <div class="js-lightbox-wrap offscreen" id="lightbox-wrap"> ${backdrop} <div class="js-lightbox-inner-wrap" id="lightbox-inner-wrap"> <div class="js-img-wrap" id="lightbox-img-wrap"> ${prevControl} ${nextControl} ${closeControl} <div class="lightbox-contents js-contents"></div> </div> </div> </div> `;
nemtsov/lightbox
src/templates.js
JavaScript
apache-2.0
1,861
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2017 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ /* global ActiveXObject:false */ // Provides control sap.m.PDFViewer. sap.ui.define([ "jquery.sap.global", "./library", "sap/ui/core/Control", "sap/ui/Device", "sap/m/PDFViewerRenderManager", "sap/m/MessageBox" ], function (jQuery, library, Control, Device, PDFViewerRenderManager, MessageBox) { "use strict"; var aAllowedMimeTypes = Object.freeze([ "application/pdf", "application/x-google-chrome-pdf" ]); function isSupportedMimeType(sMimeType) { var iFoundIndex = aAllowedMimeTypes.indexOf(sMimeType); return iFoundIndex > -1; } /** * Definition of PDFViewer control * * @param {string} [sId] id for the new control, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new control * * @class * This control enables you to display PDF documents within your app. * It can be embedded in your user interface layout, or you can set it to open in a popup dialog. * @extends sap.ui.core.Control * * @author SAP SE * @version 1.50.8 * * @constructor * @public * @alias sap.m.PDFViewer * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var PDFViewer = Control.extend("sap.m.PDFViewer", /** @lends sap.m.PDFViewer.prototype */ { metadata: { library: "sap.m", properties: { /** * Defines the height of the PDF viewer control, respective to the height of * the parent container. Can be set to a percent, pixel, or em value. */ height: {type: "sap.ui.core.CSSSize", group: "Dimension", defaultValue: "100%"}, /** * Defines the width of the PDF viewer control, respective to the width of the * parent container. Can be set to a percent, pixel, or em value. */ width: {type: "sap.ui.core.CSSSize", group: "Dimension", defaultValue: "100%"}, /** * Specifies the path to the PDF file to display. Can be set to a relative or * an absolute path. */ source: {type: "sap.ui.core.URI", group: "Misc", defaultValue: null}, /** * A custom error message that is displayed when the PDF file cannot be loaded. * @deprecated As of version 1.50.0, replaced by {@link sap.m.PDFViewer#getErrorPlaceholderMessage()}. */ errorMessage: {type: "string", group: "Misc", defaultValue: null, deprecated: true}, /** * A custom text that is displayed instead of the PDF file content when the PDF * file cannot be loaded. */ errorPlaceholderMessage: {type: "string", group: "Misc", defaultValue: null}, /** * A custom title for the PDF viewer popup dialog. Works only if the PDF viewer * is set to open in a popup dialog. * @deprecated As of version 1.50.0, replaced by {@link sap.m.PDFViewer#getTitle()}. */ popupHeaderTitle: {type: "string", group: "Misc", defaultValue: null, deprecated: true}, /** * A custom title for the PDF viewer. */ title: {type: "string", group: "Misc", defaultValue: null}, /** * Shows or hides the download button. */ showDownloadButton: {type: "boolean", group: "Misc", defaultValue: true} }, aggregations: { /** * A custom control that can be used instead of the error message specified by the * errorPlaceholderMessage property. */ errorPlaceholder: {type: "sap.ui.core.Control", multiple: false}, /** * A multiple aggregation for buttons that can be added to the footer of the popup * dialog. Works only if the PDF viewer is set to open in a popup dialog. */ popupButtons: {type: "sap.m.Button", multiple: true, singularName: "popupButton"} }, events: { /** * This event is fired when a PDF file is loaded. If the PDF is loaded in smaller chunks, * this event is fired as often as defined by the browser's plugin. This may happen after * a couple chunks are processed. */ loaded: {}, /** * This event is fired when there is an error loading the PDF file. */ error: {}, /** * This event is fired when the PDF viewer control cannot check the loaded content. For * example, the default configuration of the Mozilla Firefox browser may not allow checking * the loaded content. This may also happen when the source PDF file is stored in a different * domain. * If you want no error message to be displayed when this event is fired, call the * preventDefault() method inside the event handler. */ sourceValidationFailed: {} } } }); /** * @returns {boolean} * @private */ PDFViewer._isPdfPluginEnabled = function () { var bIsEnabled = true; if (Device.browser.firefox) { // https://bugzilla.mozilla.org/show_bug.cgi?id=1293406 // mimeType is missing for firefox even though it is enabled return bIsEnabled; } if (Device.browser.internet_explorer) { // hacky code how to recognize that pdf plugin is installed and enabled try { /* eslint-disable no-new */ new ActiveXObject("AcroPDF.PDF"); /* eslint-enable no-new */ } catch (e) { bIsEnabled = false; } return bIsEnabled; } var aMimeTypes = navigator.mimeTypes; bIsEnabled = aAllowedMimeTypes.some(function (sAllowedMimeType) { var oMimeTypeItem = aMimeTypes.namedItem(sAllowedMimeType); return oMimeTypeItem !== null; }); return bIsEnabled; }; /** * Lifecycle method * * @private */ PDFViewer.prototype.init = function () { // helper object that holds the references of nested objects this._objectsRegister = {}; // state variable that shows the state of popup (rendering of pdf in popup requires it) this._bIsPopupOpen = false; this._initPopupControl(); this._initPopupDownloadButtonControl(); this._initPlaceholderMessagePageControl(); this._initToolbarDownloadButtonControl(); this._initOverflowToolbarControl(); this._initControlState(); }; /** * Setup state variables to default state * * @private */ PDFViewer.prototype._initControlState = function () { // state property that control if the embedded pdf should or should not rendered. this._bRenderPdfContent = true; // detect that beforeunload was fired (IE only) this._bOnBeforeUnloadFired = false; }; PDFViewer.prototype.setWidth = function (sWidth) { this.setProperty("width", sWidth, true); var oDomRef = this.$(); if (oDomRef === null) { return this; } oDomRef.css("width", this._getRenderWidth()); return this; }; PDFViewer.prototype.setHeight = function (sHeight) { this.setProperty("height", sHeight, true); var oDomRef = this.$(); if (oDomRef === null) { return this; } oDomRef.css("height", this._getRenderHeight()); return this; }; PDFViewer.prototype.onBeforeRendering = function () { // IE things // because of the detecting error state in IE (double call of unload listener) // it is important to reset the flag before each render // otherwise it wrongly detects error state (the unload listener is called once even in valid use case) this._bOnBeforeUnloadFired = false; }; /** * Lifecycle method * * @private */ PDFViewer.prototype.onAfterRendering = function () { var fnInitIframeElement = function () { // cant use attachBrowserEvent because it attach event to component root node (this.$()) // load event does not bubble so it has to be bind directly to iframe element var oIframeElement = this._getIframeDOMElement(); var oIframeContentWindow = jQuery(oIframeElement.get(0).contentWindow); if (Device.browser.internet_explorer) { // being special does not mean useful // https://connect.microsoft.com/IE/feedback/details/809377/ie-11-load-event-doesnt-fired-for-pdf-in-iframe // onerror does not works on IE. Therefore readyonstatechange and unload events are used for error detection. // When invalid response is received (404, etc.), readystatechange is not fired but unload is. // When valid response is received, then readystatechange and 'complete' state of target's element is received. oIframeContentWindow.on("beforeunload", this._onBeforeUnloadListener.bind(this)); oIframeContentWindow.on("readystatechange", this._onReadyStateChangeListener.bind(this)); // some error codes load html file and fires loadEvent oIframeElement.on("load", this._onLoadIEListener.bind(this)); } else { // normal browsers supports load events as specification said oIframeElement.on("load", this._onLoadListener.bind(this)); } oIframeElement.on("error", this._onErrorListener.bind(this)); var sParametrizedSource = this.getSource(); var iCrossPosition = this.getSource().indexOf("#"); if (iCrossPosition > -1) { sParametrizedSource = sParametrizedSource.substr(0, iCrossPosition); } sParametrizedSource += "#view=FitH"; if (jQuery.sap.validateUrl(sParametrizedSource)) { oIframeElement.attr("src", encodeURI(sParametrizedSource)); } else { this._fireErrorEvent(); } }.bind(this); try { this.setBusy(true); fnInitIframeElement(); } catch (error) { this.setBusy(false); } }; /** * @private */ PDFViewer.prototype._fireErrorEvent = function () { this._renderErrorState(); this.fireEvent("error", {}, true); }; /** * @private */ PDFViewer.prototype._renderErrorState = function () { var oDownloadButton = this._objectsRegister.getToolbarDownloadButtonControl(); oDownloadButton.setEnabled(false); var oDownloadButton = this._objectsRegister.getPopupDownloadButtonControl(); oDownloadButton.setEnabled(false); this.setBusy(false); this._bRenderPdfContent = false; // calls controls invalidate because the error state should be render. // It is controlled by the state variable called _bRenderPdfContent // The main invalidate set the state of the control to the default and tries to load and render pdf Control.prototype.invalidate.call(this); }; /** * @private */ PDFViewer.prototype._fireLoadedEvent = function () { this._bRenderPdfContent = true; this.setBusy(false); try { this._getIframeDOMElement().removeClass("sapMPDFViewerLoading"); } catch (err) { jQuery.log.fatal("Iframe not founded in loaded event"); jQuery.log.fatal(err); } this.fireEvent("loaded"); }; /** * @param oEvent * @private */ PDFViewer.prototype._onLoadListener = function (oEvent) { try { var oTarget = jQuery(oEvent.target), bContinue = true; // Firefox // https://bugzilla.mozilla.org/show_bug.cgi?id=911444 // because of the embedded pdf plugin in firefox it is not possible to check contentType of the iframe document // if the content is pdf. If the content is not a pdf and it is from the same origin, it can be accessed. // Other browsers allow access to the mimeType of the iframe's document if the content is from the same origin. var sCurrentContentType = "application/pdf"; try { // browsers render pdf in iframe as html page with embed tag var aEmbeds = oTarget[0].contentWindow.document.embeds; bContinue = !!aEmbeds && aEmbeds.length === 1; if (bContinue) { sCurrentContentType = aEmbeds[0].attributes.getNamedItem("type").value; } } catch (error) { // even though the sourceValidationFailed event is fired, the default behaviour is to continue. // when preventDefault is on event object is called, the rendering ends up with error if (!Device.browser.firefox && this.fireEvent("sourceValidationFailed", {}, true)) { this._showMessageBox(); return; } } if (bContinue && isSupportedMimeType(sCurrentContentType)) { this._fireLoadedEvent(); } else { this._fireErrorEvent(); } } catch (error) { jQuery.sap.log.fatal(false, "Fatal error during the handling of load event happened."); jQuery.sap.log.fatal(false, error.message); } }; /** * @private */ PDFViewer.prototype._onErrorListener = function () { this._fireErrorEvent(); }; /** * @private */ PDFViewer.prototype._onReadyStateChangeListener = function (oEvent) { var INTERACTIVE_READY_STATE = "interactive"; var COMPLETE_READY_STATE = "complete"; switch (oEvent.target.readyState) { case INTERACTIVE_READY_STATE: // IE11 only fires interactive case COMPLETE_READY_STATE: // iframe content is not loaded when interactive ready state is fired // even though complete ready state should be fired. We were not able to simulate firing complete ready state // on IE. Therefore the validation of source is not possible. this._fireLoadedEvent(); break; } }; /** * @private */ PDFViewer.prototype._onBeforeUnloadListener = function () { // IE problems // when invalid response is received (404), beforeunload is fired twice if (this._bOnBeforeUnloadFired) { this._fireErrorEvent(); return; } this._bOnBeforeUnloadFired = true; }; /** * @param oEvent * @private */ PDFViewer.prototype._onLoadIEListener = function (oEvent) { try { // because of asynchronity of events, IE sometimes fires load event even after it unloads the content. // The contentWindow does not exists in these moments. On the other hand, the error state is already handled // by onBeforeUnloadListener, so we only need catch for catching the error and then return. // The problem is not with null reference. The access of the contentWindow sometimes fires 'access denied' error // which is not detectable otherwise. var sCurrentContentType = oEvent.currentTarget.contentWindow.document.mimeType; } catch (err) { return; } if (!isSupportedMimeType(sCurrentContentType)) { this._fireErrorEvent(); } }; /** * Downloads the PDF file. * * @public */ PDFViewer.prototype.downloadPDF = function () { var oWindow = window.open(this.getSource()); oWindow.focus(); }; /** * @param string oClickedButtonId * @private */ PDFViewer.prototype._onSourceValidationErrorMessageBoxCloseListener = function (oClickedButtonId) { if (oClickedButtonId === MessageBox.Action.CANCEL) { this._renderErrorState(); } else { this._fireLoadedEvent(); } }; /** * @param oEvent * @private */ PDFViewer.prototype._onAfterPopupClose = function (oEvent) { var oPopup = this._objectsRegister.getPopup(); // content has to be cleared from dom oPopup.removeAllContent(); this._bIsPopupOpen = false; }; /** * @returns {boolean} * @private */ PDFViewer.prototype._shouldRenderPdfContent = function () { return PDFViewer._isPdfPluginEnabled() && this._bRenderPdfContent && this.getSource() !== null; }; /** * @returns {boolean} * @private */ PDFViewer.prototype._isSourceValidToDisplay = function () { var sSource = this.getSource(); return sSource !== null && sSource !== "" && typeof sSource !== "undefined"; }; /** * Triggers rerendering of this element and its children. * * @param {sap.ui.base.ManagedObject} [oOrigin] Child control for which the method was called * * @public */ PDFViewer.prototype.invalidate = function (oOrigin) { this._initControlState(); Control.prototype.invalidate.call(this, oOrigin); }; /** * Opens the PDF viewer in a popup dialog. * * @public */ PDFViewer.prototype.open = function () { if (!this._isSourceValidToDisplay()) { jQuery.sap.assert(false, "The PDF file cannot be opened with the given source. Given source: " + this.getSource()); return; } if (this._isEmbeddedModeAllowed()) { this._openOnDesktop(); } else { this._openOnMobile(); } }; /** * Handles opening on desktop devices * @private */ PDFViewer.prototype._openOnDesktop = function () { var oPopup = this._objectsRegister.getPopup(); if (this._bIsPopupOpen) { return; } this._initControlState(); this._preparePopup(oPopup); oPopup.addContent(this); this._bIsPopupOpen = true; oPopup.open(); }; /** * Handles opening on mobile/tablet devices * @private */ PDFViewer.prototype._openOnMobile = function () { var oWindow = window.open(this.getSource()); oWindow.focus(); }; /** * Gets the iframe element from rendered DOM * @returns {*} jQuery object of iframe * @private */ PDFViewer.prototype._getIframeDOMElement = function () { var oIframeElement = this.$().find("iframe"); if (oIframeElement.length === 0) { throw Error("Underlying iframe was not found in DOM."); } if (oIframeElement.length > 1) { jQuery.sap.log.fatal("Initialization of iframe fails. Reason: the control somehow renders multiple iframes"); } return oIframeElement; }; /** * @private */ PDFViewer.prototype._isEmbeddedModeAllowed = function () { return Device.system.desktop; }; /** * @returns {jQuery.sap.util.ResourceBundle} * @private */ PDFViewer.prototype._getLibraryResourceBundle = function () { return sap.ui.getCore().getLibraryResourceBundle("sap.m"); }; /** * @returns {string} * @private */ PDFViewer.prototype._getMessagePageErrorMessage = function () { return this.getErrorPlaceholderMessage() ? this.getErrorPlaceholderMessage() : this._getLibraryResourceBundle().getText("PDF_VIEWER_PLACEHOLDER_ERROR_TEXT"); }; /** * @returns {string} * @private */ PDFViewer.prototype._getRenderWidth = function () { return this._bIsPopupOpen ? '100%' : this.getWidth(); }; /** * @returns {string} * @private */ PDFViewer.prototype._getRenderHeight = function () { return this._bIsPopupOpen ? '100%' : this.getHeight(); }; /** * @private */ PDFViewer.prototype._showMessageBox = function () { MessageBox.show(this._getLibraryResourceBundle().getText("PDF_VIEWER_SOURCE_VALIDATION_MESSAGE_TEXT"), { icon: MessageBox.Icon.WARNING, title: this._getLibraryResourceBundle().getText("PDF_VIEWER_SOURCE_VALIDATION_MESSAGE_HEADER"), actions: [MessageBox.Action.OK, MessageBox.Action.CANCEL], defaultAction: MessageBox.Action.CANCEL, id: this.getId() + "-validationErrorSourceMessageBox", styleClass: "sapUiSizeCompact", contentWidth: '100px', onClose: this._onSourceValidationErrorMessageBoxCloseListener.bind(this) }); }; /** * Lifecycle method * @private */ PDFViewer.prototype.exit = function () { jQuery.each(this._objectsRegister, function (iIndex, fnGetObject) { var oObject = fnGetObject(true); if (oObject) { oObject.destroy(); } }); }; PDFViewerRenderManager.extendPdfViewer(PDFViewer); return PDFViewer; }, /* bExport= */ true);
thbonk/electron-openui5-boilerplate
libs/openui5-runtime/resources/sap/m/PDFViewer-dbg.js
JavaScript
apache-2.0
19,266
var madson = (function () { import "nxutils/generic/base"; import "./utils"; import "./write"; import "./read"; import "./preset"; function mEncode(input, options) { var encoder = new EncodeBuffer(options); encode(encoder, cloneDecycle(input)); return encoder.read(); } function mDecode(input, options) { var decoder = new DecodeBuffer(options); decoder.append(input); return retroCycle(decode(decoder)); } function packer(input) { return Buffer.isBuffer(input) ? mDecode(input) : mEncode(input); } var madson = extend(packer, { createCodec: Codec, codec: { preset: preset }, encode: mEncode, decode: mDecode }); if ("isServer") { if (typeof module == 'object') module.exports = madson; } else global.madson = madson; return madson; })();
arash16/madson
src/index.js
JavaScript
apache-2.0
901
'use strict'; //https://evaluat-e-api.herokuapp.com angular.module('evaluateApp').factory('Student',function($resource,$cookieStore,$http,url_api){ var interface_api = { resource: $resource(url_api+'api/student/:id',{id:'@id','csrf_token' :$cookieStore._csrf, page: 1 },{ update: { method:'PUT'}, delete: { method:'DELETE', headers: { 'Content-Type': 'application/json' },params: {id: '@id'}} }), http: { getStudentsByCourse: function(id_course,page) { return $http({ url: url_api+'api/student_course', method: 'GET', params: {id_course: id_course,page: page} }); }, saveStudentCourse: function(id_course,id_student) { var data = $.param({ id_course: id_course, id_student: id_student }); var config = { headers : { 'Content-Type': 'application/x-www-form-urlencoded' } } return $http.post(url_api+'api/student_course', data, config) }, deleteStudentCourse: function(id_student,id_course) { return $http({ url: url_api+'api/student_course', method: 'DELETE', params: {id_course: id_course,id_student: id_student} }); } } } return interface_api; });
IIC3143-Equipo1/angularJS
app/scripts/services/student.js
JavaScript
apache-2.0
1,586
/** * Created by yang on 14/12/8. */ var SimpleHotCSV = require('./index').SimpleHotCSV; var HotCSV = require('./index').HotCSV; var path = require('path'); var hostCityList = path.join(__dirname,'./whiteCityList.csv'); var hotCity1 = new SimpleHotCSV(hostCityList); hotCity1.init(function(){ setInterval(function(){ console.log('simpleHotCity length ' + hotCity1.getList().length) },1000); }); var hotCity2 = new HotCSV(hostCityList); hotCity2.init( {headers : ["column1"]},function(){ setInterval(function(){ console.log('hotCity length ' + hotCity1.getList().length) },1000); });
gastrodia/hot-csv
test.js
JavaScript
apache-2.0
619
// JavaScript Document function run_timer() { var today = new Date(); var ndate=today.toString(); //April 23, 2009, 02:04:25 pm ndate=ndate.split('GMT'); document.getElementById("TimeDiv").style.border='transparent'; document.getElementById("TimeDiv").innerHTML=ndate[0]; setTimeout(run_timer,1000); } function getHeightWidht() { var viewportwidth; var viewportheight; // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight if (typeof window.innerWidth != 'undefined') { viewportwidth = window.innerWidth, viewportheight = window.innerHeight } // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document) else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) { viewportwidth = document.documentElement.clientWidth; viewportheight = document.documentElement.clientHeight } // older versions of IE else { viewportwidth = document.getElementsById('bodyid').clientWidth; viewportheight = document.getElementsById('bodyid').clientHeight; } return parseInt(viewportwidth); } function checkall(thisid) { for(var i=1;document.getElementById('check'+i);i++){ if(document.getElementById(thisid.id).checked==true){ document.getElementById('check'+i).checked = true; } if(document.getElementById(thisid.id).checked==false){ document.getElementById('check'+i).checked = false; } } } function check_check(spanid,checkid){ var chkchkstat = true; for(var i=1; document.getElementById('check'+i); i++){ if(document.getElementById('check'+i).checked == false){ chkchkstat = false; break; } } //alert(chkchkstat); if(chkchkstat == false){ $('#'+spanid).html(''); document.getElementById(checkid).checked = false; } else { document.getElementById(checkid).checked = true; } return true; } function checknummsp(e) { evt=e || window.event; var keypressed=evt.which || evt.keyCode; //alert(keypressed); if(keypressed!="48" && keypressed!="49" && keypressed!="50" && keypressed!="51" && keypressed!="52" && keypressed!="53" && keypressed!="54" && keypressed!="55" && keypressed!="8" && keypressed!="56" && keypressed!="57" && keypressed!="45" && keypressed!="46" && keypressed!="37" && keypressed!="39" && keypressed!="9") { return false; } } function showhidedata(show) { if(show==1) { if(document.getElementById('firstdiv').style.display=="block") { document.getElementById('firstdiv').style.display="none"; } else { document.getElementById('firstdiv').style.display="block"; } } } function showhidediscp(show) { if(show==1) { if(document.getElementById('dispdiv').style.display=="block") { document.getElementById('dispdiv').style.display="none"; } else { document.getElementById('dispdiv').style.display="block"; } } } function hrefHandler() { var a=window.location.pathname; var b=a.match(/[\/|\\]([^\\\/]+)$/); var ans=confirm("Are you sure? You want to delete."); return ans; } function EmptyListbox(listBoxId) { var elSel = document.getElementById(listBoxId); for (i = elSel.length - 1; i>=0; i--) { elSel.remove(i); } } function AddOptiontoListBox(listBoxId,Value,Text) { var elSel = document.getElementById(listBoxId); var opt = document.createElement("option"); elSel.options.add(opt); opt.text=Text; opt.value=Value; } function CollaspeExpand(divName) { $('#Child'+divName).slideToggle("slow"); /*if(document.getElementById('Child'+divName).style.display=="block") { document.getElementById('Child'+divName).style.display="none"; } else { document.getElementById('Child'+divName).style.display="block"; }*/ } //phone no function checkLen(charlen,e) { var mb= document.getElementById('phone_number').value; //alert(mb.length); evt=e || window.event; var keypressed=evt.which || evt.keyCode; //alert(keypressed); if(keypressed!="48" && keypressed!="49" && keypressed!="50" && keypressed!="51" && keypressed!="52" && keypressed!="53" && keypressed!="54" && keypressed!="55" && keypressed!="8" && keypressed!="56" && keypressed!="57" && keypressed!="45" && keypressed!="46" && keypressed!="37" && keypressed!="39" && keypressed!="9") { return false; } else { if(mb.length<3) { return charlen; } else if(mb.length==3 || mb.length==7 ) { var dashchar="-"; var charlen1=charlen+dashchar; var charlen2=document.getElementById('phone_number').value=charlen1; //var charlen2=charlen1.join("-"); //alert(charlen2); return charlen1; //return charlen1; } } } //print_r function print_r(arr,level) { var dumped_text = ""; if(!level) level = 0; //The padding given at the beginning of the line. var level_padding = ""; for(var j=0;j<level+1;j++) level_padding += " "; if(typeof(arr) == 'object') { //Array/Hashes/Objects for(var item in arr) { var value = arr[item]; if(typeof(value) == 'object') { //If it is an array, dumped_text += level_padding + "'" + item + "' ...\n"; dumped_text += print_r(value,level+1); } else { dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n"; } } } else { //Stings/Chars/Numbers etc. dumped_text = "===>"+arr+"<===("+typeof(arr)+")"; } return dumped_text; } function makepropertyinsurance(){ //check if checkbox is checked console.log($('#insurance'),$('#insurance').attr('checked')); if($('#insurance').attr('checked')=='checked'){ $('#is_insured').val('true'); }else{ $('#is_insured').val('false'); } } //loading overlay //element - jquery object [ $('#element') ] //image_path - path to image i.e. absolute url **:- omit trailing slash in path function loading(element,image_path){ element.append('<div class="question-overlay question-overlay-box"></div><img src="'+image_path+'/fancybox_loading2x.gif" class="question-overlay loading-image">') } function loadingComplete(){ $('.question-overlay').remove(); } function linkify(inputText) { var replacedText, replacePattern1, replacePattern2, replacePattern3; //URLs starting with http://, https://, or ftp:// replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim; replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>'); //URLs starting with "www." (without // before it, or it'd re-link the ones done above). replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim; replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>'); //Change email addresses to mailto:: links. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim; replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>'); return replacedText; }
ankuradhey/dealtrip
js/general.js
JavaScript
apache-2.0
7,612
/* Copyright 2005-2015 Alfresco Software, Ltd. * * 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'; flowableAdminApp.controller('ProcessInstanceController', ['$scope', '$rootScope', '$http', '$timeout', '$location', '$routeParams', '$modal', '$translate', '$q', 'gridConstants', function ($scope, $rootScope, $http, $timeout, $location, $routeParams, $modal, $translate, $q, gridConstants) { $rootScope.navigation = {main: 'process-engine', sub: 'instances'}; $scope.tabData = { tabs: [ {id: 'tasks', name: 'PROCESS-INSTANCE.TITLE.TASKS'}, {id: 'variables', name: 'PROCESS-INSTANCE.TITLE.VARIABLES'}, {id: 'subProcesses', name: 'PROCESS-INSTANCE.TITLE.SUBPROCESSES'}, {id: 'jobs', name: 'PROCESS-INSTANCE.TITLE.JOBS'} ] }; $scope.tabData.activeTab = $scope.tabData.tabs[0].id; $scope.returnToList = function () { $location.path("/process-instances"); }; $scope.openTask = function (task) { if (task && task.getProperty('id')) { $location.path("/task/" + task.getProperty('id')); } }; $scope.openJob = function (job) { if (job && job.getProperty('id')) { $location.path("/job/" + job.getProperty('id')); } }; $scope.openProcessInstance = function (instance) { if (instance) { var id; if (instance.getProperty !== undefined) { id = instance.getProperty('id'); } else { id = instance; } $location.path("/process-instance/" + id); } }; $scope.showAllTasks = function () { // Populate the task-filter with parentId $rootScope.filters.forced.taskFilter = { processInstanceId: $scope.process.id }; $location.path("/tasks"); }; $scope.showAllSubprocesses = function () { // Populate the process-filter with parentId $rootScope.filters.forced.instanceFilter = { superProcessInstanceId: $scope.process.id }; $scope.returnToList(); }; $scope.openProcessDefinition = function (processDefinitionId) { if (processDefinitionId) { $location.path("/process-definition/" + processDefinitionId); } }; $scope.showProcessDiagram = function () { $modal.open({ templateUrl: 'views/process-instance-diagram-popup.html', windowClass: 'modal modal-full-width', controller: 'ShowProcessInstanceDiagramPopupCtrl', resolve: { process: function () { return $scope.process; } } }); }; $scope.openDecisionTable = function (decisionTable) { if (decisionTable && decisionTable.getProperty('id')) { $location.path("/decision-table-execution/" + decisionTable.getProperty('id')); } }; $scope.openFormInstance = function (submittedForm) { if (submittedForm && submittedForm.getProperty('id')) { $location.path("/form-instance/" + submittedForm.getProperty('id')); } }; $scope.loadProcessDefinition = function () { // Load definition $http({ method: 'GET', url: '/app/rest/admin/process-definitions/' + $scope.process.processDefinitionId }).success(function (data, status, headers, config) { $scope.definition = data; }).error(function (data, status, headers, config) { }); }; $scope.loadProcessInstance = function () { $scope.process = undefined; // Load process $http({ method: 'GET', url: '/app/rest/admin/process-instances/' + $routeParams.processInstanceId }).success(function (data, status, headers, config) { $scope.process = data; if (data) { $scope.processCompleted = data.endTime != undefined; } // Start loading children $scope.loadProcessDefinition(); $scope.loadTasks(); $scope.loadVariables(); $scope.loadSubProcesses(); $scope.loadJobs(); $scope.loadDecisionTables() $scope.tabData.tabs.push({id: 'decisionTables', name: 'PROCESS-INSTANCE.TITLE.DECISION-TABLES'}); $scope.tabData.tabs.push({id: 'forms', name: 'PROCESS-INSTANCE.TITLE.FORM-INSTANCES'}); //TODO: implement when decision task runtime data is stored // $scope.loadDecisionTables(); $scope.loadFormInstances(); }).error(function (data, status, headers, config) { if (data && data.message) { // Extract error-message $rootScope.addAlert(data.message, 'error'); } else { // Use default error-message $rootScope.addAlert($translate.instant('ALERT.GENERAL.HTTP-ERROR'), 'error'); } }); }; var dateTemplate = '<div><div class="ngCellText" title="{{row.getProperty(col.field) | dateformat:\'full\'}}">{{row.getProperty(col.field) | dateformat}}</div></div>'; // Config for subtasks grid $q.all([$translate('TASKS.HEADER.ID'), $translate('TASKS.HEADER.NAME'), $translate('TASKS.HEADER.ASSIGNEE'), $translate('TASKS.HEADER.OWNER'), $translate('TASKS.HEADER.CREATE-TIME'), $translate('TASKS.HEADER.END-TIME')]) .then(function (headers) { $scope.gridTasks = { data: 'tasks.data', enableRowReordering: false, multiSelect: false, keepLastSelected: false, enableSorting: false, rowHeight: 36, afterSelectionChange: $scope.openTask, columnDefs: [ {field: 'id', displayName: headers[0], width: 50}, {field: 'name', displayName: headers[1]}, {field: 'assignee', displayName: headers[2], cellTemplate: gridConstants.defaultTemplate}, {field: 'owner', displayName: headers[3], cellTemplate: gridConstants.defaultTemplate}, {field: 'startTime', displayName: headers[4], cellTemplate: dateTemplate}, {field: 'endTime', displayName: headers[5], cellTemplate: dateTemplate} ] }; }); $q.all([$translate('VARIABLES.HEADER.NAME'), $translate('VARIABLES.HEADER.TYPE'), $translate('VARIABLES.HEADER.VALUE')]) .then(function (headers) { var variableValueTemplate = '<div><div class="ngCellText">{{row.getProperty("variable.valueUrl") && "(Binary)" || row.getProperty(col.field)}}</div></div>'; var variableTypeTemplate = '<div><div class="ngCellText">{{row.getProperty(col.field) && row.getProperty(col.field) || "null"}}</div></div>'; $scope.selectedVariables = []; // Config for variable grid $scope.gridVariables = { data: 'variables.data', enableRowReordering: false, multiSelect: false, keepLastSelected: false, enableSorting: false, rowHeight: 36, selectedItems: $scope.selectedVariables, columnDefs: [ {field: 'variable.name', displayName: headers[0]}, {field: 'variable.type', displayName: headers[1], cellTemplate: variableTypeTemplate}, {field: 'variable.value', displayName: headers[2], cellTemplate: variableValueTemplate} ] }; }); $q.all([$translate('PROCESS-INSTANCES.HEADER.ID'), $translate('PROCESS-INSTANCES.HEADER.NAME'), $translate('PROCESS-INSTANCES.HEADER.PROCESS-DEFINITION'), $translate('PROCESS-INSTANCES.HEADER.STATUS')]) .then(function (headers) { var subprocessStateTemplate = '<div><div class="ngCellText">{{row.getProperty("endTime") && "Completed" || "Active"}}</div></div>'; // Config for variable grid $scope.gridSubprocesses = { data: 'subprocesses.data', enableRowReordering: false, multiSelect: false, keepLastSelected: false, enableSorting: false, rowHeight: 36, afterSelectionChange: $scope.openProcessInstance, columnDefs: [ {field: 'id', displayName: headers[0]}, {field: 'name', displayName: headers[1]}, {field: 'processDefinitionId', displayName: headers[2]}, {field: 'endTime', displayName: headers[3], cellTemplate: subprocessStateTemplate} ] }; }); $q.all([$translate('JOBS.HEADER.ID'), $translate('JOBS.HEADER.DUE-DATE'), $translate('JOBS.HEADER.RETRIES'), $translate('JOBS.HEADER.EXCEPTION')]) .then(function (headers) { var dateTemplate = '<div><div class="ngCellText" title="{{row.getProperty(col.field) | dateformat:\'full\'}}">{{row.getProperty(col.field) | dateformat}}</div></div>'; // Config for variable grid $scope.gridJobs = { data: 'jobs.data', enableRowReordering: false, multiSelect: false, keepLastSelected: false, enableSorting: false, rowHeight: 36, afterSelectionChange: $scope.openJob, columnDefs: [ {field: 'id', displayName: headers[0], width: 50}, {field: 'dueDate', displayName: headers[1], cellTemplate: dateTemplate}, {field: 'retries', displayName: headers[2]}, {field: 'exceptionMessage', displayName: headers[3]} ] }; }); $q.all([$translate('DECISION-TABLE-EXECUTION.HEADER.ID'), $translate('DECISION-TABLE-EXECUTION.HEADER.DECISION-KEY'), $translate('DECISION-TABLE-EXECUTION.HEADER.DECISION-DEFINITION-ID'), $translate('DECISION-TABLE-EXECUTION.HEADER.END-TIME'), $translate('DECISION-TABLE-EXECUTION.HEADER.FAILED')]) .then(function (headers) { $scope.gridDecisionTables = { data: 'decisionTables.data', enableRowReordering: false, multiSelect: false, keepLastSelected: false, enableSorting: false, rowHeight: 36, afterSelectionChange: $scope.openDecisionTable, columnDefs: [ {field: 'id', displayName: headers[0]}, {field: 'decisionKey', displayName: headers[1]}, {field: 'decisionDefinitionId', displayName: headers[2]}, { field: 'endTime', displayName: headers[3], cellTemplate: gridConstants.dateTemplate }, {field: 'decisionExecutionFailed', displayName: headers[4]} ] }; }); $q.all([$translate('FORM-INSTANCE.HEADER.ID'), $translate('FORM-INSTANCE.HEADER.TASK-ID'), $translate('FORM-INSTANCE.HEADER.PROCESS-ID'), $translate('FORM-INSTANCE.HEADER.SUBMITTED'), $translate('FORM-INSTANCE.HEADER.SUBMITTED-BY')]) .then(function (headers) { $scope.gridFormInstances = { data: 'formInstances.data', enableRowReordering: false, multiSelect: false, keepLastSelected: false, enableSorting: false, rowHeight: 36, afterSelectionChange: $scope.openFormInstance, columnDefs: [ {field: 'id', displayName: headers[0]}, {field: 'taskId', displayName: headers[1]}, {field: 'processInstanceId', displayName: headers[2]}, {field: 'submittedDate', displayName: headers[3], cellTemplate: gridConstants.dateTemplate}, {field: 'submittedBy', displayName: headers[4], cellTemplate: gridConstants.userObjectTemplate} ] }; }); $scope.showAllJobs = function () { // Populate the job-filter with process id $rootScope.filters.forced.jobFilter = { processInstanceId: $scope.process.id }; $location.path("/jobs"); }; $scope.loadTasks = function () { $scope.tasks = undefined; $http({ method: 'GET', url: '/app/rest/admin/process-instances/' + $scope.process.id + '/tasks' }).success(function (data, status, headers, config) { $scope.tasks = data; $scope.tabData.tabs[0].info = data.total; }); }; $scope.loadVariables = function () { $scope.variables = undefined; $http({ method: 'GET', url: '/app/rest/admin/process-instances/' + $scope.process.id + '/variables' }).success(function (data, status, headers, config) { $scope.variables = data; $scope.tabData.tabs[1].info = data.total; }); }; $scope.loadSubProcesses = function () { $scope.subprocesses = undefined; $http({ method: 'GET', url: '/app/rest/admin/process-instances/' + $scope.process.id + '/subprocesses' }).success(function (data, status, headers, config) { $scope.subprocesses = data; $scope.tabData.tabs[2].info = data.total; }); }; $scope.loadJobs = function () { $scope.jobs = undefined; $http({ method: 'GET', url: '/app/rest/admin/process-instances/' + $scope.process.id + '/jobs' }).success(function (data, status, headers, config) { $scope.jobs = data; $scope.tabData.tabs[3].info = data.total; }); }; $scope.loadProcessDefinition = function () { // Load definition $http({ method: 'GET', url: '/app/rest/admin/process-definitions/' + $scope.process.processDefinitionId }).success(function (data, status, headers, config) { $scope.definition = data; }).error(function (data, status, headers, config) { }); }; $scope.loadDecisionTables = function () { // Load decision tables $http({ method: 'GET', url: '/app/rest/admin/process-instances/' + $scope.process.id + '/decision-executions' }).success(function (data, status, headers, config) { $scope.decisionTables = data; $scope.tabData.tabs[4].info = data.total; }).error(function (data, status, headers, config) { }); }; $scope.loadFormInstances = function () { // Load form instances $http({ method: 'GET', url: '/app/rest/admin/process-form-instances/' + $scope.process.id }).success(function (data, status, headers, config) { $scope.formInstances = data; $scope.tabData.tabs[5].info = data.total; }).error(function (data, status, headers, config) { }); }; $scope.executeWhenReady(function () { $scope.loadProcessInstance(); }); // Dialogs $scope.deleteProcessInstance = function (action) { if (!action) { action = "delete"; } var modalInstance = $modal.open({ templateUrl: 'views/process-instance-delete-popup.html', controller: 'DeleteProcessModalInstanceCtrl', resolve: { process: function () { return $scope.process; }, action: function () { return action; } } }); modalInstance.result.then(function (deleteProcessInstance) { if (deleteProcessInstance) { if (action == 'delete') { $scope.addAlert($translate.instant('ALERT.PROCESS-INSTANCE.DELETED', $scope.process), 'info'); $scope.returnToList(); } else { $scope.addAlert($translate.instant('ALERT.PROCESS-INSTANCE.TERMINATED', $scope.process), 'info'); $scope.loadProcessInstance(); } } }); }; $scope.updateSelectedVariable = function () { if ($scope.selectedVariables && $scope.selectedVariables.length > 0) { var selectedVariable = $scope.selectedVariables[0]; var modalInstance = $modal.open({ templateUrl: 'views/update-variable-popup.html', controller: 'UpdateVariableCtrl', resolve: { variable: function () { return selectedVariable.variable; }, processInstanceId: function () { return $scope.process.id; } } }); modalInstance.result.then(function (updated) { if (updated == true) { $scope.selectedVariables.splice(0, $scope.selectedVariables.length); $scope.loadVariables(); } }); } }; $scope.deleteVariable = function () { if ($scope.selectedVariables && $scope.selectedVariables.length > 0) { var selectedVariable = $scope.selectedVariables[0]; var modalInstance = $modal.open({ templateUrl: 'views/variable-delete-popup.html', controller: 'DeleteVariableCtrl', resolve: { variable: function () { return selectedVariable.variable; }, processInstanceId: function () { return $scope.process.id; } } }); modalInstance.result.then(function (updated) { if (updated == true) { $scope.selectedVariables.splice(0, $scope.selectedVariables.length); $scope.loadVariables(); } }); } }; $scope.addVariable = function () { var modalInstance = $modal.open({ templateUrl: 'views/variable-add-popup.html', controller: 'AddVariableCtrl', resolve: { processInstanceId: function () { return $scope.process.id; } } }); modalInstance.result.then(function (updated) { if (updated == true) { $scope.selectedVariables.splice(0, $scope.selectedVariables.length); $scope.loadVariables(); } }); }; $scope.terminateProcessInstance = function () { $scope.deleteProcessInstance("terminate"); }; }]); flowableAdminApp.controller('DeleteProcessModalInstanceCtrl', ['$rootScope', '$scope', '$modalInstance', '$http', 'process', 'action', function ($rootScope, $scope, $modalInstance, $http, process, action) { $scope.process = process; $scope.action = action; $scope.status = {loading: false}; $scope.model = {}; $scope.ok = function () { $scope.status.loading = true; var dataForPost = {action: $scope.action}; if ($scope.action == 'terminate' && $scope.model.deleteReason) { dataForPost.deleteReason = $scope.model.deleteReason; } $http({ method: 'POST', url: '/app/rest/admin/process-instances/' + $scope.process.id, data: dataForPost }).success(function (data, status, headers, config) { $modalInstance.close(true); $scope.status.loading = false; }).error(function (data, status, headers, config) { $modalInstance.close(false); $scope.status.loading = false; }); }; $scope.cancel = function () { if (!$scope.status.loading) { $modalInstance.dismiss('cancel'); } }; }]); flowableAdminApp.controller('ShowProcessInstanceDiagramPopupCtrl', ['$rootScope', '$scope', '$modalInstance', '$http', 'process', '$timeout', function ($rootScope, $scope, $modalInstance, $http, process, $timeout) { $scope.model = { id: process.id, name: process.name }; $scope.status = {loading: false}; $scope.cancel = function () { if (!$scope.status.loading) { $modalInstance.dismiss('cancel'); } }; $timeout(function () { $("#bpmnModel").attr("data-instance-id", process.id); $("#bpmnModel").attr("data-definition-id", process.processDefinitionId); $("#bpmnModel").attr("data-server-id", $rootScope.activeServers['process'].id); if (process.endTime != undefined) { $("#bpmnModel").attr("data-history-id", process.id); } $("#bpmnModel").load("./display/displaymodel.html?instanceId=" + process.id); }, 200); }]); flowableAdminApp.controller('UpdateVariableCtrl', ['$rootScope', '$scope', '$modalInstance', '$http', 'variable', 'processInstanceId', function ($rootScope, $scope, $modalInstance, $http, variable, processInstanceId) { $scope.status = {loading: false}; $scope.originalVariable = variable; $scope.updateVariable = { name: variable.name, value: variable.value, type: variable.type }; $scope.executeUpdateVariable = function () { $scope.status.loading = true; var dataForPut = { name: $scope.updateVariable.name, type: $scope.updateVariable.type }; if ($scope.updateVariable.value !== null || $scope.updateVariable.value !== undefined || $scope.updateVariable.value !== '') { if ($scope.updateVariable.type === 'string') { dataForPut.value = $scope.updateVariable.value; } else if ($scope.updateVariable.type === 'boolean') { if ($scope.updateVariable.value) { dataForPut.value = true; } else { dataForPut.value = false; } } else if ($scope.updateVariable.type === 'date') { dataForPut.value = $scope.updateVariable.value; } else if ($scope.updateVariable.type === 'double' || $scope.updateVariable.type === 'long' || $scope.updateVariable.type === 'integer' || $scope.updateVariable.type === 'short') { dataForPut.value = Number($scope.updateVariable.value); } } else { dataForPut.value = null; } $http({ method: 'PUT', url: '/app/rest/admin/process-instances/' + processInstanceId + '/variables/' + $scope.updateVariable.name, data: dataForPut }).success(function (data, status, headers, config) { $modalInstance.close(true); $scope.status.loading = false; }).error(function (data, status, headers, config) { $modalInstance.close(false); $scope.status.loading = false; }); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }]); flowableAdminApp.controller('DeleteVariableCtrl', ['$rootScope', '$scope', '$modalInstance', '$http', 'variable', 'processInstanceId', function ($rootScope, $scope, $modalInstance, $http, variable, processInstanceId) { $scope.status = {loading: false}; $scope.variable = variable; $scope.deleteVariable = function () { $http({ method: 'DELETE', url: '/app/rest/admin/process-instances/' + processInstanceId + '/variables/' + $scope.variable.name }).success(function (data, status, headers, config) { $modalInstance.close(true); $scope.status.loading = false; }).error(function (data, status, headers, config) { $modalInstance.close(false); $scope.status.loading = false; }); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }]); flowableAdminApp.controller('AddVariableCtrl', ['$rootScope', '$scope', '$modalInstance', '$http', 'processInstanceId', function ($rootScope, $scope, $modalInstance, $http, processInstanceId) { $scope.status = {loading: false}; $scope.types = [ "string", "boolean", "date", "double", "integer", "long", "short" ]; $scope.newVariable = {}; $scope.createVariable = function () { var data = { name: $scope.newVariable.name, type: $scope.newVariable.type, }; if ($scope.newVariable.type === 'string') { data.value = $scope.newVariable.value; } else if ($scope.newVariable.type === 'boolean') { if ($scope.newVariable.value) { data.value = true; } else { data.value = false; } } else if ($scope.newVariable.type === 'date') { data.value = $scope.newVariable.value; } else if ($scope.newVariable.type === 'double' || $scope.newVariable.type === 'long' || $scope.newVariable.type === 'integer' || $scope.newVariable.type === 'short') { data.value = Number($scope.newVariable.value); } $http({ method: 'POST', url: '/app/rest/admin/process-instances/' + processInstanceId + '/variables', data: data }).success(function (data, status, headers, config) { $modalInstance.close(true); $scope.status.loading = false; }).error(function (data, status, headers, config) { $modalInstance.close(false); $scope.status.loading = false; }); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }]);
marcus-nl/flowable-engine
modules/flowable-ui-admin/flowable-ui-admin-app/src/main/webapp/scripts/process-instance-controllers.js
JavaScript
apache-2.0
29,675
import("etherpad.log"); import("plugins.openingDesign.hooks"); function openingDesignInit() { this.hooks = ['modals', 'docbarItemsPad']; this.description = 'openingDesign'; this.docbarItemsPad = hooks.docbarItemsPad; this.modals = hooks.modals; this.install = install; this.uninstall = uninstall; } function install() { log.info("Installing openingDesign"); } function uninstall() { log.info("Uninstalling openingDesign"); }
OpeningDesign/SketchSpace
etherpad/src/plugins/openingDesign/main.js
JavaScript
apache-2.0
437
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive; var incrmmean = require( '@stdlib/stats/incr/mmean' ); // MAIN // /** * Returns an accumulator function which incrementally computes a moving mean percentage error. * * @param {PositiveInteger} W - window size * @throws {TypeError} must provide a positive integer * @returns {Function} accumulator function * * @example * var accumulator = incrmmpe( 3 ); * * var m = accumulator(); * // returns null * * m = accumulator( 2.0, 3.0 ); * // returns ~33.33 * * m = accumulator( 5.0, 2.0 ); * // returns ~-58.33 * * m = accumulator( 3.0, 2.0 ); * // returns ~-55.56 * * m = accumulator( 2.0, 5.0 ); * // returns ~-46.67 * * m = accumulator(); * // returns ~-46.67 */ function incrmmpe( W ) { var mean; if ( !isPositiveInteger( W ) ) { throw new TypeError( 'invalid argument. Must provide a positive integer. Value: `' + W + '`.' ); } mean = incrmmean( W ); return accumulator; /** * If provided input values, the accumulator function returns an updated mean percentage error. If not provided input values, the accumulator function returns the current mean percentage error. * * @private * @param {number} [f] - input value * @param {number} [a] - input value * @returns {(number|null)} mean percentage error or null */ function accumulator( f, a ) { if ( arguments.length === 0 ) { return mean(); } return mean( 100.0 * ((a-f)/a) ); } } // EXPORTS // module.exports = incrmmpe;
stdlib-js/stdlib
lib/node_modules/@stdlib/stats/incr/mmpe/lib/main.js
JavaScript
apache-2.0
2,139
import React from 'react' import PropTypes from 'prop-types' import Immutable from 'immutable' import { connect } from 'react-redux' import { Link } from 'react-router-dom' import NavigationPrompt from 'react-router-navigation-prompt' import Switch from 'react-bootstrap-switch' import { generateUnique, templateNameRenderer, filterOsByArchitecture, findOsByName, isWindows, } from '_/helpers' import { isRunning, getVmIconId, isValidOsIcon, isVmNameValid } from '../utils' import style from './style.css' import sharedStyle from '../sharedStyle.css' import CloudInitEditor from '../CloudInitEditor' import DetailContainer from '../DetailContainer' import IconUpload from './IconUpload' import ErrorAlert from '../ErrorAlert' import FieldHelp from '../FieldHelp' import NavigationConfirmationModal from '../NavigationConfirmationModal' import SelectBox from '../SelectBox' import VmIcon from '../VmIcon' import timezones from '_/components/utils/timezones.json' import { createVm, editVm } from '_/actions' import { MAX_VM_MEMORY_FACTOR } from '_/constants' import { msg } from '_/intl' const zeroUID = '00000000-0000-0000-0000-000000000000' const FIRST_DEVICE = 0 const SECOND_DEVICE = 1 const defaultDevices = ['hd', null] class VmDialog extends React.Component { constructor (props) { super(props) this.state = { correlationId: '', id: undefined, name: '', description: '', cpus: 1, memory: 1024 * 1024 * 1024, cdrom: { fileId: '', }, clusterId: undefined, templateId: undefined, osId: undefined, bootDevices: defaultDevices, saved: false, isChanged: false, bootMenuEnabled: false, cloudInit: { enabled: false, hostName: '', sshAuthorizedKeys: '', }, icon: { id: undefined, mediaType: undefined, data: undefined, }, uiErrors: { icon: undefined, }, timeZone: null, } this.submitHandler = this.submitHandler.bind(this) this.initDefaults = this.initDefaults.bind(this) this.onIntegerChanged = this.onIntegerChanged.bind(this) this.getMemoryPolicy = this.getMemoryPolicy.bind(this) this.getCluster = this.getCluster.bind(this) this.getTemplate = this.getTemplate.bind(this) this.getOS = this.getOS.bind(this) this.getOsIdFromType = this.getOsIdFromType.bind(this) this.checkTimeZone = this.checkTimeZone.bind(this) this.onChangeCluster = this.onChangeCluster.bind(this) this.onChangeTemplate = this.onChangeTemplate.bind(this) this.doChangeTemplateIdTo = this.doChangeTemplateIdTo.bind(this) this.onChangeOperatingSystem = this.onChangeOperatingSystem.bind(this) this.doChangeOsIdTo = this.doChangeOsIdTo.bind(this) this.onChangeVmName = this.onChangeVmName.bind(this) this.onChangeVmDescription = this.onChangeVmDescription.bind(this) this.onChangeVmMemory = this.onChangeVmMemory.bind(this) this.onChangeVmCpu = this.onChangeVmCpu.bind(this) this.onChangeCD = this.onChangeCD.bind(this) this.onChangeBootMenuEnabled = this.onChangeBootMenuEnabled.bind(this) this.onChangeBootDevice = this.onChangeBootDevice.bind(this) this.handleCloudInitChange = this.handleCloudInitChange.bind(this) this.onIconChange = this.onIconChange.bind(this) this.setUiError = this.setUiError.bind(this) } componentDidMount () { const vm = this.props.vm if (vm) { // 'edit' mode const bootDevices = vm.getIn(['os', 'bootDevices']).toJS() const resultDevices = [] for (let i = 0; i < defaultDevices.length; i++) { resultDevices.push(bootDevices[i] ? bootDevices[i] : defaultDevices[i]) } this.setState({ id: vm.get('id'), name: vm.get('name'), description: vm.get('description'), cpus: vm.getIn(['cpu', 'vCPUs']), memory: vm.getIn(['memory', 'total']), clusterId: vm.getIn(['cluster', 'id']), templateId: vm.getIn(['template', 'id']), osId: this.getOsIdFromType(vm.getIn(['os', 'type'])), bootDevices: resultDevices, cdrom: { fileId: null, }, bootMenuEnabled: vm.get('bootMenuEnabled'), cloudInit: vm.get('cloudInit').toJS(), icon: { id: getVmIconId(this.props.operatingSystems, vm), mediaType: undefined, data: undefined, }, timeZone: null, }) } setTimeout(() => this.initDefaults(), 0) } static getDerivedStateFromProps (props, state) { // If a user message correlating to the correlationId exists, the add/edit failed and // the state should still be marked as isChanged to prevent page navigation. if (props.userMessages.get('records').find(record => record.getIn([ 'failedAction', 'meta', 'correlationId' ]) === state.correlationId)) { return { isChanged: true } } return null } setUiError (name, error) { this.setState((prevState) => ({ uiErrors: Object.assign({}, prevState.uiErrors, { [name]: error, }), })) } submitHandler (e) { e.preventDefault() const correlationId = generateUnique('vm-dialog-') const template = this.getTemplate(this.state.templateId) const clone = !!(template && template.get('type') === 'server') this.props.vm ? this.props.updateVm(this.composeVm(), correlationId) : this.props.addVm(this.composeVm(), correlationId, clone) this.setState({ saved: true, isChanged: false, correlationId, }) } getLatestUserMessage () { const { correlationId } = this.state const filtered = this.props.userMessages .get('records') .filter(record => record.getIn([ 'failedAction', 'meta', 'correlationId' ]) === correlationId) const last = filtered.last() return last && last.get('message') } getMemoryPolicy () { const cluster = this.getCluster() const overCommitPercent = cluster && cluster.getIn(['memoryPolicy', 'overCommitPercent']) let guaranteed = overCommitPercent ? (this.state.memory * (100 / overCommitPercent)) : this.state.memory const memoryPolicy = { 'max': this.state.memory * MAX_VM_MEMORY_FACTOR, 'guaranteed': Math.round(guaranteed), } console.log('getMemoryPolicy() resulting memory_policy: ', memoryPolicy) return memoryPolicy } /** * Compose vm object from entered values * * Structure conforms vmToInternal() */ composeVm () { // TODO: Here is the old compose!! const os = this.props.operatingSystems.get(this.state.osId) return { 'id': this.state.id, 'name': this.state.name, 'description': this.state.description, 'template': { 'id': this.state.templateId }, 'cluster': { 'id': this.state.clusterId }, 'memory': this.state.memory || 0, 'memory_policy': this.getMemoryPolicy(), 'cdrom': { 'fileId': this.state.cdrom.fileId === null ? '' : this.state.cdrom.fileId, }, 'os': { 'type': os ? os.get('name') : null, 'bootDevices': this.state.bootDevices || [], }, 'cpu': { 'topology': { 'cores': '1', // TODO: fix to conform topology in template! 'sockets': this.state.cpus || 1, 'threads': '1', }, }, bootMenuEnabled: this.state.bootMenuEnabled, cloudInit: this.state.cloudInit, 'status': this.props.vm ? this.props.vm.get('status') : '', icons: { large: { id: this.state.icon.id, media_type: this.state.icon.id ? undefined : this.state.icon.mediaType, data: this.state.icon.id ? undefined : this.state.icon.data, }, }, timeZone: this.state.timeZone, } } onChangeVmName (event) { const newName = event.target.value const vmNameErrorText = isVmNameValid(newName) ? null : msg.pleaseEnterValidVmName() this.setState({ name: newName, isChanged: true, vmNameErrorText }) const template = this.getTemplate() if (!template) { return } const templateHostName = template.getIn(['cloudInit', 'hostName']) if (templateHostName) { return } this.setState(state => { state.cloudInit.hostName = newName }) } onChangeVmDescription (event) { this.setState({ description: event.target.value, isChanged: true }) } onChangeVmMemory (event) { this.onIntegerChanged({ stateProp: 'memory', value: event.target.value, factor: 1024 * 1024, isChanged: true }) } onChangeVmCpu (event) { this.onIntegerChanged({ stateProp: 'cpus', value: event.target.value }) } onChangeCD (fileId) { this.setState({ cdrom: { fileId }, isChanged: true }) } onIntegerChanged ({ value, stateProp, factor = 1 }) { let intVal = parseInt(value) if (!isNaN(intVal)) { value = intVal * factor } else { console.log('not an integer: ', value) value = '' } const stateChange = {} stateChange[stateProp] = value stateChange['isChanged'] = true this.setState(stateChange) } onChangeOperatingSystem (osId) { this.doChangeOsIdTo(osId) } doChangeOsIdTo (osId) { const os = this.props.operatingSystems.get(osId) if (os) { this.onChangeOsIconId(os.getIn(['icons', 'large', 'id'])) this.checkTimeZone({ osType: os.get('name') }) } this.setState({ osId, isChanged: true, }) } onChangeOsIconId (iconId) { if (this.state.icon.id && isValidOsIcon(this.props.operatingSystems, this.state.icon.id)) { // change unless custom icon is selected this.doChangeIconId(iconId) } } checkTimeZone ({ osType }) { const { config } = this.props let timeZone = this.state.timeZone const template = this.getTemplate() if (template && template.getIn(['timeZone', 'name'])) { timeZone = timeZone || template.get('timeZone').toJS() } const isWindowsTimeZone = timeZone && timezones.find(timezone => timezone.id === timeZone.name) const isWindowsVm = isWindows(osType) if (isWindowsVm && !isWindowsTimeZone) { timeZone = { name: config.get('defaultWindowsTimezone'), } } if (!isWindowsVm && isWindowsTimeZone) { timeZone = { name: config.get('defaultGeneralTimezone'), } } if (timeZone) { this.setState({ timeZone, }) } } doChangeIconId (iconId) { this.setUiError('icon') this.setState({ icon: { id: iconId, }, isChanged: true, }) } onIconChange (icon) { if (icon) { this.setUiError('icon') this.setState({ icon, isChanged: true, }) } else { // set default os icon const os = this.getOS() if (os) { this.doChangeIconId(os.getIn(['icons', 'large', 'id'])) } } } getOsIdFromType (type) { const os = findOsByName(this.props.operatingSystems, type) return os ? os.get('id') : undefined } /** * @returns OperatingSystem object conforming this.state.osId */ getOS () { const osId = this.state.osId if (osId) { const os = this.props.operatingSystems.get(osId) if (os) { return os } } return undefined } /** * User selected different template. */ onChangeTemplate (templateId) { this.doChangeTemplateIdTo(templateId) } doChangeTemplateIdTo (templateId) { const template = this.getTemplate(templateId) let { memory, cpus, osId, cloudInit, bootMenuEnabled } = this.state if (template) { memory = template.get('memory') cpus = template.getIn(['cpu', 'topology', 'cores'], 1) * template.getIn(['cpu', 'topology', 'sockets'], 1) * template.getIn(['cpu', 'topology', 'threads'], 1) osId = this.getOsIdFromType(template.getIn(['os', 'type'], 'Blank')) cloudInit = template.get('cloudInit').toJS() bootMenuEnabled = template.get('bootMenuEnabled') } this.setState({ templateId, memory, cpus, isChanged: true, cloudInit, bootMenuEnabled, }) const osType = this.props.operatingSystems.getIn([ osId, 'name' ]) this.checkTimeZone({ osType }) if (this.state.osId !== osId) { this.doChangeOsIdTo(osId) } // fire external data retrieval here if needed after Template change } /** * @returns template object conforming this.state.templateId */ getTemplate (templateId) { templateId = templateId || this.state.templateId if (templateId) { const template = this.props.templates.get(templateId) if (template) { return template } } return undefined } /** * User selected different cluster. */ onChangeCluster (clusterId) { this.setState({ clusterId, }) const template = this.getTemplate(this.state.templateId) if (template && template.get('clusterId') && template.get('clusterId') !== clusterId) { this.doChangeTemplateIdTo(zeroUID) // Careful: this.state.clusterId still contains previous clusterId, call setTimeout(function, 0) if needed otherwise } // fire external data retrieval here if needed after Cluster change } onChangeBootMenuEnabled (switchComponent, value) { this.setState({ bootMenuEnabled: value }) } /** * @returns cluster object conforming this.state.clusterId */ getCluster () { const clusterId = this.state.clusterId if (clusterId) { const cluster = this.props.clusters.get(clusterId) if (cluster) { return cluster } } return undefined } getCDRomFileId () { if (this.state.cdrom.fileId !== null) { return this.state.cdrom.fileId } else { return this.props.vm.getIn(['cdrom', 'fileId']) || '' } } initDefaults () { const { clusters, templates, operatingSystems } = this.props const stateChange = {} const defaultClusterName = 'Default' if (!this.getCluster()) { const clustersList = clusters.toList() const def = (clustersList.filter(item => item.get('name') === defaultClusterName).first()) || clustersList.first() stateChange.clusterId = def ? def.get('id') : undefined console.log(`VmDialog initDefaults(): Setting initial value for clusterId = ${this.state.clusterId} to ${stateChange.clusterId}`) } if (!this.getTemplate()) { const def = templates.get(zeroUID) || this.props.templates.toList().first() stateChange.templateId = def ? def.get('id') : undefined console.log(`VmDialog initDefaults(): Setting initial value for templateId = ${this.state.templateId} to ${stateChange.templateId}`) } if (!this.getOS()) { const osList = operatingSystems.toList() const os = osList.sort((a, b) => a.get('id').localeCompare(b.get('id'))).first() if (os) { stateChange.osId = os.get('id') stateChange.icon = { id: os.getIn(['icons', 'large', 'id']), } } console.log(`VmDialog initDefaults(): Setting initial value for osId = ${this.state.osId} to ${stateChange.osId}`) } if (this.getTemplate(stateChange.templateId).get('timeZone')) { stateChange.timeZone = this.getTemplate(stateChange.templateId).get('timeZone').toJS() console.log(`VmDialog initDefaults(): Setting initial value for timeZone = ${JSON.stringify(this.state.timeZone)} to ${JSON.stringify(stateChange.timeZone)}`) } this.setState(stateChange) } handleCloudInitChange (key) { return (value) => { this.setState((prevState) => { return { cloudInit: Object.assign({}, prevState.cloudInit, { [key]: value }) } }) } } onChangeBootDevice (id) { return (device) => { this.setState((prevState) => { const copiedDevices = prevState.bootDevices.slice() copiedDevices[id] = device for (let i = id + 1; i < copiedDevices.length; i++) { copiedDevices[i] = copiedDevices[i] === device ? null : copiedDevices[i] } return { bootDevices: copiedDevices } }) } } render () { const { icons, templates, clusters, storages, previousPath, operatingSystems, } = this.props const { bootDevices } = this.state const vm = this.props.vm const idPrefix = `vmdialog-${vm ? vm.get('name') : '_new'}` const files = [{ id: '', value: '[Eject]' }] storages.toList().forEach(storageDomain => { const fileList = storageDomain.get('files') if (fileList) { files.push(...fileList.map(item => ( { id: item['id'], value: item['name'] } ))) } }) const isEdit = !!vm const isUp = (isEdit && isRunning(vm.get('status'))) const filteredTemplates = templates .filter(template => template.get('clusterId') === this.state.clusterId || !template.get('clusterId')) const cluster = this.getCluster() const architecture = cluster && cluster.get('architecture') const osMap = filterOsByArchitecture(operatingSystems, architecture) const os = this.getOS() const template = this.getTemplate() const cdromFileId = this.getCDRomFileId() const submitText = isEdit ? msg.updateVm() : msg.createVm() const allowedBootDevices = ['hd', 'network', 'cdrom'] const dialogHeader = isEdit ? `${vm.get('name')} - ${msg.edit()}` : msg.createANewVm() const icon = this.state.icon.id ? icons.get(this.state.icon.id) : Immutable.fromJS(this.state.icon) const bootMenuHint = isUp ? (<React.Fragment> {msg.bootMenuTooltip()} <br /> <span className='pficon pficon-warning-triangle-o' /> &nbsp; {msg.bootMenuWarning()} </React.Fragment>) : msg.bootMenuTooltip() const vmNameError = this.state.vmNameErrorText ? (<span className={`help-block ${style['error-text']}`}>{this.state.vmNameErrorText}</span>) : null return ( <div className='detail-container'><DetailContainer> <h1 className={style['header']} id={`${idPrefix}-${isEdit ? 'edit' : 'create'}-title`}> <VmIcon icon={icon} missingIconClassName='pficon pficon-virtual-machine' /> &nbsp;{dialogHeader} </h1> {this.getLatestUserMessage() && (<ErrorAlert message={this.getLatestUserMessage()} id={`${idPrefix}-erroralert`} />)} <br /> <form> <NavigationPrompt when={this.state.isChanged}> {({ isActive, onConfirm, onCancel }) => ( <NavigationConfirmationModal show={isActive} onYes={onConfirm} onNo={onCancel} /> )} </NavigationPrompt> <div className={style['vm-dialog-container']}> <dl className={sharedStyle['vm-properties']}> <dt> <FieldHelp content={msg.uniqueNameOfTheVirtualMachine()} text={msg.name()} /> </dt> <dd className={this.state.vmNameErrorText ? 'has-error' : ''}> <input type='text' className='form-control' id='vmName' placeholder={msg.enterVmName()} onChange={this.onChangeVmName} value={this.state.name || ''} /> {vmNameError} </dd> <dt> <FieldHelp content={msg.optionalUserDescriptionOfVm()} text={msg.description()} /> </dt> <dd> <input type='text' className='form-control' id='vmDescription' placeholder={msg.enterVmDescription()} onChange={this.onChangeVmDescription} value={this.state.description || ''} /> </dd> <dt> <FieldHelp content={msg.groupOfHostsVmCanBeRunningOn()} text={msg.cluster()} /> </dt> <dd className={style['field-overflow-visible']}> <SelectBox onChange={this.onChangeCluster} selected={cluster ? cluster.get('id') : ''} idPrefix='select-cluster' sort items={clusters.toList().map(item => ( { id: item.get('id'), value: item.get('name') } )).toJS()} /> </dd> <dt> <FieldHelp content={msg.containsConfigurationAndDisksWhichWillBeUsedToCreateThisVm()} text={msg.template()} /> </dt> <dd className={style['field-overflow-visible']}> <SelectBox onChange={this.onChangeTemplate} selected={template ? template.get('id') : ''} idPrefix='select-template' sort items={filteredTemplates.toList().map(item => ( { id: item.get('id'), value: templateNameRenderer(item) } )).toJS()} /> </dd> <dt> <FieldHelp content={msg.operatingSystemInstalledOnVm()} text={msg.operatingSystem()} /> </dt> <dd className={style['field-overflow-visible']}> <SelectBox onChange={this.onChangeOperatingSystem} selected={os ? os.get('id') : ''} idPrefix='select-os' sort items={osMap.toList().map(item => ( { id: item.get('id'), value: item.get('description') } )).toJS()} /> </dd> <dt> <span className='pficon pficon-memory' /> &nbsp; <FieldHelp content={msg.totalMemoryVmWillBeEquippedWith()} text={msg.definedMemory()} /> </dt> <dd> <input type='number' className='form-control' id='vmMemory' placeholder={msg.vmMemory()} onChange={this.onChangeVmMemory} value={this.state.memory / 1024 / 1024 || ''} min={0} step={256} /> </dd> <dt> <span className='pficon pficon-cpu' /> &nbsp; <FieldHelp content={msg.totalCountOfVirtualProcessorsVmWillBeEquippedWith()} text={msg.cpus()} /> </dt> <dd> <input type='number' className='form-control' id='vmCpus' placeholder={msg.cpus()} onChange={this.onChangeVmCpu} value={this.state.cpus || ''} min={1} step={1} /> </dd> { isEdit && ( <div> {/* this <div> is ugly anti-pattern and should be replaced by React.Fragment as soon as upgraded to React 16 */} <dt> <span className='pficon pficon-storage-domain' /> &nbsp; <FieldHelp content={msg.changeCd()} text={msg.cd()} /> </dt> <dd className={style['field-overflow-visible']}> <SelectBox onChange={this.onChangeCD} idPrefix='select-changecd' selected={cdromFileId} sort items={files} /> </dd> </div> )} <dt> { (isUp && vm.get('bootMenuEnabled') !== this.state.bootMenuEnabled) && <span className={'pficon pficon-warning-triangle-o ' + style['space-right']} /> } <FieldHelp content={bootMenuHint} text={msg.bootMenu()} /> </dt> <dd> <Switch animate bsSize='mini' value={!!this.state.bootMenuEnabled} onChange={this.onChangeBootMenuEnabled} /> </dd> <dt> <FieldHelp content={msg.bootSequenceTooltip()} text={msg.bootSequence()} /> </dt> <dd /> <div> <dt className={style['field-shifted']}> <FieldHelp content={msg.firstDeviceTooltip()} text={msg.firstDevice()} /> </dt> <dd className={style['field-overflow-visible']}> <SelectBox onChange={this.onChangeBootDevice(FIRST_DEVICE)} selected={bootDevices[FIRST_DEVICE]} idPrefix='select-first-device' items={allowedBootDevices.map(item => ( { id: item, value: msg[`${item}Boot`]() } ))} /> </dd> <dt className={style['field-shifted']}> <FieldHelp content={msg.secondDeviceTooltip()} text={msg.secondDevice()} /> </dt> <dd className={style['field-overflow-visible']}> <SelectBox onChange={this.onChangeBootDevice(SECOND_DEVICE)} selected={bootDevices[SECOND_DEVICE]} idPrefix='select-second-device' items={[{ id: null, value: '[None]' }, ...allowedBootDevices.filter(item => ( item !== bootDevices[FIRST_DEVICE] )).map(item => ( { id: item, value: msg[`${item}Boot`]() } ))]} /> </dd> </div> <CloudInitEditor enabled={this.state.cloudInit.enabled} hostName={this.state.cloudInit.hostName} sshAuthorizedKeys={this.state.cloudInit.sshAuthorizedKeys} onEnabledChange={this.handleCloudInitChange('enabled')} onHostNameChange={this.handleCloudInitChange('hostName')} onSshAuthorizedKeysChange={this.handleCloudInitChange('sshAuthorizedKeys')} /> <IconUpload onIconChange={this.onIconChange} onErrorChange={(error) => this.setUiError('icon', error)} error={this.state.uiErrors.icon} /> </dl> </div> <div className={style['vm-dialog-buttons']}> <Link id='button-close' className='btn btn-default' to={previousPath}>{msg.close()}</Link> <button id='button-submit' className='btn btn-primary' type='button' onClick={this.submitHandler}>{submitText}</button> </div> </form> </DetailContainer></div> ) } } VmDialog.propTypes = { vm: PropTypes.object, // optional, VM object to edit clusters: PropTypes.object.isRequired, // deep immutable, {[id: string]: Cluster} templates: PropTypes.object.isRequired, // deep immutable, {[id: string]: Template} operatingSystems: PropTypes.object.isRequired, // deep immutable, {[id: string]: OperatingSystem} userMessages: PropTypes.object.isRequired, icons: PropTypes.object.isRequired, config: PropTypes.object.isRequired, storages: PropTypes.object.isRequired, // deep immutable, {[id: string]: StorageDomain} previousPath: PropTypes.string.isRequired, addVm: PropTypes.func.isRequired, updateVm: PropTypes.func.isRequired, } export default connect( (state) => ({ clusters: state.clusters.filter(cluster => cluster.get('canUserUseCluster')), templates: state.templates.filter(cluster => cluster.get('canUserUseTemplate')), operatingSystems: state.operatingSystems, userMessages: state.userMessages, icons: state.icons, storages: state.storageDomains, config: state.config, }), (dispatch) => ({ addVm: (vm, correlationId, clone) => dispatch(createVm({ vm, pushToDetailsOnSuccess: true, clone }, { correlationId })), updateVm: (vm, correlationId) => dispatch(editVm({ vm }, { correlationId })), }) )(VmDialog)
mareklibra/userportal
src/components/VmDialog/index.js
JavaScript
apache-2.0
28,260
/** * Copyright 2017 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {HostServices} from '../../../src/inabox/host-services'; import {ScrollManager} from './scroll-manager'; import {Services} from '../../../src/services'; import {VisibilityManagerForMApp} from './visibility-manager-for-mapp'; import { closestAncestorElementBySelector, matches, scopedQuerySelector, } from '../../../src/dom'; import {dev, user, userAssert} from '../../../src/log'; import {getMode} from '../../../src/mode'; import {layoutRectLtwh} from '../../../src/layout-rect'; import {map} from '../../../src/utils/object'; import {provideVisibilityManager} from './visibility-manager'; import {tryResolve} from '../../../src/utils/promise'; import {whenContentIniLoad} from '../../../src/ini-load'; const TAG = 'amp-analytics/analytics-root'; /** * An analytics root. Analytics can be scoped to either ampdoc, embed or * an arbitrary AMP element. * * TODO(#22733): merge analytics root properties into ampdoc. * * @implements {../../../src/service.Disposable} * @abstract */ export class AnalyticsRoot { /** * @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc */ constructor(ampdoc) { /** @const */ this.ampdoc = ampdoc; /** @const */ this.trackers_ = map(); /** @private {?./visibility-manager.VisibilityManager} */ this.visibilityManager_ = null; /** @private {?./scroll-manager.ScrollManager} */ this.scrollManager_ = null; /** @private {?Promise} */ this.usingHostAPIPromise_ = null; /** @private {?../../../src/inabox/host-services.VisibilityInterface} */ this.hostVisibilityService_ = null; } /** * @return {!Promise<boolean>} */ isUsingHostAPI() { if (this.usingHostAPIPromise_) { return this.usingHostAPIPromise_; } if (!HostServices.isAvailable(this.ampdoc)) { this.usingHostAPIPromise_ = Promise.resolve(false); } else { // TODO: Using the visibility service and apply it for all tracking types const promise = HostServices.visibilityForDoc(this.ampdoc); this.usingHostAPIPromise_ = promise .then(visibilityService => { this.hostVisibilityService_ = visibilityService; return true; }) .catch(error => { dev().fine( TAG, 'VisibilityServiceError - fallback=' + error.fallback ); if (error.fallback) { // Do not use HostAPI, fallback to original implementation. return false; } // Cannot fallback, service error. Throw user error. throw user().createError('Host Visibility Service Error'); }); } return this.usingHostAPIPromise_; } /** @override */ dispose() { for (const k in this.trackers_) { this.trackers_[k].dispose(); delete this.trackers_[k]; } if (this.visibilityManager_) { this.visibilityManager_.dispose(); } if (this.scrollManager_) { this.scrollManager_.dispose(); } } /** * Returns the type of the tracker. * @return {string} * @abstract */ getType() {} /** * The root node the analytics is scoped to. * * @return {!Document|!ShadowRoot} * @abstract */ getRoot() {} /** * The viewer of analytics root * @return {!../../../src/service/viewer-interface.ViewerInterface} */ getViewer() { return Services.viewerForDoc(this.ampdoc); } /** * The root element within the analytics root. * * @return {!Element} */ getRootElement() { const root = this.getRoot(); return dev().assertElement(root.documentElement || root.body || root); } /** * The host element of the analytics root. * * @return {?Element} * @abstract */ getHostElement() {} /** * The signals for the root. * * @return {!../../../src/utils/signals.Signals} * @abstract */ signals() {} /** * Whether this analytics root contains the specified node. * * @param {!Node} node * @return {boolean} */ contains(node) { return this.getRoot().contains(node); } /** * Returns the element with the specified ID in the scope of this root. * * @param {string} unusedId * @return {?Element} * @abstract */ getElementById(unusedId) {} /** * Returns the tracker for the specified name and list of allowed types. * * @param {string} name * @param {!Object<string, typeof ./events.EventTracker>} whitelist * @return {?./events.EventTracker} */ getTrackerForWhitelist(name, whitelist) { const trackerProfile = whitelist[name]; if (trackerProfile) { return this.getTracker(name, trackerProfile); } return null; } /** * Returns the tracker for the specified name and type. If the tracker * has not been requested before, it will be created. * * @param {string} name * @param {typeof ./events.CustomEventTracker|typeof ./events.ClickEventTracker|typeof ./events.ScrollEventTracker|typeof ./events.SignalTracker|typeof ./events.IniLoadTracker|typeof ./events.VideoEventTracker|typeof ./events.VideoEventTracker|typeof ./events.VisibilityTracker|typeof ./events.AmpStoryEventTracker} klass * @return {!./events.EventTracker} */ getTracker(name, klass) { let tracker = this.trackers_[name]; if (!tracker) { tracker = new klass(this); this.trackers_[name] = tracker; } return tracker; } /** * Returns the tracker for the specified name or `null`. * @param {string} name * @return {?./events.EventTracker} */ getTrackerOptional(name) { return this.trackers_[name] || null; } /** * Searches the element that matches the selector within the scope of the * analytics root in relationship to the specified context node. * * @param {!Element} context * @param {string} selector DOM query selector. * @param {?string=} selectionMethod Allowed values are `null`, * `'closest'` and `'scope'`. * @return {!Promise<!Element>} Element corresponding to the selector. */ getElement(context, selector, selectionMethod = null) { // Special case selectors. The selection method is irrelavant. // And no need to wait for document ready. if (selector == ':root') { return tryResolve(() => this.getRootElement()); } if (selector == ':host') { return new Promise(resolve => { resolve( user().assertElement( this.getHostElement(), `Element "${selector}" not found` ) ); }); } // Wait for document-ready to avoid false missed searches return this.ampdoc.whenReady().then(() => { let found; let result = null; // Query search based on the selection method. try { if (selectionMethod == 'scope') { found = scopedQuerySelector(context, selector); } else if (selectionMethod == 'closest') { found = closestAncestorElementBySelector(context, selector); } else { found = this.getRoot().querySelector(selector); } } catch (e) { userAssert(false, `Invalid query selector ${selector}`); } // DOM search can "look" outside the boundaries of the root, thus make // sure the result is contained. if (found && this.contains(found)) { result = found; } return user().assertElement(result, `Element "${selector}" not found`); }); } /** * Searches the AMP element that matches the selector within the scope of the * analytics root in relationship to the specified context node. * * @param {!Element} context * @param {string} selector DOM query selector. * @param {?string=} selectionMethod Allowed values are `null`, * `'closest'` and `'scope'`. * @return {!Promise<!AmpElement>} AMP element corresponding to the selector if found. */ getAmpElement(context, selector, selectionMethod) { return this.getElement(context, selector, selectionMethod).then(element => { userAssert( element.classList.contains('i-amphtml-element'), 'Element "%s" is required to be an AMP element', selector ); return element; }); } /** * Creates listener-filter for DOM events to check against the specified * selector. If the node (or its ancestors) match the selector the listener * will be called. * * @param {function(!Element, !Event)} listener The first argument is the * matched target node and the second is the original event. * @param {!Element} context * @param {string} selector DOM query selector. * @param {?string=} selectionMethod Allowed values are `null`, * `'closest'` and `'scope'`. * @return {function(!Event)} */ createSelectiveListener(listener, context, selector, selectionMethod = null) { return event => { if (selector == ':host') { // `:host` is not reachable via selective listener b/c event path // cannot be retargeted across the boundary of the embed. return; } // Navigate up the DOM tree to find the actual target. const rootElement = this.getRootElement(); const isSelectAny = selector == '*'; const isSelectRoot = selector == ':root'; let {target} = event; while (target) { // Target must be contained by this root. if (!this.contains(target)) { break; } // `:scope` context must contain the target. if ( selectionMethod == 'scope' && !isSelectRoot && !context.contains(target) ) { break; } // `closest()` target must contain the conext. if (selectionMethod == 'closest' && !target.contains(context)) { // However, the search must continue! target = target.parentElement; continue; } // Check if the target matches the selector. if ( isSelectAny || (isSelectRoot && target == rootElement) || tryMatches_(target, selector) ) { listener(target, event); // Don't fire the event multiple times even if the more than one // ancestor matches the selector. break; } target = target.parentElement; } }; } /** * Returns the promise that will be resolved as soon as the elements within * the root have been loaded inside the first viewport of the root. * @return {!Promise} * @abstract */ whenIniLoaded() {} /** * Returns the visibility root corresponding to this analytics root (ampdoc * or embed). The visibility root is created lazily as needed and takes * care of all visibility tracking functions. * * The caller needs to make sure to call getVisibilityManager after * usingHostAPIPromise has resolved * @return {!./visibility-manager.VisibilityManager} */ getVisibilityManager() { if (!this.visibilityManager_) { if (this.hostVisibilityService_) { // If there is hostAPI (hostAPI never exist with the FIE case) this.visibilityManager_ = new VisibilityManagerForMApp( this.ampdoc, this.hostVisibilityService_ ); } else { this.visibilityManager_ = provideVisibilityManager(this.getRoot()); } } return this.visibilityManager_; } /** * Returns the Scroll Managet corresponding to this analytics root. * The Scroll Manager is created lazily as needed, and will handle * calling all handlers for a scroll event. * @return {!./scroll-manager.ScrollManager} */ getScrollManager() { // TODO (zhouyx@): Disallow scroll trigger with host API if (!this.scrollManager_) { this.scrollManager_ = new ScrollManager(this.ampdoc); } return this.scrollManager_; } } /** * The implementation of the analytics root for an ampdoc. */ export class AmpdocAnalyticsRoot extends AnalyticsRoot { /** * @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc */ constructor(ampdoc) { super(ampdoc); } /** @override */ getType() { return 'ampdoc'; } /** @override */ getRoot() { return this.ampdoc.getRootNode(); } /** @override */ getHostElement() { // ampdoc is always the root of everything - no host. return null; } /** @override */ signals() { return this.ampdoc.signals(); } /** @override */ getElementById(id) { return this.ampdoc.getElementById(id); } /** @override */ whenIniLoaded() { const viewport = Services.viewportForDoc(this.ampdoc); let rect; if (getMode(this.ampdoc.win).runtime == 'inabox') { // TODO(dvoytenko, #7971): This is currently addresses incorrect position // calculations in a in-a-box viewport where all elements are offset // to the bottom of the embed. The current approach, even if fixed, still // creates a significant probability of risk condition. // Once address, we can simply switch to the 0/0 approach in the `else` // clause. rect = viewport.getLayoutRect(this.getRootElement()); } else { const size = viewport.getSize(); rect = layoutRectLtwh(0, 0, size.width, size.height); } return whenContentIniLoad(this.ampdoc, this.ampdoc.win, rect); } } /** * The implementation of the analytics root for FIE. * TODO(#22733): merge into AnalyticsRoot once ampdoc-fie is launched. */ export class EmbedAnalyticsRoot extends AnalyticsRoot { /** * @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc * @param {!../../../src/friendly-iframe-embed.FriendlyIframeEmbed} embed */ constructor(ampdoc, embed) { super(ampdoc); /** @const */ this.embed = embed; } /** @override */ getType() { return 'embed'; } /** @override */ getRoot() { return this.embed.win.document; } /** @override */ getHostElement() { return this.embed.iframe; } /** @override */ signals() { return this.embed.signals(); } /** @override */ getElementById(id) { return this.embed.win.document.getElementById(id); } /** @override */ whenIniLoaded() { return this.embed.whenIniLoaded(); } } /** * @param {!Element} el * @param {string} selector * @return {boolean} * @noinline */ function tryMatches_(el, selector) { try { return matches(el, selector); } catch (e) { user().error(TAG, 'Bad query selector.', selector, e); return false; } }
src-code/amphtml
extensions/amp-analytics/0.1/analytics-root.js
JavaScript
apache-2.0
15,094
define({ "map": { "error": "无法创建地图", "licenseError": { "message": "您的帐户无权使用非公共的可配置应用程序。 请联系您的组织管理员为您分配包含基本应用程序或附加基本应用程序许可的用户类型。", "title": "未经许可" } }, "viewer": { "content_title": "过滤器", "button_text": "应用", "filterInstructions": "通过指定值来过滤图层。", "filterOr": "以下任意表达式必须为 true。", "filterAnd": "以下表达式必须全部为 true。", "filterNo": "此 Web 地图不包含任何交互式过滤器。要启用交互式过滤器表达式,请选中 Web 地图过滤器对话框中的“请求值”。<br><br>更多有关帮助,请查看 ${link} 帮助主题了解有关如何在 web 地图中创建交互式过滤器表达式的详细信息。", "filterLink": "http://doc.arcgis.com/en/arcgis-online/use-maps/apply-filters.htm", "errors": { "message": "创建过滤器应用时出现问题" } }, "tools": { "toggle": "切换面板", "clear": "清除", "zoom": "缩放" }, "legend": { "title": "图例" } });
Esri/InteractiveFilter
js/nls/zh-CN/resources.js
JavaScript
apache-2.0
1,195
/* * Copyright (C) 2017-2019 Dremio Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { Component } from 'react'; import Radium from 'radium'; import PropTypes from 'prop-types'; import Immutable from 'immutable'; import classNames from 'classnames'; import DragColumnMenu from 'components/DragComponents/DragColumnMenu'; import ColumnDragItem from 'utils/ColumnDragItem'; import { base, inner, leftBorder, fullHeight, contentPadding } from '@app/uiTheme/less/Aggregate/AggregateContent.less'; import ColumnDragArea from './components/ColumnDragArea'; import MeasureDragArea, { MEASURE_DRAG_AREA_TEXT } from './components/MeasureDragArea'; export const NOT_SUPPORTED_TYPES = new Set(['MAP', 'LIST', 'STRUCT']); @Radium class AggregateContent extends Component { static propTypes = { fields: PropTypes.object, canSelectMeasure: PropTypes.bool, canUseFieldAsBothDimensionAndMeasure: PropTypes.bool, allColumns: PropTypes.instanceOf(Immutable.List), handleDragStart: PropTypes.func, onDragEnd: PropTypes.func, onDrop: PropTypes.func, handleMeasureChange: PropTypes.func, dragType: PropTypes.string, path: PropTypes.string, isDragInProgress: PropTypes.bool, style: PropTypes.object, dragItem: PropTypes.instanceOf(ColumnDragItem), className: PropTypes.string, canAlter: PropTypes.any }; static defaultProps = { allColumns: Immutable.List(), canSelectMeasure: true, canUseFieldAsBothDimensionAndMeasure: true }; disabledColumnNames = undefined; constructor(props) { super(props); this.receiveProps(props, {}); } componentWillReceiveProps(nextProps) { this.receiveProps(nextProps, this.props); } receiveProps(nextProps, oldProps) { // disabledColumnNames is wholly derived from these props, so only recalculate it when one of them has changed const propKeys = ['allColumns', 'fields', 'canSelectMeasure', 'canUseFieldAsBothDimensionAndMeasure']; if (propKeys.some((key) => nextProps[key] !== oldProps[key])) { this.disabledColumnNames = this.getDisabledColumnNames(nextProps); } } getDisabledColumnNames(props) { const { allColumns, fields, canSelectMeasure, canUseFieldAsBothDimensionAndMeasure } = props; const dimensionColumnNames = Immutable.Set(fields.columnsDimensions.map(col => col.column.value)); const measuresColumnNames = Immutable.Set(fields.columnsMeasures.map(col => col.column.value)); const columnsInEither = dimensionColumnNames.concat(measuresColumnNames); const columnsInBoth = dimensionColumnNames.intersect(measuresColumnNames); const disabledColumns = allColumns.filter( (column) => NOT_SUPPORTED_TYPES.has(column.get('type')) || (!canSelectMeasure && columnsInBoth.has(column.get('name'))) || (!canUseFieldAsBothDimensionAndMeasure && columnsInEither.has(column.get('name'))) ); return Immutable.Set(disabledColumns.map((column) => column.get('name'))); } render() { const { allColumns, onDrop, fields, dragType, isDragInProgress, dragItem, handleDragStart, onDragEnd, canUseFieldAsBothDimensionAndMeasure, className, canAlter } = this.props; const commonDragAreaProps = { allColumns, disabledColumnNames: this.disabledColumnNames, handleDragStart, onDragEnd, onDrop, dragType, isDragInProgress, dragItem, canUseFieldAsBothDimensionAndMeasure }; const measurementCls = classNames(['aggregate-measurement', fullHeight]); return ( <div className={classNames(['aggregate-content', base, className])} style={this.props.style}> <div className={inner}> <DragColumnMenu items={allColumns} className={fullHeight} disabledColumnNames={this.disabledColumnNames} columnType='column' handleDragStart={handleDragStart} onDragEnd={onDragEnd} dragType={dragType} name={`${this.props.path} (${la('Current')})`} canAlter={canAlter} /> </div> <div className={leftBorder}> <ColumnDragArea className={classNames(['aggregate-dimension', fullHeight])} dragContentCls={contentPadding} {...commonDragAreaProps} columnsField={fields.columnsDimensions} canAlter={canAlter} /> </div> <div className={leftBorder}> { this.props.canSelectMeasure ? <MeasureDragArea dragContentCls={contentPadding} className={measurementCls} {...commonDragAreaProps} columnsField={fields.columnsMeasures}/> : <ColumnDragArea dragContentCls={contentPadding} className={measurementCls} {...commonDragAreaProps} dragOrigin='measures' dragAreaText={MEASURE_DRAG_AREA_TEXT} columnsField={fields.columnsMeasures} canAlter={canAlter} /> } </div> </div> ); } } export default AggregateContent;
dremio/dremio-oss
dac/ui/src/components/Aggregate/AggregateContent.js
JavaScript
apache-2.0
5,729
/* Copyright ONECHAIN 2017 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. */ var StompServer=require('stomp-broker-js') var stompServer function init(http){ stompServer=new StompServer({server:http}) } module.exports.init=init module.exports.stomp=function () { return stompServer }
onechain/fabric-explorer
socket/websocketserver.js
JavaScript
apache-2.0
801
/*jslint devel: true */ /*global Titanium, module */ (function (Ti) { "use strict"; var style = { win: { backgroundColor: "#FFFFFF", layout: "vertical" }, btn: { top: 44, title: "Get GeoHash!" }, label: { top: 22, color: "#666666", font: { fontFamily: "monospace" } }, map: { top: 22, mapType: Ti.Map.STANDARD_TYPE, animate: true, regionFit: true }, extend: function (target, append) { var key; for (key in append) { if (append.hasOwnProperty(key)) { target[key] = append[key]; } } return target; } }; module.exports = style; }(Titanium));
ryugoo/TiGeoHash
Resources/style/app.style.js
JavaScript
apache-2.0
898
/** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import {plotData} from './index'; const statusElement = document.getElementById('status'); const timeSpanSelect = document.getElementById('time-span'); const selectSeries1 = document.getElementById('data-series-1'); const selectSeries2 = document.getElementById('data-series-2'); const dataNormalizedCheckbox = document.getElementById('data-normalized'); const dateTimeRangeSpan = document.getElementById('date-time-range'); const dataPrevButton = document.getElementById('data-prev'); const dataNextButton = document.getElementById('data-next'); const dataScatterCheckbox = document.getElementById('data-scatter'); export function logStatus(message) { statusElement.innerText = message; } export function populateSelects(dataObj) { const columnNames = ['None'].concat(dataObj.getDataColumnNames()); for (const selectSeries of [selectSeries1, selectSeries2]) { while (selectSeries.firstChild) { selectSeries.removeChild(selectSeries.firstChild); } console.log(columnNames); for (const name of columnNames) { const option = document.createElement('option'); option.setAttribute('value', name); option.textContent = name; selectSeries.appendChild(option); } } if (columnNames.indexOf('T (degC)') !== -1) { selectSeries1.value = 'T (degC)'; } if (columnNames.indexOf('p (mbar)') !== -1) { selectSeries2.value = 'p (mbar)'; } timeSpanSelect.value = 'week'; dataNormalizedCheckbox.checked = true; } export const TIME_SPAN_RANGE_MAP = { hour: 6, day: 6 * 24, week: 6 * 24 * 7, tenDays: 6 * 24 * 10, month: 6 * 24 * 30, year: 6 * 24 * 365, full: null }; export const TIME_SPAN_STRIDE_MAP = { day: 1, week: 1, tenDays: 6, month: 6, year: 6 * 6, full: 6 * 24 }; export let currBeginIndex = 0; export function updateDateTimeRangeSpan(jenaWeatherData) { const timeSpan = timeSpanSelect.value; const currEndIndex = currBeginIndex + TIME_SPAN_RANGE_MAP[timeSpan]; const begin = new Date(jenaWeatherData.getTime(currBeginIndex)).toLocaleDateString(); const end = new Date(jenaWeatherData.getTime(currEndIndex)).toLocaleDateString(); dateTimeRangeSpan.textContent = `${begin} - ${end}`; } export function updateScatterCheckbox() { const series1 = selectSeries1.value; const series2 = selectSeries2.value; dataScatterCheckbox.disabled = series1 === 'None' || series2 === 'None'; } dataPrevButton.addEventListener('click', () => { const timeSpan = timeSpanSelect.value; currBeginIndex -= Math.round(TIME_SPAN_RANGE_MAP[timeSpan] / 8); if (currBeginIndex >= 0) { plotData(); } else { currBeginIndex = 0; } }); dataNextButton.addEventListener('click', () => { const timeSpan = timeSpanSelect.value; currBeginIndex += Math.round(TIME_SPAN_RANGE_MAP[timeSpan] / 8); plotData(); }); timeSpanSelect.addEventListener('change', () => { plotData(); }); selectSeries1.addEventListener('change', plotData); selectSeries2.addEventListener('change', plotData); dataNormalizedCheckbox.addEventListener('change', plotData); dataScatterCheckbox.addEventListener('change', plotData); export function getDataVizOptions() { return { timeSpan: timeSpanSelect.value, series1: selectSeries1.value, series2: selectSeries2.value, normalize: dataNormalizedCheckbox.checked, scatter: dataScatterCheckbox.checked }; }
tensorflow/tfjs-examples
jena-weather/ui.js
JavaScript
apache-2.0
4,072
var dir_0c96b3d0fc842fbb51d7afc18d90cdec = [ [ "design", "dir_b39402054b6f29d8059088b0004b64ee.html", "dir_b39402054b6f29d8059088b0004b64ee" ], [ "v4", "dir_b1530cc8b78b2d9923632461f396c71c.html", "dir_b1530cc8b78b2d9923632461f396c71c" ], [ "v7", "dir_94bdcc46f12b2beb2dba250b68a1fa32.html", "dir_94bdcc46f12b2beb2dba250b68a1fa32" ] ];
feedhenry/fh-dotnet-sdk
Documentations/html/dir_0c96b3d0fc842fbb51d7afc18d90cdec.js
JavaScript
apache-2.0
347
/* Copyright© 2000 - 2022 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ import mapboxgl from 'mapbox-gl'; import { ServiceBase } from './ServiceBase'; import '../core/Base'; import { ImageService as CommonMatchImageService } from '@supermap/iclient-common'; /** * @class mapboxgl.supermap.ImageService * @version 10.2.0 * @constructs mapboxgl.supermap.ImageService * @classdesc 影像服务类 * @category iServer Image * @example * mapboxgl.supermap.ImageService(url,options) * .getCollections(function(result){ * //doSomething * }) * @param {string} url - 服务地址。例如: http://{ip}:{port}/iserver/{imageservice-imageserviceName}/restjsr/ * @param {Object} options - 参数。 * @param {string} [options.proxy] - 服务代理地址。 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {mapboxgl.supermap.ServiceBase} */ export class ImageService extends ServiceBase { constructor(url, options) { super(url, options); } /** * @function mapboxgl.supermap.ImageService.prototype.getCollections * @description 返回当前影像服务中的影像集合列表(Collections)。 * @param {RequestCallback} callback - 请求结果的回调函数。 */ getCollections(callback) { var me = this; var ImageService = new CommonMatchImageService(this.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); ImageService.getCollections(); } /** * @function mapboxgl.supermap.ImageService.prototype.getCollectionByID * @description ID值等于`collectionId`参数值的影像集合(Collection)。 ID值用于在服务中唯一标识该影像集合。 * @param {string} collectionId 影像集合(Collection)的ID,在一个影像服务中唯一标识影像集合。 * @param {RequestCallback} callback - 请求结果的回调函数。 */ getCollectionByID(collectionId, callback) { var me = this; var ImageService = new CommonMatchImageService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); ImageService.getCollectionByID(collectionId); } /** * @function mapboxgl.supermap.ImageService.prototype.search * @description 查询与过滤条件匹配的影像数据。 * @param {SuperMap.ImageSearchParameter} [itemSearch] 查询参数 * @param {RequestCallback} callback - 请求结果的回调函数。 */ search(itemSearch, callback) { var me = this; var ImageService = new CommonMatchImageService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); ImageService.search(itemSearch); } } mapboxgl.supermap.ImageService = ImageService;
SuperMap/iClient9
src/mapboxgl/services/ImageService.js
JavaScript
apache-2.0
3,968
'use strict'; /* Services that are used to interact with the backend. */ var eventManServices = angular.module('eventManServices', ['ngResource']); /* Modify, in place, an object to convert datetime. */ function convert_dates(obj) { angular.forEach(['begin_date', 'end_date', 'ticket_sales_begin_date', 'ticket_sales_end_date'], function(key, key_idx) { if (!obj[key]) { return; } obj[key] = obj[key].getTime(); }); return obj; } eventManServices.factory('Event', ['$resource', '$rootScope', function($resource, $rootScope) { return $resource('events/:id', {id: '@_id'}, { all: { method: 'GET', interceptor: {responseError: $rootScope.errorHandler}, isArray: true, transformResponse: function(data, headers) { data = angular.fromJson(data); if (data.error) { return data; } angular.forEach(data.events || [], function(event_, event_idx) { convert_dates(event_); }); return data.events; } }, get: { method: 'GET', interceptor: {responseError: $rootScope.errorHandler}, transformResponse: function(data, headers) { data = angular.fromJson(data); convert_dates(data); // strip empty keys. angular.forEach(data.tickets || [], function(ticket, ticket_idx) { angular.forEach(ticket, function(value, key) { if (value === "") { delete ticket[key]; } }); }); return data; } }, update: { method: 'PUT', interceptor: {responseError: $rootScope.errorHandler}, transformResponse: function(data, headers) { data = angular.fromJson(data); convert_dates(data); return data; } }, group_persons: { method: 'GET', url: 'events/:id/group_persons', isArray: true, transformResponse: function(data, headers) { data = angular.fromJson(data); return data.persons || []; } } }); }] ); eventManServices.factory('EventTicket', ['$resource', '$rootScope', function($resource, $rootScope) { return $resource('events/:id/tickets', {event_id: '@event_id', ticket_id: '@_id'}, { all: { method: 'GET', url: '/tickets', interceptor: {responseError: $rootScope.errorHandler}, isArray: true, transformResponse: function(data, headers) { data = angular.fromJson(data); return data.tickets; } }, get: { method: 'GET', url: 'events/:id/tickets/:ticket_id', interceptor: {responseError: $rootScope.errorHandler}, transformResponse: function(data, headers) { data = angular.fromJson(data); if (data.error) { return data; } return data.ticket; } }, add: { method: 'POST', interceptor: {responseError: $rootScope.errorHandler}, isArray: false, url: 'events/:event_id/tickets', params: {uuid: $rootScope.app_uuid}, transformResponse: function(data, headers) { data = angular.fromJson(data); if (data.error) { return data; } return data.ticket; } }, update: { method: 'PUT', interceptor: {responseError: $rootScope.errorHandler}, isArray: false, url: 'events/:event_id/tickets/:ticket_id', params: {uuid: $rootScope.app_uuid}, transformResponse: function(data, headers) { if (data.error) { return data; } return angular.fromJson(data); } }, 'delete': { method: 'DELETE', interceptor: {responseError: $rootScope.errorHandler}, isArray: false, url: 'events/:event_id/tickets/:ticket_id', params: {uuid: $rootScope.app_uuid}, transformResponse: function(data, headers) { return angular.fromJson(data); } } }); }] ); eventManServices.factory('Setting', ['$resource', '$rootScope', function($resource, $rootScope) { return $resource('settings/', {}, { query: { method: 'GET', interceptor: {responseError: $rootScope.errorHandler}, isArray: true, transformResponse: function(data, headers) { data = angular.fromJson(data); if (data.error) { return data; } return data.settings; } }, update: { method: 'PUT', interceptor: {responseError: $rootScope.errorHandler} } }); }] ); eventManServices.factory('Info', ['$resource', '$rootScope', function($resource, $rootScope) { return $resource('info/', {}, { get: { method: 'GET', interceptor: {responseError: $rootScope.errorHandler}, isArray: false, transformResponse: function(data, headers) { data = angular.fromJson(data); if (data.error) { return data; } return data.info || {}; } } }); }] ); eventManServices.factory('EbAPI', ['$resource', '$rootScope', function($resource, $rootScope) { return $resource('ebapi/', {}, { apiImport: { method: 'POST', interceptor: {responseError: $rootScope.errorHandler}, isArray: false, transformResponse: function(data, headers) { return angular.fromJson(data); } } }); }] ); eventManServices.factory('User', ['$resource', '$rootScope', function($resource, $rootScope) { return $resource('users/:id', {id: '@_id'}, { all: { method: 'GET', interceptor: {responseError: $rootScope.errorHandler}, isArray: true, transformResponse: function(data, headers) { data = angular.fromJson(data); if (data.error) { return data; } return data.users; } }, get: { method: 'GET', interceptor: {responseError: $rootScope.errorHandler}, transformResponse: function(data, headers) { return angular.fromJson(data); } }, add: { method: 'POST', interceptor: {responseError: $rootScope.errorHandler} }, update: { method: 'PUT', interceptor: {responseError: $rootScope.errorHandler} }, login: { method: 'POST', url: '/login', interceptor: {responseError: $rootScope.errorHandler} }, logout: { method: 'GET', url: '/logout', interceptor: {responseError: $rootScope.errorHandler} } }); }] ); /* WebSocket collection used to update the list of tickets of an Event. */ eventManApp.factory('EventUpdates', ['$websocket', '$location', '$log', '$rootScope', function($websocket, $location, $log, $rootScope) { var dataStream = null; var data = {}; var methods = { data: data, close: function() { $log.debug('close WebSocket connection'); dataStream.close(); }, open: function() { var proto = $location.protocol() == 'https' ? 'wss' : 'ws'; var url = proto + '://' + $location.host() + ':' + $location.port() + '/ws/' + $location.path() + '/updates?uuid=' + $rootScope.app_uuid; $log.debug('open WebSocket connection to ' + url); //dataStream && dataStream.close(); dataStream = $websocket(url); dataStream.onMessage(function(message) { $log.debug('EventUpdates message received'); data.update = angular.fromJson(message.data); }); } }; return methods; }] );
raspibo/eventman
angular_app/js/services.js
JavaScript
apache-2.0
9,665
"use strict"; var samples = {}; module.exports = samples; samples.valid_0 = { "address": "[email protected]", "type": "work place" }; samples.valid_1 = { "address": "[email protected]" }; samples.invalid_0 = {}; samples.invalid_1 = { "address": "[email protected]", "type": "work place", "other": "na" };
amida-tech/blue-button-model
test/samples/unit/cda_email.js
JavaScript
apache-2.0
320
/** * define global constant * * Created by Shiro on 16/12/20. */ const NAV = [ {name: 'Home', link: '/index'}, {name: 'Editor', link: '/editor'}, {name: 'Project', link: '/project', children: [ {name: 'RMSP', link: '/project/rmsp'}, {name: 'test', link: '/project/'}, {name: 'test', link: '/project/'} ]}, {name: 'Css', link: '/css'} ]; export {NAV}; const TITLEMAP = { login: '登录' }; export {TITLEMAP}; const MAP = { sex: ['女', '男'], zodiac: [ {zh: '鼠', emoji: '🐹'}, {zh: '牛', emoji: '🐮'}, {zh: '虎', emoji: '🐯'}, {zh: '兔', emoji: '🐰'}, {zh: '龙', emoji: '🐲'}, {zh: '蛇', emoji: '🐍'}, {zh: '马', emoji: '🦄'}, {zh: '羊', emoji: '🐑'}, {zh: '猴', emoji: '🐒'}, {zh: '鸡', emoji: '🐣'}, {zh: '狗', emoji: '🐶'}, {zh: '猪', emoji: '🐷'} ], constellation: [ {zh: '白羊座', emoji: '♈'}, {zh: '金牛座', emoji: '♉'}, {zh: '双子座', emoji: '♊'}, {zh: '巨蟹座', emoji: '♋'}, {zh: '狮子座', emoji: '♌'}, {zh: '处女座', emoji: '♍'}, {zh: '天秤座', emoji: '♎'}, {zh: '天蝎座', emoji: '♏'}, {zh: '射手座', emoji: '♐'}, {zh: '摩羯座', emoji: '♑'}, {zh: '水瓶座', emoji: '♒'}, {zh: '双鱼座', emoji: '♓'} ] }; export {MAP}
supershiro/Cancer
src/libs/const.js
JavaScript
apache-2.0
1,357
/* Modernizr (Custom Build) | MIT & BSD * Build: http://modernizr.com/download/#-shiv-load-cssclasses-csstransforms3d-flexbox-opacity-touch-cors-svg */ ;Modernizr.addTest("cors",!!(window.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest));
youwenliang/Project-6x6
dist/scripts/vendor/1aad92e4.modernizr.js
JavaScript
apache-2.0
247
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var config = require( './config.js' ); // VARIABLES // var valid; var test; // MAIN // // Create our test cases: valid = []; test = { 'code': [ '/**', '* Squares a number.', '* ', '* @param {number} x - input number', '* @returns {number} x squared', '*', '* @example', '* var y = square( 2.0 );', '* // returns 4.0', '*/', 'function square( x ) {', ' return x*x;', '}' ].join( '\n' ), 'options': [ { 'config': config } ] }; valid.push( test ); test = { 'code': [ '/**', '* Returns a pseudo-random number on [0,1].', '* ', '* @returns {number} uniform random number', '*', '* @example', '* var y = rand();', '* // e.g., returns 0.5363925252089496', '*/', 'function rand() {', ' return Math.random();', '}' ].join( '\n' ), 'options': [ { 'config': config } ] }; valid.push( test ); test = { 'code': [ '/**', '* Returns the number of minutes in a month.', '*', '* @param {(string|Date|integer)} [month] - month', '* @param {integer} [year] - year', '* @throws {TypeError} first argument must be either a string, integer, or `Date` object', '* @throws {Error} must provide a recognized month', '* @throws {RangeError} an integer month argument must be on the interval `[1,12]`', '* @throws {TypeError} second argument must be an integer', '* @returns {integer} minutes in a month', '*', '* @example', '* var num = minutesInMonth();', '* // returns <number>', '*', '* @example', '* var num = minutesInMonth( 2 );', '* // returns <number>', '*', '* @example', '* var num = minutesInMonth( 2, 2016 );', '* // returns 41760', '*', '* @example', '* var num = minutesInMonth( 2, 2017 );', '* // returns 40320', '*/', 'function minutesInMonth( month, year ) {', ' var mins;', ' var mon;', ' var yr;', ' var d;', ' if ( arguments.length === 0 ) {', ' // Note: cannot cache as application may cross over into a new year:', ' d = new Date();', ' mon = d.getMonth() + 1; // zero-based', ' yr = d.getFullYear();', ' } else if ( arguments.length === 1 ) {', ' if ( isDateObject( month ) ) {', ' d = month;', ' mon = d.getMonth() + 1; // zero-based', ' yr = d.getFullYear();', ' } else if ( isString( month ) || isInteger( month ) ) {', ' // Note: cannot cache as application may cross over into a new year:', ' yr = ( new Date() ).getFullYear();', ' mon = month;', ' } else {', ' throw new TypeError( \'invalid argument. First argument must be either a string, integer, or `Date` object. Value: `\'+month+\'`.\' );', ' }', ' } else {', ' if ( !isString( month ) && !isInteger( month ) ) {', ' throw new TypeError( \'invalid argument. First argument must be either a string or integer. Value: `\'+month+\'`.\' );', ' }', ' if ( !isInteger( year ) ) {', ' throw new TypeError( \'invalid argument. Second argument must be an integer. Value: `\'+year+\'`.\' );', ' }', ' mon = month;', ' yr = year;', ' }', ' if ( isInteger( mon ) && (mon < 1 || mon > 12) ) {', ' throw new RangeError( \'invalid argument. An integer month value must be on the interval `[1,12]`. Value: `\'+mon+\'`.\' );', ' }', ' mon = lowercase( mon.toString() );', ' mins = MINUTES_IN_MONTH[ mon ];', ' if ( mins === void 0 ) {', ' throw new Error( \'invalid argument. Must provide a recognized month. Value: `\'+mon+\'`.\' );', ' }', ' // Check if February during a leap year...', ' if ( mins === 40320 && isLeapYear( yr ) ) {', ' mins += MINUTES_IN_DAY;', ' }', ' return mins;', '}' ].join( '\n' ), 'options': [ { 'config': config } ] }; valid.push( test ); test = { 'code': [ '/**', '* Removes a UTF-8 byte order mark (BOM) from the beginning of a string.', '*', '* ## Notes', '*', '* - A UTF-8 byte order mark ([BOM][1]) is the byte sequence `0xEF,0xBB,0xBF`.', '* - To convert a UTF-8 encoded `Buffer` to a `string`, the `Buffer` must be converted to \'[UTF-16][2]. The BOM thus gets converted to the single 16-bit code point `\'\ufeff\'` \'(UTF-16 BOM).', '*', '* [1]: https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8', '* [2]: http://es5.github.io/#x4.3.16', '*', '*', '* @param {string} str - input string', '* @throws {TypeError} must provide a string primitive', '* @returns {string} string with BOM removed', '*', '* @example', '* var str = removeUTF8BOM( \'\ufeffbeep\' );', '* // returns \'beep\'', '*/', 'function removeUTF8BOM( str ) {', ' if ( !isString( str ) ) {', ' throw new TypeError( \'invalid argument. Must provide a string primitive. Value: `\' + str + \'`.\' );', ' }', ' if ( str.charCodeAt( 0 ) === BOM ) {', ' return str.slice( 1 );', ' }', ' return str;', '}' ].join( '\n' ), 'options': [ { 'config': config } ] }; valid.push( test ); test = { 'code': [ '/**', '* @name arcsine', '* @memberof random', '* @readonly', '* @type {Function}', '* @see {@link module:@stdlib/random/base/arcsine}', '*/', 'setReadOnly( random, \'arcsine\', require( \'@stdlib/random/base/arcsine\' ) );' ].join( '\n' ), 'options': [ { 'config': config } ] }; valid.push( test ); test = { 'code': [ '/**', '* Beep boop.', '*', '* Some code...', '*', '* ```javascript', '* var f = foo();', '* ```', '*', '* Some LaTeX...', '*', '* ```tex', '* \\frac{1}{2}', '* ```', '*', '* ## Notes', '*', '* - First.', '* - Second.', '* - Third.', '*', '* ## References', '*', '* - Jane Doe. Science. 2017.', '*', '* | x | y |', '* | 1 | 2 |', '* | 2 | 1 |', '*', '*', '* @param {string} str - input value', '* @returns {string} output value', '*', '* @example', '* var out = beep( "boop" );', '* // returns "beepboop"', '*/', 'function beep( str ) {', '\treturn "beep" + str;', '}' ].join( '\n' ), 'options': [ { 'config': config } ] }; valid.push( test ); // EXPORTS // module.exports = valid;
stdlib-js/stdlib
lib/node_modules/@stdlib/_tools/eslint/rules/jsdoc-markdown-remark/test/fixtures/valid.js
JavaScript
apache-2.0
6,669
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2017 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides the Design Time Metadata for the sap.uxap.ObjectPageLayout control sap.ui.define([], function() { "use strict"; return { name : { singular : function(){ return sap.uxap.i18nModel.getResourceBundle().getText("LAYOUT_CONTROL_NAME"); }, plural : function(){ return sap.uxap.i18nModel.getResourceBundle().getText("LAYOUT_CONTROL__PLURAL"); } }, aggregations : { sections : { domRef : function(oElement) { return oElement.$("sectionsContainer").get(0); }, childNames : { singular : function(){ return sap.uxap.i18nModel.getResourceBundle().getText("SECTION_CONTROL_NAME"); }, plural : function(){ return sap.uxap.i18nModel.getResourceBundle().getText("SECTION_CONTROL_NAME_PLURAL"); } }, actions : { move : "moveControls" } } }, scrollContainers : [{ domRef : "> .sapUxAPObjectPageWrapper", aggregations : ["sections", "headerContent"] }, { domRef : function(oElement) { return oElement.$("vertSB-sb").get(0); } }], cloneDomRef : ":sap-domref > header" }; }, /* bExport= */ false);
thbonk/electron-openui5-boilerplate
libs/openui5-runtime/resources/sap/uxap/ObjectPageLayout.designtime-dbg.js
JavaScript
apache-2.0
1,307
const Long = require('long'); const User = require('./User'); const Role = require('./Role'); const Emoji = require('./Emoji'); const Presence = require('./Presence').Presence; const GuildMember = require('./GuildMember'); const Constants = require('../util/Constants'); const Collection = require('../util/Collection'); const Util = require('../util/Util'); const Snowflake = require('../util/Snowflake'); /** * Represents a guild (or a server) on Discord. * <info>It's recommended to see if a guild is available before performing operations or reading data from it. You can * check this with `guild.available`.</info> */ class Guild { constructor(client, data) { /** * The client that created the instance of the the guild * @name Guild#client * @type {Client} * @readonly */ Object.defineProperty(this, 'client', { value: client }); /** * A collection of members that are in this guild. The key is the member's ID, the value is the member * @type {Collection<Snowflake, GuildMember>} */ this.members = new Collection(); /** * A collection of channels that are in this guild. The key is the channel's ID, the value is the channel * @type {Collection<Snowflake, GuildChannel>} */ this.channels = new Collection(); /** * A collection of roles that are in this guild. The key is the role's ID, the value is the role * @type {Collection<Snowflake, Role>} */ this.roles = new Collection(); /** * A collection of presences in this guild * @type {Collection<Snowflake, Presence>} */ this.presences = new Collection(); if (!data) return; if (data.unavailable) { /** * Whether the guild is available to access. If it is not available, it indicates a server outage * @type {boolean} */ this.available = false; /** * The Unique ID of the guild, useful for comparisons * @type {Snowflake} */ this.id = data.id; } else { this.available = true; this.setup(data); } } /** * Sets up the guild. * @param {*} data The raw data of the guild * @private */ setup(data) { /** * The name of the guild * @type {string} */ this.name = data.name; /** * The hash of the guild icon * @type {?string} */ this.icon = data.icon; /** * The hash of the guild splash image (VIP only) * @type {?string} */ this.splash = data.splash; /** * The region the guild is located in * @type {string} */ this.region = data.region; /** * The full amount of members in this guild as of `READY` * @type {number} */ this.memberCount = data.member_count || this.memberCount; /** * Whether the guild is "large" (has more than 250 members) * @type {boolean} */ this.large = Boolean('large' in data ? data.large : this.large); /** * An array of guild features * @type {Object[]} */ this.features = data.features; /** * The ID of the application that created this guild (if applicable) * @type {?Snowflake} */ this.applicationID = data.application_id; /** * The time in seconds before a user is counted as "away from keyboard" * @type {?number} */ this.afkTimeout = data.afk_timeout; /** * The ID of the voice channel where AFK members are moved * @type {?string} */ this.afkChannelID = data.afk_channel_id; /** * Whether embedded images are enabled on this guild * @type {boolean} */ this.embedEnabled = data.embed_enabled; /** * The verification level of the guild * @type {number} */ this.verificationLevel = data.verification_level; /** * The explicit content filter level of the guild * @type {number} */ this.explicitContentFilter = data.explicit_content_filter; /** * The timestamp the client user joined the guild at * @type {number} */ this.joinedTimestamp = data.joined_at ? new Date(data.joined_at).getTime() : this.joinedTimestamp; this.id = data.id; this.available = !data.unavailable; this.features = data.features || this.features || []; if (data.members) { this.members.clear(); for (const guildUser of data.members) this._addMember(guildUser, false); } if (data.owner_id) { /** * The user ID of this guild's owner * @type {Snowflake} */ this.ownerID = data.owner_id; } if (data.channels) { this.channels.clear(); for (const channel of data.channels) this.client.dataManager.newChannel(channel, this); } if (data.roles) { this.roles.clear(); for (const role of data.roles) { const newRole = new Role(this, role); this.roles.set(newRole.id, newRole); } } if (data.presences) { for (const presence of data.presences) { this._setPresence(presence.user.id, presence); } } this._rawVoiceStates = new Collection(); if (data.voice_states) { for (const voiceState of data.voice_states) { this._rawVoiceStates.set(voiceState.user_id, voiceState); const member = this.members.get(voiceState.user_id); if (member) { member.serverMute = voiceState.mute; member.serverDeaf = voiceState.deaf; member.selfMute = voiceState.self_mute; member.selfDeaf = voiceState.self_deaf; member.voiceSessionID = voiceState.session_id; member.voiceChannelID = voiceState.channel_id; this.channels.get(voiceState.channel_id).members.set(member.user.id, member); } } } if (!this.emojis) { /** * A collection of emojis that are in this guild. The key is the emoji's ID, the value is the emoji. * @type {Collection<Snowflake, Emoji>} */ this.emojis = new Collection(); for (const emoji of data.emojis) this.emojis.set(emoji.id, new Emoji(this, emoji)); } else { this.client.actions.GuildEmojisUpdate.handle({ guild_id: this.id, emojis: data.emojis, }); } } /** * The timestamp the guild was created at * @type {number} * @readonly */ get createdTimestamp() { return Snowflake.deconstruct(this.id).timestamp; } /** * The time the guild was created * @type {Date} * @readonly */ get createdAt() { return new Date(this.createdTimestamp); } /** * The time the client user joined the guild * @type {Date} * @readonly */ get joinedAt() { return new Date(this.joinedTimestamp); } /** * The URL to this guild's icon * @type {?string} * @readonly */ get iconURL() { if (!this.icon) return null; return Constants.Endpoints.Guild(this).Icon(this.client.options.http.cdn, this.icon); } /** * The URL to this guild's splash * @type {?string} * @readonly */ get splashURL() { if (!this.splash) return null; return Constants.Endpoints.Guild(this).Splash(this.client.options.http.cdn, this.splash); } /** * The owner of the guild * @type {GuildMember} * @readonly */ get owner() { return this.members.get(this.ownerID); } /** * If the client is connected to any voice channel in this guild, this will be the relevant VoiceConnection * @type {?VoiceConnection} * @readonly */ get voiceConnection() { if (this.client.browser) return null; return this.client.voice.connections.get(this.id) || null; } /** * The `#general` TextChannel of the guild * @type {TextChannel} * @readonly */ get defaultChannel() { return this.channels.get(this.id); } /** * The position of this guild * <warn>This is only available when using a user account.</warn> * @type {?number} */ get position() { if (this.client.user.bot) return null; if (!this.client.user.settings.guildPositions) return null; return this.client.user.settings.guildPositions.indexOf(this.id); } /** * The `@everyone` role of the guild * @type {Role} * @readonly */ get defaultRole() { return this.roles.get(this.id); } /** * The client user as a GuildMember of this guild * @type {?GuildMember} * @readonly */ get me() { return this.members.get(this.client.user.id); } /** * Fetches a collection of roles in the current guild sorted by position * @type {Collection<Snowflake, Role>} * @readonly * @private */ get _sortedRoles() { return this._sortPositionWithID(this.roles); } /** * Returns the GuildMember form of a User object, if the user is present in the guild. * @param {UserResolvable} user The user that you want to obtain the GuildMember of * @returns {?GuildMember} * @example * // Get the guild member of a user * const member = guild.member(message.author); */ member(user) { return this.client.resolver.resolveGuildMember(this, user); } /** * Fetch a collection of banned users in this guild. * @returns {Promise<Collection<Snowflake, User>>} */ fetchBans() { return this.client.rest.methods.getGuildBans(this) // This entire re-mapping can be removed in the next major release .then(bans => { const users = new Collection(); for (const ban of bans.values()) users.set(ban.user.id, ban.user); return users; }); } /** * Fetch a collection of invites to this guild. Resolves with a collection mapping invites by their codes. * @returns {Promise<Collection<string, Invite>>} */ fetchInvites() { return this.client.rest.methods.getGuildInvites(this); } /** * Fetch all webhooks for the guild. * @returns {Collection<Snowflake, Webhook>} */ fetchWebhooks() { return this.client.rest.methods.getGuildWebhooks(this); } /** * Fetch available voice regions. * @returns {Collection<string, VoiceRegion>} */ fetchVoiceRegions() { return this.client.rest.methods.fetchVoiceRegions(this.id); } /** * Fetch audit logs for this guild. * @param {Object} [options={}] Options for fetching audit logs * @param {Snowflake|GuildAuditLogsEntry} [options.before] Limit to entries from before specified entry * @param {Snowflake|GuildAuditLogsEntry} [options.after] Limit to entries from after specified entry * @param {number} [options.limit] Limit number of entries * @param {UserResolvable} [options.user] Only show entries involving this user * @param {string|number} [options.type] Only show entries involving this action type * @returns {Promise<GuildAuditLogs>} */ fetchAuditLogs(options) { return this.client.rest.methods.getGuildAuditLogs(this, options); } /** * Adds a user to the guild using OAuth2. Requires the `CREATE_INSTANT_INVITE` permission. * @param {UserResolvable} user User to add to the guild * @param {Object} options Options for the addition * @param {string} options.accessToken An OAuth2 access token for the user with the `guilds.join` scope granted to the * bot's application * @param {string} [options.nick] Nickname to give the member (requires `MANAGE_NICKNAMES`) * @param {Collection<Snowflake, Role>|Role[]|Snowflake[]} [options.roles] Roles to add to the member * (requires `MANAGE_ROLES`) * @param {boolean} [options.mute] Whether the member should be muted (requires `MUTE_MEMBERS`) * @param {boolean} [options.deaf] Whether the member should be deafened (requires `DEAFEN_MEMBERS`) * @returns {Promise<GuildMember>} */ addMember(user, options) { if (this.members.has(user.id)) return Promise.resolve(this.members.get(user.id)); return this.client.rest.methods.putGuildMember(this, user, options); } /** * Fetch a single guild member from a user. * @param {UserResolvable} user The user to fetch the member for * @param {boolean} [cache=true] Insert the user into the users cache * @returns {Promise<GuildMember>} */ fetchMember(user, cache = true) { user = this.client.resolver.resolveUser(user); if (!user) return Promise.reject(new Error('User is not cached. Use Client.fetchUser first.')); if (this.members.has(user.id)) return Promise.resolve(this.members.get(user.id)); return this.client.rest.methods.getGuildMember(this, user, cache); } /** * Fetches all the members in the guild, even if they are offline. If the guild has less than 250 members, * this should not be necessary. * @param {string} [query=''] Limit fetch to members with similar usernames * @param {number} [limit=0] Maximum number of members to request * @returns {Promise<Guild>} */ fetchMembers(query = '', limit = 0) { return new Promise((resolve, reject) => { if (this.memberCount === this.members.size) { // Uncomment in v12 // resolve(this.members) resolve(this); return; } this.client.ws.send({ op: Constants.OPCodes.REQUEST_GUILD_MEMBERS, d: { guild_id: this.id, query, limit, }, }); const handler = (members, guild) => { if (guild.id !== this.id) return; if (this.memberCount === this.members.size || members.length < 1000) { this.client.removeListener(Constants.Events.GUILD_MEMBERS_CHUNK, handler); // Uncomment in v12 // resolve(this.members) resolve(this); } }; this.client.on(Constants.Events.GUILD_MEMBERS_CHUNK, handler); this.client.setTimeout(() => reject(new Error('Members didn\'t arrive in time.')), 120 * 1000); }); } /** * Performs a search within the entire guild. * <warn>This is only available when using a user account.</warn> * @param {MessageSearchOptions} [options={}] Options to pass to the search * @returns {Promise<Array<Message[]>>} * An array containing arrays of messages. Each inner array is a search context cluster. * The message which has triggered the result will have the `hit` property set to `true`. * @example * guild.search({ * content: 'discord.js', * before: '2016-11-17' * }).then(res => { * const hit = res.messages[0].find(m => m.hit).content; * console.log(`I found: **${hit}**, total results: ${res.totalResults}`); * }).catch(console.error); */ search(options = {}) { return this.client.rest.methods.search(this, options); } /** * The data for editing a guild. * @typedef {Object} GuildEditData * @property {string} [name] The name of the guild * @property {string} [region] The region of the guild * @property {number} [verificationLevel] The verification level of the guild * @property {ChannelResolvable} [afkChannel] The AFK channel of the guild * @property {number} [afkTimeout] The AFK timeout of the guild * @property {Base64Resolvable} [icon] The icon of the guild * @property {GuildMemberResolvable} [owner] The owner of the guild * @property {Base64Resolvable} [splash] The splash screen of the guild */ /** * Updates the guild with new information - e.g. a new name. * @param {GuildEditData} data The data to update the guild with * @returns {Promise<Guild>} * @example * // Set the guild name and region * guild.edit({ * name: 'Discord Guild', * region: 'london', * }) * .then(updated => console.log(`New guild name ${updated.name} in region ${updated.region}`)) * .catch(console.error); */ edit(data) { return this.client.rest.methods.updateGuild(this, data); } /** * Edit the name of the guild. * @param {string} name The new name of the guild * @returns {Promise<Guild>} * @example * // Edit the guild name * guild.setName('Discord Guild') * .then(updated => console.log(`Updated guild name to ${guild.name}`)) * .catch(console.error); */ setName(name) { return this.edit({ name }); } /** * Edit the region of the guild. * @param {string} region The new region of the guild * @returns {Promise<Guild>} * @example * // Edit the guild region * guild.setRegion('london') * .then(updated => console.log(`Updated guild region to ${guild.region}`)) * .catch(console.error); */ setRegion(region) { return this.edit({ region }); } /** * Edit the verification level of the guild. * @param {number} verificationLevel The new verification level of the guild * @returns {Promise<Guild>} * @example * // Edit the guild verification level * guild.setVerificationLevel(1) * .then(updated => console.log(`Updated guild verification level to ${guild.verificationLevel}`)) * .catch(console.error); */ setVerificationLevel(verificationLevel) { return this.edit({ verificationLevel }); } /** * Edit the AFK channel of the guild. * @param {ChannelResolvable} afkChannel The new AFK channel * @returns {Promise<Guild>} * @example * // Edit the guild AFK channel * guild.setAFKChannel(channel) * .then(updated => console.log(`Updated guild AFK channel to ${guild.afkChannel}`)) * .catch(console.error); */ setAFKChannel(afkChannel) { return this.edit({ afkChannel }); } /** * Edit the AFK timeout of the guild. * @param {number} afkTimeout The time in seconds that a user must be idle to be considered AFK * @returns {Promise<Guild>} * @example * // Edit the guild AFK channel * guild.setAFKTimeout(60) * .then(updated => console.log(`Updated guild AFK timeout to ${guild.afkTimeout}`)) * .catch(console.error); */ setAFKTimeout(afkTimeout) { return this.edit({ afkTimeout }); } /** * Set a new guild icon. * @param {Base64Resolvable} icon The new icon of the guild * @returns {Promise<Guild>} * @example * // Edit the guild icon * guild.setIcon(fs.readFileSync('./icon.png')) * .then(updated => console.log('Updated the guild icon')) * .catch(console.error); */ setIcon(icon) { return this.edit({ icon }); } /** * Sets a new owner of the guild. * @param {GuildMemberResolvable} owner The new owner of the guild * @returns {Promise<Guild>} * @example * // Edit the guild owner * guild.setOwner(guild.members.first()) * .then(updated => console.log(`Updated the guild owner to ${updated.owner.username}`)) * .catch(console.error); */ setOwner(owner) { return this.edit({ owner }); } /** * Set a new guild splash screen. * @param {Base64Resolvable} splash The new splash screen of the guild * @returns {Promise<Guild>} * @example * // Edit the guild splash * guild.setIcon(fs.readFileSync('./splash.png')) * .then(updated => console.log('Updated the guild splash')) * .catch(console.error); */ setSplash(splash) { return this.edit({ splash }); } /** * @param {number} position Absolute or relative position * @param {boolean} [relative=false] Whether to position relatively or absolutely * @returns {Promise<Guild>} */ setPosition(position, relative) { if (this.client.user.bot) { return Promise.reject(new Error('Setting guild position is only available for user accounts')); } return this.client.user.settings.setGuildPosition(this, position, relative); } /** * Marks all messages in this guild as read. * <warn>This is only available when using a user account.</warn> * @returns {Promise<Guild>} This guild */ acknowledge() { return this.client.rest.methods.ackGuild(this); } /** * Allow direct messages from guild members. * @param {boolean} allow Whether to allow direct messages * @returns {Promise<Guild>} */ allowDMs(allow) { const settings = this.client.user.settings; if (allow) return settings.removeRestrictedGuild(this); else return settings.addRestrictedGuild(this); } /** * Bans a user from the guild. * @param {UserResolvable} user The user to ban * @param {Object} [options] Ban options. * @param {number} [options.days=0] Number of days of messages to delete * @param {string} [options.reason] Reason for banning * @returns {Promise<GuildMember|User|string>} Result object will be resolved as specifically as possible. * If the GuildMember cannot be resolved, the User will instead be attempted to be resolved. If that also cannot * be resolved, the user ID will be the result. * @example * // Ban a user by ID (or with a user/guild member object) * guild.ban('some user ID') * .then(user => console.log(`Banned ${user.username || user.id || user} from ${guild.name}`)) * .catch(console.error); */ ban(user, options = {}) { if (typeof options === 'number') { options = { reason: null, days: options }; } else if (typeof options === 'string') { options = { reason: options, days: 0 }; } return this.client.rest.methods.banGuildMember(this, user, options); } /** * Unbans a user from the guild. * @param {UserResolvable} user The user to unban * @returns {Promise<User>} * @example * // Unban a user by ID (or with a user/guild member object) * guild.unban('some user ID') * .then(user => console.log(`Unbanned ${user.username} from ${guild.name}`)) * .catch(console.error); */ unban(user) { return this.client.rest.methods.unbanGuildMember(this, user); } /** * Prunes members from the guild based on how long they have been inactive. * @param {number} days Number of days of inactivity required to kick * @param {boolean} [dry=false] If true, will return number of users that will be kicked, without actually doing it * @returns {Promise<number>} The number of members that were/will be kicked * @example * // See how many members will be pruned * guild.pruneMembers(12, true) * .then(pruned => console.log(`This will prune ${pruned} people!`)) * .catch(console.error); * @example * // Actually prune the members * guild.pruneMembers(12) * .then(pruned => console.log(`I just pruned ${pruned} people!`)) * .catch(console.error); */ pruneMembers(days, dry = false) { if (typeof days !== 'number') throw new TypeError('Days must be a number.'); return this.client.rest.methods.pruneGuildMembers(this, days, dry); } /** * Syncs this guild (already done automatically every 30 seconds). * <warn>This is only available when using a user account.</warn> */ sync() { if (!this.client.user.bot) this.client.syncGuilds([this]); } /** * Creates a new channel in the guild. * @param {string} name The name of the new channel * @param {string} type The type of the new channel, either `text` or `voice` * @param {Array<PermissionOverwrites|Object>} overwrites Permission overwrites to apply to the new channel * @returns {Promise<TextChannel|VoiceChannel>} * @example * // Create a new text channel * guild.createChannel('new-general', 'text') * .then(channel => console.log(`Created new channel ${channel}`)) * .catch(console.error); */ createChannel(name, type, overwrites) { return this.client.rest.methods.createChannel(this, name, type, overwrites); } /** * The data needed for updating a channel's position. * @typedef {Object} ChannelPosition * @property {ChannelResolvable} channel Channel to update * @property {number} position New position for the channel */ /** * Batch-updates the guild's channels' positions. * @param {ChannelPosition[]} channelPositions Channel positions to update * @returns {Promise<Guild>} * @example * guild.updateChannels([{ channel: channelID, position: newChannelIndex }]) * .then(guild => console.log(`Updated channel positions for ${guild.id}`)) * .catch(console.error); */ setChannelPositions(channelPositions) { return this.client.rest.methods.updateChannelPositions(this.id, channelPositions); } /** * Creates a new role in the guild with given information * @param {RoleData} [data] The data to update the role with * @returns {Promise<Role>} * @example * // Create a new role * guild.createRole() * .then(role => console.log(`Created role ${role}`)) * .catch(console.error); * @example * // Create a new role with data * guild.createRole({ * name: 'Super Cool People', * color: 'BLUE', * }) * .then(role => console.log(`Created role ${role}`)) * .catch(console.error) */ createRole(data = {}) { return this.client.rest.methods.createGuildRole(this, data); } /** * Creates a new custom emoji in the guild. * @param {BufferResolvable|Base64Resolvable} attachment The image for the emoji * @param {string} name The name for the emoji * @param {Collection<Snowflake, Role>|Role[]} [roles] Roles to limit the emoji to * @returns {Promise<Emoji>} The created emoji * @example * // Create a new emoji from a url * guild.createEmoji('https://i.imgur.com/w3duR07.png', 'rip') * .then(emoji => console.log(`Created new emoji with name ${emoji.name}!`)) * .catch(console.error); * @example * // Create a new emoji from a file on your computer * guild.createEmoji('./memes/banana.png', 'banana') * .then(emoji => console.log(`Created new emoji with name ${emoji.name}!`)) * .catch(console.error); */ createEmoji(attachment, name, roles) { return new Promise(resolve => { if (typeof attachment === 'string' && attachment.startsWith('data:')) { resolve(this.client.rest.methods.createEmoji(this, attachment, name, roles)); } else { this.client.resolver.resolveBuffer(attachment).then(data => { const dataURI = this.client.resolver.resolveBase64(data); resolve(this.client.rest.methods.createEmoji(this, dataURI, name, roles)); }); } }); } /** * Delete an emoji. * @param {Emoji|string} emoji The emoji to delete * @returns {Promise} */ deleteEmoji(emoji) { if (!(emoji instanceof Emoji)) emoji = this.emojis.get(emoji); return this.client.rest.methods.deleteEmoji(emoji); } /** * Causes the client to leave the guild. * @returns {Promise<Guild>} * @example * // Leave a guild * guild.leave() * .then(g => console.log(`Left the guild ${g}`)) * .catch(console.error); */ leave() { return this.client.rest.methods.leaveGuild(this); } /** * Causes the client to delete the guild. * @returns {Promise<Guild>} * @example * // Delete a guild * guild.delete() * .then(g => console.log(`Deleted the guild ${g}`)) * .catch(console.error); */ delete() { return this.client.rest.methods.deleteGuild(this); } /** * Whether this guild equals another guild. It compares all properties, so for most operations * it is advisable to just compare `guild.id === guild2.id` as it is much faster and is often * what most users need. * @param {Guild} guild The guild to compare with * @returns {boolean} */ equals(guild) { let equal = guild && this.id === guild.id && this.available === !guild.unavailable && this.splash === guild.splash && this.region === guild.region && this.name === guild.name && this.memberCount === guild.member_count && this.large === guild.large && this.icon === guild.icon && Util.arraysEqual(this.features, guild.features) && this.ownerID === guild.owner_id && this.verificationLevel === guild.verification_level && this.embedEnabled === guild.embed_enabled; if (equal) { if (this.embedChannel) { if (this.embedChannel.id !== guild.embed_channel_id) equal = false; } else if (guild.embed_channel_id) { equal = false; } } return equal; } /** * When concatenated with a string, this automatically concatenates the guild's name instead of the guild object. * @returns {string} * @example * // Logs: Hello from My Guild! * console.log(`Hello from ${guild}!`); * @example * // Logs: Hello from My Guild! * console.log('Hello from ' + guild + '!'); */ toString() { return this.name; } _addMember(guildUser, emitEvent = true) { const existing = this.members.has(guildUser.user.id); if (!(guildUser.user instanceof User)) guildUser.user = this.client.dataManager.newUser(guildUser.user); guildUser.joined_at = guildUser.joined_at || 0; const member = new GuildMember(this, guildUser); this.members.set(member.id, member); if (this._rawVoiceStates && this._rawVoiceStates.has(member.user.id)) { const voiceState = this._rawVoiceStates.get(member.user.id); member.serverMute = voiceState.mute; member.serverDeaf = voiceState.deaf; member.selfMute = voiceState.self_mute; member.selfDeaf = voiceState.self_deaf; member.voiceSessionID = voiceState.session_id; member.voiceChannelID = voiceState.channel_id; if (this.client.channels.has(voiceState.channel_id)) { this.client.channels.get(voiceState.channel_id).members.set(member.user.id, member); } else { this.client.emit('warn', `Member ${member.id} added in guild ${this.id} with an uncached voice channel`); } } /** * Emitted whenever a user joins a guild. * @event Client#guildMemberAdd * @param {GuildMember} member The member that has joined a guild */ if (this.client.ws.connection.status === Constants.Status.READY && emitEvent && !existing) { this.client.emit(Constants.Events.GUILD_MEMBER_ADD, member); } return member; } _updateMember(member, data) { const oldMember = Util.cloneObject(member); if (data.roles) member._roles = data.roles; if (typeof data.nick !== 'undefined') member.nickname = data.nick; const notSame = member.nickname !== oldMember.nickname || !Util.arraysEqual(member._roles, oldMember._roles); if (this.client.ws.connection.status === Constants.Status.READY && notSame) { /** * Emitted whenever a guild member changes - i.e. new role, removed role, nickname. * @event Client#guildMemberUpdate * @param {GuildMember} oldMember The member before the update * @param {GuildMember} newMember The member after the update */ this.client.emit(Constants.Events.GUILD_MEMBER_UPDATE, oldMember, member); } return { old: oldMember, mem: member, }; } _removeMember(guildMember) { this.members.delete(guildMember.id); } _memberSpeakUpdate(user, speaking) { const member = this.members.get(user); if (member && member.speaking !== speaking) { member.speaking = speaking; /** * Emitted once a guild member starts/stops speaking. * @event Client#guildMemberSpeaking * @param {GuildMember} member The member that started/stopped speaking * @param {boolean} speaking Whether or not the member is speaking */ this.client.emit(Constants.Events.GUILD_MEMBER_SPEAKING, member, speaking); } } _setPresence(id, presence) { if (this.presences.get(id)) { this.presences.get(id).update(presence); return; } this.presences.set(id, new Presence(presence)); } /** * Set the position of a role in this guild. * @param {string|Role} role The role to edit, can be a role object or a role ID * @param {number} position The new position of the role * @param {boolean} [relative=false] Position Moves the role relative to its current position * @returns {Promise<Guild>} */ setRolePosition(role, position, relative = false) { if (typeof role === 'string') { role = this.roles.get(role); if (!role) return Promise.reject(new Error('Supplied role is not a role or snowflake.')); } position = Number(position); if (isNaN(position)) return Promise.reject(new Error('Supplied position is not a number.')); let updatedRoles = this._sortedRoles.array(); Util.moveElementInArray(updatedRoles, role, position, relative); updatedRoles = updatedRoles.map((r, i) => ({ id: r.id, position: i })); return this.client.rest.methods.setRolePositions(this.id, updatedRoles); } /** * Set the position of a channel in this guild. * @param {string|GuildChannel} channel The channel to edit, can be a channel object or a channel ID * @param {number} position The new position of the channel * @param {boolean} [relative=false] Position Moves the channel relative to its current position * @returns {Promise<Guild>} */ setChannelPosition(channel, position, relative = false) { if (typeof channel === 'string') { channel = this.channels.get(channel); if (!channel) return Promise.reject(new Error('Supplied channel is not a channel or snowflake.')); } position = Number(position); if (isNaN(position)) return Promise.reject(new Error('Supplied position is not a number.')); let updatedChannels = this._sortedChannels(channel.type).array(); Util.moveElementInArray(updatedChannels, channel, position, relative); updatedChannels = updatedChannels.map((r, i) => ({ id: r.id, position: i })); return this.client.rest.methods.setChannelPositions(this.id, updatedChannels); } /** * Fetches a collection of channels in the current guild sorted by position. * @param {string} type The channel type * @returns {Collection<Snowflake, GuildChannel>} * @private */ _sortedChannels(type) { return this._sortPositionWithID(this.channels.filter(c => { if (type === 'voice' && c.type === 'voice') return true; else if (type !== 'voice' && c.type !== 'voice') return true; else return type === c.type; })); } /** * Sorts a collection by object position or ID if the positions are equivalent. * Intended to be identical to Discord's sorting method. * @param {Collection} collection The collection to sort * @returns {Collection} * @private */ _sortPositionWithID(collection) { return collection.sort((a, b) => a.position !== b.position ? a.position - b.position : Long.fromString(a.id).sub(Long.fromString(b.id)).toNumber() ); } } module.exports = Guild;
aemino/discord.js
src/structures/Guild.js
JavaScript
apache-2.0
34,442
var when = require('when'); var request = require('request'); var settings = require("../../../../settings"); var log = require("../../../log"); // view components var view_start = require('../nodes/view/start'); var view_choice = require('../nodes/view/choice'); var view_form = require('../nodes/view/form'); var view_grid = require('../nodes/view/grid'); var view_info = require('../nodes/view/info'); var view_url = require('../nodes/view/url'); var view_zendesk_ticket = require('../nodes/view/zendesk-ticket'); var submit_call = require('../nodes/view/call'); var zopim_chat = require('../nodes/view/zopim_chat'); // action components var action_submit_email = require('../nodes/action/submit-email'); var action_submit_zendesk_ticket = require('../nodes/action/submit-zendesk-ticket'); var PLIST_DEPLOY = settings.staticPlistSubmittingService; var PLIST_HOST = settings.staticPlistHostingUrl || "https://designer.ubicall.com/plist/"; if (!PLIST_DEPLOY) { throw new Error("ws.ubicall.com is abslote use new configuration i.e. config_version=20150920") } function extractFlow(flow) { return when.promise(function(resolve, reject) { // initialize flow with content of start node var __flow = view_start.createStart(flow); for (var i = 0; i < flow.Nodes.length; i++) { var node = flow.Nodes[i]; switch (node.type) { case "view-choice": __flow[node.id] = view_choice.createChoice(node); break; case "view-form": __flow[node.id] = view_form.createForm(node); break; case "view-grid": __flow[node.id] = view_grid.createGrid(node); break; case "view-info": __flow[node.id] = view_info.createInfo(node); break; case "view-url": __flow[node.id] = view_url.createURL(node); break; case "view-zendesk-ticket-form": __flow[node.id] = view_zendesk_ticket.createZendeskForm(node); break; case "view-submit-call": __flow[node.id] = submit_call.createViewCall(node); break; case "view-zopim-chat": __flow[node.id] = zopim_chat.createZopimChat(node); break; // action components case "action-submit-email": __flow[node.id] = action_submit_email.createActionEmail(node); break; case "action-submit-zendesk-ticket": __flow[node.id] = action_submit_zendesk_ticket.createActionZendeskTicket(node); break; // do nothing nodes case "view-zendesk-help-center": break; case "tab": break; default: if (node.type !== "start") { // it aleardy handle outside switch statment log.info("unknown node " + JSON.stringify(node)); } } } return resolve(__flow); }); } function deployFlowOnline(authorization_header, version) { return when.promise(function(resolve, reject) { var options = { url: PLIST_DEPLOY + version, method: 'POST' }; if (authorization_header) { options.headers = options.headers || {}; options.headers['Authorization'] = authorization_header; } if (process.env.node_env !== "production") { log.warn("This info appear because you are not start with production flag"); log.warn(JSON.stringify(options, null, 4)); } request(options, function(err, response, body) { if (err || response.statusCode !== 200) { log.error(err || response.statusCode); return reject(err || response.statusCode); } else { return resolve(body); } }); }); } module.exports = { extractFlow: extractFlow, deployFlowOnline: deployFlowOnline }
Ubicall/node-red
red/ubicall/plist/utils/index.js
JavaScript
apache-2.0
3,754
/** * @license * Copyright 2012 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview JavaScript for Blockly's Code demo. * @author [email protected] (Neil Fraser) */ 'use strict'; /** * Create a namespace for the application. */ var Code = {}; /** * Lookup for names of supported languages. Keys should be in ISO 639 format. */ Code.LANGUAGE_NAME = { 'ar': 'العربية', 'be-tarask': 'Taraškievica', 'br': 'Brezhoneg', 'ca': 'Català', 'cs': 'Česky', 'da': 'Dansk', 'de': 'Deutsch', 'el': 'Ελληνικά', 'en': 'English', 'es': 'Español', 'et': 'Eesti', 'fa': 'فارسی', 'fr': 'Français', 'he': 'עברית', 'hrx': 'Hunsrik', 'hu': 'Magyar', 'ia': 'Interlingua', 'is': 'Íslenska', 'it': 'Italiano', 'ja': '日本語', 'kab': 'Kabyle', 'ko': '한국어', 'mk': 'Македонски', 'ms': 'Bahasa Melayu', 'nb': 'Norsk Bokmål', 'nl': 'Nederlands, Vlaams', 'oc': 'Lenga d\'òc', 'pl': 'Polski', 'pms': 'Piemontèis', 'pt-br': 'Português Brasileiro', 'ro': 'Română', 'ru': 'Русский', 'sc': 'Sardu', 'sk': 'Slovenčina', 'sr': 'Српски', 'sv': 'Svenska', 'ta': 'தமிழ்', 'th': 'ภาษาไทย', 'tlh': 'tlhIngan Hol', 'tr': 'Türkçe', 'uk': 'Українська', 'vi': 'Tiếng Việt', 'zh-hans': '简体中文', 'zh-hant': '正體中文' }; /** * List of RTL languages. */ Code.LANGUAGE_RTL = ['ar', 'fa', 'he', 'lki']; /** * Blockly's main workspace. * @type {Blockly.WorkspaceSvg} */ Code.workspace = null; /** * Extracts a parameter from the URL. * If the parameter is absent default_value is returned. * @param {string} name The name of the parameter. * @param {string} defaultValue Value to return if parameter not found. * @return {string} The parameter value or the default value if not found. */ Code.getStringParamFromUrl = function(name, defaultValue) { var val = location.search.match(new RegExp('[?&]' + name + '=([^&]+)')); return val ? decodeURIComponent(val[1].replace(/\+/g, '%20')) : defaultValue; }; /** * Get the language of this user from the URL. * @return {string} User's language. */ Code.getLang = function() { var lang = Code.getStringParamFromUrl('lang', ''); if (Code.LANGUAGE_NAME[lang] === undefined) { // Default to English. lang = 'en'; } return lang; }; /** * Is the current language (Code.LANG) an RTL language? * @return {boolean} True if RTL, false if LTR. */ Code.isRtl = function() { return Code.LANGUAGE_RTL.indexOf(Code.LANG) != -1; }; /** * Load blocks saved on App Engine Storage or in session/local storage. * @param {string} defaultXml Text representation of default blocks. */ Code.loadBlocks = function(defaultXml) { try { var loadOnce = window.sessionStorage.loadOnceBlocks; } catch(e) { // Firefox sometimes throws a SecurityError when accessing sessionStorage. // Restarting Firefox fixes this, so it looks like a bug. var loadOnce = null; } if ('BlocklyStorage' in window && window.location.hash.length > 1) { // An href with #key trigers an AJAX call to retrieve saved blocks. BlocklyStorage.retrieveXml(window.location.hash.substring(1)); } else if (loadOnce) { // Language switching stores the blocks during the reload. delete window.sessionStorage.loadOnceBlocks; var xml = Blockly.Xml.textToDom(loadOnce); Blockly.Xml.domToWorkspace(xml, Code.workspace); } else if (defaultXml) { // Load the editor with default starting blocks. var xml = Blockly.Xml.textToDom(defaultXml); Blockly.Xml.domToWorkspace(xml, Code.workspace); } else if ('BlocklyStorage' in window) { // Restore saved blocks in a separate thread so that subsequent // initialization is not affected from a failed load. window.setTimeout(BlocklyStorage.restoreBlocks, 0); } }; /** * Save the blocks and reload with a different language. */ Code.changeLanguage = function() { // Store the blocks for the duration of the reload. // MSIE 11 does not support sessionStorage on file:// URLs. if (window.sessionStorage) { var xml = Blockly.Xml.workspaceToDom(Code.workspace); var text = Blockly.Xml.domToText(xml); window.sessionStorage.loadOnceBlocks = text; } var languageMenu = document.getElementById('languageMenu'); var newLang = encodeURIComponent( languageMenu.options[languageMenu.selectedIndex].value); var search = window.location.search; if (search.length <= 1) { search = '?lang=' + newLang; } else if (search.match(/[?&]lang=[^&]*/)) { search = search.replace(/([?&]lang=)[^&]*/, '$1' + newLang); } else { search = search.replace(/\?/, '?lang=' + newLang + '&'); } window.location = window.location.protocol + '//' + window.location.host + window.location.pathname + search; }; /** * Bind a function to a button's click event. * On touch enabled browsers, ontouchend is treated as equivalent to onclick. * @param {!Element|string} el Button element or ID thereof. * @param {!Function} func Event handler to bind. */ Code.bindClick = function(el, func) { if (typeof el == 'string') { el = document.getElementById(el); } el.addEventListener('click', func, true); el.addEventListener('touchend', func, true); }; /** * Load the Prettify CSS and JavaScript. */ Code.importPrettify = function() { var script = document.createElement('script'); script.setAttribute('src', 'https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js'); document.head.appendChild(script); }; /** * Compute the absolute coordinates and dimensions of an HTML element. * @param {!Element} element Element to match. * @return {!Object} Contains height, width, x, and y properties. * @private */ Code.getBBox_ = function(element) { var height = element.offsetHeight; var width = element.offsetWidth; var x = 0; var y = 0; do { x += element.offsetLeft; y += element.offsetTop; element = element.offsetParent; } while (element); return { height: height, width: width, x: x, y: y }; }; /** * User's language (e.g. "en"). * @type {string} */ Code.LANG = Code.getLang(); /** * List of tab names. * @private */ Code.TABS_ = ['blocks', 'javascript', 'php', 'python', 'dart', 'lua', 'xml']; Code.selected = 'blocks'; /** * Switch the visible pane when a tab is clicked. * @param {string} clickedName Name of tab clicked. */ Code.tabClick = function(clickedName) { // If the XML tab was open, save and render the content. if (document.getElementById('tab_xml').className == 'tabon') { var xmlTextarea = document.getElementById('content_xml'); var xmlText = xmlTextarea.value; var xmlDom = null; try { xmlDom = Blockly.Xml.textToDom(xmlText); } catch (e) { var q = window.confirm(MSG['badXml'].replace('%1', e)); if (!q) { // Leave the user on the XML tab. return; } } if (xmlDom) { Code.workspace.clear(); Blockly.Xml.domToWorkspace(xmlDom, Code.workspace); } } if (document.getElementById('tab_blocks').className == 'tabon') { Code.workspace.setVisible(false); } // Deselect all tabs and hide all panes. for (var i = 0; i < Code.TABS_.length; i++) { var name = Code.TABS_[i]; document.getElementById('tab_' + name).className = 'taboff'; document.getElementById('content_' + name).style.visibility = 'hidden'; } // Select the active tab. Code.selected = clickedName; document.getElementById('tab_' + clickedName).className = 'tabon'; // Show the selected pane. document.getElementById('content_' + clickedName).style.visibility = 'visible'; Code.renderContent(); if (clickedName == 'blocks') { Code.workspace.setVisible(true); } Blockly.svgResize(Code.workspace); }; /** * Populate the currently selected pane with content generated from the blocks. */ Code.renderContent = function() { var content = document.getElementById('content_' + Code.selected); // Initialize the pane. if (content.id == 'content_xml') { var xmlTextarea = document.getElementById('content_xml'); var xmlDom = Blockly.Xml.workspaceToDom(Code.workspace); var xmlText = Blockly.Xml.domToPrettyText(xmlDom); xmlTextarea.value = xmlText; xmlTextarea.focus(); } else if (content.id == 'content_javascript') { Code.attemptCodeGeneration(Blockly.JavaScript); } else if (content.id == 'content_python') { Code.attemptCodeGeneration(Blockly.Python); } else if (content.id == 'content_php') { Code.attemptCodeGeneration(Blockly.PHP); } else if (content.id == 'content_dart') { Code.attemptCodeGeneration(Blockly.Dart); } else if (content.id == 'content_lua') { Code.attemptCodeGeneration(Blockly.Lua); } if (typeof PR == 'object') { PR.prettyPrint(); } }; /** * Attempt to generate the code and display it in the UI, pretty printed. * @param generator {!Blockly.Generator} The generator to use. */ Code.attemptCodeGeneration = function(generator) { var content = document.getElementById('content_' + Code.selected); content.textContent = ''; if (Code.checkAllGeneratorFunctionsDefined(generator)) { var code = generator.workspaceToCode(Code.workspace); content.textContent = code; // Remove the 'prettyprinted' class, so that Prettify will recalculate. content.className = content.className.replace('prettyprinted', ''); } }; /** * Check whether all blocks in use have generator functions. * @param generator {!Blockly.Generator} The generator to use. */ Code.checkAllGeneratorFunctionsDefined = function(generator) { var blocks = Code.workspace.getAllBlocks(false); var missingBlockGenerators = []; for (var i = 0; i < blocks.length; i++) { var blockType = blocks[i].type; if (!generator[blockType]) { if (missingBlockGenerators.indexOf(blockType) == -1) { missingBlockGenerators.push(blockType); } } } var valid = missingBlockGenerators.length == 0; if (!valid) { var msg = 'The generator code for the following blocks not specified for ' + generator.name_ + ':\n - ' + missingBlockGenerators.join('\n - '); Blockly.alert(msg); // Assuming synchronous. No callback. } return valid; }; /** * Initialize Blockly. Called on page load. */ Code.init = function() { Code.initLanguage(); var rtl = Code.isRtl(); var container = document.getElementById('content_area'); var onresize = function(e) { var bBox = Code.getBBox_(container); for (var i = 0; i < Code.TABS_.length; i++) { var el = document.getElementById('content_' + Code.TABS_[i]); el.style.top = bBox.y + 'px'; el.style.left = bBox.x + 'px'; // Height and width need to be set, read back, then set again to // compensate for scrollbars. el.style.height = bBox.height + 'px'; el.style.height = (2 * bBox.height - el.offsetHeight) + 'px'; el.style.width = bBox.width + 'px'; el.style.width = (2 * bBox.width - el.offsetWidth) + 'px'; } // Make the 'Blocks' tab line up with the toolbox. if (Code.workspace && Code.workspace.toolbox_.width) { document.getElementById('tab_blocks').style.minWidth = (Code.workspace.toolbox_.width - 38) + 'px'; // Account for the 19 pixel margin and on each side. } }; window.addEventListener('resize', onresize, false); // The toolbox XML specifies each category name using Blockly's messaging // format (eg. `<category name="%{BKY_CATLOGIC}">`). // These message keys need to be defined in `Blockly.Msg` in order to // be decoded by the library. Therefore, we'll use the `MSG` dictionary that's // been defined for each language to import each category name message // into `Blockly.Msg`. // TODO: Clean up the message files so this is done explicitly instead of // through this for-loop. for (var messageKey in MSG) { if (messageKey.indexOf('cat') == 0) { Blockly.Msg[messageKey.toUpperCase()] = MSG[messageKey]; } } // Construct the toolbox XML, replacing translated variable names. var toolboxText = document.getElementById('toolbox').outerHTML; toolboxText = toolboxText.replace(/(^|[^%]){(\w+)}/g, function(m, p1, p2) {return p1 + MSG[p2];}); var toolboxXml = Blockly.Xml.textToDom(toolboxText); Code.workspace = Blockly.inject('content_blocks', {grid: {spacing: 25, length: 3, colour: '#ccc', snap: true}, media: '../../media/', rtl: rtl, toolbox: toolboxXml, zoom: {controls: true, wheel: true} }); // Add to reserved word list: Local variables in execution environment (runJS) // and the infinite loop detection function. Blockly.JavaScript.addReservedWords('code,timeouts,checkTimeout'); Code.loadBlocks(''); if ('BlocklyStorage' in window) { // Hook a save function onto unload. BlocklyStorage.backupOnUnload(Code.workspace); } Code.tabClick(Code.selected); Code.bindClick('trashButton', function() {Code.discard(); Code.renderContent();}); Code.bindClick('runButton', Code.runJS); // Disable the link button if page isn't backed by App Engine storage. var linkButton = document.getElementById('linkButton'); if ('BlocklyStorage' in window) { BlocklyStorage['HTTPREQUEST_ERROR'] = MSG['httpRequestError']; BlocklyStorage['LINK_ALERT'] = MSG['linkAlert']; BlocklyStorage['HASH_ERROR'] = MSG['hashError']; BlocklyStorage['XML_ERROR'] = MSG['xmlError']; Code.bindClick(linkButton, function() {BlocklyStorage.link(Code.workspace);}); } else if (linkButton) { linkButton.className = 'disabled'; } for (var i = 0; i < Code.TABS_.length; i++) { var name = Code.TABS_[i]; Code.bindClick('tab_' + name, function(name_) {return function() {Code.tabClick(name_);};}(name)); } onresize(); Blockly.svgResize(Code.workspace); // Lazy-load the syntax-highlighting. window.setTimeout(Code.importPrettify, 1); }; /** * Initialize the page language. */ Code.initLanguage = function() { // Set the HTML's language and direction. var rtl = Code.isRtl(); document.dir = rtl ? 'rtl' : 'ltr'; document.head.parentElement.setAttribute('lang', Code.LANG); // Sort languages alphabetically. var languages = []; for (var lang in Code.LANGUAGE_NAME) { languages.push([Code.LANGUAGE_NAME[lang], lang]); } var comp = function(a, b) { // Sort based on first argument ('English', 'Русский', '简体字', etc). if (a[0] > b[0]) return 1; if (a[0] < b[0]) return -1; return 0; }; languages.sort(comp); // Populate the language selection menu. var languageMenu = document.getElementById('languageMenu'); languageMenu.options.length = 0; for (var i = 0; i < languages.length; i++) { var tuple = languages[i]; var lang = tuple[tuple.length - 1]; var option = new Option(tuple[0], lang); if (lang == Code.LANG) { option.selected = true; } languageMenu.options.add(option); } languageMenu.addEventListener('change', Code.changeLanguage, true); // Inject language strings. document.title += ' ' + MSG['title']; document.getElementById('title').textContent = MSG['title']; document.getElementById('tab_blocks').textContent = MSG['blocks']; document.getElementById('linkButton').title = MSG['linkTooltip']; document.getElementById('runButton').title = MSG['runTooltip']; document.getElementById('trashButton').title = MSG['trashTooltip']; }; /** * Execute the user's code. * Just a quick and dirty eval. Catch infinite loops. */ Code.runJS = function() { Blockly.JavaScript.INFINITE_LOOP_TRAP = 'checkTimeout();\n'; var timeouts = 0; var checkTimeout = function() { if (timeouts++ > 1000000) { throw MSG['timeout']; } }; var code = Blockly.JavaScript.workspaceToCode(Code.workspace); Blockly.JavaScript.INFINITE_LOOP_TRAP = null; try { eval(code); } catch (e) { alert(MSG['badCode'].replace('%1', e)); } }; /** * Discard all blocks from the workspace. */ Code.discard = function() { var count = Code.workspace.getAllBlocks(false).length; if (count < 2 || window.confirm(Blockly.Msg['DELETE_ALL_BLOCKS'].replace('%1', count))) { Code.workspace.clear(); if (window.location.hash) { window.location.hash = ''; } } }; // Load the Code demo's language strings. document.write('<script src="msg/' + Code.LANG + '.js"></script>\n'); // Load Blockly's language strings. document.write('<script src="../../msg/js/' + Code.LANG + '.js"></script>\n'); window.addEventListener('load', Code.init);
picklesrus/blockly
demos/code/code.js
JavaScript
apache-2.0
17,281
// Copyright 2022 Google LLC // // 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 // // https://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. // // ** This file is automatically generated by gapic-generator-typescript. ** // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** 'use strict'; function main() { // [START cloudkms_v1_generated_KeyManagementService_GenerateRandomBytes_async] /** * TODO(developer): Uncomment these variables before running the sample. */ /** * The project-specific location in which to generate random bytes. * For example, "projects/my-project/locations/us-central1". */ // const location = 'abc123' /** * The length in bytes of the amount of randomness to retrieve. Minimum 8 * bytes, maximum 1024 bytes. */ // const lengthBytes = 1234 /** * The ProtectionLevel google.cloud.kms.v1.ProtectionLevel to use when * generating the random data. Currently, only * HSM google.cloud.kms.v1.ProtectionLevel.HSM protection level is * supported. */ // const protectionLevel = {} // Imports the Kms library const {KeyManagementServiceClient} = require('@google-cloud/kms').v1; // Instantiates a client const kmsClient = new KeyManagementServiceClient(); async function callGenerateRandomBytes() { // Construct request const request = { }; // Run request const response = await kmsClient.generateRandomBytes(request); console.log(response); } callGenerateRandomBytes(); // [END cloudkms_v1_generated_KeyManagementService_GenerateRandomBytes_async] } process.on('unhandledRejection', err => { console.error(err.message); process.exitCode = 1; }); main(...process.argv.slice(2));
googleapis/nodejs-kms
samples/generated/v1/key_management_service.generate_random_bytes.js
JavaScript
apache-2.0
2,228
try { if (Koadic.JOBKEY != "stage") { if (Koadic.isHTA()) { //HKCU\SOFTWARE\Microsoft\Internet Explorer\Style\MaxScriptStatements = 0xFFFFFFFF var path = "SOFTWARE\\Microsoft\\Internet Explorer\\Styles"; var key = "MaxScriptStatements"; Koadic.registry.write(Koadic.registry.HKCU, path, key, 0xFFFFFFFF, Koadic.registry.DWORD); } Koadic.work.report(Koadic.user.info()); try { Koadic.work.fork(""); } catch (e) { Koadic.work.error(e) } Koadic.exit(); } else { if (Koadic.isHTA()) DoWorkTimeout(); else DoWorkLoop(); } } catch (e) { // todo: critical error reporting Koadic.work.error(e); } function DoWork() { var epoch = new Date().getTime(); var expire = parseInt(Koadic.EXPIRE); if (epoch > expire) { return false; } try { var work = Koadic.work.get(); // 201 = x64 or x86 // 202 = force x86 if (work.status == 501 || work.status == 502) { if (work.responseText.length > 0) { var jobkey = work.responseText; Koadic.work.fork(jobkey, work.status == 502); } } else // if (work.status == 500) // kill code { return false; } } catch (e) { return false; } return true; } function DoWorkLoop() { while (DoWork()) ; Koadic.exit(); } function DoWorkTimeout() { for (var i = 0; i < 10; ++i) { if (!DoWork()) { Koadic.exit(); return; } } //window.setTimeout(DoWorkTimeoutCallback, 0); Koadic.work.fork(""); Koadic.exit(); }
zerosum0x0/koadic
data/stager/js/stage.js
JavaScript
apache-2.0
1,812
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconExposurePlus1(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M10 7H8v4H4v2h4v4h2v-4h4v-2h-4V7zm10 11h-2V7.38L15 8.4V6.7L19.7 5h.3v13z"/> </g> </Icon> ); } IconExposurePlus1.displayName = 'IconExposurePlus1'; IconExposurePlus1.category = 'image';
mineral-ui/mineral-ui
packages/mineral-ui-icons/src/IconExposurePlus1.js
JavaScript
apache-2.0
553
Ti.UI.setBackgroundColor('#fff'); var inicio = Ti.UI.createWindow({ backgroundColor:'#fff' }); var titulo = Ti.UI.createLabel({ text:'UAM', width:'300dp', height:'50dp', left:'10dp', top:'100dp', font:{fontSize:30, fontFamily:'Helvetica Neue'}, textAlign:'center', }); inicio.add(titulo); var data = [{title:'Ingresar'},{title:'Registrarse'}]; var opciones = Ti.UI.createTableView({ width:'300dp', height:'100dp', top:'180dp', left:'10dp', data:data, color:'#000' }); inicio.add(opciones); opciones.addEventListener('click', function(e){ if(e.index==0){ var vIng = Ti.UI.createWindow({ url:'/ui/ingresar' }); vIng.open({modal:true}); } else{ alert('Registrar' +e.index); Ti.API.info('Estoy en la opcion registrarse'+ e.index); } }); inicio.open();
addieljuarez/TallerUAM
Resources/app.js
JavaScript
apache-2.0
789
var httpManager = require("httpManager"); Alloy.Globals.isSearch = true; if (OS_ANDROID) { $.search.windowSoftInputMode = Ti.UI.Android.SOFT_INPUT_ADJUST_PAN; } var dataTitles = [ { name : "Find Us", view : "findUs" }, { name : "Deals", view : "deals" }, { name : "Testimonials", view : "testmonials" }, { name : "Loyalty", view : "loyalty" }, { name : "Be Social", view : "beSocial" }, { name : "Before & After", view : "beforeAfter" }, { name : "About Us", view : "aboutUs" }, { name : "Services for dermatology", view : "services" }, { name : "Services for dental", view : "services" }, ]; var data =[]; for (var i=0; i < dataTitles.length; i++) { var row = Titanium.UI.createTableViewRow({ title:dataTitles[i].name, color:'black', height:50, id : i, }); data.push(row); } var search = Titanium.UI.createSearchBar({ barColor : '#DA308A', showCancel : true, height : 43, top : 0, }); search.addEventListener('cancel', function() { search.blur(); }); var listView = Ti.UI.createListView({ searchView : search, caseInsensitiveSearch : true, backgroundColor:'white', top :"60", bottom :"60", }); var listSection = Ti.UI.createListSection( ); var data = []; for (var i = 0; i < dataTitles.length; i++) { data.push({ properties : { title : dataTitles[i].name, searchableText :dataTitles[i].name, color :"black", height : "40", } }); } listSection.setItems(data); listView.sections = [listSection]; listView.addEventListener('itemclick', function(e){ Alloy.createController(dataTitles[e.itemIndex].view).getView(); }); $.search.add(listView); function logoutClicked (e) { httpManager.userLogout(function(response) { if(response.success == 1) { Alloy.createController('login').getView(); $.search .close(); } }); } Ti.App.addEventListener('android:back', function() { $.search.exitOnClose = true; var myActivity = Ti.Android.currentActivity(); myActivity.finish(); }); Alloy.Globals.closeSearchWindow = function(){ $.search .close(); }; $.search.open();
SrinivasReddy987/Lookswoow
app/controllers/search.js
JavaScript
apache-2.0
2,071
/* * Kendo UI v2014.3.1119 (http://www.telerik.com/kendo-ui) * Copyright 2014 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial license terms. */ (function(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["de-LI"] = { name: "de-LI", numberFormat: { pattern: ["-n"], decimals: 2, ",": "'", ".": ".", groupSize: [3], percent: { pattern: ["-n%","n%"], decimals: 2, ",": "'", ".": ".", groupSize: [3], symbol: "%" }, currency: { pattern: ["$-n","$ n"], decimals: 2, ",": "'", ".": ".", groupSize: [3], symbol: "CHF" } }, calendars: { standard: { days: { names: ["Sonntag","Montag","Dienstag","Mittwoch","Donnerstag","Freitag","Samstag"], namesAbbr: ["So","Mo","Di","Mi","Do","Fr","Sa"], namesShort: ["So","Mo","Di","Mi","Do","Fr","Sa"] }, months: { names: ["Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember",""], namesAbbr: ["Jan","Feb","Mrz","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez",""] }, AM: [""], PM: [""], patterns: { d: "dd.MM.yyyy", D: "dddd, d. MMMM yyyy", F: "dddd, d. MMMM yyyy HH:mm:ss", g: "dd.MM.yyyy HH:mm", G: "dd.MM.yyyy HH:mm:ss", m: "dd MMMM", M: "dd MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "HH:mm", T: "HH:mm:ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM yyyy", Y: "MMMM yyyy" }, "/": ".", ":": ":", firstDay: 1 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
y-todorov/Inventory
Inventory.MVC/Scripts/Kendo/cultures/kendo.culture.de-LI.js
JavaScript
apache-2.0
2,637
(function() { 'use strict'; angular .module('gastronomeeApp') .controller('MenuDeleteController',MenuDeleteController); MenuDeleteController.$inject = ['$uibModalInstance', 'entity', 'Menu']; function MenuDeleteController($uibModalInstance, entity, Menu) { var vm = this; vm.menu = entity; vm.clear = clear; vm.confirmDelete = confirmDelete; function clear () { $uibModalInstance.dismiss('cancel'); } function confirmDelete (id) { Menu.delete({id: id}, function () { $uibModalInstance.close(true); }); } } })();
goxhaj/gastronomee
src/main/webapp/app/dashboard/menu/menu-delete-dialog.controller.js
JavaScript
apache-2.0
694
var WaitState = function(game){this.game = game}; WaitState.prototype.preload = function(){ }; WaitState.prototype.create = function(){ this.background = this.game.add.sprite(0,0,'fence'); this.title = this.add.sprite(400,200, 'waitforplay'); this.title.anchor.setTo(0.5, 0.5); this.waitBar = this.game.add.tileSprite(0,500,800,29,'tankbar'); this.waitBar.autoScroll(-200,0); this.menubutton = this.game.add.button(400,350,'menubutton',this.menuClick, this); this.menubutton.anchor.setTo(0.5,0.5); this.searching = this.game.add.audio('searching'); this.searching.play(); try{ socket.emit("new player", {gameRequest: this.game.gameRequest, character: this.game.character, x: game.width/2 , y: game.height-100}); console.log("Player sent"); }catch(err){ console.log("PLayer could not be sent"); console.log(err.message); } }; WaitState.prototype.update = function(){ if(otherPlayerReady){ this.searching.stop(); this.game.state.start("GameState"); }else if(noGames){ this.title.destroy() this.title = this.add.sprite(400,200,'nogames'); this.title.anchor.setTo(0.5, 0.5); } }; WaitState.prototype.menuClick = function(){ //this.game.state.start("MenuState",true,false); window.location.replace(window.location.pathname); };
siracoj/ProPain
ProPain/src/Wait.js
JavaScript
apache-2.0
1,384
/* * Copyright 2021 Google LLC * * 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 * * https://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. */ /** * External dependencies */ import { memo } from '@googleforcreators/react'; /** * Internal dependencies */ import { SwapMedia, LayerOpacity, FlipHorizontal, FlipVertical, BorderWidthAndColor, More, Separator, Dismiss, } from '../elements'; const FloatingImageMenu = memo(function FloatingImageMenu() { return ( <> <SwapMedia /> <Separator /> <LayerOpacity /> <Separator /> <FlipHorizontal /> <FlipVertical /> <Separator /> <BorderWidthAndColor /> <Separator /> <More /> <Separator /> <Dismiss /> </> ); }); export default FloatingImageMenu;
GoogleForCreators/web-stories-wp
packages/story-editor/src/components/floatingMenu/menus/image.js
JavaScript
apache-2.0
1,257
define([],function(){return function(n){n.addEndpointDescription("_nodes/hot_threads",{methods:["GET"],patterns:["_nodes/hot_threads","_nodes/{nodes}/hot_threads"]})}});
skyjia/elasticsearch-rtf
plugins/marvel/_site/sense/app/kb/api_0_90/nodes.js
JavaScript
apache-2.0
169
function Bibliography() { this.searchOptions = { source: 0, value: '', style: '' }; this.bibliography = []; this.bibliographyText = []; this.localStorageKey = "Bibliography"; }; Bibliography.prototype.showBookSearchResult = function (results) { for (key in results) { var title = results[key].display.title; var description = ""; var contributors = results[key].data.contributors; contributors.forEach(function (contributors_item) { if (description != "") { description += ", " + contributors_item.first + " " + contributors_item.last; } else { description += contributors_item.first + " " + contributors_item.last; } }); if (results[key].display.publisher) { description += " - " + results[key].display.publisher; } if (results[key].display.year) { description += " - " + results[key].display.year; } createSearchItem(title, description, key); } }; Bibliography.prototype.showJournalSearchResult = function(results) { results.forEach(function(results_item, i) { var title = results_item.data.journal.title; var description = results_item.data.pubjournal.title; createSearchItem(title, description, i); }); }; Bibliography.prototype.showWebSiteSearchResult = function (results) { var urlSearchResult; results.forEach(function(results_item, i) { try { urlSearchResult = new URL(results_item.display.displayurl).hostname; } catch(error) { urlSearchResult = results_item.display.displayurl; } createSearchItem(results_item.display.title + "(" + results_item.display.displayurl + ")", results_item.display.summary, i); }); }; Bibliography.prototype.createCitations = function (id, data) { var biblist = this; $.ajax({ url: '/api/2.0/files/easybib-citation', type: "POST", data: { citationData: JSON.stringify(data) }, success: function(answer) { if (answer.response.success) { try { var citation = JSON.parse(answer.response.citation); if (citation.status === 'ok') { biblist.bibliographyText.push({ id: id, data: citation.data }); createBibItem(id, citation.data); } } catch(e) { console.log(e.message); } } }, }); }; Bibliography.prototype.updateCitations = function (id, data) { var biblist = this; $.ajax({ url: '/api/2.0/files/easybib-citation', type: "POST", data: { citationData: JSON.stringify(data) }, success: function (answer) { if (answer.response.success) { try { var citation = JSON.parse(answer.response.citation); if (citation.status === 'ok') { if (biblist.bibliographyText.length > 0) { biblist.bibliographyText.forEach(function (item) { if (item.id == id) { item.data = citation.data; } }); } createBibItem(id, citation.data); } } catch (e) { console.log(e.message); } } }, }); }; Bibliography.prototype.getCitation = function (id, foundData, bibliographyStorage, fileId) { var biblist = this; var source = foundData.results[id]; var data; switch (this.searchOptions.source) { case 0: data = { style: $('#styles option:selected').val() ? $('#styles option:selected').val() : "3d-research", pubtype: source.data.pubtype, pubnonperiodical: source.data.pubnonperiodical, contributors: source.data.contributors, other: source.data.other, source: source.data.source }; break; case 1: data = { style: $('#styles option:selected').val() ? $('#styles option:selected').val() : "3d-research", pubtype: source.data.pubtype, pubjournal: source.data.pubjournal, publication_type: source.data.publication_type, contributors: source.data.contributors, other: source.data.other, source: source.data.source }; break; case 2: source.data.pubonline.url = source.display.displayurl; data = { style: $('#styles option:selected').val() ? $('#styles option:selected').val() : "3d-research", autocite: source.display.displayurl, pubtype: source.data.pubtype, pubonline: source.data.pubonline, other: source.data.other, website: source.data.website, source: source.data.source }; break; default: break; }; $.ajax({ url: '/api/2.0/files/easybib-citation', type: "POST", data: { citationData: JSON.stringify(data) }, success: function (answer) { if (answer.response.success && answer.response.citations != "error") { var citation = JSON.parse(answer.response.citation); if (citation.status === 'ok') { saveCitation.call(biblist, citation, data, bibliographyStorage, fileId); } else if (citation.status === 'error') { alert("ERROR. " + citation.msg); } } return true; }, error: function(err) { console.log(err); } }); }; Bibliography.prototype.fillListStyles = function (styles, bibliographyStyle) { var selectStyles = $('#styles'); for (var style in styles) { var value = styles[style]; selectStyles[0].options[selectStyles[0].options.length] = new Option(value, style); } $("#styles :first").remove(); selectStyles.attr('disabled', false); if (bibliographyStyle) { $("#styles option[value=" + bibliographyStyle + "]").attr('selected', 'true'); } }; function escapeHtml(str) { if (str) return $('<div />').text(str).html(); else return null; }; function createSearchItem(title, description, id) { var searchResult = $("#search_result"); $("#search_result").show(); $(".result-container .search-title").show(); $(".result-container .bibliography-title").hide(); $("#bib").hide(); searchResult.show(); var item = "<div class=\"search-item\" id=" + escapeHtml(id) + ">" + "<div class = \"citation\">" + "<h4 style=\"overflow-x: hidden;margin:0\">" + escapeHtml(title) + "</h4>" + "<p style=\";margin:0\">" + escapeHtml(description) + "</p>" + "</div>" + "<div class=\"add-button-container\">" + "<div class=\"add-button\" onclick=\"addItem(this)\"></div>" + "</div>" + "</div>"; $('#titleContent').text('Your Search Results'); searchResult.append(item); }; function createBibItem(id, data) { var item = "<div class=\"bibliography-part\">" + "<div class=\"bibliography-part-data\">" + escapeHtml(data) + "</div>" + "<div class=\"del-button-container\">" + "<div onclick=\"delBibliographyPart(this)\" id=bibliography-path_" + escapeHtml(id) + " class=\"del-bibliography-part\"></div>" + "</div>" + "</br>"; $('#bib').append(item); }; function saveCitation(citation, data, bibliographyStorage, fileId) { var id, bibliographyItem; if (this.bibliography.length > 0) { id = this.bibliography[this.bibliography.length - 1].id + 1; } else { id = 1; } bibliographyItem = { id: id, data: data }; this.bibliography.push(bibliographyItem); this.bibliographyText.push({ id: id, data: citation.data }); $("#search_result").empty(); $("#search_result").hide(); $(".result-container .search-title").hide(); $(".result-container .bibliography-title").show(); $("#bib").show(); createBibItem(id, citation.data); if (!localStorageManager.isAvailable || fileId == null) { return null; } else { if (bibliographyStorage) { bibliographyStorage[fileId] = this.bibliography; localStorageManager.setItem(this.localStorageKey, bibliographyStorage); } else { bibliographyStorage = {}; bibliographyStorage[fileId] = this.bibliography; localStorageManager.setItem(this.localStorageKey, bibliographyStorage); } } };
ONLYOFFICE/CommunityServer
web/studio/ASC.Web.Studio/ThirdParty/plugin/easybib/bibliography.js
JavaScript
apache-2.0
9,168
module.exports = function(app, express) { app.configure(function() { app.use(express.logger()); }); app.configure('development', function() { app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); app.configure('production', function() { app.use(express.errorHandler()); }); };
Ken-Richard/tincan_nodejs
config/environment.js
JavaScript
apache-2.0
385
$(document).ready(function() { PromotionGroup.init(); PromotionGroup.loadImage(); $('#add-new-promotion').on('click', function(){ PromotionGroup.addNew(); }) $('#update-promotion').on('click', function(){ PromotionGroup.update(); }) // date picker $('#promotion-add-end-date').datepicker({ format: "dd/mm/yyyy" }); $('#promotion-add-start-date').datepicker({ format: "dd/mm/yyyy" }); $('#promotion-update-start-date').datepicker({ format: "dd/mm/yyyy" }); $('#promotion-update-end-date').datepicker({ format: "dd/mm/yyyy" }); //editor CKEDITOR.replace('promotionContent'); CKEDITOR.replace('promotionContentUpdate'); }); var PromotionGroup = function () { // load list promotion var loadListPromotion = function() { var html = ''; $.ajax({ url: URL + 'spaCMS/promotion/xhrLoad_promotion_list', type: 'get', dataType: 'json', }) .done(function(data) { $('span#promotion-title-spa').text('DANH SÁCH TIN KHUYẾN MÃI'); if(data['list'].length >0 ){ $('#promotion-mesage-list').hide('fast'); var totalPublish = 0; $.each(data['list'], function(k, val){ totalPublish = (val.promotion_state == 1)? totalPublish+1 : totalPublish; var state = (val.promotion_state == 0)? "button-other": "hide"; var nowDay = new Date(); var endDay = val.promotion_end_date; var createDay = val.promotion_create_date; var end_Day = val.promotion_end_date; var startDay = val.promotion_start_date; var strMark = ""; strMark = (new Date(end_Day) < new Date())? "color: red; text-decoration: line-through;" : ""; createDay = createDay.substr(8, 2)+'/'+ createDay.substr(5, 2)+'/'+createDay.substr(0, 4); startDay = startDay.substr(8, 2)+'/'+ startDay.substr(5, 2)+'/'+startDay.substr(0, 4); end_Day = end_Day.substr(8, 2)+'/'+ end_Day.substr(5, 2)+'/'+end_Day.substr(0, 4); // var promotion_img = JSON.parse(val.promotion_img); html += '<li class="row promotion-list-item" data-toggle="modal" data-target="#updatePromotion" data-id-promotion="'+val.promotion_id+'">'; html += '<div class="col-md-5" style="font-weight: 600; color: #888;">'+val.promotion_title+'</div>'; html += '<div class="col-md-2 created-date">'+createDay+'</div>'; html += '<div class="col-md-2">'+startDay+'</div>'; html += '<div class="col-md-2 end-date" style="'+strMark+'">'+end_Day+'</div>'; // html += '<div class="col-md-1">'+totalDay+'</div>'; html += '<div class="col-md-1 text-right" style="padding:0px;">'; html += '<button class="button '+state+' promotion-items-publish" data-promotion-id="'+val.promotion_id+'" title="Kích hoạt"> '; html += '<i class="fa fa-check"></i>'; html += '</button> '; html += '<button class="button button-secondary redeem promotion-items-delete" data-promotion-id="'+val.promotion_id+'" title="Xóa"> '; html += '<i class="fa fa-trash"></i>'; html += '</button>'; html += '</div>'; html += '</li>'; }); html += '<input class="input-hide-state" type="hidden" value="'+totalPublish+'">'; $('#promotion-content').html(html); }else{ $('#promotion-content').html(''); $('#promotion-mesage-list').fadeIn('fast'); } }) .always(function(){ $('.promotion-items-delete').on('click',function(e){ var id_promotion = $(this).attr('data-promotion-id'); e.stopPropagation(); var cfr = confirm('Bạn có muốn xóa promotion này không?'); if(cfr == true){ deletePromotion(id_promotion); } }); $('.promotion-items-publish').on('click',function(e){ var id_promotion = $(this).attr('data-promotion-id'); var self = $(this); var state = 1; // kich hoat e.stopPropagation(); if($('input.input-hide-state').val() >4){ alert('Chỉ hiển thị được 5 promotion.'); }else{ publishPromotion(id_promotion, state); } }); $('.btn-close-modal').on('click',function (){ $(".modal").modal('hide'); }) $('#refres-promotion').on('click', function(){ refresh(); }); $('li.promotion-list-item').on('click', function(){ var self = $(this); var id_promotion = self.attr('data-id-promotion'); $.ajax({ url: URL + 'spaCMS/promotion/xhrLoad_promotion_item', type: 'post', dataType: 'json', data: {promotion_id: id_promotion}, }) .done(function(data) { $.each(data, function(index, value) { var title = value.promotion_title; var id_promotion = value.promotion_id; // img var image = JSON.parse(value.promotion_img); var img = image.img; var thumbnail = image.thumbnail; //date var sDate = value.promotion_start_date; sDate = sDate.replace(/-/g,' '); var startDate = new Date(sDate); var endDate = value.promotion_end_date; endDate = new Date(endDate.replace(/-/g,' ')); var mainUpdate = $('#updatePromotion'); mainUpdate.find('#promotion-update-title').val(title); mainUpdate.attr('data-id-promotion', id_promotion); $('#promotion-update-start-date').datepicker('update',startDate); $('#promotion-update-end-date').datepicker('update',endDate); CKEDITOR.instances.promotionContentUpdate.setData(value.promotion_content); var items = $('#ListIM_editUS'); var caller = $('#iM_editUS'); // ktra so luong hinh anh da co caller.hide(); var out = null; var html = '<li class="single-picture">'; html += '<div class="single-picture-wrapper">'; html += '<img id="user_slide_thumbnail" src=":img_thumbnail" data-img=":data-image" style="width:100px; height:70px;">'; html += '<input type="hidden" name="user_service_image[]" value=":image">'; html += '</div>'; html += '<div class="del_image icons-delete2"></div>'; html += '</li>'; out = html.replace(':img_thumbnail', thumbnail); out = out.replace(':data-image', img); out = out.replace(':image', img); items.html(out); // del image $('.del_image').on("click", function(){ var self = $(this).parent(); // self.attr("disabled","disabled"); self.remove(); // Truong hop dac biet, ktra so luong hinh anh da co var childrens = items.children().length; if(childrens < 5) { caller.fadeIn(); } }); }); }) .always(function() { }); }) }); } function loadAsidePublish() { var html = ''; $.ajax({ url: URL + 'spaCMS/promotion/xhrLoad_promotion_publish', type: 'post', dataType: 'json', data: {promotion_state: 1}, }) .done(function(respon) { if(respon.length > 0){ $.each(respon, function(index, val) { // img var title = val.promotion_title; var image = JSON.parse(val.promotion_img); var img = image.img; var thumbnail = image.thumbnail; html += '<div class="promotion-item-publish">'; html += '<div class="row-fluid">'; html += '<div class="promotion-item-puslish-title col-md-12">'; html += '<i class="fa fa-bullhorn"></i>'; html += '<span>'+title+'</span>'; html += '</div>'; // html += '<div class="col-sm-1">'; html += '<button class="btn btn-black promotion-items-change-publish" data-promotion-id="'+val.promotion_id+'" title="Tạm ngưng"> <i class="fa fa-close"></i></button>'; html += '</div>'; // html += '</div>'; html += '<div class="promotion-item-publish-img row-fluid">'; html += '<img class="pic" alt="" src="'+thumbnail+'"> '; html += '</div>'; html += '</div>'; }); //end each }else{ html +='<div class="row-fluid" style="padding:5px;padding: 5px; border: 1px solid #d88c8a;background-color: #F7E4E4;"><span><i class="fa fa-warning" style="color: #ffcc00;"></i> Hiện tại không có quảng cáo nào hiển thị.</span></div>'; } $('.promotion-item-publish-wrap').html(html); }) .fail(function() { console.log("error"); }) .always(function() { $('.promotion-items-change-publish').on('click', function(){ var promotion_id = $(this).attr('data-promotion-id'); publishPromotion(promotion_id,0); }); }); } // add new promotion var addNewPromotion = function() { var title = $('#promotion-add-title').val(); var now = new Date(); month = now.getMonth()+1; var start_day = $('#promotion-add-start-date').val(); if(start_day.length >0){ start_day = start_day.substring(6,10)+'-'+start_day.substring(3,5)+'-'+start_day.substring(0,2)+' 00:00:00'; }else{ start_day = now.getFullYear()+'-'+month+'-'+now.getDate()+' 00:00:00'; } var end_day = $('#promotion-add-end-date').val(); if(end_day.length >0){ end_day = end_day.substring(6,10)+'-'+end_day.substring(3,5)+'-'+end_day.substring(0,2)+' 00:00:00'; }else{ end_day = now.getFullYear()+'-'+month+'-'+now.getDate()+' 00:00:00'; } var url_img = ""; var tagImg = $('#user_slide_thumbnail'); if(tagImg[0]){ var img = tagImg.attr('data-img'); var thumbnail = tagImg.attr('src'); url_img={}; url_img.img = img; url_img.thumbnail = thumbnail; }else{ url_img={}; url_img.img = URL+'/public/assets/img/noimage.jpg'; url_img.thumbnail = URL+'/public/assets/img/noimage.jpg'; } var content = CKEDITOR.instances.promotionContent.getData(); var message = $('.promotion-message'); var jdata = {"title": title, "start_date": start_day, "end_date": end_day, "url_img": JSON.stringify(url_img), "content": content}; if(title.length<4){ message.text('Tiêu đề phải hơn 4 kí tự.').fadeIn('fast'); return false; }else{ $.ajax({ url: URL + 'spaCMS/promotion/xhrInsert_promotion_item', type: 'post', dataType: 'json', data: jdata, }) .done(function(respon) { if(respon === 1){ alert('Thêm promotion thành công.') }else{ alert('Thêm promotion thất bại, bạn vui lòng thử lại.') } }) .fail(function() { }) .always(function() { loadListPromotion(); $(".modal").modal('hide'); refresh(); }); } } //delete Promotion var deletePromotion = function(id_promotion) { $.ajax({ url: URL + 'spaCMS/promotion/xhrDelete_promotion_item', type: 'post', dataType: 'json', data: {'id_promotion': id_promotion}, }) .done(function(respon) { if(respon==0){ alert('Xóa promotion thất bại, Xin vui lòng kiểm tra lại'); } }) .fail(function(error) { console.log("error: "+error); }) .always(function() { loadListPromotion(); loadAsidePublish(); }); } var publishPromotion = function(id_promotion,state){ $.ajax({ url: URL + 'spaCMS/promotion/xhrPublish_promotion_item', type: 'post', dataType: 'json', data: {'id_promotion': id_promotion, 'state_promotion': state}, }) .done(function(respon) { if(respon == 0){ alert('Kích hoạt promotion thất bại, Xin vui lòng kiểm tra lại'); } }) .fail(function(error) { console.log("error: "+error); }) .always(function() { loadListPromotion(); loadAsidePublish() }); } // update Promotion var updatePromotion = function(){ var title = $('#promotion-update-title').val(); var id_promotion = $('#updatePromotion').attr('data-id-promotion'); var start_day = $('#promotion-update-start-date').val(); var end_day = $('#promotion-update-end-date').val(); var now = new Date(); var month = now.getMonth()+1; if( end_day.length >0 ){ end_day = end_day.substring(6,10)+'-'+end_day.substring(3,5)+'-'+end_day.substring(0,2)+' 00:00:00'; } else { end_day = now.getFullYear()+'-'+month+'-'+now.getDate()+' 00:00:00'; } if( start_day.length >0 ){ start_day = start_day.substring(6,10)+'-'+start_day.substring(3,5)+'-'+start_day.substring(0,2)+' 00:00:00'; } else { start_day = now.getFullYear()+'-'+month+'-'+now.getDate()+' 00:00:00'; } var url_img = ""; var tagImg = $('#user_slide_thumbnail'); if(tagImg[0]){ var img = tagImg.attr('data-img'); var thumbnail = tagImg.attr('src'); // url_img = '{"img": "'+img+'", "thumbnail": "'+thumbnail+'"}'; url_img={}; url_img.img = img; url_img.thumbnail = thumbnail; }else{ url_img={}; url_img.img = URL+'/public/assets/img/noimage.jpg'; url_img.thumbnail = URL+'/public/assets/img/noimage.jpg'; } var content = CKEDITOR.instances.promotionContentUpdate.getData(); var message = $('.promotion-message'); var jdata = {"id_promotion": id_promotion, "title": title, "start_date": start_day, "end_date": end_day, "url_img": JSON.stringify(url_img), "content": content}; if(title.length<4){ message.text('Tiêu đề phải hơn 4 kí tự.').fadeIn('fast'); return false; }else{ $.ajax({ url: URL + 'spaCMS/promotion/xhrUpdate_promotion_item', type: 'post', dataType: 'json', data: jdata, }) .done(function(respon) { if(respon === 1){ alert('Cập nhật promotion thành công.') }else{ alert('Cập nhật promotion thất bại, bạn vui lòng thử lại.') } }) .fail(function() { console.log("error"); }) .always(function() { loadListPromotion(); loadAsidePublish(); $(".modal").modal('hide'); }); } } // refresh form promotion var refresh = function(){ var frmPromotion = $('#form-promotion'); frmPromotion.find('input#promotion-add-title').val(''); frmPromotion.find('input#promotion-add-end-date').val(''); frmPromotion.find('input#promotion-add-end-date').val(''); frmPromotion.find('span.promotion-message').fadeOut('fast').text(''); CKEDITOR.instances.promotionContent.setData(''); // del image var self = $('.del_image').parent(); self.remove(); $('#iM_addUS').fadeIn('fast'); } // Image Manager var imageManager = function() { // Gán thuộc tính cover_id tương ứng $('#iM_editUS').click(function(){ $('#imageManager_saveChange').attr('cover_id','editUS'); }); $('#iM_addUS').click(function(){ $('#imageManager_saveChange').attr('cover_id','addUS'); }); // <!-- Save Change --> $('#imageManager_saveChange').on('click', function(evt) { evt.preventDefault(); // Define position insert to image var cover_id = $(this).attr('cover_id'); // Define selected image var radio_checked = $("input:radio[name='iM-radio']:checked"); // Radio checked // image and thumbnail_image var image = radio_checked.val(); var thumbnail = radio_checked.attr('data-image'); // Truong hop dac biet if(cover_id == 'addUS') { var caller = $('#iM_addUS'); var items = $('#ListIM_addUS'); } else if(cover_id == 'editUS') { var caller = $('#iM_editUS'); var items = $('#ListIM_editUS'); } // ktra so luong hinh anh da co var childrens = items.children().length + 1; if(childrens == 1) { caller.hide(); } var out = null; var html = '<li class="single-picture">'; html += '<div class="single-picture-wrapper">'; html += '<img id="user_slide_thumbnail" src=":img_thumbnail" data-img=":data-image" style="width:100px; height:60px;">'; html += '<input type="hidden" name="user_service_image[]" value=":image">'; html += '</div>'; html += '<div class="del_image icons-delete2"></div>'; html += '</li>'; out = html.replace(':img_thumbnail', thumbnail); out = out.replace(':data-image', image); out = out.replace(':image', image); items.html(out); // del image $('.del_image').on("click", function(){ var self = $(this).parent(); // self.attr("disabled","disabled"); self.remove(); // Truong hop dac biet, ktra so luong hinh anh da co var childrens = items.children().length; if(childrens < 1) { caller.fadeIn(); } }); // Hide Modal $("#imageManager_modal").modal('hide'); }); } return { init: function() { loadListPromotion(); loadAsidePublish();}, addNew: function(){ addNewPromotion(); }, update: function(){ updatePromotion(); }, loadImage: function(){ imageManager(); } } var refresh = function() { console.log('refresh'); } }(); // function offsetDay(dayStart, dayEnd){ // var offset = dayEnd.getTime() - dayStart.getTime(); // console.log(dayEnd.getTime()+'-'+dayStart.getTime()); // // lấy độ lệch của 2 mốc thời gian, đơn vị tính là millisecond // var totalDays = Math.round(offset / 1000 / 60 / 60 / 24); // console.log(dayStart.getTime()); // return totalDays; // }
imtoantran/beleza
Views/spaCMS/promotion/js/spaCMS_promotion.js
JavaScript
apache-2.0
21,895
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Erlang distributed pseudorandom numbers. * * @module @stdlib/random/base/erlang * * @example * var erlang = require( '@stdlib/random/base/erlang' ); * * var v = erlang( 3, 2.5 ); * // returns <number> * * @example * var factory = require( '@stdlib/random/base/erlang' ).factory; * * var erlang = factory( 8, 5.9, { * 'seed': 297 * }); * * var v = erlang(); * // returns <number> */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var erlang = require( './main.js' ); var factory = require( './factory.js' ); // MAIN // setReadOnly( erlang, 'factory', factory ); // EXPORTS // module.exports = erlang;
stdlib-js/stdlib
lib/node_modules/@stdlib/random/base/erlang/lib/index.js
JavaScript
apache-2.0
1,304
function qSc(){} function sUc(){} function W6d(){} function Q6d(){} function FV(b){b.c.Ze(JN(b.b.b))} function jJ(b,c,d){return new sSc(b,c,d)} function Gte(){kse.call(this,(gCe(),eCe))} function kse(b){this.M=new Object;this.M[Ghf]=zqg;this.M[kRf]=b.b} function sSc(b,c,d){fY.call(this,b,c);this.d=d;uld(this.j,263).Wc(this);uld(uld(this.j,263).Xc(),3).b=uld(this.d,264).Tc()} function Y6d(){T6d=new W6d;Vad((Sad(),Rad),38);!!$stats&&$stats(Kbd(Cqg,cif,-1,-1));T6d.Re();!!$stats&&$stats(Kbd(Cqg,$Df,-1,-1))} function V6d(){var b,d,e;while(R6d){d=$8c;e=R6d;R6d=R6d.c;!R6d&&(S6d=null);if(!d){FV(e.b)}else{try{FV(e.b)}catch(b){b=xVd(b);if(!xld(b,209))throw b}}}} function JN(b){var c;!b.oc&&(b.oc=(c=jJ((!b.Jc&&(b.Jc=new une),b.Jc),(!b.vc&&(b.vc=new vUc),b.vc),(!b.nc&&(b.nc=new zSc),b.nc),!b.Ic&&(b.Ic=(new lme).df(new Wle,new $le))),c.Pc(),c));return b.oc} function iSc(){var b,c,d,e,f,g,i;if(gSc){return gSc}else{gSc=new X1c;gSc.se(sqg);c=new Gte;DHe(c.M,xDf,(EUe(),EUe(),DUe));i=new Hte(kRf,QOf);f=new Hte(tqg,aPf);b=new Hte(uqg,N8f);e=new ute(vqg,P8f);g=new ute(wqg,R8f);d=new Hte(eMf,KTf);U1c(gSc,gld(tUd,{272:1,322:1},103,[c,i,f,b,e,g,d]));gSc.re(xqg);s1c(gSc,yqg,DUe,false);return gSc}} function vUc(){var b,c,d,e,f,g,i,j,k,n;this.b=new s8c;Uub(this.b,gld(ZUd,{272:1,322:1},137,[(b=new ekb,Nhb(b)?(j=b.fd(),j.setProperty(ucf,rcf),undefined):(b.o[ucf]=rcf,undefined),Nhb(b)?(k=b.fd(),k.setProperty(qcf,rcf),undefined):(b.o[qcf]=rcf,undefined),Uhb(b,OFf,(EUe(),EUe(),DUe),true),Nhb(b)?(n=b.fd(),n.setProperty(PFf,0),undefined):(b.o[PFf]=0,undefined),f=new TPe(zqg,llg,100),i=new TPe(kRf,QOf,200),i.M[WEf]=NGe(gld(mVd,{272:1,322:1,323:1},1,[Aqg,Bqg])),d=new TPe(tqg,aPf,400),c=new TPe(vqg,P8f,100),e=new TPe(wqg,R8f,100),g=new SPe(eMf,KTf),Nhb(b)?aib(b,LDf,NGe(gld(cVd,{272:1,322:1},190,[f,i,d,c,e,g]))):(b.o[LDf]=NGe(gld(cVd,{272:1,322:1},190,[f,i,d,c,e,g])),undefined),Uhb(b,QFf,DUe,true),Uhb(b,RFf,DUe,true),Thb(b,JDf,p1c(iSc())),Uhb(b,KDf,DUe,false),Nhb(b)?undefined:(b.o[eZf]=kRf,undefined),Phb(b,(rCe(),oCe)),Uhb(b,SDf,DUe,true),Uhb(b,CQf,DUe,true),b)]))} var sqg='/assignedtask/tasks/task',Dqg='AssignedTaskPresenter',Eqg='AssignedTaskView',Fqg='AsyncLoader38',Aqg='Human Resources - Recruitment',Bqg='Human Resources - Travel Management',uqg='assignee',xqg='ds/test_data/assignedtask.data.xml',Cqg='runCallbacks38',vqg='taskdate',tqg='taskdesc',wqg='taskduedate',zqg='taskid';var gSc=null;_=sSc.prototype=qSc.prototype=new KX;_.gC=function tSc(){return mId};_.Rc=function uSc(){tne(this.g,this,new sqe((O3c(),M3c),this))};_.cM={87:1,309:1};_=vUc.prototype=sUc.prototype=new vZ;_.Xc=function wUc(){return this.b};_.gC=function xUc(){return DId};_.cM={263:1};_.b=null;_=W6d.prototype=Q6d.prototype=new ZH;_.gC=function X6d(){return HNd};_.Re=function _6d(){V6d()};_.cM={};_=Gte.prototype=Ete.prototype;var mId=VUe(suf,Dqg),DId=VUe(bbg,Eqg),HNd=VUe(wyf,Fqg);$entry(Y6d)();
yauritux/venice-legacy
Venice/Venice-Web/target/Venice-Web-1.0/Venice/deferredjs/AB044E8946F390304175332DF12BD630/38.cache.js
JavaScript
apache-2.0
2,880
function removeFile() { var sheet = SpreadsheetApp.getActiveSheet(); //Activate sheet var tno = sheet.getRange('C1').getValues(); var file_name = 'Current Test Buffer-'+tno+'.zip'; var folder = DriveApp.getFolderById('0B5Sb6IOPwl52flVvMXg4dGJuVVdCYl9fNk1MNlBzazBMdk1IZ3BiWkJRR05TNXFZWUtYV3M'); var file1 = DriveApp.getFilesByName(file_name).next(); //File removal code start var files = folder.getFiles(); var name = folder.getName(); while ( files.hasNext() ) { var file = files.next(); folder.removeFile(file); } //File removal code ended var tlatest = Number(tno)+1;//Counter++ for test series number //Logger.log(tlatest); SpreadsheetApp.getActiveSheet().getRange('C1').setValue(tlatest); }
arpan-chavda/my_google_scripts
file_cleaner.js
JavaScript
apache-2.0
736
/* * Copyright (c) 2014 DataTorrent, Inc. ALL Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; angular.module('ui.dashboard', ['ui.bootstrap', 'ui.sortable']); angular.module('ui.dashboard') .directive('dashboard', ['WidgetModel', 'WidgetDefCollection', '$uibModal', 'DashboardState', '$log', function (WidgetModel, WidgetDefCollection, $uibModal, DashboardState, $log) { return { restrict: 'A', templateUrl: function(element, attr) { return attr.templateUrl ? attr.templateUrl : 'components/directives/dashboard/dashboard.html'; }, scope: true, controller: ['$scope', '$attrs', function (scope, attrs) { // default options var defaults = { stringifyStorage: true, hideWidgetSettings: false, hideWidgetClose: false, settingsModalOptions: { templateUrl: 'components/directives/dashboard/widget-settings-template.html', controller: 'WidgetSettingsCtrl' }, onSettingsClose: function(result, widget) { // NOTE: dashboard scope is also passed as 3rd argument jQuery.extend(true, widget, result); }, onSettingsDismiss: function(reason) { // NOTE: dashboard scope is also passed as 2nd argument $log.info('widget settings were dismissed. Reason: ', reason); } }; // from dashboard="options" scope.options = scope.$eval(attrs.dashboard); // Ensure settingsModalOptions exists on scope.options scope.options.settingsModalOptions = scope.options.settingsModalOptions !== undefined ? scope.options.settingsModalOptions : {}; // Set defaults _.defaults(scope.options.settingsModalOptions, defaults.settingsModalOptions); // Shallow options _.defaults(scope.options, defaults); // sortable options var sortableDefaults = { stop: function () { scope.saveDashboard(); }, handle: '.widget-header', distance: 5 }; scope.sortableOptions = angular.extend({}, sortableDefaults, scope.options.sortableOptions || {}); }], link: function (scope) { // Save default widget config for reset scope.defaultWidgets = scope.options.defaultWidgets; scope.widgetDefs = new WidgetDefCollection(scope.options.widgetDefinitions); var count = 1; // Instantiate new instance of dashboard state scope.dashboardState = new DashboardState( scope.options.storage, scope.options.storageId, scope.options.storageHash, scope.widgetDefs, scope.options.stringifyStorage ); function getWidget(widgetToInstantiate) { if (typeof widgetToInstantiate === 'string') { widgetToInstantiate = { name: widgetToInstantiate }; } var defaultWidgetDefinition = scope.widgetDefs.getByName(widgetToInstantiate.name); if (!defaultWidgetDefinition) { throw 'Widget ' + widgetToInstantiate.name + ' is not found.'; } // Determine the title for the new widget var title; if (!widgetToInstantiate.title && !defaultWidgetDefinition.title) { widgetToInstantiate.title = 'Widget ' + count++; } // Instantiation return new WidgetModel(defaultWidgetDefinition, widgetToInstantiate); } /** * Instantiates a new widget and append it the dashboard * @param {Object} widgetToInstantiate The definition object of the widget to be instantiated */ scope.addWidget = function (widgetToInstantiate, doNotSave) { var widget = getWidget(widgetToInstantiate); // Add to the widgets array scope.widgets.push(widget); if (!doNotSave) { scope.saveDashboard(); } return widget; }; /** * Instantiates a new widget and insert it a beginning of dashboard */ scope.prependWidget = function(widgetToInstantiate, doNotSave) { var widget = getWidget(widgetToInstantiate); // Add to the widgets array scope.widgets.unshift(widget); if (!doNotSave) { scope.saveDashboard(); } return widget; }; /** * Removes a widget instance from the dashboard * @param {Object} widget The widget instance object (not a definition object) */ scope.removeWidget = function (widget) { scope.widgets.splice(_.indexOf(scope.widgets, widget), 1); scope.saveDashboard(); }; /** * Opens a dialog for setting and changing widget properties * @param {Object} widget The widget instance object */ scope.openWidgetSettings = function (widget) { // Set up $uibModal options var options = _.defaults( { scope: scope }, widget.settingsModalOptions, scope.options.settingsModalOptions); // Ensure widget is resolved options.resolve = { widget: function () { return widget; } }; // Create the modal var modalInstance = $uibModal.open(options); var onClose = widget.onSettingsClose || scope.options.onSettingsClose; var onDismiss = widget.onSettingsDismiss || scope.options.onSettingsDismiss; // Set resolve and reject callbacks for the result promise modalInstance.result.then( function (result) { // Call the close callback onClose(result, widget, scope); //AW Persist title change from options editor scope.$emit('widgetChanged', widget); }, function (reason) { // Call the dismiss callback onDismiss(reason, scope); } ); }; /** * Remove all widget instances from dashboard */ scope.clear = function (doNotSave) { scope.widgets = []; if (doNotSave === true) { return; } scope.saveDashboard(); }; /** * Used for preventing default on click event * @param {Object} event A click event * @param {Object} widgetDef A widget definition object */ scope.addWidgetInternal = function (event, widgetDef) { event.preventDefault(); scope.addWidget(widgetDef); }; /** * Uses dashboardState service to save state */ scope.saveDashboard = function (force) { if (!scope.options.explicitSave) { return scope.dashboardState.save(scope.widgets); } else { if (!angular.isNumber(scope.options.unsavedChangeCount)) { scope.options.unsavedChangeCount = 0; } if (force) { scope.options.unsavedChangeCount = 0; return scope.dashboardState.save(scope.widgets); } else { ++scope.options.unsavedChangeCount; } } }; /** * Wraps saveDashboard for external use. */ scope.externalSaveDashboard = function(force) { if (angular.isDefined(force)) { return scope.saveDashboard(force); } else { return scope.saveDashboard(true); } }; /** * Clears current dash and instantiates widget definitions * @param {Array} widgets Array of definition objects */ scope.loadWidgets = function (widgets) { // AW dashboards are continuously saved today (no "save" button). //scope.defaultWidgets = widgets; scope.savedWidgetDefs = widgets; scope.clear(true); _.each(widgets, function (widgetDef) { scope.addWidget(widgetDef, true); }); }; /** * Resets widget instances to default config * @return {[type]} [description] */ scope.resetWidgetsToDefault = function () { scope.loadWidgets(scope.defaultWidgets); scope.saveDashboard(); }; // Set default widgets array var savedWidgetDefs = scope.dashboardState.load(); // Success handler function handleStateLoad(saved) { scope.options.unsavedChangeCount = 0; if (saved && saved.length) { scope.loadWidgets(saved); } else if (scope.defaultWidgets) { scope.loadWidgets(scope.defaultWidgets); } else { scope.clear(true); } } if (angular.isArray(savedWidgetDefs)) { handleStateLoad(savedWidgetDefs); } else if (savedWidgetDefs && angular.isObject(savedWidgetDefs) && angular.isFunction(savedWidgetDefs.then)) { savedWidgetDefs.then(handleStateLoad, handleStateLoad); } else { handleStateLoad(); } // expose functionality externally // functions are appended to the provided dashboard options scope.options.addWidget = scope.addWidget; scope.options.prependWidget = scope.prependWidget; scope.options.loadWidgets = scope.loadWidgets; scope.options.saveDashboard = scope.externalSaveDashboard; scope.options.removeWidget = scope.removeWidget; scope.options.openWidgetSettings = scope.openWidgetSettings; scope.options.clear = scope.clear; scope.options.resetWidgetsToDefault = scope.resetWidgetsToDefault; scope.options.currentWidgets = scope.widgets; // save state scope.$on('widgetChanged', function (event) { event.stopPropagation(); scope.saveDashboard(); }); } }; }]);
DataTorrent/malhar-angular-dashboard
src/components/directives/dashboard/dashboard.js
JavaScript
apache-2.0
10,601
module.exports = function (grunt) { // Project configuration. grunt.initConfig({ //Read the package.json (optional) pkg: grunt.file.readJSON('package.json'), // Metadata. meta: { basePath: './', srcPath: './src/', deployPath: './bin/', unittestsPath : "./unittests/" }, banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %>\n' + '* Copyright (c) <%= grunt.template.today("yyyy") %> ', tsd: { refresh: { options: { // execute a command command: 'reinstall', //optional: always get from HEAD latest: true, // optional: specify config file config: '<%= meta.basePath %>/tsd.json', // experimental: options to pass to tsd.API opts: { // props from tsd.Options } } } }, typescript: { base: { src: ['<%= meta.srcPath %>/*.ts'], dest: '<%= meta.deployPath %>/Knockout.WinJS.js', options: { target: 'es5', //or es3 basePath: '.', sourceMap: true, declaration: true } }, observableTests: { src: ['<%= meta.srcPath %>/*.ts', '<%= meta.unittestsPath %>/observableTests.ts'], dest: '<%= meta.deployPath %>/unittests/observableTests.js', options: { target: 'es5', //or es3 basePath: '.', sourceMap: true, declaration: false } }, defaultBindTests: { src: ['<%= meta.srcPath %>/*.ts', '<%= meta.unittestsPath %>/defaultBindTests.ts'], dest: '<%= meta.deployPath %>/unittests/defaultBindTests.js', options: { target: 'es5', //or es3 basePath: '.', sourceMap: true, declaration: false } } }, uglify: { my_target: { files: { '<%= meta.deployPath %>/Knockout.WinJS.min.js': ['<%= meta.deployPath %>/Knockout.WinJS.js'] } } }, copy: { tests: { files: [ // includes files within path { expand: true, src: ['<%= meta.unittestsPath %>/*.html'], dest: '<%= meta.deployPath %>/', filter: 'isFile' }, ] } } //concat: { // options: { // stripBanners: true // }, // dist: { // src: ['<%= meta.srcPath %>/Knockout.WinJS.js', '<%= meta.srcPath %>/defaultBind.js'], // dest: '<%= meta.deployPath %>/Knockout.WinJS.js' // } //} }); grunt.loadNpmTasks('grunt-tsd'); grunt.loadNpmTasks('grunt-typescript'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-copy'); // Default task grunt.registerTask('default', ['tsd', 'typescript', 'uglify', 'copy']); };
wildcatsoft/Knockout.WinJS
gruntfile.js
JavaScript
apache-2.0
3,484
/** * Copyright 2014 IBM Corp. 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. */ 'use strict'; // Module dependencies var express = require('express'), favicon = require('serve-favicon'), errorhandler = require('errorhandler'), bodyParser = require('body-parser'), csrf = require('csurf'), cookieParser = require('cookie-parser'); module.exports = function (app) { app.set('view engine', 'ejs'); app.enable('trust proxy'); // use only https var env = process.env.NODE_ENV || 'development'; if ('production' === env) { app.use(errorhandler()); } // Configure Express app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // Setup static public directory app.use(express.static(__dirname + '/../public')); app.use(favicon(__dirname + '/../public/images/favicon.ico')); // cookies var secret = Math.random().toString(36).substring(7); app.use(cookieParser(secret)); // csrf var csrfProtection = csrf({ cookie: true }); app.get('/', csrfProtection, function(req, res) { res.render('index', { ct: req.csrfToken() }); }); // apply to all requests that begin with /api/ // csfr token app.use('/api/', csrfProtection); };
tonybndt/BlueMix-Tutorials
config/express.js
JavaScript
apache-2.0
1,764
sap.ui.define(['exports'], function (exports) { 'use strict'; var messagebundle_es = { BARCODE_SCANNER_DIALOG_CANCEL_BUTTON_TXT: "Cancelar", BARCODE_SCANNER_DIALOG_LOADING_TXT: "Cargando", FCL_START_COLUMN_TXT: "Primera columna", FCL_MIDDLE_COLUMN_TXT: "Columna media", FCL_END_COLUMN_TXT: "Última columna", FCL_START_COLUMN_EXPAND_BUTTON_TOOLTIP: "Desplegar la primera columna", FCL_START_COLUMN_COLLAPSE_BUTTON_TOOLTIP: "Comprimir la primera columna", FCL_END_COLUMN_EXPAND_BUTTON_TOOLTIP: "Desplegar la última columna", FCL_END_COLUMN_COLLAPSE_BUTTON_TOOLTIP: "Comprimir la última columna", NOTIFICATION_LIST_ITEM_TXT: "Notificación", NOTIFICATION_LIST_ITEM_SHOW_MORE: "Visualizar más", NOTIFICATION_LIST_ITEM_SHOW_LESS: "Visualizar menos", NOTIFICATION_LIST_ITEM_OVERLOW_BTN_TITLE: "Más", NOTIFICATION_LIST_ITEM_CLOSE_BTN_TITLE: "Cerrar", NOTIFICATION_LIST_ITEM_READ: "Leídos", NOTIFICATION_LIST_ITEM_UNREAD: "No leídos", NOTIFICATION_LIST_ITEM_HIGH_PRIORITY_TXT: "Prioridad alta", NOTIFICATION_LIST_ITEM_MEDIUM_PRIORITY_TXT: "Prioridad media", NOTIFICATION_LIST_ITEM_LOW_PRIORITY_TXT: "Prioridad baja", NOTIFICATION_LIST_GROUP_ITEM_TXT: "Grupo de notificaciones", NOTIFICATION_LIST_GROUP_ITEM_COUNTER_TXT: "Contador", NOTIFICATION_LIST_GROUP_ITEM_CLOSE_BTN_TITLE: "Cerrar todo", NOTIFICATION_LIST_GROUP_ITEM_TOGGLE_BTN_COLLAPSE_TITLE: "Ocultar grupo", NOTIFICATION_LIST_GROUP_ITEM_TOGGLE_BTN_EXPAND_TITLE: "Desplegar grupo", TIMELINE_ARIA_LABEL: "Cronología", UPLOADCOLLECTIONITEM_CANCELBUTTON_TEXT: "Cancelar", UPLOADCOLLECTIONITEM_RENAMEBUTTON_TEXT: "Cambiar nombre", UPLOADCOLLECTIONITEM_ERROR_STATE: "Concluido", UPLOADCOLLECTIONITEM_READY_STATE: "Pendiente", UPLOADCOLLECTIONITEM_UPLOADING_STATE: "Cargando", UPLOADCOLLECTIONITEM_TERMINATE_BUTTON_TEXT: "Finalizar", UPLOADCOLLECTIONITEM_RETRY_BUTTON_TEXT: "Volver a intentar", UPLOADCOLLECTIONITEM_EDIT_BUTTON_TEXT: "Editar", UPLOADCOLLECTION_NO_DATA_TEXT: "No existen ficheros.", UPLOADCOLLECTION_NO_DATA_DESCRIPTION: "Soltar los ficheros para cargarlos o utilizar el botón \"Cargar\".", UPLOADCOLLECTION_ARIA_ROLE_DESCRIPTION: "Cargar colección", UPLOADCOLLECTION_DRAG_FILE_INDICATOR: "Arrastrar ficheros aquí.", UPLOADCOLLECTION_DROP_FILE_INDICATOR: "Soltar ficheros para cargalos.", SHELLBAR_LABEL: "Barra de shell", SHELLBAR_LOGO: "Logotipo", SHELLBAR_COPILOT: "CoPilot", SHELLBAR_NOTIFICATIONS: "Notificaciones {0}", SHELLBAR_PROFILE: "Perfil", SHELLBAR_PRODUCTS: "Productos", PRODUCT_SWITCH_CONTAINER_LABEL: "Productos", SHELLBAR_SEARCH: "Buscar", SHELLBAR_OVERFLOW: "Más", SHELLBAR_CANCEL: "Cancelar", WIZARD_NAV_ARIA_LABEL: "Barra de progreso del asistente", WIZARD_LIST_ARIA_LABEL: "Pasos del asistente", WIZARD_LIST_ARIA_DESCRIBEDBY: "Para activarlo, pulse la barra espaciadora o Intro", WIZARD_ACTIONSHEET_STEPS_ARIA_LABEL: "Pasos", WIZARD_OPTIONAL_STEP_ARIA_LABEL: "Opcional", WIZARD_STEP_ACTIVE: "Activo", WIZARD_STEP_INACTIVE: "Inactivo", WIZARD_STEP_ARIA_LABEL: "Paso {0}", WIZARD_NAV_ARIA_ROLE_DESCRIPTION: "Asistente", WIZARD_NAV_STEP_DEFAULT_HEADING: "Paso", VSD_DIALOG_TITLE_SORT: "Ver opciones", VSD_SUBMIT_BUTTON: "OK", VSD_CANCEL_BUTTON: "Cancelar", VSD_RESET_BUTTON: "Reinicializar", VSD_SORT_ORDER: "Orden de clasificación", VSD_FILTER_BY: "Filtrar por", VSD_SORT_BY: "Clasificar por", VSD_ORDER_ASCENDING: "Ascendente", VSD_ORDER_DESCENDING: "Descendente", IM_TITLE_BEFORESEARCH: "Obtengamos resultados", IM_SUBTITLE_BEFORESEARCH: "Comience proporcionando los criterios de búsqueda.", IM_TITLE_NOACTIVITIES: "Todavía no ha añadido actividades", IM_SUBTITLE_NOACTIVITIES: "¿Desea añadir una ahora?", IM_TITLE_NODATA: "Todavía no hay datos", IM_SUBTITLE_NODATA: "Cuando haya, los verá aquí.", IM_TITLE_NOMAIL: "Ningún correo nuevo", IM_SUBTITLE_NOMAIL: "Vuelva a comprobarlo de nuevo más tarde.", IM_TITLE_NOENTRIES: "Todavía no hay entradas", IM_SUBTITLE_NOENTRIES: "Cuando haya, las verá aquí.", IM_TITLE_NONOTIFICATIONS: "No tiene ninguna notificación nueva", IM_SUBTITLE_NONOTIFICATIONS: "Vuelva a comprobarlo de nuevo más tarde.", IM_TITLE_NOSAVEDITEMS: "Todavía no ha añadido favoritos", IM_SUBTITLE_NOSAVEDITEMS: "¿Desea crear una lista de las posiciones favoritas ahora?", IM_TITLE_NOSEARCHRESULTS: "No existen resultados", IM_SUBTITLE_NOSEARCHRESULTS: "Intente modificar los criterios de búsqueda.", IM_TITLE_NOTASKS: "No tiene ninguna tarea nueva", IM_SUBTITLE_NOTASKS: "Cuando tenga, las verá aquí.", IM_TITLE_UNABLETOLOAD: "No se pueden cargar datos", IM_SUBTITLE_UNABLETOLOAD: "Compruebe su conexión a internet. Si esto no funciona, intente volver a cargar la página. Si esto tampoco funciona, verifique con su administrador.", IM_TITLE_UNABLETOLOADIMAGE: "No se puede cargar la imagen", IM_SUBTITLE_UNABLETOLOADIMAGE: "No se ha podido encontrar la imagen en la ubicación especificada o el servidor no responde.", IM_TITLE_UNABLETOUPLOAD: "No se pueden cargar datos", IM_SUBTITLE_UNABLETOUPLOAD: "Compruebe su conexión a internet. Si esto no funciona, compruebe el formato de fichero y el tamaño de fichero. De lo contrario, póngase en contacto con su administrador.", IM_TITLE_ADDCOLUMN: "Parece que hay espacio libre", IM_SUBTITLE_ADDCOLUMN: "Puede añadir más columnas en las opciones de tabla.", IM_TITLE_ADDPEOPLE: "Aún no ha añadido a nadie al calendario", IM_SUBTITLE_ADDPEOPLE: "¿Desea añadir a alguien ahora?", IM_TITLE_BALLOONSKY: "Se le valora.", IM_SUBTITLE_BALLOONSKY: "Siga trabajando tan bien.", IM_TITLE_EMPTYPLANNINGCALENDAR: "Aún no hay nada planificado", IM_SUBTITLE_EMPTYPLANNINGCALENDAR: "No hay actividades en este intervalo de tiempo", IM_TITLE_FILTERTABLE: "Hay opciones de filtro disponibles", IM_SUBTITLE_FILTERTABLE: "Los filtros le ayudan a concentrarse en lo que considera más relevante.", IM_TITLE_GROUPTABLE: "Intente agrupar elementos para obtener un mejor resumen", IM_SUBTITLE_GROUPTABLE: "Puede optar por agrupar categorías en las opciones de grupo.", IM_TITLE_NOFILTERRESULTS: "No existen resultados", IM_SUBTITLE_NOFILTERRESULTS: "Intente ajustar sus criterio de filtro.", IM_TITLE_PAGENOTFOUND: "Lo sentimos, la página no existe", IM_SUBTITLE_PAGENOTFOUND: "Verifique el URL que está utilizando para llamar la aplicación.", IM_TITLE_RESIZECOLUMN: "Seleccione su propio ancho de columna", IM_SUBTITLE_RESIZECOLUMN: "Puede ajustar columnas arrastrando los bordes de la columna.", IM_TITLE_SORTCOLUMN: "¿No ve primero los elementos más importantes?", IM_SUBTITLE_SORTCOLUMN: "Seleccione los criterios de clasificación en las opciones de clasificación.", IM_TITLE_SUCCESSSCREEN: "Bien hecho.", IM_SUBTITLE_SUCCESSSCREEN: "Ha completado todas sus asignaciones de aprendizaje.", IM_TITLE_UPLOADCOLLECTION: "Suelte aquí los archivos", IM_SUBTITLE_UPLOADCOLLECTION: "También puede cargar varios archivos a la vez.", DSC_SIDE_ARIA_LABEL: "Contenido lateral" }; exports.default = messagebundle_es; });
SAP/openui5
src/sap.ui.webc.fiori/src/sap/ui/webc/fiori/thirdparty/_chunks/messagebundle_es.js
JavaScript
apache-2.0
7,123
Ext.define('MCLM.view.cenarios.GerenciarGruposCenarioWindow', { requires: [ 'MCLM.store.Grupo', 'Ext.grid.plugin.DragDrop', 'MCLM.view.cenarios.GerenciarGruposCenarioController' ], extend: 'Ext.window.Window', id: 'gerenciarGruposCenarioWindow', itemId: 'gerenciarGruposCenarioWindow', controller: 'gerenciar-grupos-cenario', modal: true, width: '60%', height: 500, layout: { type: 'vbox', align: 'stretch', pack: 'start' }, tbar: [ {iconCls: 'save-icon', tooltip: '<b>Salvar Alterações</b>', handler: 'onSaveBtnClick'} ], items: [ { xtype: 'container', layout: 'hbox', height: '50%', width: '100%', items: [ { itemId: 'associatedGroupsGrid', xtype: 'grid', title: 'Grupos Associados', titleAlign: 'center', scrollable: true, width: '50%', height: '100%', store: { proxy: 'memory', sorters: ['name'], autoSort: true }, tools: [{ iconCls: 'group-add-icon', tooltip: '<b>Compartilhar com Grupos</b>', handler: () => Ext.getCmp('gerenciarGruposCenarioWindow').down('#groupsGrid').expand() }], columns: [ { dataIndex: 'name', text: 'Nome', width: '90%', items: [ { xtype: 'textfield', emptyText: 'Filtrar', enableKeyEvents: true, listeners: { keyup: 'onAssociatedGroupFilterKeyup', buffer: 500 } } ] }, { xtype: 'actioncolumn', width: '5%', items: [ {iconCls: "details-icon", tooltip: 'Detalhes', handler: 'onGroupDetailsBtnClick'} ] }, { xtype: 'actioncolumn', width: '5%', items: [ {tooltip: 'Remover Associação', iconCls: 'cancel-icon', handler: 'onAssociatedGroupRemoveBtnClick'} ]} ] }, { itemId: 'groupsGrid', xtype: 'grid', title: 'Grupos', titleAlign: 'center', scrollable: true, width: '50%', collapsed: true, collapsible: true, animCollapse: true, height: '100%', store: { type: 'grupo', pageSize: 0 }, columns: [ { dataIndex: 'name', text: 'Nome', width: '90%', items: [ { xtype: 'textfield', emptyText: 'Filtrar', enableKeyEvents: true, listeners: { keyup: 'onGroupFilterKeyup', buffer: 500 } } ] }, { xtype: 'actioncolumn', width: '5%', items: [ {iconCls: 'details-icon', tooltip: 'Detalhes', handler: 'onGroupDetailsBtnClick'} ] }, { xtype: 'actioncolumn', width: '5%', items: [ {tooltip: 'Associar', iconCls: 'plus-icon', handler: 'onGroupAssociationBtnClick'} ]} ], listeners: { rowdblclick: 'onGroupRowDblClick' } } ] }, { xtype: 'container', layout: 'hbox', height: '50%', width: '100%', items: [ { itemId: 'associatedUsersGrid', xtype: 'grid', titleAlign: 'center', scrollable: true, title: 'Usuários Associados', width: '50%', height: '100%', store: { proxy: 'memory', sorters: ['nome'], autoSort: true }, tools: [{ iconCls: 'user-add-icon', tooltip: '<b>Compartilhar com Usuários</b>', handler: () => Ext.getCmp('gerenciarGruposCenarioWindow').down('#usersGrid').expand() }], columns: [ { dataIndex: 'cpf', text: 'CPF', renderer: ColumnRenderer.cpf, width: '30%', items: [ { xtype: 'textfield', emptyText: 'Filtrar', enableKeyEvents: true, listeners: { keyup: 'onAssociatedUserFilterKeyup', buffer: 500 } } ] }, { dataIndex: 'nome', text: 'Nome', width: '40%', items: [ { xtype: 'textfield', emptyText: 'Filtrar', enableKeyEvents: true, listeners: { keyup: 'onAssociatedUserFilterKeyup', buffer: 500 } } ] }, {dataIndex: 'siglaOm', text: 'OM', width: '10%'}, {dataIndex: 'siglaForca', text: 'Força', width: '10%'}, {xtype: 'actioncolumn', width: '10%', items: [ {tooltip: 'Remover', iconCls: 'cancel-icon', handler: 'onAssociatedUserRemoveBtnClick'} ]} ] }, { itemId: 'usersGrid', xtype: 'grid', titleAlign: 'center', scrollable: true, title: 'Usuários', width: '50%', collapsed: true, collapsible: true, animCollapse: true, height: '100%', store: { type: 'apolo-user', autoLoad: true, pageSize: 10 }, columns: [ { dataIndex: 'cpf', text: 'CPF', renderer: ColumnRenderer.cpf, width: '30%', items: [ { xtype: 'textfield', emptyText: 'Filtrar', enableKeyEvents: true, listeners: { keyup: 'onUserFilterKeyup', buffer: 500 } } ] }, { dataIndex: 'nome', text: 'Nome', width: '40%', items: [ { xtype: 'textfield', emptyText: 'Filtrar', enableKeyEvents: true, listeners: { keyup: 'onUserFilterKeyup', buffer: 500 } } ] }, {dataIndex: 'siglaOm', text: 'OM', width: '10%'}, {dataIndex: 'siglaForca', text: 'Força', width: '10%'}, {xtype: 'actioncolumn', width: '10%', items: [ {tooltip: 'Associar', iconCls: 'plus-icon', handler: 'onUserAssociationBtnClick'} ]} ], listeners: { rowdblclick: 'onUserRowDblClick' }, dockedItems: [{ xtype: 'pagingtoolbar', store: { type: 'apolo-user', autoLoad: true, pageSize: 10 }, // same store GridPanel is using dock: 'bottom', displayInfo: true }] } ] } ], listeners: {show: 'onShow'} });
icemagno/mclm
src/main/webapp/app/view/cenarios/GerenciarGruposCenarioWindow.js
JavaScript
apache-2.0
10,122
/* global QUnit */ sap.ui.define([ "sap/ui/core/Control", "sap/ui/fl/write/api/SmartVariantManagementWriteAPI", "sap/ui/fl/Layer", "sap/ui/rta/command/CommandFactory", "sap/ui/thirdparty/sinon-4" ], function( Control, SmartVariantManagementWriteAPI, Layer, CommandFactory, sinon ) { "use strict"; var sandbox = sinon.createSandbox(); QUnit.module("Given a control", { beforeEach: function() { this.oControl = new Control(); }, afterEach: function() { this.oControl.destroy(); sandbox.restore(); } }, function() { QUnit.test("Update in the Save scenario", function(assert) { var oUpdateCommand; var sVariantId = "variantId"; var oContent = {foo: "bar"}; var oUpdateControlStub = sandbox.stub(); this.oControl.updateVariant = oUpdateControlStub; var oSetModifiedStub = sandbox.stub(); this.oControl.setModified = oSetModifiedStub; var oUpdateFlAPIStub = sandbox.stub(SmartVariantManagementWriteAPI, "updateVariant"); var oUndoVariantFlAPIStub = sandbox.stub(SmartVariantManagementWriteAPI, "revert"); return CommandFactory.getCommandFor(this.oControl, "compVariantUpdate", { newVariantProperties: { variantId: { content: oContent } }, onlySave: true }, {}) .then(function(oCreatedCommand) { oUpdateCommand = oCreatedCommand; return oUpdateCommand.execute(); }).then(function() { assert.equal(oUpdateFlAPIStub.callCount, 1, "the FL update function was called"); var mExpectedProperties = { id: sVariantId, control: this.oControl, content: oContent, generator: "sap.ui.rta.command", command: "compVariantUpdate", layer: Layer.CUSTOMER }; assert.deepEqual(oUpdateFlAPIStub.lastCall.args[0], mExpectedProperties, "the FL API was called with the correct properties"); assert.equal(oSetModifiedStub.callCount, 1, "the setModified was called.."); assert.equal(oSetModifiedStub.lastCall.args[0], false, "and set to false"); return oUpdateCommand.undo(); }.bind(this)).then(function() { assert.equal(oUndoVariantFlAPIStub.callCount, 1, "the undo function was called"); assert.equal(oSetModifiedStub.callCount, 2, "the setModified was called again.."); assert.equal(oSetModifiedStub.lastCall.args[0], true, "and set to true"); return oUpdateCommand.execute(); }).then(function() { assert.equal(oUpdateFlAPIStub.callCount, 2, "the FL update function was called again"); var mExpectedProperties = { id: sVariantId, control: this.oControl, content: oContent, generator: "sap.ui.rta.command", command: "compVariantUpdate", layer: Layer.CUSTOMER }; assert.deepEqual(oUpdateFlAPIStub.lastCall.args[0], mExpectedProperties, "the FL API was called with the correct properties"); assert.equal(oSetModifiedStub.callCount, 3, "the setModified was called again.."); assert.equal(oSetModifiedStub.lastCall.args[0], false, "and set to false"); }.bind(this)); }); QUnit.test("Update in the Manage Views scenario", function(assert) { var oUpdateCommand; var oUpdateControlStub = sandbox.stub(); this.oControl.updateVariant = oUpdateControlStub; var oRemoveControlStub = sandbox.stub(); this.oControl.removeVariant = oRemoveControlStub; var oAddControlStub = sandbox.stub(); this.oControl.addVariant = oAddControlStub; var oSetDefaultControlStub = sandbox.stub(); this.oControl.setDefaultVariantId = oSetDefaultControlStub; var oSetModifiedStub = sandbox.stub(); this.oControl.setModified = oSetModifiedStub; var oUpdateFlAPIStub = sandbox.stub(SmartVariantManagementWriteAPI, "updateVariant").callsFake(function(mPropertyBag) { return mPropertyBag.id; }); var oSetDefaultFlAPIStub = sandbox.stub(SmartVariantManagementWriteAPI, "setDefaultVariantId"); var oRevertDefaultFlAPIStub = sandbox.stub(SmartVariantManagementWriteAPI, "revertSetDefaultVariantId"); var oRemoveVariantFlAPIStub = sandbox.stub(SmartVariantManagementWriteAPI, "removeVariant"); var oRevertFlAPIStub = sandbox.stub(SmartVariantManagementWriteAPI, "revert").callsFake(function(mPropertyBag) { return mPropertyBag.id; }); function assertExecute(oControl) { assert.equal(oUpdateFlAPIStub.callCount, 2, "the FL update function was called twice"); var mExpectedProperties1 = { id: "variant2", control: oControl, generator: "sap.ui.rta.command", command: "compVariantUpdate", layer: Layer.CUSTOMER, favorite: false }; assert.deepEqual(oUpdateFlAPIStub.getCall(0).args[0], mExpectedProperties1, "the FL API was called with the correct properties 2"); var mExpectedProperties2 = { id: "variant3", control: oControl, generator: "sap.ui.rta.command", command: "compVariantUpdate", layer: Layer.CUSTOMER, executeOnSelection: true, name: "newName", oldName: "oldName", favorite: true }; assert.deepEqual(oUpdateFlAPIStub.getCall(1).args[0], mExpectedProperties2, "the FL API was called with the correct properties 3"); assert.equal(oSetDefaultFlAPIStub.callCount, 1, "the FL API setDefault was called"); assert.equal(oSetDefaultFlAPIStub.lastCall.args[0].defaultVariantId, "variant3", "the correct variant id was passed"); assert.equal(oRemoveVariantFlAPIStub.callCount, 1, "the FL API removeVariant was called"); assert.equal(oRemoveVariantFlAPIStub.lastCall.args[0].id, "variant1", "the correct variant id was passed"); assert.equal(oUpdateControlStub.callCount, 2, "the control API updateVariant was called twice"); assert.equal(oUpdateControlStub.getCall(0).args[0], "variant2", "with the return value of FL updateVariant"); assert.equal(oUpdateControlStub.getCall(1).args[0], "variant3", "with the return value of FL updateVariant"); assert.equal(oSetDefaultControlStub.callCount, 1, "the control API setDefault was called"); assert.equal(oSetDefaultControlStub.lastCall.args[0], "variant3", "the correct variant id was passed"); assert.equal(oRemoveControlStub.callCount, 1, "the control API removeVariant was called"); assert.equal(oRemoveControlStub.lastCall.args[0].variantId, "variant1", "the correct variant id was passed"); } return CommandFactory.getCommandFor(this.oControl, "compVariantUpdate", { newVariantProperties: { variant1: { executeOnSelection: false, deleted: true }, variant2: { favorite: false }, variant3: { executeOnSelection: true, name: "newName", oldName: "oldName", favorite: true } }, newDefaultVariantId: "variant3", oldDefaultVariantId: "variant1" }, {}) .then(function(oCreatedCommand) { oUpdateCommand = oCreatedCommand; return oUpdateCommand.execute(); }).then(function() { assertExecute(this.oControl); return oUpdateCommand.undo(); }.bind(this)).then(function() { assert.equal(oRevertFlAPIStub.callCount, 3, "the revert function was called thrice"); assert.equal(oRevertFlAPIStub.getCall(0).args[0].id, "variant1", "the correct variant id was passed 1"); assert.equal(oRevertFlAPIStub.getCall(1).args[0].id, "variant2", "the correct variant id was passed 2"); assert.equal(oRevertFlAPIStub.getCall(2).args[0].id, "variant3", "the correct variant id was passed 3"); assert.equal(oRevertDefaultFlAPIStub.callCount, 1, "the revertSetDefaultVariantId function was called once"); assert.equal(oAddControlStub.lastCall.args[0], "variant1", "the correct variant was added"); assert.equal(oAddControlStub.callCount, 1, "the addVariant function on the control was called once"); assert.equal(oAddControlStub.lastCall.args[0], "variant1", "the correct variant was added"); assert.equal(oUpdateControlStub.callCount, 4, "the updateVariant function on the control was called twice"); assert.equal(oUpdateControlStub.getCall(2).args[0], "variant2", "the correct variant was updated 1"); assert.equal(oUpdateControlStub.getCall(3).args[0], "variant3", "the correct variant was updated 2"); sandbox.resetHistory(); return oUpdateCommand.execute(); }).then(function() { assertExecute(this.oControl); }.bind(this)); }); }); });
SAP/openui5
src/sap.ui.rta/test/sap/ui/rta/qunit/command/compVariant/CompVariantUpdate.qunit.js
JavaScript
apache-2.0
8,251
/* * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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. */ // Protractor configuration file, see link for more information // https://github.com/angular/protractor/blob/master/lib/config.ts const { SpecReporter } = require('jasmine-spec-reporter'); exports.config = { allScriptsTimeout: 11000, specs: [ './e2e/**/*.e2e-spec.ts' ], capabilities: { 'browserName': 'chrome' }, directConnect: true, baseUrl: 'http://localhost:4200/', framework: 'jasmine', jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 30000, print: function() {} }, beforeLaunch: function() { require('ts-node').register({ project: 'e2e/tsconfig.e2e.json' }); }, onPrepare() { jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); } };
gravitee-io/graviteeio-access-management
gravitee-am-ui/protractor.conf.js
JavaScript
apache-2.0
1,386
window.onload = function() { var Synth = function(audiolet) { AudioletGroup.apply(this, [audiolet, 0, 1]); // Basic wave this.saw = new Saw(audiolet, 100); // Frequency LFO this.frequencyLFO = new Sine(audiolet, 2); this.frequencyMA = new MulAdd(audiolet, 10, 100); // Filter this.filter = new LowPassFilter(audiolet, 1000); // Filter LFO this.filterLFO = new Sine(audiolet, 8); this.filterMA = new MulAdd(audiolet, 900, 1000); // Gain envelope this.gain = new Gain(audiolet); this.env = new ADSREnvelope(audiolet, 1, // Gate 1.5, // Attack 0.2, // Decay 0.9, // Sustain 2); // Release // Main signal path this.saw.connect(this.filter); this.filter.connect(this.gain); this.gain.connect(this.outputs[0]); // Frequency LFO this.frequencyLFO.connect(this.frequencyMA); this.frequencyMA.connect(this.saw); // Filter LFO this.filterLFO.connect(this.filterMA); this.filterMA.connect(this.filter, 0, 1); // Envelope this.env.connect(this.gain, 0, 1); }; extend(Synth, AudioletGroup); var audiolet = new Audiolet(); var synth = new Synth(audiolet); var frequencyPattern = new PSequence([55, 55, 98, 98, 73, 73, 98, 98], Infinity); var filterLFOPattern = new PChoose([2, 4, 6, 8], Infinity); var gatePattern = new PSequence([1, 0], Infinity); var patterns = [frequencyPattern, filterLFOPattern, gatePattern]; audiolet.scheduler.play(patterns, 2, function(frequency, filterLFOFrequency, gate) { this.frequencyMA.add.setValue(frequency); this.filterLFO.frequency.setValue(filterLFOFrequency); this.env.gate.setValue(gate); }.bind(synth) ); synth.connect(audiolet.output); };
accraze/Audiolet
examples/synth/js/synth.js
JavaScript
apache-2.0
2,107
(function ($) { "use strict"; /*---------------------------- price-slider active ------------------------------ */ var range = $('#slider-range'); var amount = $('#amount'); range.slider({ range: true, min: 2, max: 300, values: [ 2, 300 ], slide: function( event, ui ) { amount.val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] ); } }); amount.val( "$" + range.slider( "values", 0 ) + " - $" + range.slider( "values", 1 ) ); /*---------------------------- jQuery MeanMenu ------------------------------ */ jQuery('#mobile-menu-active').meanmenu(); /*---------------------- Carousel Activation ----------------------*/ $(".let_new_carasel").owlCarousel({ autoPlay: true, slideSpeed:2000, pagination:true, navigation:true, items : 1, /* transitionStyle : "fade", */ /* [This code for animation ] */ navigationText:["<i class='fa fa-caret-left'></i>","<i class='fa fa-caret-right'></i>"], itemsDesktop : [1199,1], itemsDesktopSmall : [980,1], itemsTablet: [768,1], itemsMobile : [767,1], }); /*---------------------------- Tooltip ------------------------------ */ $('[data-toggle="tooltip"]').tooltip({ animated: 'fade', placement: 'top', container: 'body' }); /*---------------------------- single portfolio activation ------------------------------ */ $(".sub_pix").owlCarousel({ autoPlay: true, slideSpeed:2000, pagination:true, navigation:false, items : 5, /* transitionStyle : "fade", */ /* [This code for animation ] */ navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"], itemsDesktop : [1199,4], itemsDesktopSmall : [980,3], itemsTablet: [768,5], itemsMobile : [767,3], }); /*---------------------------- toggole active ------------------------------ */ $( ".all_catagories" ).on("click", function() { $( ".cat_mega_start" ).slideToggle( "slow" ); }); $( ".showmore-items" ).on("click", function() { $( ".cost-menu" ).slideToggle( "slow" ); }); /*---------------------- New Products Carousel Activation ----------------------*/ $(".whole_product").owlCarousel({ autoPlay: false, slideSpeed:2000, pagination:false, navigation:true, items : 3, /* transitionStyle : "fade", */ /* [This code for animation ] */ navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"], itemsDesktop : [1199,3], itemsDesktopSmall : [980,3], itemsTablet: [768,1], itemsMobile : [767,1], }); /*---------------------- Hot Deals Carousel Activation ----------------------*/ $(".new_cosmatic").owlCarousel({ autoPlay: false, slideSpeed:2000, pagination:false, navigation:true, items : 1, /* transitionStyle : "fade", */ /* [This code for animation ] */ navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"], itemsDesktop : [1199,1], itemsDesktopSmall : [980,3], itemsTablet: [768,2], itemsMobile : [767,1], }); /*--------------------- countdown --------------------- */ $('[data-countdown]').each(function() { var $this = $(this), finalDate = $(this).data('countdown'); $this.countdown(finalDate, function(event) { $this.html(event.strftime('<span class="cdown days"><span class="time-count">%-D</span> <p>Days</p></span> <span class="cdown hour"><span class="time-count">%-H</span> <p>Hour</p></span> <span class="cdown minutes"><span class="time-count">%M</span> <p>Min</p></span> <span class="cdown second"> <span><span class="time-count">%S</span> <p>Sec</p></span>')); }); }); /*---------------------- Products Catagory Carousel Activation ----------------------*/ $(".feature-carousel").owlCarousel({ autoPlay: false, slideSpeed:2000, pagination:false, navigation:true, items : 4, /* transitionStyle : "fade", */ /* [This code for animation ] */ navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"], itemsDesktop : [1199,3], itemsDesktopSmall : [980,3], itemsTablet: [768,2], itemsMobile : [767,1], }); /*---------------------------- Top Rate Carousel Activation ------------------------------ */ $(".all_ayntex").owlCarousel({ autoPlay: false, slideSpeed:2000, pagination:false, navigation:true, items : 1, /* transitionStyle : "fade", */ /* [This code for animation ] */ navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"], itemsDesktop : [1199,1], itemsDesktopSmall : [980,3], itemsTablet: [768,2], itemsMobile : [767,1], }); /*---------------------------- Featured Catagories Carousel Activation ------------------------------ */ $(".achard_all").owlCarousel({ autoPlay: false, slideSpeed:2000, pagination:false, navigation:true, items : 5, /* transitionStyle : "fade", */ /* [This code for animation ] */ navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"], itemsDesktop : [1199,4], itemsDesktopSmall : [980,3], itemsTablet: [768,4], itemsMobile : [767,2 ], }); /*---------------------------- Blog Post Carousel Activation ------------------------------ */ $(".blog_carasel").owlCarousel({ autoPlay: false, slideSpeed:2000, pagination:false, navigation:true, items : 3, /* transitionStyle : "fade", */ /* [This code for animation ] */ navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"], itemsDesktop : [1199,2], itemsDesktopSmall : [980,3], itemsTablet: [768,2], itemsMobile : [767,1], }); /*---------------------------- Brand Logo Carousel Activation ------------------------------ */ $(".all_brand").owlCarousel({ autoPlay: false, slideSpeed:2000, pagination:false, navigation:true, items : 6, /* transitionStyle : "fade", */ /* [This code for animation ] */ navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"], itemsDesktop : [1199,4], itemsDesktopSmall : [980,3], itemsTablet: [768,2], itemsMobile : [480,2], }); /*---------------------- scrollUp ----------------------*/ $.scrollUp({ scrollText: '<i class="fa fa-angle-double-up"></i>', easingType: 'linear', scrollSpeed: 900, animation: 'fade' }); /*---------------------- New Products home-page-2 Carousel Activation ----------------------*/ $(".product_2").owlCarousel({ autoPlay: false, slideSpeed:2000, pagination:false, navigation:true, items : 4, /* transitionStyle : "fade", */ /* [This code for animation ] */ navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"], itemsDesktop : [1199,3], itemsDesktopSmall : [980,4], itemsTablet: [768,2], itemsMobile : [767,1], }); /*---------------------------- Blog Post home-page-2 Carousel Activation ------------------------------ */ $(".blog_new_carasel_2").owlCarousel({ autoPlay: false, slideSpeed:2000, pagination:false, navigation:true, items : 2, /* transitionStyle : "fade", */ /* [This code for animation ] */ navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"], itemsDesktop : [1199,2], itemsDesktopSmall : [980,2], itemsTablet: [768,1], itemsMobile : [767,1], }); /*---------------------------- Products Catagory-2 Carousel Activation ------------------------------ */ $(".feature-carousel-2").owlCarousel({ autoPlay: false, slideSpeed:2000, pagination:false, navigation:true, items : 2, /* transitionStyle : "fade", */ /* [This code for animation ] */ navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"], itemsDesktop : [1199,2], itemsDesktopSmall : [980,3], itemsTablet: [768,2], itemsMobile : [767,1], }); /*---------------------------- Blog Post home-page-3 Carousel Activation ------------------------------ */ $(".blog_carasel_5").owlCarousel({ autoPlay: false, slideSpeed:2000, pagination:false, navigation:true, items : 4, /* transitionStyle : "fade", */ /* [This code for animation ] */ navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"], itemsDesktop : [1199,4], itemsDesktopSmall : [980,3], itemsTablet: [768,2], itemsMobile : [767,1], }); /*----------------------------- Category Menu toggle -------------------------------*/ $('.expandable a').on('click', function() { $(this).parent().find('.category-sub').toggleClass('submenu-active'); $(this).toggleClass('submenu-active'); return false; }); /*---------------------------- MixItUp: ------------------------------ */ $('#Container') .mixItUp(); /*---------------------------- magnificPopup: ------------------------------ */ $('.magnify').magnificPopup({type:'image'}); /*------------------------- Create an account toggle function --------------------------*/ $( "#cbox" ).on("click", function() { $( "#cbox_info" ).slideToggle(900); }); $( '#showlogin, #showcoupon' ).on('click', function() { $(this).parent().next().slideToggle(600); }); /*------------------------- accordion toggle function --------------------------*/ $('.payment-accordion').find('.payment-accordion-toggle').on('click', function(){ //Expand or collapse this panel $(this).next().slideToggle(500); //Hide the other panels $(".payment-content").not($(this).next()).slideUp(500); }); /* ------------------------------------------------------- accordion active class for style ----------------------------------------------------------*/ $('.payment-accordion-toggle').on('click', function(event) { $(this).siblings('.active').removeClass('active'); $(this).addClass('active'); event.preventDefault(); }); })(jQuery);
TZClub/OMIPlatform
shopping-platfrom/src/main/webapp/resources/js/main.js
JavaScript
apache-2.0
10,332
require('./second.js'); var i = 0; console.log('Hello Webpack!'); console.log('Webpack is cool.');
jitendraag/webpack-2-examples
example2/input.js
JavaScript
apache-2.0
99
/** * @license Copyright 2020 The Lighthouse Authors. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; /** * @fileoverview Audit which identifies third-party code on the page which can be lazy loaded. * The audit will recommend a facade alternative which is used to imitate the third-party resource until it is needed. * * Entity: Set of domains which are used by a company or product area to deliver third-party resources * Product: Specific piece of software belonging to an entity. Entities can have multiple products. * Facade: Placeholder for a product which looks likes the actual product and replaces itself with that product when the user needs it. */ /** @typedef {import("third-party-web").IEntity} ThirdPartyEntity */ /** @typedef {import("third-party-web").IProduct} ThirdPartyProduct*/ /** @typedef {import("third-party-web").IFacade} ThirdPartyFacade*/ /** @typedef {{product: ThirdPartyProduct, entity: ThirdPartyEntity}} FacadableProduct */ const Audit = require('./audit.js'); const i18n = require('../lib/i18n/i18n.js'); const thirdPartyWeb = require('../lib/third-party-web.js'); const NetworkRecords = require('../computed/network-records.js'); const MainResource = require('../computed/main-resource.js'); const MainThreadTasks = require('../computed/main-thread-tasks.js'); const ThirdPartySummary = require('./third-party-summary.js'); const UIStrings = { /** Title of a diagnostic audit that provides details about the third-party code on a web page that can be lazy loaded with a facade alternative. This descriptive title is shown to users when no resources have facade alternatives available. A facade is a lightweight component which looks like the desired resource. Lazy loading means resources are deferred until they are needed. Third-party code refers to resources that are not within the control of the site owner. */ title: 'Lazy load third-party resources with facades', /** Title of a diagnostic audit that provides details about the third-party code on a web page that can be lazy loaded with a facade alternative. This descriptive title is shown to users when one or more third-party resources have available facade alternatives. A facade is a lightweight component which looks like the desired resource. Lazy loading means resources are deferred until they are needed. Third-party code refers to resources that are not within the control of the site owner. */ failureTitle: 'Some third-party resources can be lazy loaded with a facade', /** Description of a Lighthouse audit that identifies the third-party code on the page that can be lazy loaded with a facade alternative. This is displayed after a user expands the section to see more. No character length limits. 'Learn More' becomes link text to additional documentation. A facade is a lightweight component which looks like the desired resource. Lazy loading means resources are deferred until they are needed. Third-party code refers to resources that are not within the control of the site owner. */ description: 'Some third-party embeds can be lazy loaded. ' + 'Consider replacing them with a facade until they are required. [Learn more](https://web.dev/third-party-facades/).', /** Summary text for the result of a Lighthouse audit that identifies the third-party code on a web page that can be lazy loaded with a facade alternative. This text summarizes the number of lazy loading facades that can be used on the page. A facade is a lightweight component which looks like the desired resource. */ displayValue: `{itemCount, plural, =1 {# facade alternative available} other {# facade alternatives available} }`, /** Label for a table column that displays the name of the product that a URL is used for. The products in the column will be pieces of software used on the page, like the "YouTube Embedded Player" or the "Drift Live Chat" box. */ columnProduct: 'Product', /** * @description Template for a table entry that gives the name of a product which we categorize as video related. * @example {YouTube Embedded Player} productName */ categoryVideo: '{productName} (Video)', /** * @description Template for a table entry that gives the name of a product which we categorize as customer success related. Customer success means the product supports customers by offering chat and contact solutions. * @example {Intercom Widget} productName */ categoryCustomerSuccess: '{productName} (Customer Success)', /** * @description Template for a table entry that gives the name of a product which we categorize as marketing related. * @example {Drift Live Chat} productName */ categoryMarketing: '{productName} (Marketing)', /** * @description Template for a table entry that gives the name of a product which we categorize as social related. * @example {Facebook Messenger Customer Chat} productName */ categorySocial: '{productName} (Social)', }; const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings); /** @type {Record<string, string>} */ const CATEGORY_UI_MAP = { 'video': UIStrings.categoryVideo, 'customer-success': UIStrings.categoryCustomerSuccess, 'marketing': UIStrings.categoryMarketing, 'social': UIStrings.categorySocial, }; class ThirdPartyFacades extends Audit { /** * @return {LH.Audit.Meta} */ static get meta() { return { id: 'third-party-facades', title: str_(UIStrings.title), failureTitle: str_(UIStrings.failureTitle), description: str_(UIStrings.description), requiredArtifacts: ['traces', 'devtoolsLogs', 'URL'], }; } /** * Sort items by transfer size and combine small items into a single row. * Items will be mutated in place to a maximum of 6 rows. * @param {ThirdPartySummary.URLSummary[]} items */ static condenseItems(items) { items.sort((a, b) => b.transferSize - a.transferSize); // Items <1KB are condensed. If all items are <1KB, condense all but the largest. let splitIndex = items.findIndex((item) => item.transferSize < 1000) || 1; // Show details for top 5 items. if (splitIndex === -1 || splitIndex > 5) splitIndex = 5; // If there is only 1 item to condense, leave it as is. if (splitIndex >= items.length - 1) return; const remainder = items.splice(splitIndex); const finalItem = remainder.reduce((result, item) => { result.transferSize += item.transferSize; result.blockingTime += item.blockingTime; return result; }); // If condensed row is still <1KB, don't show it. if (finalItem.transferSize < 1000) return; finalItem.url = str_(i18n.UIStrings.otherResourcesLabel); items.push(finalItem); } /** * @param {Map<string, ThirdPartySummary.Summary>} byURL * @param {ThirdPartyEntity | undefined} mainEntity * @return {FacadableProduct[]} */ static getProductsWithFacade(byURL, mainEntity) { /** @type {Map<string, FacadableProduct>} */ const facadableProductMap = new Map(); for (const url of byURL.keys()) { const entity = thirdPartyWeb.getEntity(url); if (!entity || thirdPartyWeb.isFirstParty(url, mainEntity)) continue; const product = thirdPartyWeb.getProduct(url); if (!product || !product.facades || !product.facades.length) continue; if (facadableProductMap.has(product.name)) continue; facadableProductMap.set(product.name, {product, entity}); } return Array.from(facadableProductMap.values()); } /** * @param {LH.Artifacts} artifacts * @param {LH.Audit.Context} context * @return {Promise<LH.Audit.Product>} */ static async audit(artifacts, context) { const settings = context.settings; const trace = artifacts.traces[Audit.DEFAULT_PASS]; const devtoolsLog = artifacts.devtoolsLogs[Audit.DEFAULT_PASS]; const networkRecords = await NetworkRecords.request(devtoolsLog, context); const mainResource = await MainResource.request({devtoolsLog, URL: artifacts.URL}, context); const mainEntity = thirdPartyWeb.getEntity(mainResource.url); const tasks = await MainThreadTasks.request(trace, context); const multiplier = settings.throttlingMethod === 'simulate' ? settings.throttling.cpuSlowdownMultiplier : 1; const summaries = ThirdPartySummary.getSummaries(networkRecords, tasks, multiplier); const facadableProducts = ThirdPartyFacades.getProductsWithFacade(summaries.byURL, mainEntity); /** @type {LH.Audit.Details.TableItem[]} */ const results = []; for (const {product, entity} of facadableProducts) { const categoryTemplate = CATEGORY_UI_MAP[product.categories[0]]; let productWithCategory; if (categoryTemplate) { // Display product name with category next to it in the same column. productWithCategory = str_(categoryTemplate, {productName: product.name}); } else { // Just display product name if no category is found. productWithCategory = product.name; } const urls = summaries.urls.get(entity); const entitySummary = summaries.byEntity.get(entity); if (!urls || !entitySummary) continue; const items = Array.from(urls).map((url) => { const urlStats = summaries.byURL.get(url); return /** @type {ThirdPartySummary.URLSummary} */ ({url, ...urlStats}); }); this.condenseItems(items); results.push({ product: productWithCategory, transferSize: entitySummary.transferSize, blockingTime: entitySummary.blockingTime, subItems: {type: 'subitems', items}, }); } if (!results.length) { return { score: 1, notApplicable: true, }; } /** @type {LH.Audit.Details.Table['headings']} */ const headings = [ /* eslint-disable max-len */ {key: 'product', itemType: 'text', subItemsHeading: {key: 'url', itemType: 'url'}, text: str_(UIStrings.columnProduct)}, {key: 'transferSize', itemType: 'bytes', subItemsHeading: {key: 'transferSize'}, granularity: 1, text: str_(i18n.UIStrings.columnTransferSize)}, {key: 'blockingTime', itemType: 'ms', subItemsHeading: {key: 'blockingTime'}, granularity: 1, text: str_(i18n.UIStrings.columnBlockingTime)}, /* eslint-enable max-len */ ]; return { score: 0, displayValue: str_(UIStrings.displayValue, { itemCount: results.length, }), details: Audit.makeTableDetails(headings, results), }; } } module.exports = ThirdPartyFacades; module.exports.UIStrings = UIStrings;
ev1stensberg/lighthouse
lighthouse-core/audits/third-party-facades.js
JavaScript
apache-2.0
11,065
/* @flow */ import Crypto from '../components/cryptography'; import Config from '../components/config'; import ListenerManager from '../components/listener_manager'; import ReconnectionManager from '../components/reconnection_manager'; import utils from '../utils'; import { MessageAnnouncement, SubscribeEnvelope, StatusAnnouncement, PresenceAnnouncement } from '../flow_interfaces'; import categoryConstants from '../constants/categories'; type SubscribeArgs = { channels: Array<string>, channelGroups: Array<string>, withPresence: ?boolean, timetoken: ?number } type UnsubscribeArgs = { channels: Array<string>, channelGroups: Array<string> } type StateArgs = { channels: Array<string>, channelGroups: Array<string>, state: Object } type SubscriptionManagerConsturct = { leaveEndpoint: Function, subscribeEndpoint: Function, timeEndpoint: Function, heartbeatEndpoint: Function, setStateEndpoint: Function, config: Config, crypto: Crypto, listenerManager: ListenerManager } export default class { _crypto: Crypto; _config: Config; _listenerManager: ListenerManager; _reconnectionManager: ReconnectionManager; _leaveEndpoint: Function; _heartbeatEndpoint: Function; _setStateEndpoint: Function; _subscribeEndpoint: Function; _channels: Object; _presenceChannels: Object; _channelGroups: Object; _presenceChannelGroups: Object; _timetoken: number; _region: number; _subscribeCall: ?Object; _heartbeatTimer: ?number; _subscriptionStatusAnnounced: boolean; constructor({ subscribeEndpoint, leaveEndpoint, heartbeatEndpoint, setStateEndpoint, timeEndpoint, config, crypto, listenerManager }: SubscriptionManagerConsturct) { this._listenerManager = listenerManager; this._config = config; this._leaveEndpoint = leaveEndpoint; this._heartbeatEndpoint = heartbeatEndpoint; this._setStateEndpoint = setStateEndpoint; this._subscribeEndpoint = subscribeEndpoint; this._crypto = crypto; this._channels = {}; this._presenceChannels = {}; this._channelGroups = {}; this._presenceChannelGroups = {}; this._timetoken = 0; this._subscriptionStatusAnnounced = false; this._reconnectionManager = new ReconnectionManager({ timeEndpoint }); } adaptStateChange(args: StateArgs, callback: Function) { const { state, channels = [], channelGroups = [] } = args; channels.forEach((channel) => { if (channel in this._channels) this._channels[channel].state = state; }); channelGroups.forEach((channelGroup) => { if (channelGroup in this._channelGroups) this._channelGroups[channelGroup].state = state; }); this._setStateEndpoint({ state, channels, channelGroups }, callback); } adaptSubscribeChange(args: SubscribeArgs) { const { timetoken, channels = [], channelGroups = [], withPresence = false } = args; if (timetoken) this._timetoken = timetoken; channels.forEach((channel) => { this._channels[channel] = { state: {} }; if (withPresence) this._presenceChannels[channel] = {}; }); channelGroups.forEach((channelGroup) => { this._channelGroups[channelGroup] = { state: {} }; if (withPresence) this._presenceChannelGroups[channelGroup] = {}; }); this._subscriptionStatusAnnounced = false; this.reconnect(); } adaptUnsubscribeChange(args: UnsubscribeArgs) { const { channels = [], channelGroups = [] } = args; channels.forEach((channel) => { if (channel in this._channels) delete this._channels[channel]; if (channel in this._presenceChannels) delete this._presenceChannels[channel]; }); channelGroups.forEach((channelGroup) => { if (channelGroup in this._channelGroups) delete this._channelGroups[channelGroup]; if (channelGroup in this._presenceChannelGroups) delete this._channelGroups[channelGroup]; }); if (this._config.suppressLeaveEvents === false) { this._leaveEndpoint({ channels, channelGroups }, (status) => { this._listenerManager.announceStatus(status); }); } this.reconnect(); } unsubscribeAll() { this.adaptUnsubscribeChange({ channels: this.getSubscribedChannels(), channelGroups: this.getSubscribedChannelGroups() }); } getSubscribedChannels() { return Object.keys(this._channels); } getSubscribedChannelGroups() { return Object.keys(this._channelGroups); } reconnect() { this._startSubscribeLoop(); this._registerHeartbeatTimer(); } disconnect() { this._stopSubscribeLoop(); this._stopHeartbeatTimer(); } _registerHeartbeatTimer() { this._stopHeartbeatTimer(); this._performHeartbeatLoop(); this._heartbeatTimer = setInterval(this._performHeartbeatLoop.bind(this), this._config.getHeartbeatInterval() * 1000); } _stopHeartbeatTimer() { if (this._heartbeatTimer) { clearInterval(this._heartbeatTimer); this._heartbeatTimer = null; } } _performHeartbeatLoop() { let presenceChannels = Object.keys(this._channels); let presenceChannelGroups = Object.keys(this._channelGroups); let presenceState = {}; if (presenceChannels.length === 0 && presenceChannelGroups.length === 0) { return; } presenceChannels.forEach((channel) => { let channelState = this._channels[channel].state; if (Object.keys(channelState).length) presenceState[channel] = channelState; }); presenceChannelGroups.forEach((channelGroup) => { let channelGroupState = this._channelGroups[channelGroup].state; if (Object.keys(channelGroupState).length) presenceState[channelGroup] = channelGroupState; }); let onHeartbeat = (status: StatusAnnouncement) => { if (status.error && this._config.announceFailedHeartbeats) { this._listenerManager.announceStatus(status); } if (!status.error && this._config.announceSuccessfulHeartbeats) { this._listenerManager.announceStatus(status); } }; this._heartbeatEndpoint({ channels: presenceChannels, channelGroups: presenceChannelGroups, state: presenceState }, onHeartbeat.bind(this)); } _startSubscribeLoop() { this._stopSubscribeLoop(); let channels = []; let channelGroups = []; Object.keys(this._channels).forEach(channel => channels.push(channel)); Object.keys(this._presenceChannels).forEach(channel => channels.push(channel + '-pnpres')); Object.keys(this._channelGroups).forEach(channelGroup => channelGroups.push(channelGroup)); Object.keys(this._presenceChannelGroups).forEach(channelGroup => channelGroups.push(channelGroup + '-pnpres')); if (channels.length === 0 && channelGroups.length === 0) { return; } const subscribeArgs = { channels, channelGroups, timetoken: this._timetoken, filterExpression: this._config.filterExpression, region: this._region }; this._subscribeCall = this._subscribeEndpoint(subscribeArgs, this._processSubscribeResponse.bind(this)); } _processSubscribeResponse(status: StatusAnnouncement, payload: SubscribeEnvelope) { if (status.error) { // if we timeout from server, restart the loop. if (status.category === categoryConstants.PNTimeoutCategory) { this._startSubscribeLoop(); } // we lost internet connection, alert the reconnection manager and terminate all loops if (status.category === categoryConstants.PNNetworkIssuesCategory) { this.disconnect(); this._reconnectionManager.onReconnection(() => { this.reconnect(); this._subscriptionStatusAnnounced = true; let reconnectedAnnounce: StatusAnnouncement = { category: categoryConstants.PNReconnectedCategory, operation: status.operation }; this._listenerManager.announceStatus(reconnectedAnnounce); }); this._reconnectionManager.startPolling(); this._listenerManager.announceStatus(status); } return; } if (!this._subscriptionStatusAnnounced) { let connectedAnnounce: StatusAnnouncement = {}; connectedAnnounce.category = categoryConstants.PNConnectedCategory; connectedAnnounce.operation = status.operation; this._subscriptionStatusAnnounced = true; this._listenerManager.announceStatus(connectedAnnounce); } payload.messages.forEach((message) => { let channel = message.channel; let subscriptionMatch = message.subscriptionMatch; let publishMetaData = message.publishMetaData; if (channel === subscriptionMatch) { subscriptionMatch = null; } if (utils.endsWith(message.channel, '-pnpres')) { let announce: PresenceAnnouncement = {}; announce.channel = null; announce.subscription = null; // deprecated --> announce.actualChannel = (subscriptionMatch != null) ? channel : null; announce.subscribedChannel = subscriptionMatch != null ? subscriptionMatch : channel; // <-- deprecated if (channel) { announce.channel = channel.substring(0, channel.lastIndexOf('-pnpres')); } if (subscriptionMatch) { announce.subscription = subscriptionMatch.substring(0, subscriptionMatch.lastIndexOf('-pnpres')); } announce.action = message.payload.action; announce.state = message.payload.data; announce.timetoken = publishMetaData.publishTimetoken; announce.occupancy = message.payload.occupancy; announce.uuid = message.payload.uuid; announce.timestamp = message.payload.timestamp; this._listenerManager.announcePresence(announce); } else { let announce: MessageAnnouncement = {}; announce.channel = null; announce.subscription = null; // deprecated --> announce.actualChannel = (subscriptionMatch != null) ? channel : null; announce.subscribedChannel = subscriptionMatch != null ? subscriptionMatch : channel; // <-- deprecated announce.channel = channel; announce.subscription = subscriptionMatch; announce.timetoken = publishMetaData.publishTimetoken; if (this._config.cipherKey) { announce.message = this._crypto.decrypt(message.payload); } else { announce.message = message.payload; } this._listenerManager.announceMessage(announce); } }); this._region = payload.metadata.region; this._timetoken = payload.metadata.timetoken; this._startSubscribeLoop(); } _stopSubscribeLoop() { if (this._subscribeCall) { this._subscribeCall.abort(); this._subscribeCall = null; } } }
amriteshkumar1/sales-service
node_modules/pubnub/src/core/components/subscription_manager.js
JavaScript
apache-2.0
10,768
'use strict'; /** * Requirements * @ignore */ const BaseValueObject = require('../BaseValueObject.js').BaseValueObject; const Entity = require('./Entity.js').Entity; const Site = require('../site/Site.js').Site; const ContentKind = require('../ContentKind.js'); const BaseMap = require('../../base/BaseMap.js').BaseMap; const EntityIdTemplate = require('./EntityIdTemplate.js').EntityIdTemplate; const assertParameter = require('../../utils/assert.js').assertParameter; /** * @namespace model.entity */ class EntityAspect extends BaseValueObject { /** * @param {model.entity.Entity} entity * @param {model.site.Site} site */ constructor(entity, site, entityIdTemplate) { super(); //Check params assertParameter(this, 'entity', entity, true, Entity); assertParameter(this, 'site', site, true, Site); //assertParameter(this, 'entityIdTemplate', entityIdTemplate, true, EntityIdTemplate); // Add initial values this._entity = entity; this._site = site; this._entityIdTemplate = entityIdTemplate; // Extend id this._entityId = this._entity.id.clone(); this._entityId.site = this._site; // Get extended sites this._extendedSites = []; let currentSite = this._site; while(currentSite) { this._extendedSites.unshift(currentSite); currentSite = currentSite.extends; } // Extend files, properties, documentation & tests const properties = new BaseMap(); const examples = {}; const macros = {}; const texts = []; const datamodels = []; const tests = []; for (const s of this._extendedSites) { // Files this.files.load(this._entity.files.filter(file => file.site === s)); // Examples const siteExamples = this._entity.documentation.filter(doc => doc.contentKind === ContentKind.EXAMPLE); for (const siteExample of siteExamples) { examples[siteExample.file.basename] = siteExample; } // Models const siteDatamodels = this._entity.documentation.filter(doc => doc.contentKind === ContentKind.DATAMODEL); for (const siteDatamodel of siteDatamodels) { datamodels.push(siteDatamodel); } // Macros const siteMacros = this._entity.documentation.filter(doc => doc.contentKind === ContentKind.MACRO); for (const siteMacro of siteMacros) { macros[siteMacro.name] = siteMacro; } // Text const siteTexts = this._entity.documentation.filter(doc => doc.contentKind === ContentKind.TEXT); for (const siteText of siteTexts) { texts.push(siteText); } // Properties const siteProperties = this._entity.properties.getByPath(s.name.toLowerCase(), {}); properties.merge(siteProperties); // Tests this.tests.load(this._entity.tests.filter(test => test.site === s)); } this.properties.load(properties); this.documentation.load(examples); this.documentation.load(datamodels); this.documentation.load(macros); this.documentation.load(texts); } /** * @inheritDoc */ static get injections() { return { 'parameters': [Entity, Site, EntityIdTemplate] }; } /** * @inheritDoc */ static get className() { return 'model.entity/EntityAspect'; } /** * @property {*} */ get uniqueId() { return this.pathString; } /** * @property {entity.EntityId} */ get id() { return this._entityId; } /** * @property {String} */ get idString() { return this._entityId.idString; } /** * @property {String} */ get pathString() { return this._entityId.pathString; } /** * @property {model.entity.Entity} */ get entity() { return this._entity; } /** * @property {model.site.Site} */ get site() { return this._site; } /** * @property {Bool} */ get isGlobal() { return this._entity.isGlobal; } /** * @inheritDoc */ toString() { return `[${this.className} ${this.site.name}/${this.id.category.longName}-${this.id.name}]`; } } /** * Exports * @ignore */ module.exports.EntityAspect = EntityAspect;
entoj/entoj-core
source/model/entity/EntityAspect.js
JavaScript
apache-2.0
4,718
function swl_scrollStopExtend() { var a = SWL.$.event.special, b = "D" + +new Date, c = "D" + (+new Date + 1); a.scrollstart = { setup : function() { var c, d = function(b) { var d = this, e = arguments; c ? clearTimeout(c) : (b.type = "scrollstart", SWL.$.event.handle.apply(d, e)), c = setTimeout(function() { c = null }, a.scrollstop.latency) }; SWL.$(this).bind("scroll", d).data(b, d) }, teardown : function() { SWL.$(this).unbind("scroll", SWL.$(this).data(b)) } }, a.scrollstop = { latency : 300, setup : function() { var b, d = function(c) { var d = this, e = arguments; b && clearTimeout(b), b = setTimeout(function() { b = null, c.type = "scrollstop", SWL.$.event.handle.apply(d, e) }, a.scrollstop.latency) }; SWL.$(this).bind("scroll", d).data(c, d) }, teardown : function() { SWL.$(this).unbind("scroll", SWL.$(this).data(c)) } } } function swl_scrollStopInit() { return "undefined" == typeof SWL ? (window.setTimeout(function() { swl_scrollStopInit() }, 50), void 0) : (swl_scrollStopExtend(), void 0) }swl_scrollStopInit();
EZWebvietnam/vieclam24h
template/home/js/jquery.scrollstore.js
JavaScript
apache-2.0
1,126
import { resolve, join } from 'path' import merge from 'webpack-merge' import parts from './webpack/parts' if (process.env.WDS_HOST === undefined) process.env.WDS_HOST = 'localhost' if (process.env.WDS_PORT === undefined) process.env.WDS_PORT = 3001 const isVendor = ({ resource }) => resource && resource.indexOf('node_modules') >= 0 && resource.match(/\.js$/) const PATHS = { root: resolve(__dirname), sources: join(__dirname, 'src'), build: join(__dirname, 'build'), exclude: [ join(__dirname, 'build'), /node_modules/, ], } const commonConfig = merge([ { context: PATHS.sources, output: { path: PATHS.build, filename: '[name].js', publicPath: '/', }, }, parts.lintStyles({ include: PATHS.sources }), parts.lintJavascript({ include: PATHS.sources }), parts.loadHtml(), parts.loadAssets(), parts.loadJavascript({ include: PATHS.sources, exclude: PATHS.exclude }), parts.namedModulesPlugin(), parts.noErrorsPlugin(), ]) const developmentConfig = merge([ { output: { pathinfo: true }, }, parts.loadStyles({ include: PATHS.sources, exclude: PATHS.exclude }), parts.devServer({ host: 'localhost', port: 3001 }), parts.generateSourceMaps('cheap-module-eval-source-map'), ]) const productionConfig = merge([ { output: { chunkFilename: '[name].[chunkhash:8].js', filename: '[name].[chunkhash:8].js', }, performance: { hints: 'warning', maxEntrypointSize: 100000, maxAssetSize: 450000, }, }, parts.cleanPlugin({ path: PATHS.build, root: PATHS.root }), parts.definePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production'), }, }), parts.minifyJavascript(), parts.extractStyles(), parts.extractJavascript([ { name: 'vendor', chunks: [ 'app' ], minChunks: isVendor }, { name: 'manifest', minChunks: Infinity }, ]), parts.hashedModuleIdsPlugin(), parts.generateSourceMaps('source-map'), ]) export default (env) => { process.env.NODE_ENV = env process.env.BABEL_ENV = env const isDevelopment = env === 'development' const config = merge([ parts.page({ title: 'React Skellington Test', template: 'index.ejs', entry: { app: ( isDevelopment ? parts.hotloader() : [] ).concat([ './client/index.js' ]), }, }), commonConfig, isDevelopment ? developmentConfig : productionConfig, ]) // console.dir(config, { depth: null, colors: true }) return config }
buildit/bookit-web
webpack.config.babel.js
JavaScript
apache-2.0
2,535
"use strict"; jest.autoMockOff(); const MockDate = require("mockdate"); const DataStore = require("../../src/resources/DataStore"); const FIELDS = ["foo", "bar", "baz"]; describe("DataStore construction", () => { it("tests constructor fails", () => { const check = (fields) => { try { new DataStore(fields); expect(false).toBe(true); } catch (Exception) { expect(true).toBe(true); } }; check(null); check(undefined); check("this is not an array"); check(["col1", "time", "col2"]); check(["TimE", "col1"]); check(["col1", "time_offset", "col2"]); check(["Time_OffseT", "col2"]); check(["col1", "all", "col2"]); check(["ALL", "none"]); check(["fine", undefined]); check(["fine", null]); check(["fine", ""]); check(["fine", 5]); }); it("tests constructor", () => { const batch = new DataStore(FIELDS); const have = batch.fields(); expect(have.length).toBe(FIELDS.length); expect(batch instanceof DataStore).toBe(true); for (let i = 0; i < FIELDS.length; i++) { expect(have[i]).toBe(FIELDS[i]); } }); it("tests constructor deep copies", () => { const temp = ["a", "b", "c"]; const batch = new DataStore(temp); let have = batch.fields(); expect(have.length).toBe(temp.length); expect(batch instanceof DataStore).toBe(true); for (let i = 0; i < temp.length; i++) { expect(have[i]).toBe(temp[i]); } temp.push("d"); have = batch.fields(); expect(have.length).toBe(temp.length - 1); }); }); describe("adding to batches", () => { it("tests full row", () => { const check = (have, wantTime, wantData) => { expect(have.time).toBe(wantTime); expect(have.foo).toBe(wantData.foo); expect(have.bar).toBe(wantData.bar); expect(have.baz).toBe(wantData.baz); }; const batch = new DataStore(FIELDS); const row1 = {foo: 0.0, bar: 2.0, baz: 3.0}; batch.add(0, row1); let have = batch.rows(); expect(have.length).toBe(1); check(have[0], 0, row1); const row2 = {foo: 4.0, bar: 5.0, baz: 6.0}; batch.add(1000, row2); have = batch.rows(); expect(have.length).toBe(2); check(have[0], 0, row1); check(have[1], 1000, row2); }); it("tests sparse row", () => { const batch = new DataStore(FIELDS); const row1 = {foo: 1.0, baz: 3.0}; batch.add(0, row1); let have = batch.rows(); expect(have.length).toBe(1); expect(have[0].time).toBe(0); expect(have[0].foo).toBe(row1.foo); expect(have[0].bar).toBe(null); expect(have[0].baz).toBe(row1.baz); const row2 = {foo: 1.0}; batch.add(1000, row2); have = batch.rows(); expect(have.length).toBe(2); expect(have[1].time).toBe(1000); expect(have[1].foo).toBe(row1.foo); expect(have[1].bar).toBe(null); expect(have[1].baz).toBe(null); }); it("tests bad data errors", () => { const check = (badRow) => { try { batch.add(0, badRow); expect(false).toBe(true); } catch (Exception) { expect(batch.rows().length).toBe(0); } }; const batch = new DataStore(FIELDS); check({wrong: 5.0}); check({foo: 1.0, bar: 2.0, baz: 3.0, bad: 5.0}); check(null); check(undefined); }); }); describe("add now", () => { const check = (have, wantTime, wantData) => { expect(have.time).toBe(wantTime); expect(have.foo).toBe(wantData.foo); expect(have.bar).toBe(wantData.bar); expect(have.baz).toBe(wantData.baz); }; it("tests functionality", () => { let now = 1000; MockDate.set(now); const batch = new DataStore(FIELDS); const row1 = {foo: 1.0, bar: 2.0, baz: 3.0}; batch.addNow(row1); let have = batch.rows(); expect(have.length).toBe(1); check(have[0], now, row1); now = 2000; MockDate.set(now); const row2 = {foo: 4.0, bar: 5.0, baz: 6.0}; batch.addNow(row2); have = batch.rows(); expect(have.length).toBe(2); check(have[1], now, row2); }); }); describe("adding too many to batch", () => { const batch = new DataStore(FIELDS); it("tests size function", () => { for (let i = 0; i < 166; i++) { batch.add(i, {foo: i, bar: i, baz: i}); expect(batch.size()).toBe((i + 1) * 3); } }); it("tests than > 500 fails", () => { try { batch.add(167, {foo: 167}); expect(false).toBe(true); } catch (Exception) { expect(batch.size()).toBe(498); } }); }); describe("tests reset", () => { const batch = new DataStore(FIELDS); it("tests reset removes all rows", () => { for (let i = 0; i < 100; i++) { batch.add(i, {foo: i, bar: i, baz: i}); expect(batch.size()).toBe((i + 1) * 3); } batch.reset(); expect(batch.size()).toBe(0); expect(batch.rows().length).toBe(0); batch.add(0, {foo: 0, bar: 0, baz: 0}); expect(batch.rows().length).toBe(1); }); }); describe("tests snapshot", () => { const batch = new DataStore(FIELDS); for (let i = 0; i < 5; i++) { batch.add(i, {foo: i, bar: i, baz: i}); } it("tests snapshot is a copy", () => { const batch2 = batch.snapshot(); expect(batch2 instanceof DataStore).toBe(true); expect(batch2.size()).toBe(batch.size()); expect(batch2.rows().length).toBe(batch.rows().length); for (let i = 0; i < batch2.fields().length; i++ ) { expect(batch2.fields()[i]).toBe(batch.fields()[i]); } for (let i = 0; i < batch2.rows().length; i++ ) { const t2 = batch2.rows()[i]; const t1 = batch.rows()[i]; expect(Object.keys(t2).length).toBe(Object.keys(t1).length); Object.keys(t2).forEach((k) => { expect(t2[k]).toBe(t1[k]); }); } }); it("tests snapshot is deep copy", () => { const batch2 = batch.snapshot(); expect(batch2 instanceof DataStore).toBe(true); expect(batch2.size()).toBe(batch.size()); expect(batch2.rows().length).toBe(batch.rows().length); batch.add(6, {foo: 6}); expect(batch2.size()).toBe(batch.size() - 3); expect(batch2.rows().length).toBe(batch.rows().length - 1); }); });
iobeam/iobeam-client-node
tests/resources/test_DataStore.js
JavaScript
apache-2.0
6,869
/* * Licensed to STRATIO (C) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. The STRATIO (C) licenses this file * to you 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'; /** * @ngdoc directive * @name explorerWebApp.directive:ngEnter * @description * # ngEnter * Bind the <enter> event * * @author anthonycorbacho */ angular.module('explorerWebApp').directive('ngEnter', function() { return function(scope, element, attrs) { element.bind('keydown keypress', function(event) { if (event.which === 13) { scope.$apply(function() { scope.$eval(attrs.ngEnter); }); event.preventDefault(); } }); }; });
Stratio/Explorer
web/app/scripts/directives/ngenter.js
JavaScript
apache-2.0
1,295
(function() { var CusPromise, root; root = typeof exports !== "undefined" && exports !== null ? exports : this; CusPromise = function(promise_) { var obj; obj = { to: function(target, attr, callback) { this.promise.then(function(data) { if (data.data !== void 0 && data.result !== void 0 && data.msg !== void 0) { target[attr] = data.data; return callback && callback.call(this, target[attr], data.result, data.msg); } else { target[attr] = data; return callback && callback.call(this, target[attr]); } }); return promise_; }, then: function(callback) { return this.promise.then(callback); }, promise: promise_ }; return obj; }; ng_app.factory("NetManager", [ '$q', '$http', 'SERVER_HOST', '$timeout', function($q, $http, SERVER_HOST, $timeout) { var net; net = { get: function(url, params_, flag) { var base, counter, deferred, try_connect; deferred = $q.defer(); base = SERVER_HOST; counter = 0; try_connect = function() { return $http.get(base + url, { params: params_ }).success(function(data) { return deferred.resolve(data); }).error(function(data) { if (counter > 4) { return alert('操作失败!'); } else { counter++; return $timeout(try_connect, counter * 500); } }); }; try_connect(); return CusPromise(deferred.promise); }, post: function(url, data_, flag) { var base, counter, deferred, try_connect; deferred = $q.defer(); base = SERVER_HOST; counter = 0; try_connect = function() { return $http.post(base + url, data_).success(function(data) { return deferred.resolve(data); }).error(function(data) { if (counter > 4) { return alert('操作失败!'); } else { counter++; return $timeout(try_connect, counter * 500); } }); }; try_connect(); return deferred.promise; } }; return net; } ]); }).call(this);
zhaowenjian/CCCourse
front/output/js/coffee-js/net_manager.js
JavaScript
apache-2.0
2,423
//// [varArgParamTypeCheck.ts] function sequence(...sequences:{():void;}[]) { } function callback(clb:()=>void) { } sequence( function bar() { }, function foo() { callback(()=>{ this(); }); }, function baz() { callback(()=>{ this(); }); } ); //// [varArgParamTypeCheck.js] function sequence() { var sequences = []; for (var _i = 0; _i < (arguments.length - 0); _i++) { sequences[_i] = arguments[_i + 0]; } } function callback(clb) { } sequence(function bar() { }, function foo() { var _this = this; callback(function () { _this(); }); }, function baz() { var _this = this; callback(function () { _this(); }); });
fdecampredon/jsx-typescript-old-version
tests/baselines/reference/varArgParamTypeCheck.js
JavaScript
apache-2.0
785
import { expect } from 'chai'; import sinon from 'sinon'; import flatMap from 'lodash/flatMap'; import createStore from '../../../store'; import emitterMiddleware from '../../../middlewares/emitter'; /* eslint-disable no-unused-expressions */ describe('Middleware', () => { let store; let callback; beforeEach(() => { store = createStore(10); callback = sinon.spy(); emitterMiddleware(store); }); describe('Emitter', () => { it('should add on and off methods to the store', () => { expect(store.on).to.exist; expect(store.on).to.be.a('function'); expect(store.off).to.exist; expect(store.off).to.be.a('function'); }); it('should emit if data in the store changed', () => { store.on('data', callback); store .dispatch((value) => value - 4) .dispatch((value) => value * 10); expect(callback.callCount).to.be.equal(2); expect(flatMap(callback.args)).to.eql([6, 60]); store.off('data', callback); }); it('should not emit, if data after change is the same', () => { store.on('data', callback); store .dispatch((value) => value - 4) .dispatch((value) => value * 1) .dispatch((value) => value + 0); expect(callback.callCount).to.be.equal(1); expect(flatMap(callback.args)).to.eql([6]); store.off('data', callback); }); it('should remove listeners', () => { store.on('data', callback); store .dispatch((value) => value - 4) .dispatch((value) => value * 10); expect(callback.callCount).to.be.equal(2); expect(flatMap(callback.args)).to.eql([6, 60]); store.off('data', callback); store.dispatch((value) => value - 4); expect(callback.callCount).to.be.equal(2); expect(flatMap(callback.args)).to.eql([6, 60]); }); }); }); /* eslint-enable no-unused-expressions */
maxmert/reflecti
test/unit/middlewares/emitter.js
JavaScript
apache-2.0
2,160
/* * Copyright (c) 2016 Samsung Electronics Co., Ltd. * * 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. */ var assert = require('assert') var GpioCtrl = require('../libs/gpioctrl').GpioCtrl describe('gpioctrl', function () { var ctrl = new GpioCtrl(0, true) it('setOn with on event', function (done) { ctrl.on('on', done) ctrl.setOn() }) it('setOff with off event', function (done) { ctrl.on('off', done) ctrl.setOff() }) })
SamsungARTIK/demokit
test/test_gpioctrl.js
JavaScript
apache-2.0
965
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; function drainQueue() { if (draining) { return; } draining = true; var currentQueue; var len = queue.length; while(len) { currentQueue = queue; queue = []; var i = -1; while (++i < len) { currentQueue[i](); } len = queue.length; } draining = false; } process.nextTick = function (fun) { queue.push(fun); if (!draining) { setTimeout(drainQueue, 0); } }; 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'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],2:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule AutoFocusMixin * @typechecks static-only */ 'use strict'; var focusNode = require("./focusNode"); var AutoFocusMixin = { componentDidMount: function() { if (this.props.autoFocus) { focusNode(this.getDOMNode()); } } }; module.exports = AutoFocusMixin; },{"./focusNode":120}],3:[function(require,module,exports){ /** * Copyright 2013-2015 Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule BeforeInputEventPlugin * @typechecks static-only */ 'use strict'; var EventConstants = require("./EventConstants"); var EventPropagators = require("./EventPropagators"); var ExecutionEnvironment = require("./ExecutionEnvironment"); var FallbackCompositionState = require("./FallbackCompositionState"); var SyntheticCompositionEvent = require("./SyntheticCompositionEvent"); var SyntheticInputEvent = require("./SyntheticInputEvent"); var keyOf = require("./keyOf"); var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space var START_KEYCODE = 229; var canUseCompositionEvent = ( ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window ); var documentMode = null; if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) { documentMode = document.documentMode; } // Webkit offers a very useful `textInput` event that can be used to // directly represent `beforeInput`. The IE `textinput` event is not as // useful, so we don't use it. var canUseTextInputEvent = ( ExecutionEnvironment.canUseDOM && 'TextEvent' in window && !documentMode && !isPresto() ); // In IE9+, we have access to composition events, but the data supplied // by the native compositionend event may be incorrect. Japanese ideographic // spaces, for instance (\u3000) are not recorded correctly. var useFallbackCompositionData = ( ExecutionEnvironment.canUseDOM && ( (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11) ) ); /** * Opera <= 12 includes TextEvent in window, but does not fire * text input events. Rely on keypress instead. */ function isPresto() { var opera = window.opera; return ( typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12 ); } var SPACEBAR_CODE = 32; var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); var topLevelTypes = EventConstants.topLevelTypes; // Events and their corresponding property names. var eventTypes = { beforeInput: { phasedRegistrationNames: { bubbled: keyOf({onBeforeInput: null}), captured: keyOf({onBeforeInputCapture: null}) }, dependencies: [ topLevelTypes.topCompositionEnd, topLevelTypes.topKeyPress, topLevelTypes.topTextInput, topLevelTypes.topPaste ] }, compositionEnd: { phasedRegistrationNames: { bubbled: keyOf({onCompositionEnd: null}), captured: keyOf({onCompositionEndCapture: null}) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topCompositionEnd, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown ] }, compositionStart: { phasedRegistrationNames: { bubbled: keyOf({onCompositionStart: null}), captured: keyOf({onCompositionStartCapture: null}) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topCompositionStart, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown ] }, compositionUpdate: { phasedRegistrationNames: { bubbled: keyOf({onCompositionUpdate: null}), captured: keyOf({onCompositionUpdateCapture: null}) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topCompositionUpdate, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown ] } }; // Track whether we've ever handled a keypress on the space key. var hasSpaceKeypress = false; /** * Return whether a native keypress event is assumed to be a command. * This is required because Firefox fires `keypress` events for key commands * (cut, copy, select-all, etc.) even though no character is inserted. */ function isKeypressCommand(nativeEvent) { return ( (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command. !(nativeEvent.ctrlKey && nativeEvent.altKey) ); } /** * Translate native top level events into event types. * * @param {string} topLevelType * @return {object} */ function getCompositionEventType(topLevelType) { switch (topLevelType) { case topLevelTypes.topCompositionStart: return eventTypes.compositionStart; case topLevelTypes.topCompositionEnd: return eventTypes.compositionEnd; case topLevelTypes.topCompositionUpdate: return eventTypes.compositionUpdate; } } /** * Does our fallback best-guess model think this event signifies that * composition has begun? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionStart(topLevelType, nativeEvent) { return ( topLevelType === topLevelTypes.topKeyDown && nativeEvent.keyCode === START_KEYCODE ); } /** * Does our fallback mode think that this event is the end of composition? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionEnd(topLevelType, nativeEvent) { switch (topLevelType) { case topLevelTypes.topKeyUp: // Command keys insert or clear IME input. return (END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1); case topLevelTypes.topKeyDown: // Expect IME keyCode on each keydown. If we get any other // code we must have exited earlier. return (nativeEvent.keyCode !== START_KEYCODE); case topLevelTypes.topKeyPress: case topLevelTypes.topMouseDown: case topLevelTypes.topBlur: // Events are not possible without cancelling IME. return true; default: return false; } } /** * Google Input Tools provides composition data via a CustomEvent, * with the `data` property populated in the `detail` object. If this * is available on the event object, use it. If not, this is a plain * composition event and we have nothing special to extract. * * @param {object} nativeEvent * @return {?string} */ function getDataFromCustomEvent(nativeEvent) { var detail = nativeEvent.detail; if (typeof detail === 'object' && 'data' in detail) { return detail.data; } return null; } // Track the current IME composition fallback object, if any. var currentComposition = null; /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {?object} A SyntheticCompositionEvent. */ function extractCompositionEvent( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent ) { var eventType; var fallbackData; if (canUseCompositionEvent) { eventType = getCompositionEventType(topLevelType); } else if (!currentComposition) { if (isFallbackCompositionStart(topLevelType, nativeEvent)) { eventType = eventTypes.compositionStart; } } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) { eventType = eventTypes.compositionEnd; } if (!eventType) { return null; } if (useFallbackCompositionData) { // The current composition is stored statically and must not be // overwritten while composition continues. if (!currentComposition && eventType === eventTypes.compositionStart) { currentComposition = FallbackCompositionState.getPooled(topLevelTarget); } else if (eventType === eventTypes.compositionEnd) { if (currentComposition) { fallbackData = currentComposition.getData(); } } } var event = SyntheticCompositionEvent.getPooled( eventType, topLevelTargetID, nativeEvent ); if (fallbackData) { // Inject data generated from fallback path into the synthetic event. // This matches the property of native CompositionEventInterface. event.data = fallbackData; } else { var customData = getDataFromCustomEvent(nativeEvent); if (customData !== null) { event.data = customData; } } EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The string corresponding to this `beforeInput` event. */ function getNativeBeforeInputChars(topLevelType, nativeEvent) { switch (topLevelType) { case topLevelTypes.topCompositionEnd: return getDataFromCustomEvent(nativeEvent); case topLevelTypes.topKeyPress: /** * If native `textInput` events are available, our goal is to make * use of them. However, there is a special case: the spacebar key. * In Webkit, preventing default on a spacebar `textInput` event * cancels character insertion, but it *also* causes the browser * to fall back to its default spacebar behavior of scrolling the * page. * * Tracking at: * https://code.google.com/p/chromium/issues/detail?id=355103 * * To avoid this issue, use the keypress event as if no `textInput` * event is available. */ var which = nativeEvent.which; if (which !== SPACEBAR_CODE) { return null; } hasSpaceKeypress = true; return SPACEBAR_CHAR; case topLevelTypes.topTextInput: // Record the characters to be added to the DOM. var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled // it at the keypress level and bail immediately. Android Chrome // doesn't give us keycodes, so we need to blacklist it. if (chars === SPACEBAR_CHAR && hasSpaceKeypress) { return null; } return chars; default: // For other native event types, do nothing. return null; } } /** * For browsers that do not provide the `textInput` event, extract the * appropriate string to use for SyntheticInputEvent. * * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The fallback string for this `beforeInput` event. */ function getFallbackBeforeInputChars(topLevelType, nativeEvent) { // If we are currently composing (IME) and using a fallback to do so, // try to extract the composed characters from the fallback object. if (currentComposition) { if ( topLevelType === topLevelTypes.topCompositionEnd || isFallbackCompositionEnd(topLevelType, nativeEvent) ) { var chars = currentComposition.getData(); FallbackCompositionState.release(currentComposition); currentComposition = null; return chars; } return null; } switch (topLevelType) { case topLevelTypes.topPaste: // If a paste event occurs after a keypress, throw out the input // chars. Paste events should not lead to BeforeInput events. return null; case topLevelTypes.topKeyPress: /** * As of v27, Firefox may fire keypress events even when no character * will be inserted. A few possibilities: * * - `which` is `0`. Arrow keys, Esc key, etc. * * - `which` is the pressed key code, but no char is available. * Ex: 'AltGr + d` in Polish. There is no modified character for * this key combination and no character is inserted into the * document, but FF fires the keypress for char code `100` anyway. * No `input` event will occur. * * - `which` is the pressed key code, but a command combination is * being used. Ex: `Cmd+C`. No character is inserted, and no * `input` event will occur. */ if (nativeEvent.which && !isKeypressCommand(nativeEvent)) { return String.fromCharCode(nativeEvent.which); } return null; case topLevelTypes.topCompositionEnd: return useFallbackCompositionData ? null : nativeEvent.data; default: return null; } } /** * Extract a SyntheticInputEvent for `beforeInput`, based on either native * `textInput` or fallback behavior. * * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {?object} A SyntheticInputEvent. */ function extractBeforeInputEvent( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent ) { var chars; if (canUseTextInputEvent) { chars = getNativeBeforeInputChars(topLevelType, nativeEvent); } else { chars = getFallbackBeforeInputChars(topLevelType, nativeEvent); } // If no characters are being inserted, no BeforeInput event should // be fired. if (!chars) { return null; } var event = SyntheticInputEvent.getPooled( eventTypes.beforeInput, topLevelTargetID, nativeEvent ); event.data = chars; EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * Create an `onBeforeInput` event to match * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents. * * This event plugin is based on the native `textInput` event * available in Chrome, Safari, Opera, and IE. This event fires after * `onKeyPress` and `onCompositionEnd`, but before `onInput`. * * `beforeInput` is spec'd but not implemented in any browsers, and * the `input` event does not provide any useful information about what has * actually been added, contrary to the spec. Thus, `textInput` is the best * available event to identify the characters that have actually been inserted * into the target node. * * This plugin is also responsible for emitting `composition` events, thus * allowing us to share composition fallback code for both `beforeInput` and * `composition` event types. */ var BeforeInputEventPlugin = { eventTypes: eventTypes, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent ) { return [ extractCompositionEvent( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent ), extractBeforeInputEvent( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent ) ]; } }; module.exports = BeforeInputEventPlugin; },{"./EventConstants":15,"./EventPropagators":20,"./ExecutionEnvironment":21,"./FallbackCompositionState":22,"./SyntheticCompositionEvent":94,"./SyntheticInputEvent":98,"./keyOf":142}],4:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSProperty */ 'use strict'; /** * CSS properties which accept numbers but are not in units of "px". */ var isUnitlessNumber = { boxFlex: true, boxFlexGroup: true, columnCount: true, flex: true, flexGrow: true, flexPositive: true, flexShrink: true, flexNegative: true, fontWeight: true, lineClamp: true, lineHeight: true, opacity: true, order: true, orphans: true, widows: true, zIndex: true, zoom: true, // SVG-related properties fillOpacity: true, strokeDashoffset: true, strokeOpacity: true, strokeWidth: true }; /** * @param {string} prefix vendor-specific prefix, eg: Webkit * @param {string} key style name, eg: transitionDuration * @return {string} style name prefixed with `prefix`, properly camelCased, eg: * WebkitTransitionDuration */ function prefixKey(prefix, key) { return prefix + key.charAt(0).toUpperCase() + key.substring(1); } /** * Support style names that may come passed in prefixed by adding permutations * of vendor prefixes. */ var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an // infinite loop, because it iterates over the newly added props too. Object.keys(isUnitlessNumber).forEach(function(prop) { prefixes.forEach(function(prefix) { isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; }); }); /** * Most style properties can be unset by doing .style[prop] = '' but IE8 * doesn't like doing that with shorthand properties so for the properties that * IE8 breaks on, which are listed here, we instead unset each of the * individual properties. See http://bugs.jquery.com/ticket/12385. * The 4-value 'clock' properties like margin, padding, border-width seem to * behave without any problems. Curiously, list-style works too without any * special prodding. */ var shorthandPropertyExpansions = { background: { backgroundImage: true, backgroundPosition: true, backgroundRepeat: true, backgroundColor: 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 } }; var CSSProperty = { isUnitlessNumber: isUnitlessNumber, shorthandPropertyExpansions: shorthandPropertyExpansions }; module.exports = CSSProperty; },{}],5:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSPropertyOperations * @typechecks static-only */ 'use strict'; var CSSProperty = require("./CSSProperty"); var ExecutionEnvironment = require("./ExecutionEnvironment"); var camelizeStyleName = require("./camelizeStyleName"); var dangerousStyleValue = require("./dangerousStyleValue"); var hyphenateStyleName = require("./hyphenateStyleName"); var memoizeStringOnly = require("./memoizeStringOnly"); var warning = require("./warning"); var processStyleName = memoizeStringOnly(function(styleName) { return hyphenateStyleName(styleName); }); var styleFloatAccessor = 'cssFloat'; if (ExecutionEnvironment.canUseDOM) { // IE8 only supports accessing cssFloat (standard) as styleFloat if (document.documentElement.style.cssFloat === undefined) { styleFloatAccessor = 'styleFloat'; } } if ("production" !== process.env.NODE_ENV) { // 'msTransform' is correct, but the other prefixes should be capitalized var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; // style values shouldn't contain a semicolon var badStyleValueWithSemicolonPattern = /;\s*$/; var warnedStyleNames = {}; var warnedStyleValues = {}; var warnHyphenatedStyleName = function(name) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; ("production" !== process.env.NODE_ENV ? warning( false, 'Unsupported style property %s. Did you mean %s?', name, camelizeStyleName(name) ) : null); }; var warnBadVendoredStyleName = function(name) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; ("production" !== process.env.NODE_ENV ? warning( false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1) ) : null); }; var warnStyleValueWithSemicolon = function(name, value) { if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { return; } warnedStyleValues[value] = true; ("production" !== process.env.NODE_ENV ? warning( false, 'Style property values shouldn\'t contain a semicolon. ' + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, '') ) : null); }; /** * @param {string} name * @param {*} value */ var warnValidStyle = function(name, value) { if (name.indexOf('-') > -1) { warnHyphenatedStyleName(name); } else if (badVendoredStyleNamePattern.test(name)) { warnBadVendoredStyleName(name); } else if (badStyleValueWithSemicolonPattern.test(value)) { warnStyleValueWithSemicolon(name, value); } }; } /** * Operations for dealing with CSS properties. */ var CSSPropertyOperations = { /** * Serializes a mapping of style properties for use as inline styles: * * > createMarkupForStyles({width: '200px', height: 0}) * "width:200px;height:0;" * * Undefined values are ignored so that declarative programming is easier. * The result should be HTML-escaped before insertion into the DOM. * * @param {object} styles * @return {?string} */ createMarkupForStyles: function(styles) { var serialized = ''; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var styleValue = styles[styleName]; if ("production" !== process.env.NODE_ENV) { warnValidStyle(styleName, styleValue); } if (styleValue != null) { serialized += processStyleName(styleName) + ':'; serialized += dangerousStyleValue(styleName, styleValue) + ';'; } } return serialized || null; }, /** * Sets the value for multiple styles on a node. If a value is specified as * '' (empty string), the corresponding style property will be unset. * * @param {DOMElement} node * @param {object} styles */ setValueForStyles: function(node, styles) { var style = node.style; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } if ("production" !== process.env.NODE_ENV) { warnValidStyle(styleName, styles[styleName]); } var styleValue = dangerousStyleValue(styleName, styles[styleName]); if (styleName === 'float') { styleName = styleFloatAccessor; } if (styleValue) { style[styleName] = styleValue; } else { var expansion = 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; }).call(this,require('_process')) },{"./CSSProperty":4,"./ExecutionEnvironment":21,"./camelizeStyleName":109,"./dangerousStyleValue":114,"./hyphenateStyleName":134,"./memoizeStringOnly":144,"./warning":155,"_process":1}],6:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CallbackQueue */ 'use strict'; var PooledClass = require("./PooledClass"); var assign = require("./Object.assign"); var invariant = require("./invariant"); /** * 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) { ("production" !== process.env.NODE_ENV ? invariant( callbacks.length === contexts.length, 'Mismatched list of contexts in callback queue' ) : invariant(callbacks.length === contexts.length)); this._callbacks = null; this._contexts = null; for (var i = 0, l = callbacks.length; i < l; i++) { callbacks[i].call(contexts[i]); } callbacks.length = 0; contexts.length = 0; } }, /** * Resets the internal queue. * * @internal */ reset: function() { this._callbacks = null; this._contexts = null; }, /** * `PooledClass` looks for this. */ destructor: function() { this.reset(); } }); PooledClass.addPoolingTo(CallbackQueue); module.exports = CallbackQueue; }).call(this,require('_process')) },{"./Object.assign":27,"./PooledClass":28,"./invariant":136,"_process":1}],7:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ChangeEventPlugin */ 'use strict'; var EventConstants = require("./EventConstants"); var EventPluginHub = require("./EventPluginHub"); var EventPropagators = require("./EventPropagators"); var ExecutionEnvironment = require("./ExecutionEnvironment"); var ReactUpdates = require("./ReactUpdates"); var SyntheticEvent = require("./SyntheticEvent"); var isEventSupported = require("./isEventSupported"); var isTextInputElement = require("./isTextInputElement"); var keyOf = require("./keyOf"); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { change: { phasedRegistrationNames: { bubbled: keyOf({onChange: null}), captured: keyOf({onChangeCapture: null}) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topChange, topLevelTypes.topClick, topLevelTypes.topFocus, topLevelTypes.topInput, topLevelTypes.topKeyDown, topLevelTypes.topKeyUp, topLevelTypes.topSelectionChange ] } }; /** * For IE shims */ var activeElement = null; var activeElementID = null; var activeElementValue = null; var activeElementValueProp = null; /** * SECTION: handle `change` event */ function shouldUseChangeEvent(elem) { return ( elem.nodeName === 'SELECT' || (elem.nodeName === 'INPUT' && elem.type === 'file') ); } var doesChangeEventBubble = false; if (ExecutionEnvironment.canUseDOM) { // See `handleChange` comment below doesChangeEventBubble = isEventSupported('change') && ( (!('documentMode' in document) || document.documentMode > 8) ); } function manualDispatchChangeEvent(nativeEvent) { var event = SyntheticEvent.getPooled( eventTypes.change, activeElementID, nativeEvent ); 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(); } function startWatchingForChangeEventIE8(target, targetID) { activeElement = target; activeElementID = targetID; activeElement.attachEvent('onchange', manualDispatchChangeEvent); } function stopWatchingForChangeEventIE8() { if (!activeElement) { return; } activeElement.detachEvent('onchange', manualDispatchChangeEvent); activeElement = null; activeElementID = null; } function getTargetIDForChangeEvent( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topChange) { return topLevelTargetID; } } function handleEventsForChangeEventIE8( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topFocus) { // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForChangeEventIE8(); startWatchingForChangeEventIE8(topLevelTarget, topLevelTargetID); } else if (topLevelType === topLevelTypes.topBlur) { stopWatchingForChangeEventIE8(); } } /** * SECTION: handle `input` event */ var isInputEventSupported = false; if (ExecutionEnvironment.canUseDOM) { // IE9 claims to support the input event but fails to trigger it when // deleting text, so we ignore its input events isInputEventSupported = isEventSupported('input') && ( (!('documentMode' in document) || document.documentMode > 9) ); } /** * (For old IE.) Replacement getter/setter for the `value` property that gets * set on the active element. */ var newValueProp = { get: function() { return activeElementValueProp.get.call(this); }, set: function(val) { // Cast to a string so we can do equality checks. activeElementValue = '' + val; activeElementValueProp.set.call(this, val); } }; /** * (For old IE.) Starts tracking propertychange events on the passed-in element * and override the value property so that we can distinguish user events from * value changes in JS. */ function startWatchingForValueChange(target, targetID) { activeElement = target; activeElementID = targetID; activeElementValue = target.value; activeElementValueProp = Object.getOwnPropertyDescriptor( target.constructor.prototype, 'value' ); Object.defineProperty(activeElement, 'value', newValueProp); activeElement.attachEvent('onpropertychange', handlePropertyChange); } /** * (For old IE.) Removes the event listeners from the currently-tracked element, * if any exists. */ function stopWatchingForValueChange() { if (!activeElement) { return; } // delete restores the original property definition delete activeElement.value; activeElement.detachEvent('onpropertychange', handlePropertyChange); activeElement = null; activeElementID = null; activeElementValue = null; activeElementValueProp = null; } /** * (For old IE.) Handles a propertychange event, sending a `change` event if * the value of the active element has changed. */ function handlePropertyChange(nativeEvent) { if (nativeEvent.propertyName !== 'value') { return; } var value = nativeEvent.srcElement.value; if (value === activeElementValue) { return; } activeElementValue = value; manualDispatchChangeEvent(nativeEvent); } /** * If a `change` event should be fired, returns the target's ID. */ function getTargetIDForInputEvent( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topInput) { // In modern browsers (i.e., not IE8 or IE9), the input event is exactly // what we want so fall through here and trigger an abstract event return topLevelTargetID; } } // For IE8 and IE9. function handleEventsForInputEventIE( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topFocus) { // In IE8, we can capture almost all .value changes by adding a // propertychange handler and looking for events with propertyName // equal to 'value' // In IE9, propertychange fires for most input events but is buggy and // doesn't fire when text is deleted, but conveniently, selectionchange // appears to fire in all of the remaining cases so we catch those and // forward the event if the value has changed // In either case, we don't want to call the event handler if the value // is changed from JS so we redefine a setter for `.value` that updates // our activeElementValue variable, allowing us to ignore those changes // // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForValueChange(); startWatchingForValueChange(topLevelTarget, topLevelTargetID); } else if (topLevelType === topLevelTypes.topBlur) { stopWatchingForValueChange(); } } // For IE8 and IE9. function getTargetIDForInputEventIE( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topSelectionChange || topLevelType === topLevelTypes.topKeyUp || topLevelType === topLevelTypes.topKeyDown) { // On the selectionchange event, the target is just document which isn't // helpful for us so just check activeElement instead. // // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire // propertychange on the first input event after setting `value` from a // script and fires only keydown, keypress, keyup. Catching keyup usually // gets it and catching keydown lets us fire an event for the first // keystroke if user does a key repeat (it'll be a little delayed: right // before the second keystroke). Other input methods (e.g., paste) seem to // fire selectionchange normally. if (activeElement && activeElement.value !== activeElementValue) { activeElementValue = activeElement.value; return activeElementID; } } } /** * SECTION: handle `click` event */ function shouldUseClickEvent(elem) { // Use the `click` event to detect changes to checkbox and radio inputs. // This approach works across all browsers, whereas `change` does not fire // until `blur` in IE8. return ( elem.nodeName === 'INPUT' && (elem.type === 'checkbox' || elem.type === 'radio') ); } function getTargetIDForClickEvent( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topClick) { return topLevelTargetID; } } /** * This plugin creates an `onChange` event that normalizes change events * across form elements. This event fires at a time when it's possible to * change the element's value without seeing a flicker. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - select */ var ChangeEventPlugin = { eventTypes: eventTypes, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var getTargetIDFunc, handleEventFunc; if (shouldUseChangeEvent(topLevelTarget)) { if (doesChangeEventBubble) { getTargetIDFunc = getTargetIDForChangeEvent; } else { handleEventFunc = handleEventsForChangeEventIE8; } } else if (isTextInputElement(topLevelTarget)) { if (isInputEventSupported) { getTargetIDFunc = getTargetIDForInputEvent; } else { getTargetIDFunc = getTargetIDForInputEventIE; handleEventFunc = handleEventsForInputEventIE; } } else if (shouldUseClickEvent(topLevelTarget)) { getTargetIDFunc = getTargetIDForClickEvent; } if (getTargetIDFunc) { var targetID = getTargetIDFunc( topLevelType, topLevelTarget, topLevelTargetID ); if (targetID) { var event = SyntheticEvent.getPooled( eventTypes.change, targetID, nativeEvent ); EventPropagators.accumulateTwoPhaseDispatches(event); return event; } } if (handleEventFunc) { handleEventFunc( topLevelType, topLevelTarget, topLevelTargetID ); } } }; module.exports = ChangeEventPlugin; },{"./EventConstants":15,"./EventPluginHub":17,"./EventPropagators":20,"./ExecutionEnvironment":21,"./ReactUpdates":88,"./SyntheticEvent":96,"./isEventSupported":137,"./isTextInputElement":139,"./keyOf":142}],8:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ClientReactRootIndex * @typechecks */ 'use strict'; var nextReactRootIndex = 0; var ClientReactRootIndex = { createReactRootIndex: function() { return nextReactRootIndex++; } }; module.exports = ClientReactRootIndex; },{}],9:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMChildrenOperations * @typechecks static-only */ 'use strict'; var Danger = require("./Danger"); var ReactMultiChildUpdateTypes = require("./ReactMultiChildUpdateTypes"); var setTextContent = require("./setTextContent"); var invariant = require("./invariant"); /** * Inserts `childNode` as a child of `parentNode` at the `index`. * * @param {DOMElement} parentNode Parent node in which to insert. * @param {DOMElement} childNode Child node to insert. * @param {number} index Index at which to insert the child. * @internal */ function insertChildAt(parentNode, childNode, index) { // By exploiting arrays returning `undefined` for an undefined index, we can // rely exclusively on `insertBefore(node, null)` instead of also using // `appendChild(node)`. However, using `undefined` is not allowed by all // browsers so we must replace it with `null`. parentNode.insertBefore( childNode, parentNode.childNodes[index] || null ); } /** * Operations for updating with DOM children. */ var DOMChildrenOperations = { dangerouslyReplaceNodeWithMarkup: Danger.dangerouslyReplaceNodeWithMarkup, updateTextContent: setTextContent, /** * Updates a component's children by processing a series of updates. The * update configurations are each expected to have a `parentNode` property. * * @param {array<object>} updates List of update configurations. * @param {array<string>} markupList List of markup strings. * @internal */ processUpdates: function(updates, markupList) { var update; // Mapping from parent IDs to initial child orderings. var initialChildren = null; // List of children that will be moved or removed. var updatedChildren = null; for (var i = 0; i < updates.length; i++) { update = updates[i]; if (update.type === ReactMultiChildUpdateTypes.MOVE_EXISTING || update.type === ReactMultiChildUpdateTypes.REMOVE_NODE) { var updatedIndex = update.fromIndex; var updatedChild = update.parentNode.childNodes[updatedIndex]; var parentID = update.parentID; ("production" !== process.env.NODE_ENV ? invariant( updatedChild, 'processUpdates(): Unable to find child %s of element. This ' + 'probably means the DOM was unexpectedly mutated (e.g., by the ' + 'browser), usually due to forgetting a <tbody> when using tables, ' + 'nesting tags like <form>, <p>, or <a>, or using non-SVG elements ' + 'in an <svg> parent. Try inspecting the child nodes of the element ' + 'with React ID `%s`.', updatedIndex, parentID ) : invariant(updatedChild)); initialChildren = initialChildren || {}; initialChildren[parentID] = initialChildren[parentID] || []; initialChildren[parentID][updatedIndex] = updatedChild; updatedChildren = updatedChildren || []; updatedChildren.push(updatedChild); } } var renderedMarkup = Danger.dangerouslyRenderMarkup(markupList); // Remove updated children first so that `toIndex` is consistent. if (updatedChildren) { for (var j = 0; j < updatedChildren.length; j++) { updatedChildren[j].parentNode.removeChild(updatedChildren[j]); } } for (var k = 0; k < updates.length; k++) { update = updates[k]; switch (update.type) { case ReactMultiChildUpdateTypes.INSERT_MARKUP: insertChildAt( update.parentNode, renderedMarkup[update.markupIndex], update.toIndex ); break; case ReactMultiChildUpdateTypes.MOVE_EXISTING: insertChildAt( update.parentNode, initialChildren[update.parentID][update.fromIndex], update.toIndex ); break; case ReactMultiChildUpdateTypes.TEXT_CONTENT: setTextContent( update.parentNode, update.textContent ); break; case ReactMultiChildUpdateTypes.REMOVE_NODE: // Already removed by the for-loop above. break; } } } }; module.exports = DOMChildrenOperations; }).call(this,require('_process')) },{"./Danger":12,"./ReactMultiChildUpdateTypes":73,"./invariant":136,"./setTextContent":150,"_process":1}],10:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMProperty * @typechecks static-only */ /*jslint bitwise: true */ 'use strict'; var invariant = require("./invariant"); function checkMask(value, bitmask) { return (value & bitmask) === bitmask; } var DOMPropertyInjection = { /** * Mapping from normalized, camelcased property names to a configuration that * specifies how the associated DOM property should be accessed or rendered. */ MUST_USE_ATTRIBUTE: 0x1, MUST_USE_PROPERTY: 0x2, HAS_SIDE_EFFECTS: 0x4, HAS_BOOLEAN_VALUE: 0x8, HAS_NUMERIC_VALUE: 0x10, HAS_POSITIVE_NUMERIC_VALUE: 0x20 | 0x10, HAS_OVERLOADED_BOOLEAN_VALUE: 0x40, /** * Inject some specialized knowledge about the DOM. This takes a config object * with the following properties: * * isCustomAttribute: function that given an attribute name will return true * if it can be inserted into the DOM verbatim. Useful for data-* or aria-* * attributes where it's impossible to enumerate all of the possible * attribute names, * * Properties: object mapping DOM property name to one of the * DOMPropertyInjection constants or null. If your attribute isn't in here, * it won't get written to the DOM. * * DOMAttributeNames: object mapping React attribute name to the DOM * attribute name. Attribute names not specified use the **lowercase** * normalized name. * * 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 Properties = domPropertyConfig.Properties || {}; 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) { ("production" !== process.env.NODE_ENV ? invariant( !DOMProperty.isStandardName.hasOwnProperty(propName), 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property ' + '\'%s\' which has already been injected. You may be accidentally ' + 'injecting the same DOM property config twice, or you may be ' + 'injecting two configs that have conflicting property names.', propName ) : invariant(!DOMProperty.isStandardName.hasOwnProperty(propName))); DOMProperty.isStandardName[propName] = true; var lowerCased = propName.toLowerCase(); DOMProperty.getPossibleStandardName[lowerCased] = propName; if (DOMAttributeNames.hasOwnProperty(propName)) { var attributeName = DOMAttributeNames[propName]; DOMProperty.getPossibleStandardName[attributeName] = propName; DOMProperty.getAttributeName[propName] = attributeName; } else { DOMProperty.getAttributeName[propName] = lowerCased; } DOMProperty.getPropertyName[propName] = DOMPropertyNames.hasOwnProperty(propName) ? DOMPropertyNames[propName] : propName; if (DOMMutationMethods.hasOwnProperty(propName)) { DOMProperty.getMutationMethod[propName] = DOMMutationMethods[propName]; } else { DOMProperty.getMutationMethod[propName] = null; } var propConfig = Properties[propName]; DOMProperty.mustUseAttribute[propName] = checkMask(propConfig, DOMPropertyInjection.MUST_USE_ATTRIBUTE); DOMProperty.mustUseProperty[propName] = checkMask(propConfig, DOMPropertyInjection.MUST_USE_PROPERTY); DOMProperty.hasSideEffects[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_SIDE_EFFECTS); DOMProperty.hasBooleanValue[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_BOOLEAN_VALUE); DOMProperty.hasNumericValue[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_NUMERIC_VALUE); DOMProperty.hasPositiveNumericValue[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_POSITIVE_NUMERIC_VALUE); DOMProperty.hasOverloadedBooleanValue[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_OVERLOADED_BOOLEAN_VALUE); ("production" !== process.env.NODE_ENV ? invariant( !DOMProperty.mustUseAttribute[propName] || !DOMProperty.mustUseProperty[propName], 'DOMProperty: Cannot require using both attribute and property: %s', propName ) : invariant(!DOMProperty.mustUseAttribute[propName] || !DOMProperty.mustUseProperty[propName])); ("production" !== process.env.NODE_ENV ? invariant( DOMProperty.mustUseProperty[propName] || !DOMProperty.hasSideEffects[propName], 'DOMProperty: Properties that have side effects must use property: %s', propName ) : invariant(DOMProperty.mustUseProperty[propName] || !DOMProperty.hasSideEffects[propName])); ("production" !== process.env.NODE_ENV ? invariant( !!DOMProperty.hasBooleanValue[propName] + !!DOMProperty.hasNumericValue[propName] + !!DOMProperty.hasOverloadedBooleanValue[propName] <= 1, 'DOMProperty: Value can be one of boolean, overloaded boolean, or ' + 'numeric value, but not a combination: %s', propName ) : invariant(!!DOMProperty.hasBooleanValue[propName] + !!DOMProperty.hasNumericValue[propName] + !!DOMProperty.hasOverloadedBooleanValue[propName] <= 1)); } } }; var defaultValueCache = {}; /** * DOMProperty exports lookup objects that can be used like functions: * * > DOMProperty.isValid['id'] * true * > DOMProperty.isValid['foobar'] * undefined * * Although this may be confusing, it performs better in general. * * @see http://jsperf.com/key-exists * @see http://jsperf.com/key-missing */ var DOMProperty = { ID_ATTRIBUTE_NAME: 'data-reactid', /** * Checks whether a property name is a standard property. * @type {Object} */ isStandardName: {}, /** * Mapping from lowercase property names to the properly cased version, used * to warn in the case of missing properties. * @type {Object} */ getPossibleStandardName: {}, /** * Mapping from normalized names to attribute names that differ. Attribute * names are used when rendering markup or with `*Attribute()`. * @type {Object} */ getAttributeName: {}, /** * Mapping from normalized names to properties on DOM node instances. * (This includes properties that mutate due to external factors.) * @type {Object} */ getPropertyName: {}, /** * Mapping from normalized names to mutation methods. This will only exist if * mutation cannot be set simply by the property or `setAttribute()`. * @type {Object} */ getMutationMethod: {}, /** * Whether the property must be accessed and mutated as an object property. * @type {Object} */ mustUseAttribute: {}, /** * Whether the property must be accessed and mutated using `*Attribute()`. * (This includes anything that fails `<propName> in <element>`.) * @type {Object} */ mustUseProperty: {}, /** * Whether or not setting a value causes side effects such as triggering * resources to be loaded or text selection changes. We must ensure that * the value is only set if it has changed. * @type {Object} */ hasSideEffects: {}, /** * Whether the property should be removed when set to a falsey value. * @type {Object} */ hasBooleanValue: {}, /** * Whether the property must be numeric or parse as a * numeric and should be removed when set to a falsey value. * @type {Object} */ hasNumericValue: {}, /** * Whether the property must be positive numeric or parse as a positive * numeric and should be removed when set to a falsey value. * @type {Object} */ hasPositiveNumericValue: {}, /** * 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. * @type {Object} */ hasOverloadedBooleanValue: {}, /** * All of the isCustomAttribute() functions that have been injected. */ _isCustomAttributeFunctions: [], /** * Checks whether a property name is a custom attribute. * @method */ isCustomAttribute: function(attributeName) { for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) { var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i]; if (isCustomAttributeFn(attributeName)) { return true; } } return false; }, /** * Returns the default property value for a DOM property (i.e., not an * attribute). Most default values are '' or false, but not all. Worse yet, * some (in particular, `type`) vary depending on the type of element. * * TODO: Is it better to grab all the possible properties when creating an * element to avoid having to create the same element twice? */ getDefaultValueForProperty: function(nodeName, prop) { var nodeDefaults = defaultValueCache[nodeName]; var testElement; if (!nodeDefaults) { defaultValueCache[nodeName] = nodeDefaults = {}; } if (!(prop in nodeDefaults)) { testElement = document.createElement(nodeName); nodeDefaults[prop] = testElement[prop]; } return nodeDefaults[prop]; }, injection: DOMPropertyInjection }; module.exports = DOMProperty; }).call(this,require('_process')) },{"./invariant":136,"_process":1}],11:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMPropertyOperations * @typechecks static-only */ 'use strict'; var DOMProperty = require("./DOMProperty"); var quoteAttributeValueForBrowser = require("./quoteAttributeValueForBrowser"); var warning = require("./warning"); function shouldIgnoreValue(name, value) { return value == null || (DOMProperty.hasBooleanValue[name] && !value) || (DOMProperty.hasNumericValue[name] && isNaN(value)) || (DOMProperty.hasPositiveNumericValue[name] && (value < 1)) || (DOMProperty.hasOverloadedBooleanValue[name] && value === false); } if ("production" !== process.env.NODE_ENV) { var reactProps = { children: true, dangerouslySetInnerHTML: true, key: true, ref: true }; var warnedProperties = {}; var warnUnknownProperty = function(name) { if (reactProps.hasOwnProperty(name) && reactProps[name] || warnedProperties.hasOwnProperty(name) && warnedProperties[name]) { return; } warnedProperties[name] = true; var lowerCasedName = name.toLowerCase(); // data-* attributes should be lowercase; suggest the lowercase version var standardName = ( DOMProperty.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null ); // For now, only warn when we have a suggested correction. This prevents // logging too much when using transferPropsTo. ("production" !== process.env.NODE_ENV ? warning( standardName == null, 'Unknown DOM property %s. Did you mean %s?', name, standardName ) : null); }; } /** * 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); }, /** * 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 (DOMProperty.isStandardName.hasOwnProperty(name) && DOMProperty.isStandardName[name]) { if (shouldIgnoreValue(name, value)) { return ''; } var attributeName = DOMProperty.getAttributeName[name]; if (DOMProperty.hasBooleanValue[name] || (DOMProperty.hasOverloadedBooleanValue[name] && value === true)) { return attributeName; } return attributeName + '=' + quoteAttributeValueForBrowser(value); } else if (DOMProperty.isCustomAttribute(name)) { if (value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); } else if ("production" !== process.env.NODE_ENV) { warnUnknownProperty(name); } return null; }, /** * Sets the value for a property on a node. * * @param {DOMElement} node * @param {string} name * @param {*} value */ setValueForProperty: function(node, name, value) { if (DOMProperty.isStandardName.hasOwnProperty(name) && DOMProperty.isStandardName[name]) { var mutationMethod = DOMProperty.getMutationMethod[name]; if (mutationMethod) { mutationMethod(node, value); } else if (shouldIgnoreValue(name, value)) { this.deleteValueForProperty(node, name); } else if (DOMProperty.mustUseAttribute[name]) { // `setAttribute` with objects becomes only `[object]` in IE8/9, // ('' + value) makes it output the correct toString()-value. node.setAttribute(DOMProperty.getAttributeName[name], '' + value); } else { var propName = DOMProperty.getPropertyName[name]; // Must explicitly cast values for HAS_SIDE_EFFECTS-properties to the // property type before comparing; only `value` does and is string. if (!DOMProperty.hasSideEffects[name] || ('' + node[propName]) !== ('' + value)) { // Contrary to `setAttribute`, object properties are properly // `toString`ed by IE8/9. node[propName] = value; } } } else if (DOMProperty.isCustomAttribute(name)) { if (value == null) { node.removeAttribute(name); } else { node.setAttribute(name, '' + value); } } else if ("production" !== process.env.NODE_ENV) { warnUnknownProperty(name); } }, /** * Deletes the value for a property on a node. * * @param {DOMElement} node * @param {string} name */ deleteValueForProperty: function(node, name) { if (DOMProperty.isStandardName.hasOwnProperty(name) && DOMProperty.isStandardName[name]) { var mutationMethod = DOMProperty.getMutationMethod[name]; if (mutationMethod) { mutationMethod(node, undefined); } else if (DOMProperty.mustUseAttribute[name]) { node.removeAttribute(DOMProperty.getAttributeName[name]); } else { var propName = DOMProperty.getPropertyName[name]; var defaultValue = DOMProperty.getDefaultValueForProperty( node.nodeName, propName ); if (!DOMProperty.hasSideEffects[name] || ('' + node[propName]) !== defaultValue) { node[propName] = defaultValue; } } } else if (DOMProperty.isCustomAttribute(name)) { node.removeAttribute(name); } else if ("production" !== process.env.NODE_ENV) { warnUnknownProperty(name); } } }; module.exports = DOMPropertyOperations; }).call(this,require('_process')) },{"./DOMProperty":10,"./quoteAttributeValueForBrowser":148,"./warning":155,"_process":1}],12:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Danger * @typechecks static-only */ /*jslint evil: true, sub: true */ 'use strict'; var ExecutionEnvironment = require("./ExecutionEnvironment"); var createNodesFromMarkup = require("./createNodesFromMarkup"); var emptyFunction = require("./emptyFunction"); var getMarkupWrap = require("./getMarkupWrap"); var invariant = require("./invariant"); var OPEN_TAG_NAME_EXP = /^(<[^ \/>]+)/; var RESULT_INDEX_ATTR = 'data-danger-index'; /** * Extracts the `nodeName` from a string of markup. * * NOTE: Extracting the `nodeName` does not require a regular expression match * because we make assumptions about React-generated markup (i.e. there are no * spaces surrounding the opening tag and there is at least one attribute). * * @param {string} markup String of markup. * @return {string} Node name of the supplied markup. * @see http://jsperf.com/extract-nodename */ function getNodeName(markup) { return markup.substring(1, markup.indexOf(' ')); } var Danger = { /** * Renders markup into an array of nodes. The markup is expected to render * into a list of root nodes. Also, the length of `resultList` and * `markupList` should be the same. * * @param {array<string>} markupList List of markup strings to render. * @return {array<DOMElement>} List of rendered nodes. * @internal */ dangerouslyRenderMarkup: function(markupList) { ("production" !== process.env.NODE_ENV ? invariant( ExecutionEnvironment.canUseDOM, 'dangerouslyRenderMarkup(...): Cannot render markup in a worker ' + 'thread. Make sure `window` and `document` are available globally ' + 'before requiring React when unit testing or use ' + 'React.renderToString for server rendering.' ) : invariant(ExecutionEnvironment.canUseDOM)); var nodeName; var markupByNodeName = {}; // Group markup by `nodeName` if a wrap is necessary, else by '*'. for (var i = 0; i < markupList.length; i++) { ("production" !== process.env.NODE_ENV ? invariant( markupList[i], 'dangerouslyRenderMarkup(...): Missing markup.' ) : invariant(markupList[i])); nodeName = getNodeName(markupList[i]); nodeName = getMarkupWrap(nodeName) ? nodeName : '*'; markupByNodeName[nodeName] = markupByNodeName[nodeName] || []; markupByNodeName[nodeName][i] = markupList[i]; } var resultList = []; var resultListAssignmentCount = 0; for (nodeName in markupByNodeName) { if (!markupByNodeName.hasOwnProperty(nodeName)) { continue; } var markupListByNodeName = markupByNodeName[nodeName]; // This for-in loop skips the holes of the sparse array. The order of // iteration should follow the order of assignment, which happens to match // numerical index order, but we don't rely on that. var resultIndex; for (resultIndex in markupListByNodeName) { if (markupListByNodeName.hasOwnProperty(resultIndex)) { var markup = markupListByNodeName[resultIndex]; // Push the requested markup with an additional RESULT_INDEX_ATTR // attribute. If the markup does not start with a < character, it // will be discarded below (with an appropriate console.error). markupListByNodeName[resultIndex] = markup.replace( OPEN_TAG_NAME_EXP, // This index will be parsed back out below. '$1 ' + RESULT_INDEX_ATTR + '="' + resultIndex + '" ' ); } } // Render each group of markup with similar wrapping `nodeName`. var renderNodes = createNodesFromMarkup( markupListByNodeName.join(''), emptyFunction // Do nothing special with <script> tags. ); for (var j = 0; j < renderNodes.length; ++j) { var renderNode = renderNodes[j]; if (renderNode.hasAttribute && renderNode.hasAttribute(RESULT_INDEX_ATTR)) { resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR); renderNode.removeAttribute(RESULT_INDEX_ATTR); ("production" !== process.env.NODE_ENV ? invariant( !resultList.hasOwnProperty(resultIndex), 'Danger: Assigning to an already-occupied result index.' ) : invariant(!resultList.hasOwnProperty(resultIndex))); resultList[resultIndex] = renderNode; // This should match resultList.length and markupList.length when // we're done. resultListAssignmentCount += 1; } else if ("production" !== process.env.NODE_ENV) { console.error( 'Danger: Discarding unexpected node:', renderNode ); } } } // Although resultList was populated out of order, it should now be a dense // array. ("production" !== process.env.NODE_ENV ? invariant( resultListAssignmentCount === resultList.length, 'Danger: Did not assign to every index of resultList.' ) : invariant(resultListAssignmentCount === resultList.length)); ("production" !== process.env.NODE_ENV ? invariant( resultList.length === markupList.length, 'Danger: Expected markup to render %s nodes, but rendered %s.', markupList.length, resultList.length ) : invariant(resultList.length === markupList.length)); return resultList; }, /** * Replaces a node with a string of markup at its current position within its * parent. The markup must render into a single root node. * * @param {DOMElement} oldChild Child node to replace. * @param {string} markup Markup to render in place of the child node. * @internal */ dangerouslyReplaceNodeWithMarkup: function(oldChild, markup) { ("production" !== process.env.NODE_ENV ? invariant( ExecutionEnvironment.canUseDOM, 'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a ' + 'worker thread. Make sure `window` and `document` are available ' + 'globally before requiring React when unit testing or use ' + 'React.renderToString for server rendering.' ) : invariant(ExecutionEnvironment.canUseDOM)); ("production" !== process.env.NODE_ENV ? invariant(markup, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : invariant(markup)); ("production" !== process.env.NODE_ENV ? invariant( oldChild.tagName.toLowerCase() !== 'html', '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 React.renderToString().' ) : invariant(oldChild.tagName.toLowerCase() !== 'html')); var newChild = createNodesFromMarkup(markup, emptyFunction)[0]; oldChild.parentNode.replaceChild(newChild, oldChild); } }; module.exports = Danger; }).call(this,require('_process')) },{"./ExecutionEnvironment":21,"./createNodesFromMarkup":113,"./emptyFunction":115,"./getMarkupWrap":128,"./invariant":136,"_process":1}],13:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DefaultEventPluginOrder */ 'use strict'; var keyOf = require("./keyOf"); /** * 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}), keyOf({AnalyticsEventPlugin: null}), keyOf({MobileSafariClickEventPlugin: null}) ]; module.exports = DefaultEventPluginOrder; },{"./keyOf":142}],14:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EnterLeaveEventPlugin * @typechecks static-only */ 'use strict'; var EventConstants = require("./EventConstants"); var EventPropagators = require("./EventPropagators"); var SyntheticMouseEvent = require("./SyntheticMouseEvent"); var ReactMount = require("./ReactMount"); var keyOf = require("./keyOf"); var topLevelTypes = EventConstants.topLevelTypes; var getFirstReactDOM = ReactMount.getFirstReactDOM; var eventTypes = { mouseEnter: { registrationName: keyOf({onMouseEnter: null}), dependencies: [ topLevelTypes.topMouseOut, topLevelTypes.topMouseOver ] }, mouseLeave: { registrationName: keyOf({onMouseLeave: null}), dependencies: [ topLevelTypes.topMouseOut, topLevelTypes.topMouseOver ] } }; var extractedEvents = [null, null]; var EnterLeaveEventPlugin = { eventTypes: eventTypes, /** * For almost every interaction we care about, there will be both a top-level * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that * we do not extract duplicate events. However, moving the mouse into the * browser from outside will not fire a `mouseout` event. In this case, we use * the `mouseover` top-level event. * * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { if (topLevelType === topLevelTypes.topMouseOver && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { return null; } if (topLevelType !== topLevelTypes.topMouseOut && topLevelType !== topLevelTypes.topMouseOver) { // Must not be a mouse in or mouse out - ignoring. return null; } var win; if (topLevelTarget.window === topLevelTarget) { // `topLevelTarget` is probably a window object. win = topLevelTarget; } else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. var doc = topLevelTarget.ownerDocument; if (doc) { win = doc.defaultView || doc.parentWindow; } else { win = window; } } var from, to; if (topLevelType === topLevelTypes.topMouseOut) { from = topLevelTarget; to = getFirstReactDOM(nativeEvent.relatedTarget || nativeEvent.toElement) || win; } else { from = win; to = topLevelTarget; } if (from === to) { // Nothing pertains to our managed components. return null; } var fromID = from ? ReactMount.getID(from) : ''; var toID = to ? ReactMount.getID(to) : ''; var leave = SyntheticMouseEvent.getPooled( eventTypes.mouseLeave, fromID, nativeEvent ); leave.type = 'mouseleave'; leave.target = from; leave.relatedTarget = to; var enter = SyntheticMouseEvent.getPooled( eventTypes.mouseEnter, toID, nativeEvent ); enter.type = 'mouseenter'; enter.target = to; enter.relatedTarget = from; EventPropagators.accumulateEnterLeaveDispatches(leave, enter, fromID, toID); extractedEvents[0] = leave; extractedEvents[1] = enter; return extractedEvents; } }; module.exports = EnterLeaveEventPlugin; },{"./EventConstants":15,"./EventPropagators":20,"./ReactMount":71,"./SyntheticMouseEvent":100,"./keyOf":142}],15:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventConstants */ 'use strict'; var keyMirror = require("./keyMirror"); var PropagationPhases = keyMirror({bubbled: null, captured: null}); /** * Types of raw signals from the browser caught at the top level. */ var topLevelTypes = keyMirror({ topBlur: 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, topError: null, topFocus: null, topInput: null, topKeyDown: null, topKeyPress: null, topKeyUp: null, topLoad: null, topMouseDown: null, topMouseMove: null, topMouseOut: null, topMouseOver: null, topMouseUp: null, topPaste: null, topReset: null, topScroll: null, topSelectionChange: null, topSubmit: null, topTextInput: null, topTouchCancel: null, topTouchEnd: null, topTouchMove: null, topTouchStart: null, topWheel: null }); var EventConstants = { topLevelTypes: topLevelTypes, PropagationPhases: PropagationPhases }; module.exports = EventConstants; },{"./keyMirror":141}],16:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule EventListener * @typechecks */ var emptyFunction = require("./emptyFunction"); /** * Upstream version of event listener. Does not take into account specific * nature of platform. */ var EventListener = { /** * Listen to DOM events during the bubble phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ listen: function(target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, false); return { remove: function() { target.removeEventListener(eventType, callback, false); } }; } else if (target.attachEvent) { target.attachEvent('on' + eventType, callback); return { remove: function() { target.detachEvent('on' + eventType, callback); } }; } }, /** * Listen to DOM events during the capture phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ capture: function(target, eventType, callback) { if (!target.addEventListener) { if ("production" !== process.env.NODE_ENV) { 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 }; } else { target.addEventListener(eventType, callback, true); return { remove: function() { target.removeEventListener(eventType, callback, true); } }; } }, registerDefault: function() {} }; module.exports = EventListener; }).call(this,require('_process')) },{"./emptyFunction":115,"_process":1}],17:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginHub */ 'use strict'; var EventPluginRegistry = require("./EventPluginRegistry"); var EventPluginUtils = require("./EventPluginUtils"); var accumulateInto = require("./accumulateInto"); var forEachAccumulated = require("./forEachAccumulated"); var invariant = require("./invariant"); /** * 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. * @private */ var executeDispatchesAndRelease = function(event) { if (event) { var executeDispatch = EventPluginUtils.executeDispatch; // Plugins can provide custom behavior when dispatching events. var PluginModule = EventPluginRegistry.getPluginModuleForEvent(event); if (PluginModule && PluginModule.executeDispatch) { executeDispatch = PluginModule.executeDispatch; } EventPluginUtils.executeDispatchesInOrder(event, executeDispatch); if (!event.isPersistent()) { event.constructor.release(event); } } }; /** * - `InstanceHandle`: [required] Module that performs logical traversals of DOM * hierarchy given ids of the logical DOM elements involved. */ var InstanceHandle = null; function validateInstanceHandle() { var valid = InstanceHandle && InstanceHandle.traverseTwoPhase && InstanceHandle.traverseEnterLeave; ("production" !== process.env.NODE_ENV ? invariant( valid, 'InstanceHandle not injected before use!' ) : invariant(valid)); } /** * This is a unified interface for event plugins to be installed and configured. * * Event plugins can implement the following properties: * * `extractEvents` {function(string, DOMEventTarget, string, object): *} * Required. When a top-level event is fired, this method is expected to * extract synthetic events that will in turn be queued and dispatched. * * `eventTypes` {object} * Optional, plugins that fire events must publish a mapping of registration * names that are used to register listeners. Values of this mapping must * be objects that contain `registrationName` or `phasedRegistrationNames`. * * `executeDispatch` {function(object, function, string)} * Optional, allows plugins to override how an event gets dispatched. By * default, the listener is simply invoked. * * Each plugin that is injected into `EventsPluginHub` is immediately operable. * * @public */ var EventPluginHub = { /** * Methods for injecting dependencies. */ injection: { /** * @param {object} InjectedMount * @public */ injectMount: EventPluginUtils.injection.injectMount, /** * @param {object} InjectedInstanceHandle * @public */ injectInstanceHandle: function(InjectedInstanceHandle) { InstanceHandle = InjectedInstanceHandle; if ("production" !== process.env.NODE_ENV) { validateInstanceHandle(); } }, getInstanceHandle: function() { if ("production" !== process.env.NODE_ENV) { validateInstanceHandle(); } return InstanceHandle; }, /** * @param {array} InjectedEventPluginOrder * @public */ injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder, /** * @param {object} injectedNamesToPlugins Map from names to plugin modules. */ injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName }, eventNameDispatchConfigs: EventPluginRegistry.eventNameDispatchConfigs, registrationNameModules: EventPluginRegistry.registrationNameModules, /** * Stores `listener` at `listenerBank[registrationName][id]`. Is idempotent. * * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {?function} listener The callback to store. */ putListener: function(id, registrationName, listener) { ("production" !== process.env.NODE_ENV ? invariant( !listener || typeof listener === 'function', 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener ) : invariant(!listener || typeof listener === 'function')); var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {}); bankForRegistrationName[id] = listener; }, /** * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ getListener: function(id, registrationName) { var bankForRegistrationName = listenerBank[registrationName]; return bankForRegistrationName && bankForRegistrationName[id]; }, /** * Deletes a listener from the registration bank. * * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). */ deleteListener: function(id, registrationName) { var bankForRegistrationName = listenerBank[registrationName]; if (bankForRegistrationName) { delete bankForRegistrationName[id]; } }, /** * Deletes all listeners for the DOM element with the supplied ID. * * @param {string} id ID of the DOM element. */ deleteAllListeners: function(id) { for (var registrationName in listenerBank) { delete listenerBank[registrationName][id]; } }, /** * Allows registered plugins an opportunity to extract events from top-level * native browser events. * * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @internal */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var events; var plugins = EventPluginRegistry.plugins; for (var i = 0, l = plugins.length; i < l; i++) { // Not every plugin in the ordering may be loaded at runtime. var possiblePlugin = plugins[i]; if (possiblePlugin) { var extractedEvents = possiblePlugin.extractEvents( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent ); 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() { // Set `eventQueue` to null before processing it so that we can tell if more // events get enqueued while processing. var processingEventQueue = eventQueue; eventQueue = null; forEachAccumulated(processingEventQueue, executeDispatchesAndRelease); ("production" !== process.env.NODE_ENV ? invariant( !eventQueue, 'processEventQueue(): Additional events were enqueued while processing ' + 'an event queue. Support for this has not yet been implemented.' ) : invariant(!eventQueue)); }, /** * These are needed for tests only. Do not use! */ __purge: function() { listenerBank = {}; }, __getListenerBank: function() { return listenerBank; } }; module.exports = EventPluginHub; }).call(this,require('_process')) },{"./EventPluginRegistry":18,"./EventPluginUtils":19,"./accumulateInto":106,"./forEachAccumulated":121,"./invariant":136,"_process":1}],18:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginRegistry * @typechecks static-only */ 'use strict'; var invariant = require("./invariant"); /** * 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); ("production" !== process.env.NODE_ENV ? invariant( pluginIndex > -1, 'EventPluginRegistry: Cannot inject event plugins that do not exist in ' + 'the plugin ordering, `%s`.', pluginName ) : invariant(pluginIndex > -1)); if (EventPluginRegistry.plugins[pluginIndex]) { continue; } ("production" !== process.env.NODE_ENV ? invariant( PluginModule.extractEvents, 'EventPluginRegistry: Event plugins must implement an `extractEvents` ' + 'method, but `%s` does not.', pluginName ) : invariant(PluginModule.extractEvents)); EventPluginRegistry.plugins[pluginIndex] = PluginModule; var publishedEvents = PluginModule.eventTypes; for (var eventName in publishedEvents) { ("production" !== process.env.NODE_ENV ? invariant( publishEventForPlugin( publishedEvents[eventName], PluginModule, eventName ), 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName ) : invariant(publishEventForPlugin( publishedEvents[eventName], PluginModule, eventName ))); } } } /** * 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) { ("production" !== process.env.NODE_ENV ? invariant( !EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName), 'EventPluginHub: More than one plugin attempted to publish the same ' + 'event name, `%s`.', eventName ) : invariant(!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName))); 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) { ("production" !== process.env.NODE_ENV ? invariant( !EventPluginRegistry.registrationNameModules[registrationName], 'EventPluginHub: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName ) : invariant(!EventPluginRegistry.registrationNameModules[registrationName])); EventPluginRegistry.registrationNameModules[registrationName] = PluginModule; EventPluginRegistry.registrationNameDependencies[registrationName] = PluginModule.eventTypes[eventName].dependencies; } /** * Registers plugins so that they can extract and dispatch events. * * @see {EventPluginHub} */ var EventPluginRegistry = { /** * Ordered list of injected plugins. */ plugins: [], /** * Mapping from event name to dispatch config */ eventNameDispatchConfigs: {}, /** * Mapping from registration name to plugin module */ registrationNameModules: {}, /** * Mapping from registration name to event name */ registrationNameDependencies: {}, /** * Injects an ordering of plugins (by plugin name). This allows the ordering * to be decoupled from injection of the actual plugins so that ordering is * always deterministic regardless of packaging, on-the-fly injection, etc. * * @param {array} InjectedEventPluginOrder * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ injectEventPluginOrder: function(InjectedEventPluginOrder) { ("production" !== process.env.NODE_ENV ? invariant( !EventPluginOrder, 'EventPluginRegistry: Cannot inject event plugin ordering more than ' + 'once. You are likely trying to load more than one copy of React.' ) : invariant(!EventPluginOrder)); // 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) { ("production" !== process.env.NODE_ENV ? invariant( !namesToPlugins[pluginName], 'EventPluginRegistry: Cannot inject two different event plugins ' + 'using the same name, `%s`.', pluginName ) : invariant(!namesToPlugins[pluginName])); namesToPlugins[pluginName] = PluginModule; isOrderingDirty = true; } } if (isOrderingDirty) { recomputePluginOrdering(); } }, /** * Looks up the plugin for the supplied event. * * @param {object} event A synthetic event. * @return {?object} The plugin that created the supplied event. * @internal */ getPluginModuleForEvent: function(event) { var dispatchConfig = event.dispatchConfig; if (dispatchConfig.registrationName) { return EventPluginRegistry.registrationNameModules[ dispatchConfig.registrationName ] || null; } for (var phase in dispatchConfig.phasedRegistrationNames) { if (!dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[ dispatchConfig.phasedRegistrationNames[phase] ]; if (PluginModule) { return PluginModule; } } return null; }, /** * Exposed for unit testing. * @private */ _resetEventPlugins: function() { EventPluginOrder = null; for (var pluginName in namesToPlugins) { if (namesToPlugins.hasOwnProperty(pluginName)) { delete namesToPlugins[pluginName]; } } EventPluginRegistry.plugins.length = 0; var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs; for (var eventName in eventNameDispatchConfigs) { if (eventNameDispatchConfigs.hasOwnProperty(eventName)) { delete eventNameDispatchConfigs[eventName]; } } var registrationNameModules = EventPluginRegistry.registrationNameModules; for (var registrationName in registrationNameModules) { if (registrationNameModules.hasOwnProperty(registrationName)) { delete registrationNameModules[registrationName]; } } } }; module.exports = EventPluginRegistry; }).call(this,require('_process')) },{"./invariant":136,"_process":1}],19:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginUtils */ 'use strict'; var EventConstants = require("./EventConstants"); var invariant = require("./invariant"); /** * Injected dependencies: */ /** * - `Mount`: [required] Module that can convert between React dom IDs and * actual node references. */ var injection = { Mount: null, injectMount: function(InjectedMount) { injection.Mount = InjectedMount; if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? invariant( InjectedMount && InjectedMount.getNode, 'EventPluginUtils.injection.injectMount(...): Injected Mount module ' + 'is missing getNode.' ) : invariant(InjectedMount && InjectedMount.getNode)); } } }; 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 ("production" !== process.env.NODE_ENV) { validateEventDispatches = function(event) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; var listenersIsArr = Array.isArray(dispatchListeners); var idsIsArr = Array.isArray(dispatchIDs); var IDsLen = idsIsArr ? dispatchIDs.length : dispatchIDs ? 1 : 0; var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; ("production" !== process.env.NODE_ENV ? invariant( idsIsArr === listenersIsArr && IDsLen === listenersLen, 'EventPluginUtils: Invalid `event`.' ) : invariant(idsIsArr === listenersIsArr && IDsLen === listenersLen)); }; } /** * Invokes `cb(event, listener, id)`. Avoids using call if no scope is * provided. The `(listener,id)` pair effectively forms the "dispatch" but are * kept separate to conserve memory. */ function forEachEventDispatch(event, cb) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; if ("production" !== process.env.NODE_ENV) { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and IDs are two parallel arrays that are always in sync. cb(event, dispatchListeners[i], dispatchIDs[i]); } } else if (dispatchListeners) { cb(event, dispatchListeners, dispatchIDs); } } /** * Default implementation of PluginModule.executeDispatch(). * @param {SyntheticEvent} SyntheticEvent to handle * @param {function} Application-level callback * @param {string} domID DOM id to pass to the callback. */ function executeDispatch(event, listener, domID) { event.currentTarget = injection.Mount.getNode(domID); var returnValue = listener(event, domID); event.currentTarget = null; return returnValue; } /** * Standard/simple iteration through an event's collected dispatches. */ function executeDispatchesInOrder(event, cb) { forEachEventDispatch(event, cb); event._dispatchListeners = null; event._dispatchIDs = null; } /** * Standard/simple iteration through an event's collected dispatches, but stops * at the first dispatch execution returning true, and returns that id. * * @return id of the first dispatch execution who's listener returns true, or * null if no listener returned true. */ function executeDispatchesInOrderStopAtTrueImpl(event) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; if ("production" !== process.env.NODE_ENV) { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and IDs are two parallel arrays that are always in sync. if (dispatchListeners[i](event, dispatchIDs[i])) { return dispatchIDs[i]; } } } else if (dispatchListeners) { if (dispatchListeners(event, dispatchIDs)) { return dispatchIDs; } } return null; } /** * @see executeDispatchesInOrderStopAtTrueImpl */ function executeDispatchesInOrderStopAtTrue(event) { var ret = executeDispatchesInOrderStopAtTrueImpl(event); event._dispatchIDs = null; event._dispatchListeners = null; return ret; } /** * Execution of a "direct" dispatch - there must be at most one dispatch * accumulated on the event or it is considered an error. It doesn't really make * sense for an event with multiple dispatches (bubbled) to keep track of the * return values at each dispatch execution, but it does tend to make sense when * dealing with "direct" dispatches. * * @return The return value of executing the single dispatch. */ function executeDirectDispatch(event) { if ("production" !== process.env.NODE_ENV) { validateEventDispatches(event); } var dispatchListener = event._dispatchListeners; var dispatchID = event._dispatchIDs; ("production" !== process.env.NODE_ENV ? invariant( !Array.isArray(dispatchListener), 'executeDirectDispatch(...): Invalid `event`.' ) : invariant(!Array.isArray(dispatchListener))); var res = dispatchListener ? dispatchListener(event, dispatchID) : null; event._dispatchListeners = null; event._dispatchIDs = null; return res; } /** * @param {SyntheticEvent} event * @return {bool} 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, executeDispatch: executeDispatch, executeDispatchesInOrder: executeDispatchesInOrder, executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, hasDispatches: hasDispatches, injection: injection, useTouchEvents: false }; module.exports = EventPluginUtils; }).call(this,require('_process')) },{"./EventConstants":15,"./invariant":136,"_process":1}],20:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPropagators */ 'use strict'; var EventConstants = require("./EventConstants"); var EventPluginHub = require("./EventPluginHub"); var accumulateInto = require("./accumulateInto"); var forEachAccumulated = require("./forEachAccumulated"); var PropagationPhases = EventConstants.PropagationPhases; var getListener = EventPluginHub.getListener; /** * Some event types have a notion of different registration names for different * "phases" of propagation. This finds listeners by a given phase. */ function listenerAtPhase(id, event, propagationPhase) { var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(id, registrationName); } /** * Tags a `SyntheticEvent` with dispatched listeners. Creating this function * here, allows us to not have to bind or create functions for each event. * Mutating the event's members allows us to not have to create a wrapping * "dispatch" object that pairs the event with the listener. */ function accumulateDirectionalDispatches(domID, upwards, event) { if ("production" !== process.env.NODE_ENV) { if (!domID) { throw new Error('Dispatching id must not be null'); } } var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured; var listener = listenerAtPhase(domID, event, phase); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchIDs = accumulateInto(event._dispatchIDs, domID); } } /** * Collect dispatches (must be entirely collected before dispatching - see unit * tests). Lazily allocate the array to conserve memory. We must loop through * each event and perform the traversal for each one. We can not perform a * single traversal for the entire collection of events because each event may * have a different target. */ function accumulateTwoPhaseDispatchesSingle(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { EventPluginHub.injection.getInstanceHandle().traverseTwoPhase( event.dispatchMarker, accumulateDirectionalDispatches, event ); } } /** * Accumulates without regard to direction, does not look for phased * registration names. Same as `accumulateDirectDispatchesSingle` but without * requiring that the `dispatchMarker` be the same as the dispatched ID. */ function accumulateDispatches(id, ignoredDirection, event) { if (event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(id, registrationName); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchIDs = accumulateInto(event._dispatchIDs, id); } } } /** * Accumulates dispatches on an `SyntheticEvent`, but only for the * `dispatchMarker`. * @param {SyntheticEvent} event */ function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event.dispatchMarker, null, event); } } function accumulateTwoPhaseDispatches(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); } function accumulateEnterLeaveDispatches(leave, enter, fromID, toID) { EventPluginHub.injection.getInstanceHandle().traverseEnterLeave( fromID, toID, accumulateDispatches, leave, enter ); } function accumulateDirectDispatches(events) { forEachAccumulated(events, accumulateDirectDispatchesSingle); } /** * A small set of propagation patterns, each of which will accept a small amount * of information, and generate a set of "dispatch ready event objects" - which * are sets of events that have already been annotated with a set of dispatched * listener functions/ids. The API is designed this way to discourage these * propagation strategies from actually executing the dispatches, since we * always want to collect the entire set of dispatches before executing event a * single one. * * @constructor EventPropagators */ var EventPropagators = { accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches, accumulateDirectDispatches: accumulateDirectDispatches, accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches }; module.exports = EventPropagators; }).call(this,require('_process')) },{"./EventConstants":15,"./EventPluginHub":17,"./accumulateInto":106,"./forEachAccumulated":121,"_process":1}],21:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ExecutionEnvironment */ /*jslint evil: true */ "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; },{}],22:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FallbackCompositionState * @typechecks static-only */ 'use strict'; var PooledClass = require("./PooledClass"); var assign = require("./Object.assign"); var getTextContentAccessor = require("./getTextContentAccessor"); /** * 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, { /** * 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; },{"./Object.assign":27,"./PooledClass":28,"./getTextContentAccessor":131}],23:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule HTMLDOMPropertyConfig */ /*jslint bitwise: true*/ 'use strict'; var DOMProperty = require("./DOMProperty"); var ExecutionEnvironment = require("./ExecutionEnvironment"); var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE; var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY; var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE; var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS; var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE; var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE; var HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE; var hasSVG; if (ExecutionEnvironment.canUseDOM) { var implementation = document.implementation; hasSVG = ( implementation && implementation.hasFeature && implementation.hasFeature( 'http://www.w3.org/TR/SVG11/feature#BasicStructure', '1.1' ) ); } var HTMLDOMPropertyConfig = { isCustomAttribute: RegExp.prototype.test.bind( /^(data|aria)-[a-z_][a-z\d_.\-]*$/ ), Properties: { /** * Standard Properties */ accept: null, acceptCharset: null, accessKey: null, action: null, allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, allowTransparency: MUST_USE_ATTRIBUTE, alt: null, async: HAS_BOOLEAN_VALUE, autoComplete: null, // autoFocus is polyfilled/normalized by AutoFocusMixin // autoFocus: HAS_BOOLEAN_VALUE, autoPlay: HAS_BOOLEAN_VALUE, cellPadding: null, cellSpacing: null, charSet: MUST_USE_ATTRIBUTE, checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, classID: MUST_USE_ATTRIBUTE, // To set className on SVG elements, it's necessary to use .setAttribute; // this works on HTML elements too in all browsers except IE8. Conveniently, // IE8 doesn't support SVG and so we can simply use the attribute in // browsers that support SVG and the property in browsers that don't, // regardless of whether the element is HTML or SVG. className: hasSVG ? MUST_USE_ATTRIBUTE : MUST_USE_PROPERTY, cols: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, colSpan: null, content: null, contentEditable: null, contextMenu: MUST_USE_ATTRIBUTE, controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, coords: null, crossOrigin: null, data: null, // For `<object />` acts as `src`. dateTime: MUST_USE_ATTRIBUTE, defer: HAS_BOOLEAN_VALUE, dir: null, disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, download: HAS_OVERLOADED_BOOLEAN_VALUE, draggable: null, encType: null, form: MUST_USE_ATTRIBUTE, formAction: MUST_USE_ATTRIBUTE, formEncType: MUST_USE_ATTRIBUTE, formMethod: MUST_USE_ATTRIBUTE, formNoValidate: HAS_BOOLEAN_VALUE, formTarget: MUST_USE_ATTRIBUTE, frameBorder: MUST_USE_ATTRIBUTE, headers: null, height: MUST_USE_ATTRIBUTE, hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, high: null, href: null, hrefLang: null, htmlFor: null, httpEquiv: null, icon: null, id: MUST_USE_PROPERTY, label: null, lang: null, list: MUST_USE_ATTRIBUTE, loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, low: null, manifest: MUST_USE_ATTRIBUTE, marginHeight: null, marginWidth: null, max: null, maxLength: MUST_USE_ATTRIBUTE, media: MUST_USE_ATTRIBUTE, mediaGroup: null, method: null, min: null, multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, name: null, noValidate: HAS_BOOLEAN_VALUE, open: HAS_BOOLEAN_VALUE, optimum: null, pattern: null, placeholder: null, poster: null, preload: null, radioGroup: null, readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, rel: null, required: HAS_BOOLEAN_VALUE, role: MUST_USE_ATTRIBUTE, rows: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, rowSpan: null, sandbox: null, scope: null, scoped: HAS_BOOLEAN_VALUE, scrolling: null, seamless: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, shape: null, size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, sizes: MUST_USE_ATTRIBUTE, span: HAS_POSITIVE_NUMERIC_VALUE, spellCheck: null, src: null, srcDoc: MUST_USE_PROPERTY, srcSet: MUST_USE_ATTRIBUTE, start: HAS_NUMERIC_VALUE, step: null, style: null, tabIndex: null, target: null, title: null, type: null, useMap: null, value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS, width: MUST_USE_ATTRIBUTE, wmode: MUST_USE_ATTRIBUTE, /** * Non-standard Properties */ // autoCapitalize and autoCorrect are supported in Mobile Safari for // keyboard hints. autoCapitalize: null, autoCorrect: null, // itemProp, itemScope, itemType are for // Microdata support. See http://schema.org/docs/gs.html itemProp: MUST_USE_ATTRIBUTE, itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, itemType: MUST_USE_ATTRIBUTE, // itemID and itemRef are for Microdata support as well but // only specified in the the WHATWG spec document. See // https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api itemID: MUST_USE_ATTRIBUTE, itemRef: MUST_USE_ATTRIBUTE, // property is supported for OpenGraph in meta tags. property: null, // IE-only attribute that controls focus behavior unselectable: MUST_USE_ATTRIBUTE }, DOMAttributeNames: { acceptCharset: 'accept-charset', className: 'class', htmlFor: 'for', httpEquiv: 'http-equiv' }, DOMPropertyNames: { autoCapitalize: 'autocapitalize', autoComplete: 'autocomplete', autoCorrect: 'autocorrect', autoFocus: 'autofocus', autoPlay: 'autoplay', // `encoding` is equivalent to `enctype`, IE8 lacks an `enctype` setter. // http://www.w3.org/TR/html5/forms.html#dom-fs-encoding encType: 'encoding', hrefLang: 'hreflang', radioGroup: 'radiogroup', spellCheck: 'spellcheck', srcDoc: 'srcdoc', srcSet: 'srcset' } }; module.exports = HTMLDOMPropertyConfig; },{"./DOMProperty":10,"./ExecutionEnvironment":21}],24:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule LinkedValueUtils * @typechecks static-only */ 'use strict'; var ReactPropTypes = require("./ReactPropTypes"); var invariant = require("./invariant"); var hasReadOnlyValue = { 'button': true, 'checkbox': true, 'image': true, 'hidden': true, 'radio': true, 'reset': true, 'submit': true }; function _assertSingleLink(input) { ("production" !== process.env.NODE_ENV ? invariant( input.props.checkedLink == null || input.props.valueLink == null, 'Cannot provide a checkedLink and a valueLink. If you want to use ' + 'checkedLink, you probably don\'t want to use valueLink and vice versa.' ) : invariant(input.props.checkedLink == null || input.props.valueLink == null)); } function _assertValueLink(input) { _assertSingleLink(input); ("production" !== process.env.NODE_ENV ? invariant( input.props.value == null && input.props.onChange == null, 'Cannot provide a valueLink and a value or onChange event. If you want ' + 'to use value or onChange, you probably don\'t want to use valueLink.' ) : invariant(input.props.value == null && input.props.onChange == null)); } function _assertCheckedLink(input) { _assertSingleLink(input); ("production" !== process.env.NODE_ENV ? invariant( input.props.checked == null && input.props.onChange == null, 'Cannot provide a checkedLink and a checked property or onChange event. ' + 'If you want to use checked or onChange, you probably don\'t want to ' + 'use checkedLink' ) : invariant(input.props.checked == null && input.props.onChange == null)); } /** * @param {SyntheticEvent} e change event to handle */ function _handleLinkedValueChange(e) { /*jshint validthis:true */ this.props.valueLink.requestChange(e.target.value); } /** * @param {SyntheticEvent} e change event to handle */ function _handleLinkedCheckChange(e) { /*jshint validthis:true */ this.props.checkedLink.requestChange(e.target.checked); } /** * Provide a linked `value` attribute for controlled forms. You should not use * this outside of the ReactDOM controlled form components. */ var LinkedValueUtils = { Mixin: { 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 } }, /** * @param {ReactComponent} input Form component * @return {*} current value of the input either from value prop or link. */ getValue: function(input) { if (input.props.valueLink) { _assertValueLink(input); return input.props.valueLink.value; } return input.props.value; }, /** * @param {ReactComponent} input Form component * @return {*} current checked status of the input either from checked prop * or link. */ getChecked: function(input) { if (input.props.checkedLink) { _assertCheckedLink(input); return input.props.checkedLink.value; } return input.props.checked; }, /** * @param {ReactComponent} input Form component * @return {function} change callback either from onChange prop or link. */ getOnChange: function(input) { if (input.props.valueLink) { _assertValueLink(input); return _handleLinkedValueChange; } else if (input.props.checkedLink) { _assertCheckedLink(input); return _handleLinkedCheckChange; } return input.props.onChange; } }; module.exports = LinkedValueUtils; }).call(this,require('_process')) },{"./ReactPropTypes":79,"./invariant":136,"_process":1}],25:[function(require,module,exports){ (function (process){ /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule LocalEventTrapMixin */ 'use strict'; var ReactBrowserEventEmitter = require("./ReactBrowserEventEmitter"); var accumulateInto = require("./accumulateInto"); var forEachAccumulated = require("./forEachAccumulated"); var invariant = require("./invariant"); function remove(event) { event.remove(); } var LocalEventTrapMixin = { trapBubbledEvent:function(topLevelType, handlerBaseName) { ("production" !== process.env.NODE_ENV ? invariant(this.isMounted(), 'Must be mounted to trap events') : invariant(this.isMounted())); // 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. var node = this.getDOMNode(); ("production" !== process.env.NODE_ENV ? invariant( node, 'LocalEventTrapMixin.trapBubbledEvent(...): Requires node to be rendered.' ) : invariant(node)); var listener = ReactBrowserEventEmitter.trapBubbledEvent( topLevelType, handlerBaseName, node ); this._localEventListeners = accumulateInto(this._localEventListeners, listener); }, // trapCapturedEvent would look nearly identical. We don't implement that // method because it isn't currently needed. componentWillUnmount:function() { if (this._localEventListeners) { forEachAccumulated(this._localEventListeners, remove); } } }; module.exports = LocalEventTrapMixin; }).call(this,require('_process')) },{"./ReactBrowserEventEmitter":31,"./accumulateInto":106,"./forEachAccumulated":121,"./invariant":136,"_process":1}],26:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule MobileSafariClickEventPlugin * @typechecks static-only */ 'use strict'; var EventConstants = require("./EventConstants"); var emptyFunction = require("./emptyFunction"); var topLevelTypes = EventConstants.topLevelTypes; /** * 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. * * This particular plugin works around the bug by attaching an empty click * listener on `touchstart` (which does fire on every element). */ var MobileSafariClickEventPlugin = { eventTypes: null, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { if (topLevelType === topLevelTypes.topTouchStart) { var target = nativeEvent.target; if (target && !target.onclick) { target.onclick = emptyFunction; } } } }; module.exports = MobileSafariClickEventPlugin; },{"./EventConstants":15,"./emptyFunction":115}],27:[function(require,module,exports){ /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Object.assign */ // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign 'use strict'; function assign(target, sources) { if (target == null) { throw new TypeError('Object.assign target cannot be null or undefined'); } var to = Object(target); var hasOwnProperty = Object.prototype.hasOwnProperty; for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) { var nextSource = arguments[nextIndex]; if (nextSource == null) { continue; } var from = Object(nextSource); // We don't currently support accessors nor proxies. Therefore this // copy cannot throw. If we ever supported this then we must handle // exceptions and side-effects. We don't support symbols so they won't // be transferred. for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } } return to; } module.exports = assign; },{}],28:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule PooledClass */ 'use strict'; var invariant = require("./invariant"); /** * 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 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; ("production" !== process.env.NODE_ENV ? invariant( instance instanceof Klass, 'Trying to release an instance into a pool of a different type.' ) : invariant(instance instanceof Klass)); if (instance.destructor) { instance.destructor(); } if (Klass.instancePool.length < Klass.poolSize) { Klass.instancePool.push(instance); } }; var DEFAULT_POOL_SIZE = 10; var DEFAULT_POOLER = oneArgumentPooler; /** * Augments `CopyConstructor` to be a poolable class, augmenting only the class * itself (statically) not adding any prototypical fields. Any CopyConstructor * you give this may have a `poolSize` property, and will look for a * prototypical `destructor` on instances (optional). * * @param {Function} CopyConstructor Constructor that can be used to reset. * @param {Function} pooler Customizable pooler. */ var addPoolingTo = function(CopyConstructor, pooler) { var NewKlass = CopyConstructor; NewKlass.instancePool = []; NewKlass.getPooled = pooler || DEFAULT_POOLER; if (!NewKlass.poolSize) { NewKlass.poolSize = DEFAULT_POOL_SIZE; } NewKlass.release = standardReleaser; return NewKlass; }; var PooledClass = { addPoolingTo: addPoolingTo, oneArgumentPooler: oneArgumentPooler, twoArgumentPooler: twoArgumentPooler, threeArgumentPooler: threeArgumentPooler, fiveArgumentPooler: fiveArgumentPooler }; module.exports = PooledClass; }).call(this,require('_process')) },{"./invariant":136,"_process":1}],29:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule React */ /* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/ 'use strict'; var EventPluginUtils = require("./EventPluginUtils"); var ReactChildren = require("./ReactChildren"); var ReactComponent = require("./ReactComponent"); var ReactClass = require("./ReactClass"); var ReactContext = require("./ReactContext"); var ReactCurrentOwner = require("./ReactCurrentOwner"); var ReactElement = require("./ReactElement"); var ReactElementValidator = require("./ReactElementValidator"); var ReactDOM = require("./ReactDOM"); var ReactDOMTextComponent = require("./ReactDOMTextComponent"); var ReactDefaultInjection = require("./ReactDefaultInjection"); var ReactInstanceHandles = require("./ReactInstanceHandles"); var ReactMount = require("./ReactMount"); var ReactPerf = require("./ReactPerf"); var ReactPropTypes = require("./ReactPropTypes"); var ReactReconciler = require("./ReactReconciler"); var ReactServerRendering = require("./ReactServerRendering"); var assign = require("./Object.assign"); var findDOMNode = require("./findDOMNode"); var onlyChild = require("./onlyChild"); ReactDefaultInjection.inject(); var createElement = ReactElement.createElement; var createFactory = ReactElement.createFactory; var cloneElement = ReactElement.cloneElement; if ("production" !== process.env.NODE_ENV) { createElement = ReactElementValidator.createElement; createFactory = ReactElementValidator.createFactory; cloneElement = ReactElementValidator.cloneElement; } var render = ReactPerf.measure('React', 'render', ReactMount.render); var React = { Children: { map: ReactChildren.map, forEach: ReactChildren.forEach, count: ReactChildren.count, only: onlyChild }, Component: ReactComponent, DOM: ReactDOM, PropTypes: ReactPropTypes, initializeTouchEvents: function(shouldUseTouch) { EventPluginUtils.useTouchEvents = shouldUseTouch; }, createClass: ReactClass.createClass, createElement: createElement, cloneElement: cloneElement, createFactory: createFactory, createMixin: function(mixin) { // Currently a noop. Will be used to validate and trace mixins. return mixin; }, constructAndRenderComponent: ReactMount.constructAndRenderComponent, constructAndRenderComponentByID: ReactMount.constructAndRenderComponentByID, findDOMNode: findDOMNode, render: render, renderToString: ReactServerRendering.renderToString, renderToStaticMarkup: ReactServerRendering.renderToStaticMarkup, unmountComponentAtNode: ReactMount.unmountComponentAtNode, isValidElement: ReactElement.isValidElement, withContext: ReactContext.withContext, // Hook for JSX spread, don't use this for anything else. __spread: assign }; // Inject the runtime into a devtools global hook regardless of browser. // Allows for debugging when the hook is injected on the page. if ( typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') { __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ CurrentOwner: ReactCurrentOwner, InstanceHandles: ReactInstanceHandles, Mount: ReactMount, Reconciler: ReactReconciler, TextComponent: ReactDOMTextComponent }); } if ("production" !== process.env.NODE_ENV) { var ExecutionEnvironment = require("./ExecutionEnvironment"); if (ExecutionEnvironment.canUseDOM && window.top === window.self) { // If we're in Chrome, look for the devtools marker and provide a download // link if not installed. if (navigator.userAgent.indexOf('Chrome') > -1) { if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { console.debug( 'Download the React DevTools for a better development experience: ' + 'http://fb.me/react-devtools' ); } } var expectedFeatures = [ // shims Array.isArray, Array.prototype.every, Array.prototype.forEach, Array.prototype.indexOf, Array.prototype.map, Date.now, Function.prototype.bind, Object.keys, String.prototype.split, String.prototype.trim, // shams Object.create, Object.freeze ]; for (var i = 0; i < expectedFeatures.length; i++) { if (!expectedFeatures[i]) { console.error( 'One or more ES5 shim/shams expected by React are not available: ' + 'http://fb.me/react-warning-polyfills' ); break; } } } } React.version = '0.13.2'; module.exports = React; }).call(this,require('_process')) },{"./EventPluginUtils":19,"./ExecutionEnvironment":21,"./Object.assign":27,"./ReactChildren":33,"./ReactClass":34,"./ReactComponent":35,"./ReactContext":39,"./ReactCurrentOwner":40,"./ReactDOM":41,"./ReactDOMTextComponent":52,"./ReactDefaultInjection":55,"./ReactElement":58,"./ReactElementValidator":59,"./ReactInstanceHandles":67,"./ReactMount":71,"./ReactPerf":76,"./ReactPropTypes":79,"./ReactReconciler":82,"./ReactServerRendering":85,"./findDOMNode":118,"./onlyChild":145,"_process":1}],30:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactBrowserComponentMixin */ 'use strict'; var findDOMNode = require("./findDOMNode"); var ReactBrowserComponentMixin = { /** * Returns the DOM node rendered by this component. * * @return {DOMElement} The root node of this component. * @final * @protected */ getDOMNode: function() { return findDOMNode(this); } }; module.exports = ReactBrowserComponentMixin; },{"./findDOMNode":118}],31:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactBrowserEventEmitter * @typechecks static-only */ 'use strict'; var EventConstants = require("./EventConstants"); var EventPluginHub = require("./EventPluginHub"); var EventPluginRegistry = require("./EventPluginRegistry"); var ReactEventEmitterMixin = require("./ReactEventEmitterMixin"); var ViewportMetrics = require("./ViewportMetrics"); var assign = require("./Object.assign"); var isEventSupported = require("./isEventSupported"); /** * Summary of `ReactBrowserEventEmitter` event handling: * * - Top-level delegation is used to trap most native browser events. This * may only occur in the main thread and is the responsibility of * ReactEventListener, which is injected and can therefore support pluggable * event sources. This is the only work that occurs in the main thread. * * - We normalize and de-duplicate events to account for browser quirks. This * may be done in the worker thread. * * - Forward these native events (with the associated top-level type used to * trap it) to `EventPluginHub`, which in turn will ask plugins if they want * to extract any synthetic events. * * - The `EventPluginHub` will then process each event by annotating them with * "dispatches", a sequence of listeners and IDs that care about that event. * * - The `EventPluginHub` then dispatches the events. * * Overview of React and the event system: * * +------------+ . * | DOM | . * +------------+ . * | . * v . * +------------+ . * | ReactEvent | . * | Listener | . * +------------+ . +-----------+ * | . +--------+|SimpleEvent| * | . | |Plugin | * +-----|------+ . v +-----------+ * | | | . +--------------+ +------------+ * | +-----------.--->|EventPluginHub| | Event | * | | . | | +-----------+ | Propagators| * | ReactEvent | . | | |TapEvent | |------------| * | Emitter | . | |<---+|Plugin | |other plugin| * | | . | | +-----------+ | utilities | * | +-----------.--->| | +------------+ * | | | . +--------------+ * +-----|------+ . ^ +-----------+ * | . | |Enter/Leave| * + . +-------+|Plugin | * +-------------+ . +-----------+ * | application | . * |-------------| . * | | . * | | . * +-------------+ . * . * React Core . General Purpose Event Plugin System */ var alreadyListeningTo = {}; var isMonitoringScrollValue = false; var reactTopListenersCounter = 0; // For events like 'submit' which don't consistently bubble (which we trap at a // lower node than `document`), binding at `document` would cause duplicate // events so we don't include them here var topEventMapping = { topBlur: 'blur', 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', topFocus: 'focus', topInput: 'input', topKeyDown: 'keydown', topKeyPress: 'keypress', topKeyUp: 'keyup', topMouseDown: 'mousedown', topMouseMove: 'mousemove', topMouseOut: 'mouseout', topMouseOver: 'mouseover', topMouseUp: 'mouseup', topPaste: 'paste', topScroll: 'scroll', topSelectionChange: 'selectionchange', topTextInput: 'textInput', topTouchCancel: 'touchcancel', topTouchEnd: 'touchend', topTouchMove: 'touchmove', topTouchStart: 'touchstart', topWheel: 'wheel' }; /** * To ensure no conflicts with other potential React instances on the page */ var topListenersIDKey = '_reactListenersID' + String(Math.random()).slice(2); function getListeningForDocument(mountAt) { // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty` // directly. if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) { mountAt[topListenersIDKey] = reactTopListenersCounter++; alreadyListeningTo[mountAt[topListenersIDKey]] = {}; } return alreadyListeningTo[mountAt[topListenersIDKey]]; } /** * `ReactBrowserEventEmitter` is used to attach top-level event listeners. For * example: * * ReactBrowserEventEmitter.putListener('myID', 'onClick', myFunction); * * This would allocate a "registration" of `('onClick', myFunction)` on 'myID'. * * @internal */ var ReactBrowserEventEmitter = assign({}, ReactEventEmitterMixin, { /** * Injectable event backend */ ReactEventListener: null, injection: { /** * @param {object} ReactEventListener */ injectReactEventListener: function(ReactEventListener) { ReactEventListener.setHandleTopLevel( ReactBrowserEventEmitter.handleTopLevel ); ReactBrowserEventEmitter.ReactEventListener = ReactEventListener; } }, /** * Sets whether or not any created callbacks should be enabled. * * @param {boolean} enabled True if callbacks should be enabled. */ setEnabled: function(enabled) { if (ReactBrowserEventEmitter.ReactEventListener) { ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled); } }, /** * @return {boolean} True if callbacks are enabled. */ isEnabled: function() { return !!( (ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled()) ); }, /** * We listen for bubbled touch events on the document object. * * Firefox v8.01 (and possibly others) exhibited strange behavior when * mounting `onmousemove` events at some node that was not the document * element. The symptoms were that if your mouse is not moving over something * contained within that mount point (for example on the background) the * top-level listeners for `onmousemove` won't be called. However, if you * register the `mousemove` on the document object, then it will of course * catch all `mousemove`s. This along with iOS quirks, justifies restricting * top-level listeners to the document object only, at least for these * movement types of events and possibly all events. * * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html * * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but * they bubble to document. * * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {object} contentDocumentHandle Document which owns the container */ listenTo: function(registrationName, contentDocumentHandle) { var mountAt = contentDocumentHandle; var isListening = getListeningForDocument(mountAt); var dependencies = EventPluginRegistry. registrationNameDependencies[registrationName]; var topLevelTypes = EventConstants.topLevelTypes; for (var i = 0, l = dependencies.length; i < l; i++) { var dependency = dependencies[i]; if (!( (isListening.hasOwnProperty(dependency) && isListening[dependency]) )) { if (dependency === topLevelTypes.topWheel) { if (isEventSupported('wheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topWheel, 'wheel', mountAt ); } else if (isEventSupported('mousewheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topWheel, 'mousewheel', mountAt ); } else { // Firefox needs to capture a different mouse scroll event. // @see http://www.quirksmode.org/dom/events/tests/scroll.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topWheel, 'DOMMouseScroll', mountAt ); } } else if (dependency === topLevelTypes.topScroll) { if (isEventSupported('scroll', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelTypes.topScroll, 'scroll', mountAt ); } else { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topScroll, 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE ); } } else if (dependency === topLevelTypes.topFocus || dependency === topLevelTypes.topBlur) { if (isEventSupported('focus', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelTypes.topFocus, 'focus', mountAt ); ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelTypes.topBlur, 'blur', mountAt ); } else if (isEventSupported('focusin')) { // IE has `focusin` and `focusout` events which bubble. // @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topFocus, 'focusin', mountAt ); ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topBlur, 'focusout', mountAt ); } // to make sure blur and focus event listeners are only attached once isListening[topLevelTypes.topBlur] = true; isListening[topLevelTypes.topFocus] = true; } else if (topEventMapping.hasOwnProperty(dependency)) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( dependency, topEventMapping[dependency], mountAt ); } isListening[dependency] = true; } } }, trapBubbledEvent: function(topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelType, handlerBaseName, handle ); }, trapCapturedEvent: function(topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelType, handlerBaseName, handle ); }, /** * Listens to window scroll and resize events. We cache scroll values so that * application code can access them without triggering reflows. * * NOTE: Scroll events do not bubble. * * @see http://www.quirksmode.org/dom/events/scroll.html */ ensureScrollValueMonitoring: function() { if (!isMonitoringScrollValue) { var refresh = ViewportMetrics.refreshScrollValues; ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh); isMonitoringScrollValue = true; } }, eventNameDispatchConfigs: EventPluginHub.eventNameDispatchConfigs, registrationNameModules: EventPluginHub.registrationNameModules, putListener: EventPluginHub.putListener, getListener: EventPluginHub.getListener, deleteListener: EventPluginHub.deleteListener, deleteAllListeners: EventPluginHub.deleteAllListeners }); module.exports = ReactBrowserEventEmitter; },{"./EventConstants":15,"./EventPluginHub":17,"./EventPluginRegistry":18,"./Object.assign":27,"./ReactEventEmitterMixin":62,"./ViewportMetrics":105,"./isEventSupported":137}],32:[function(require,module,exports){ /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactChildReconciler * @typechecks static-only */ 'use strict'; var ReactReconciler = require("./ReactReconciler"); var flattenChildren = require("./flattenChildren"); var instantiateReactComponent = require("./instantiateReactComponent"); var shouldUpdateReactComponent = require("./shouldUpdateReactComponent"); /** * 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) { var children = flattenChildren(nestedChildNodes); for (var name in children) { if (children.hasOwnProperty(name)) { var child = children[name]; // The rendered children must be turned into instances as they're // mounted. var childInstance = instantiateReactComponent(child, null); children[name] = childInstance; } } return children; }, /** * Updates the rendered children and returns a new set of children. * * @param {?object} prevChildren Previously initialized set of children. * @param {?object} nextNestedChildNodes Nested child maps. * @param {ReactReconcileTransaction} transaction * @param {object} context * @return {?object} A new set of child instances. * @internal */ updateChildren: function( prevChildren, nextNestedChildNodes, transaction, context) { // We currently don't have a way to track moves here but if we use iterators // instead of for..in we can zip the iterators and check if an item has // moved. // TODO: If nothing has changed, return the prevChildren object so that we // can quickly bailout if nothing has changed. var nextChildren = flattenChildren(nextNestedChildNodes); if (!nextChildren && !prevChildren) { return null; } var name; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } var prevChild = prevChildren && prevChildren[name]; var prevElement = prevChild && prevChild._currentElement; var nextElement = nextChildren[name]; if (shouldUpdateReactComponent(prevElement, nextElement)) { ReactReconciler.receiveComponent( prevChild, nextElement, transaction, context ); nextChildren[name] = prevChild; } else { if (prevChild) { ReactReconciler.unmountComponent(prevChild, name); } // The child must be instantiated before it's mounted. var nextChildInstance = instantiateReactComponent( nextElement, null ); nextChildren[name] = nextChildInstance; } } // Unmount children that are no longer present. for (name in prevChildren) { if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) { ReactReconciler.unmountComponent(prevChildren[name]); } } return nextChildren; }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. * * @param {?object} renderedChildren Previously initialized set of children. * @internal */ unmountChildren: function(renderedChildren) { for (var name in renderedChildren) { var renderedChild = renderedChildren[name]; ReactReconciler.unmountComponent(renderedChild); } } }; module.exports = ReactChildReconciler; },{"./ReactReconciler":82,"./flattenChildren":119,"./instantiateReactComponent":135,"./shouldUpdateReactComponent":152}],33:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactChildren */ 'use strict'; var PooledClass = require("./PooledClass"); var ReactFragment = require("./ReactFragment"); var traverseAllChildren = require("./traverseAllChildren"); var warning = require("./warning"); var twoArgumentPooler = PooledClass.twoArgumentPooler; var threeArgumentPooler = PooledClass.threeArgumentPooler; /** * 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.forEachFunction = forEachFunction; this.forEachContext = forEachContext; } PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler); function forEachSingleChild(traverseContext, child, name, i) { var forEachBookKeeping = traverseContext; forEachBookKeeping.forEachFunction.call( forEachBookKeeping.forEachContext, child, i); } /** * Iterates through children that are typically specified as `props.children`. * * The provided forEachFunc(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc. * @param {*} forEachContext Context for forEachContext. */ function forEachChildren(children, forEachFunc, forEachContext) { if (children == null) { return children; } var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext); traverseAllChildren(children, forEachSingleChild, traverseContext); ForEachBookKeeping.release(traverseContext); } /** * PooledClass representing the bookkeeping associated with performing a child * mapping. Allows avoiding binding callbacks. * * @constructor MapBookKeeping * @param {!*} mapResult Object containing the ordered map of results. * @param {!function} mapFunction Function to perform mapping with. * @param {?*} mapContext Context to perform mapping with. */ function MapBookKeeping(mapResult, mapFunction, mapContext) { this.mapResult = mapResult; this.mapFunction = mapFunction; this.mapContext = mapContext; } PooledClass.addPoolingTo(MapBookKeeping, threeArgumentPooler); function mapSingleChildIntoContext(traverseContext, child, name, i) { var mapBookKeeping = traverseContext; var mapResult = mapBookKeeping.mapResult; var keyUnique = !mapResult.hasOwnProperty(name); if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( keyUnique, 'ReactChildren.map(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name ) : null); } if (keyUnique) { var mappedChild = mapBookKeeping.mapFunction.call(mapBookKeeping.mapContext, child, i); mapResult[name] = mappedChild; } } /** * Maps children that are typically specified as `props.children`. * * The provided mapFunction(child, key, index) will be called for each * leaf child. * * TODO: This may likely break any calls to `ReactChildren.map` that were * previously relying on the fact that we guarded against null children. * * @param {?*} children Children tree container. * @param {function(*, int)} mapFunction. * @param {*} mapContext Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapChildren(children, func, context) { if (children == null) { return children; } var mapResult = {}; var traverseContext = MapBookKeeping.getPooled(mapResult, func, context); traverseAllChildren(children, mapSingleChildIntoContext, traverseContext); MapBookKeeping.release(traverseContext); return ReactFragment.create(mapResult); } function forEachSingleChildDummy(traverseContext, child, name, i) { return null; } /** * Count the number of children that are typically specified as * `props.children`. * * @param {?*} children Children tree container. * @return {number} The number of children. */ function countChildren(children, context) { return traverseAllChildren(children, forEachSingleChildDummy, null); } var ReactChildren = { forEach: forEachChildren, map: mapChildren, count: countChildren }; module.exports = ReactChildren; }).call(this,require('_process')) },{"./PooledClass":28,"./ReactFragment":64,"./traverseAllChildren":154,"./warning":155,"_process":1}],34:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactClass */ 'use strict'; var ReactComponent = require("./ReactComponent"); var ReactCurrentOwner = require("./ReactCurrentOwner"); var ReactElement = require("./ReactElement"); var ReactErrorUtils = require("./ReactErrorUtils"); var ReactInstanceMap = require("./ReactInstanceMap"); var ReactLifeCycle = require("./ReactLifeCycle"); var ReactPropTypeLocations = require("./ReactPropTypeLocations"); var ReactPropTypeLocationNames = require("./ReactPropTypeLocationNames"); var ReactUpdateQueue = require("./ReactUpdateQueue"); var assign = require("./Object.assign"); var invariant = require("./invariant"); var keyMirror = require("./keyMirror"); var keyOf = require("./keyOf"); var warning = require("./warning"); 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 native components. * * To create a new type of `ReactClass`, pass a specification of * your new class to `React.createClass`. The only requirement of your class * specification is that you implement a `render` method. * * var MyComponent = React.createClass({ * render: function() { * return <div>Hello World</div>; * } * }); * * The class specification supports a specific protocol of methods that have * special meaning (e.g. `render`). See `ReactClassInterface` for * more the comprehensive protocol. Any other properties and methods in the * class specification will 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 ("production" !== process.env.NODE_ENV) { validateTypeDef( Constructor, childContextTypes, ReactPropTypeLocations.childContext ); } Constructor.childContextTypes = assign( {}, Constructor.childContextTypes, childContextTypes ); }, contextTypes: function(Constructor, contextTypes) { if ("production" !== process.env.NODE_ENV) { 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 ("production" !== process.env.NODE_ENV) { validateTypeDef( Constructor, propTypes, ReactPropTypeLocations.prop ); } Constructor.propTypes = assign( {}, Constructor.propTypes, propTypes ); }, statics: function(Constructor, statics) { mixStaticSpecIntoComponent(Constructor, statics); } }; function validateTypeDef(Constructor, typeDef, location) { for (var propName in typeDef) { if (typeDef.hasOwnProperty(propName)) { // use a warning instead of an invariant so components // don't show up in prod but not in __DEV__ ("production" !== process.env.NODE_ENV ? 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 ) : null); } } } function validateMethodOverride(proto, name) { var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null; // Disallow overriding of base class methods unless explicitly allowed. if (ReactClassMixin.hasOwnProperty(name)) { ("production" !== process.env.NODE_ENV ? invariant( specPolicy === SpecPolicy.OVERRIDE_BASE, 'ReactClassInterface: You are attempting to override ' + '`%s` from your class specification. Ensure that your method names ' + 'do not overlap with React methods.', name ) : invariant(specPolicy === SpecPolicy.OVERRIDE_BASE)); } // Disallow defining methods more than once unless explicitly allowed. if (proto.hasOwnProperty(name)) { ("production" !== process.env.NODE_ENV ? invariant( specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED, 'ReactClassInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name ) : invariant(specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED)); } } /** * Mixin helper which handles policy validation and reserved * specification keys when building React classses. */ function mixSpecIntoComponent(Constructor, spec) { if (!spec) { return; } ("production" !== process.env.NODE_ENV ? invariant( typeof spec !== 'function', 'ReactClass: You\'re attempting to ' + 'use a component class as a mixin. Instead, just use a regular object.' ) : invariant(typeof spec !== 'function')); ("production" !== process.env.NODE_ENV ? invariant( !ReactElement.isValidElement(spec), 'ReactClass: You\'re attempting to ' + 'use a component as a mixin. Instead, just use a regular object.' ) : invariant(!ReactElement.isValidElement(spec))); var proto = Constructor.prototype; // By handling mixins before any other properties, we ensure the same // chaining order is applied to methods with DEFINE_MANY policy, whether // mixins are listed before or after these methods in the spec. if (spec.hasOwnProperty(MIXINS_KEY)) { RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins); } for (var name in spec) { if (!spec.hasOwnProperty(name)) { continue; } if (name === MIXINS_KEY) { // We have already handled mixins in a special case above continue; } var property = spec[name]; validateMethodOverride(proto, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { RESERVED_SPEC_KEYS[name](Constructor, property); } else { // Setup methods on prototype: // The following member methods should not be automatically bound: // 1. Expected ReactClass methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isReactClassMethod = ReactClassInterface.hasOwnProperty(name); var isAlreadyDefined = proto.hasOwnProperty(name); var markedDontBind = property && property.__reactDontBind; var isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && !markedDontBind; if (shouldAutoBind) { if (!proto.__reactAutoBindMap) { proto.__reactAutoBindMap = {}; } proto.__reactAutoBindMap[name] = property; proto[name] = property; } else { if (isAlreadyDefined) { var specPolicy = ReactClassInterface[name]; // These cases should already be caught by validateMethodOverride ("production" !== process.env.NODE_ENV ? invariant( isReactClassMethod && ( (specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY) ), 'ReactClass: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name ) : invariant(isReactClassMethod && ( (specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY) ))); // 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 ("production" !== process.env.NODE_ENV) { // 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; ("production" !== process.env.NODE_ENV ? invariant( !isReserved, 'ReactClass: You are attempting to define a reserved ' + 'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' + 'as an instance property instead; it will still be accessible on the ' + 'constructor.', name ) : invariant(!isReserved)); var isInherited = name in Constructor; ("production" !== process.env.NODE_ENV ? invariant( !isInherited, 'ReactClass: You are attempting to define ' + '`%s` on your component more than once. This conflict may be ' + 'due to a mixin.', name ) : invariant(!isInherited)); 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) { ("production" !== process.env.NODE_ENV ? invariant( one && two && typeof one === 'object' && typeof two === 'object', 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.' ) : invariant(one && two && typeof one === 'object' && typeof two === 'object')); for (var key in two) { if (two.hasOwnProperty(key)) { ("production" !== process.env.NODE_ENV ? invariant( one[key] === undefined, 'mergeIntoWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: `%s`. This conflict ' + 'may be due to a mixin; in particular, this may be caused by two ' + 'getInitialState() or getDefaultProps() methods returning objects ' + 'with clashing keys.', key ) : invariant(one[key] === undefined)); one[key] = two[key]; } } return one; } /** * Creates a function that invokes two functions and merges their return values. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createMergedResultFunction(one, two) { return function mergedResult() { var a = one.apply(this, arguments); var b = two.apply(this, arguments); if (a == null) { return b; } else if (b == null) { return a; } var c = {}; mergeIntoWithNoDuplicateKeys(c, a); mergeIntoWithNoDuplicateKeys(c, b); return c; }; } /** * Creates a function that invokes two functions and ignores their return vales. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createChainedFunction(one, two) { return function chainedFunction() { one.apply(this, arguments); two.apply(this, arguments); }; } /** * Binds a method to the component. * * @param {object} component Component whose method is going to be bound. * @param {function} method Method to be bound. * @return {function} The bound method. */ function bindAutoBindMethod(component, method) { var boundMethod = method.bind(component); if ("production" !== process.env.NODE_ENV) { boundMethod.__reactBoundContext = component; boundMethod.__reactBoundMethod = method; boundMethod.__reactBoundArguments = null; var componentName = component.constructor.displayName; var _bind = boundMethod.bind; /* eslint-disable block-scoped-var, no-undef */ boundMethod.bind = function(newThis ) {for (var args=[],$__0=1,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]); // 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) { ("production" !== process.env.NODE_ENV ? warning( false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName ) : null); } else if (!args.length) { ("production" !== process.env.NODE_ENV ? 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 ) : null); return boundMethod; } var reboundMethod = _bind.apply(boundMethod, arguments); reboundMethod.__reactBoundContext = component; reboundMethod.__reactBoundMethod = method; reboundMethod.__reactBoundArguments = args; return reboundMethod; /* eslint-enable */ }; } return boundMethod; } /** * Binds all auto-bound methods in a component. * * @param {object} component Component whose method is going to be bound. */ function bindAutoBindMethods(component) { for (var autoBindKey in component.__reactAutoBindMap) { if (component.__reactAutoBindMap.hasOwnProperty(autoBindKey)) { var method = component.__reactAutoBindMap[autoBindKey]; component[autoBindKey] = bindAutoBindMethod( component, ReactErrorUtils.guard( method, component.constructor.displayName + '.' + autoBindKey ) ); } } } var typeDeprecationDescriptor = { enumerable: false, get: function() { var displayName = this.displayName || this.name || 'Component'; ("production" !== process.env.NODE_ENV ? warning( false, '%s.type is deprecated. Use %s directly to access the class.', displayName, displayName ) : null); Object.defineProperty(this, 'type', { value: this }); return this; } }; /** * 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) { ReactUpdateQueue.enqueueReplaceState(this, newState); if (callback) { ReactUpdateQueue.enqueueCallback(this, callback); } }, /** * Checks whether or not this composite component is mounted. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function() { if ("production" !== process.env.NODE_ENV) { var owner = ReactCurrentOwner.current; if (owner !== null) { ("production" !== process.env.NODE_ENV ? 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' ) : null); owner._warnedAboutRefsInRender = true; } } var internalInstance = ReactInstanceMap.get(this); return ( internalInstance && internalInstance !== ReactLifeCycle.currentlyMountingInstance ); }, /** * Sets a subset of the props. * * @param {object} partialProps Subset of the next props. * @param {?function} callback Called after props are updated. * @final * @public * @deprecated */ setProps: function(partialProps, callback) { ReactUpdateQueue.enqueueSetProps(this, partialProps); if (callback) { ReactUpdateQueue.enqueueCallback(this, callback); } }, /** * Replace all the props. * * @param {object} newProps Subset of the next props. * @param {?function} callback Called after props are updated. * @final * @public * @deprecated */ replaceProps: function(newProps, callback) { ReactUpdateQueue.enqueueReplaceProps(this, newProps); if (callback) { ReactUpdateQueue.enqueueCallback(this, callback); } } }; var ReactClassComponent = function() {}; assign( ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin ); /** * Module for creating composite components. * * @class ReactClass */ var ReactClass = { /** * Creates a composite component class given a class specification. * * @param {object} spec Class specification (which must define `render`). * @return {function} Component constructor function. * @public */ createClass: function(spec) { var Constructor = function(props, context) { // This constructor is overridden by mocks. The argument is used // by mocks to assert on what gets mounted. if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: http://fb.me/react-legacyfactory' ) : null); } // Wire up auto-binding if (this.__reactAutoBindMap) { bindAutoBindMethods(this); } this.props = props; this.context = context; 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 ("production" !== process.env.NODE_ENV) { // We allow auto-mocks to proceed as if they're returning null. if (typeof initialState === 'undefined' && this.getInitialState._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. initialState = null; } } ("production" !== process.env.NODE_ENV ? invariant( typeof initialState === 'object' && !Array.isArray(initialState), '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent' ) : invariant(typeof initialState === 'object' && !Array.isArray(initialState))); this.state = initialState; }; Constructor.prototype = new ReactClassComponent(); Constructor.prototype.constructor = Constructor; injectedMixins.forEach( mixSpecIntoComponent.bind(null, Constructor) ); mixSpecIntoComponent(Constructor, spec); // Initialize the defaultProps property after all mixins have been merged if (Constructor.getDefaultProps) { Constructor.defaultProps = Constructor.getDefaultProps(); } if ("production" !== process.env.NODE_ENV) { // 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 = {}; } } ("production" !== process.env.NODE_ENV ? invariant( Constructor.prototype.render, 'createClass(...): Class specification must implement a `render` method.' ) : invariant(Constructor.prototype.render)); if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? 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' ) : null); } // Reduce time spent doing lookups by setting these on the prototype. for (var methodName in ReactClassInterface) { if (!Constructor.prototype[methodName]) { Constructor.prototype[methodName] = null; } } // Legacy hook Constructor.type = Constructor; if ("production" !== process.env.NODE_ENV) { try { Object.defineProperty(Constructor, 'type', typeDeprecationDescriptor); } catch (x) { // IE will fail on defineProperty (es5-shim/sham too) } } return Constructor; }, injection: { injectMixin: function(mixin) { injectedMixins.push(mixin); } } }; module.exports = ReactClass; }).call(this,require('_process')) },{"./Object.assign":27,"./ReactComponent":35,"./ReactCurrentOwner":40,"./ReactElement":58,"./ReactErrorUtils":61,"./ReactInstanceMap":68,"./ReactLifeCycle":69,"./ReactPropTypeLocationNames":77,"./ReactPropTypeLocations":78,"./ReactUpdateQueue":87,"./invariant":136,"./keyMirror":141,"./keyOf":142,"./warning":155,"_process":1}],35:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponent */ 'use strict'; var ReactUpdateQueue = require("./ReactUpdateQueue"); var invariant = require("./invariant"); var warning = require("./warning"); /** * Base class helpers for the updating state of a component. */ function ReactComponent(props, context) { this.props = props; this.context = context; } /** * 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) { ("production" !== process.env.NODE_ENV ? invariant( typeof partialState === 'object' || typeof partialState === 'function' || partialState == null, 'setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.' ) : invariant(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null)); if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().' ) : null); } ReactUpdateQueue.enqueueSetState(this, partialState); if (callback) { ReactUpdateQueue.enqueueCallback(this, callback); } }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ ReactComponent.prototype.forceUpdate = function(callback) { ReactUpdateQueue.enqueueForceUpdate(this); if (callback) { ReactUpdateQueue.enqueueCallback(this, callback); } }; /** * Deprecated APIs. These APIs used to exist on classic React classes but since * we would like to deprecate them, we're not going to move them over to this * modern base class. Instead, we define a getter that warns if it's accessed. */ if ("production" !== process.env.NODE_ENV) { var deprecatedAPIs = { getDOMNode: 'getDOMNode', isMounted: 'isMounted', replaceProps: 'replaceProps', replaceState: 'replaceState', setProps: 'setProps' }; var defineDeprecationWarning = function(methodName, displayName) { try { Object.defineProperty(ReactComponent.prototype, methodName, { get: function() { ("production" !== process.env.NODE_ENV ? warning( false, '%s(...) is deprecated in plain JavaScript React classes.', displayName ) : null); return undefined; } }); } catch (x) { // IE will fail on defineProperty (es5-shim/sham too) } }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } module.exports = ReactComponent; }).call(this,require('_process')) },{"./ReactUpdateQueue":87,"./invariant":136,"./warning":155,"_process":1}],36:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponentBrowserEnvironment */ /*jslint evil: true */ 'use strict'; var ReactDOMIDOperations = require("./ReactDOMIDOperations"); var ReactMount = require("./ReactMount"); /** * Abstracts away all functionality of the reconciler that requires knowledge of * the browser context. TODO: These callers should be refactored to avoid the * need for this injection. */ var ReactComponentBrowserEnvironment = { processChildrenUpdates: ReactDOMIDOperations.dangerouslyProcessChildrenUpdates, replaceNodeWithMarkupByID: ReactDOMIDOperations.dangerouslyReplaceNodeWithMarkupByID, /** * If a particular environment requires that some resources be cleaned up, * specify this in the injected Mixin. In the DOM, we would likely want to * purge any cached node ID lookups. * * @private */ unmountIDFromEnvironment: function(rootNodeID) { ReactMount.purgeID(rootNodeID); } }; module.exports = ReactComponentBrowserEnvironment; },{"./ReactDOMIDOperations":45,"./ReactMount":71}],37:[function(require,module,exports){ (function (process){ /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponentEnvironment */ 'use strict'; var invariant = require("./invariant"); var injected = false; var ReactComponentEnvironment = { /** * Optionally injectable environment dependent cleanup hook. (server vs. * browser etc). Example: A browser system caches DOM nodes based on component * ID and must remove that cache entry when this instance is unmounted. */ unmountIDFromEnvironment: null, /** * Optionally injectable hook for swapping out mount images in the middle of * the tree. */ replaceNodeWithMarkupByID: null, /** * Optionally injectable hook for processing a queue of child updates. Will * later move into MultiChildComponents. */ processChildrenUpdates: null, injection: { injectEnvironment: function(environment) { ("production" !== process.env.NODE_ENV ? invariant( !injected, 'ReactCompositeComponent: injectEnvironment() can only be called once.' ) : invariant(!injected)); ReactComponentEnvironment.unmountIDFromEnvironment = environment.unmountIDFromEnvironment; ReactComponentEnvironment.replaceNodeWithMarkupByID = environment.replaceNodeWithMarkupByID; ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates; injected = true; } } }; module.exports = ReactComponentEnvironment; }).call(this,require('_process')) },{"./invariant":136,"_process":1}],38:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCompositeComponent */ 'use strict'; var ReactComponentEnvironment = require("./ReactComponentEnvironment"); var ReactContext = require("./ReactContext"); var ReactCurrentOwner = require("./ReactCurrentOwner"); var ReactElement = require("./ReactElement"); var ReactElementValidator = require("./ReactElementValidator"); var ReactInstanceMap = require("./ReactInstanceMap"); var ReactLifeCycle = require("./ReactLifeCycle"); var ReactNativeComponent = require("./ReactNativeComponent"); var ReactPerf = require("./ReactPerf"); var ReactPropTypeLocations = require("./ReactPropTypeLocations"); var ReactPropTypeLocationNames = require("./ReactPropTypeLocationNames"); var ReactReconciler = require("./ReactReconciler"); var ReactUpdates = require("./ReactUpdates"); var assign = require("./Object.assign"); var emptyObject = require("./emptyObject"); var invariant = require("./invariant"); var shouldUpdateReactComponent = require("./shouldUpdateReactComponent"); var warning = require("./warning"); function getDeclarationErrorAddendum(component) { var owner = component._currentElement._owner || null; if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * ------------------ The Life-Cycle of a Composite Component ------------------ * * - constructor: Initialization of state. The instance is now retained. * - componentWillMount * - render * - [children's constructors] * - [children's componentWillMount and render] * - [children's componentDidMount] * - componentDidMount * * Update Phases: * - componentWillReceiveProps (only called if parent updated) * - shouldComponentUpdate * - componentWillUpdate * - render * - [children's constructors or receive props phases] * - componentDidUpdate * * - componentWillUnmount * - [children's componentWillUnmount] * - [children destroyed] * - (destroyed): The instance is now blank, released by React and ready for GC. * * ----------------------------------------------------------------------------- */ /** * An incrementing ID assigned to each component when it is mounted. This is * used to enforce the order in which `ReactUpdates` updates dirty components. * * @private */ var nextMountID = 1; /** * @lends {ReactCompositeComponent.prototype} */ var ReactCompositeComponentMixin = { /** * Base constructor for all composite component. * * @param {ReactElement} element * @final * @internal */ construct: function(element) { this._currentElement = element; this._rootNodeID = null; this._instance = null; // See ReactUpdateQueue this._pendingElement = null; this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._renderedComponent = null; this._context = null; this._mountOrder = 0; this._isTopLevel = false; // See ReactUpdates and ReactUpdateQueue. this._pendingCallbacks = null; }, /** * Initializes the component, renders markup, and registers event listeners. * * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function(rootID, transaction, context) { this._context = context; this._mountOrder = nextMountID++; this._rootNodeID = rootID; var publicProps = this._processProps(this._currentElement.props); var publicContext = this._processContext(this._currentElement._context); var Component = ReactNativeComponent.getComponentClassForElement( this._currentElement ); // Initialize the public class var inst = new Component(publicProps, publicContext); if ("production" !== process.env.NODE_ENV) { // This will throw later in _renderValidatedComponent, but add an early // warning now to help debugging ("production" !== process.env.NODE_ENV ? warning( inst.render != null, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render` in your ' + 'component or you may have accidentally tried to render an element ' + 'whose type is a function that isn\'t a React component.', Component.displayName || Component.name || 'Component' ) : null); } // 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; this._instance = inst; // Store a reference from the instance back to the internal representation ReactInstanceMap.set(inst, this); if ("production" !== process.env.NODE_ENV) { this._warnIfContextsDiffer(this._currentElement._context, context); } if ("production" !== process.env.NODE_ENV) { // 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. ("production" !== process.env.NODE_ENV ? 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' ) : null); ("production" !== process.env.NODE_ENV ? 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' ) : null); ("production" !== process.env.NODE_ENV ? warning( !inst.propTypes, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', this.getName() || 'a component' ) : null); ("production" !== process.env.NODE_ENV ? warning( !inst.contextTypes, 'contextTypes was defined as an instance property on %s. Use a ' + 'static property to define contextTypes instead.', this.getName() || 'a component' ) : null); ("production" !== process.env.NODE_ENV ? 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') ) : null); } var initialState = inst.state; if (initialState === undefined) { inst.state = initialState = null; } ("production" !== process.env.NODE_ENV ? invariant( typeof initialState === 'object' && !Array.isArray(initialState), '%s.state: must be set to an object or null', this.getName() || 'ReactCompositeComponent' ) : invariant(typeof initialState === 'object' && !Array.isArray(initialState))); this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; var renderedElement; var previouslyMounting = ReactLifeCycle.currentlyMountingInstance; ReactLifeCycle.currentlyMountingInstance = this; try { if (inst.componentWillMount) { inst.componentWillMount(); // When mounting, calls to `setState` by `componentWillMount` will set // `this._pendingStateQueue` without triggering a re-render. if (this._pendingStateQueue) { inst.state = this._processPendingState(inst.props, inst.context); } } renderedElement = this._renderValidatedComponent(); } finally { ReactLifeCycle.currentlyMountingInstance = previouslyMounting; } this._renderedComponent = this._instantiateReactComponent( renderedElement, this._currentElement.type // The wrapping type ); var markup = ReactReconciler.mountComponent( this._renderedComponent, rootID, transaction, this._processChildContext(context) ); if (inst.componentDidMount) { transaction.getReactMountReady().enqueue(inst.componentDidMount, inst); } return markup; }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function() { var inst = this._instance; if (inst.componentWillUnmount) { var previouslyUnmounting = ReactLifeCycle.currentlyUnmountingInstance; ReactLifeCycle.currentlyUnmountingInstance = this; try { inst.componentWillUnmount(); } finally { ReactLifeCycle.currentlyUnmountingInstance = previouslyUnmounting; } } ReactReconciler.unmountComponent(this._renderedComponent); this._renderedComponent = null; // Reset pending fields 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; // 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; }, /** * Schedule a partial update to the props. Only used for internal testing. * * @param {object} partialProps Subset of the next props. * @param {?function} callback Called after props are updated. * @final * @internal */ _setPropsInternal: function(partialProps, callback) { // This is a deoptimized path. We optimize for always having an element. // This creates an extra internal element. var element = this._pendingElement || this._currentElement; this._pendingElement = ReactElement.cloneAndReplaceProps( element, assign({}, element.props, partialProps) ); ReactUpdates.enqueueUpdate(this, callback); }, /** * Filters the context object to only contain keys specified in * `contextTypes` * * @param {object} context * @return {?object} * @private */ _maskContext: function(context) { var maskedContext = null; // This really should be getting the component class for the element, // but we know that we're not going to need it for built-ins. if (typeof this._currentElement.type === 'string') { return emptyObject; } var contextTypes = this._currentElement.type.contextTypes; if (!contextTypes) { return emptyObject; } maskedContext = {}; for (var contextName in contextTypes) { maskedContext[contextName] = context[contextName]; } return maskedContext; }, /** * Filters the context object to only contain keys specified in * `contextTypes`, and asserts that they are valid. * * @param {object} context * @return {?object} * @private */ _processContext: function(context) { var maskedContext = this._maskContext(context); if ("production" !== process.env.NODE_ENV) { var Component = ReactNativeComponent.getComponentClassForElement( this._currentElement ); if (Component.contextTypes) { this._checkPropTypes( Component.contextTypes, maskedContext, ReactPropTypeLocations.context ); } } return maskedContext; }, /** * @param {object} currentContext * @return {object} * @private */ _processChildContext: function(currentContext) { var inst = this._instance; var childContext = inst.getChildContext && inst.getChildContext(); if (childContext) { ("production" !== process.env.NODE_ENV ? invariant( typeof inst.constructor.childContextTypes === 'object', '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', this.getName() || 'ReactCompositeComponent' ) : invariant(typeof inst.constructor.childContextTypes === 'object')); if ("production" !== process.env.NODE_ENV) { this._checkPropTypes( inst.constructor.childContextTypes, childContext, ReactPropTypeLocations.childContext ); } for (var name in childContext) { ("production" !== process.env.NODE_ENV ? invariant( name in inst.constructor.childContextTypes, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || 'ReactCompositeComponent', name ) : invariant(name in inst.constructor.childContextTypes)); } return assign({}, currentContext, childContext); } return currentContext; }, /** * Processes props by setting default values for unspecified props and * asserting that the props are valid. Does not mutate its argument; returns * a new props object with defaults merged in. * * @param {object} newProps * @return {object} * @private */ _processProps: function(newProps) { if ("production" !== process.env.NODE_ENV) { var Component = ReactNativeComponent.getComponentClassForElement( this._currentElement ); if (Component.propTypes) { this._checkPropTypes( Component.propTypes, newProps, ReactPropTypeLocations.prop ); } } return newProps; }, /** * Assert that the props are valid * * @param {object} propTypes Map of prop name to a ReactPropType * @param {object} props * @param {string} location e.g. "prop", "context", "child context" * @private */ _checkPropTypes: function(propTypes, props, location) { // TODO: Stop validating prop types here and only use the element // validation. var componentName = this.getName(); for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error; try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. ("production" !== process.env.NODE_ENV ? invariant( typeof propTypes[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually ' + 'from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName ) : invariant(typeof propTypes[propName] === 'function')); error = propTypes[propName](props, propName, componentName, location); } catch (ex) { error = ex; } if (error instanceof Error) { // We may want to extend this logic for similar errors in // React.render calls, so I'm abstracting it away into // a function to minimize refactoring in the future var addendum = getDeclarationErrorAddendum(this); if (location === ReactPropTypeLocations.prop) { // Preface gives us something to blacklist in warning module ("production" !== process.env.NODE_ENV ? warning( false, 'Failed Composite propType: %s%s', error.message, addendum ) : null); } else { ("production" !== process.env.NODE_ENV ? warning( false, 'Failed Context Types: %s%s', error.message, addendum ) : null); } } } } }, receiveComponent: function(nextElement, transaction, nextContext) { var prevElement = this._currentElement; var prevContext = this._context; this._pendingElement = null; this.updateComponent( transaction, prevElement, nextElement, prevContext, nextContext ); }, /** * If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate` * is set, update the component. * * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function(transaction) { if (this._pendingElement != null) { ReactReconciler.receiveComponent( this, this._pendingElement || this._currentElement, transaction, this._context ); } if (this._pendingStateQueue !== null || this._pendingForceUpdate) { if ("production" !== process.env.NODE_ENV) { ReactElementValidator.checkAndWarnForMutatedProps( this._currentElement ); } this.updateComponent( transaction, this._currentElement, this._currentElement, this._context, this._context ); } }, /** * Compare two contexts, warning if they are different * TODO: Remove this check when owner-context is removed */ _warnIfContextsDiffer: function(ownerBasedContext, parentBasedContext) { ownerBasedContext = this._maskContext(ownerBasedContext); parentBasedContext = this._maskContext(parentBasedContext); var parentKeys = Object.keys(parentBasedContext).sort(); var displayName = this.getName() || 'ReactCompositeComponent'; for (var i = 0; i < parentKeys.length; i++) { var key = parentKeys[i]; ("production" !== process.env.NODE_ENV ? warning( ownerBasedContext[key] === parentBasedContext[key], 'owner-based and parent-based contexts differ ' + '(values: `%s` vs `%s`) for key (%s) while mounting %s ' + '(see: http://fb.me/react-context-by-parent)', ownerBasedContext[key], parentBasedContext[key], key, displayName ) : 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; var nextContext = inst.context; var nextProps = inst.props; // Distinguish between a props update versus a simple state update if (prevParentElement !== nextParentElement) { nextContext = this._processContext(nextParentElement._context); nextProps = this._processProps(nextParentElement.props); if ("production" !== process.env.NODE_ENV) { if (nextUnmaskedContext != null) { this._warnIfContextsDiffer( nextParentElement._context, nextUnmaskedContext ); } } // An update here will schedule an update but immediately set // _pendingStateQueue which will ensure that any state updates gets // immediately reconciled instead of waiting for the next batch. if (inst.componentWillReceiveProps) { inst.componentWillReceiveProps(nextProps, nextContext); } } var nextState = this._processPendingState(nextProps, nextContext); var shouldUpdate = this._pendingForceUpdate || !inst.shouldComponentUpdate || inst.shouldComponentUpdate(nextProps, nextState, nextContext); if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( typeof shouldUpdate !== 'undefined', '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', this.getName() || 'ReactCompositeComponent' ) : 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; } var nextState = assign({}, replace ? queue[0] : inst.state); for (var i = replace ? 1 : 0; i < queue.length; i++) { var partial = queue[i]; assign( nextState, typeof partial === 'function' ? partial.call(inst, nextState, props, context) : partial ); } return nextState; }, /** * Merges new props and state, notifies delegate methods of update and * performs update. * * @param {ReactElement} nextElement Next element * @param {object} nextProps Next public object to set as properties. * @param {?object} nextState Next object to set as state. * @param {?object} nextContext Next public object to set as context. * @param {ReactReconcileTransaction} transaction * @param {?object} unmaskedContext * @private */ _performComponentUpdate: function( nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext ) { var inst = this._instance; var prevProps = inst.props; var prevState = inst.state; var prevContext = inst.context; if (inst.componentWillUpdate) { inst.componentWillUpdate(nextProps, nextState, nextContext); } this._currentElement = nextElement; this._context = unmaskedContext; inst.props = nextProps; inst.state = nextState; inst.context = nextContext; this._updateRenderedComponent(transaction, unmaskedContext); if (inst.componentDidUpdate) { transaction.getReactMountReady().enqueue( inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), inst ); } }, /** * Call the component's `render` method and update the DOM accordingly. * * @param {ReactReconcileTransaction} transaction * @internal */ _updateRenderedComponent: function(transaction, context) { var prevComponentInstance = this._renderedComponent; var prevRenderedElement = prevComponentInstance._currentElement; var nextRenderedElement = this._renderValidatedComponent(); if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) { ReactReconciler.receiveComponent( prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context) ); } else { // These two IDs are actually the same! But nothing should rely on that. var thisID = this._rootNodeID; var prevComponentID = prevComponentInstance._rootNodeID; ReactReconciler.unmountComponent(prevComponentInstance); this._renderedComponent = this._instantiateReactComponent( nextRenderedElement, this._currentElement.type ); var nextMarkup = ReactReconciler.mountComponent( this._renderedComponent, thisID, transaction, this._processChildContext(context) ); this._replaceNodeWithMarkupByID(prevComponentID, nextMarkup); } }, /** * @protected */ _replaceNodeWithMarkupByID: function(prevComponentID, nextMarkup) { ReactComponentEnvironment.replaceNodeWithMarkupByID( prevComponentID, nextMarkup ); }, /** * @protected */ _renderValidatedComponentWithoutOwnerOrContext: function() { var inst = this._instance; var renderedComponent = inst.render(); if ("production" !== process.env.NODE_ENV) { // We allow auto-mocks to proceed as if they're returning null. if (typeof renderedComponent === 'undefined' && inst.render._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. renderedComponent = null; } } return renderedComponent; }, /** * @private */ _renderValidatedComponent: function() { var renderedComponent; var previousContext = ReactContext.current; ReactContext.current = this._processChildContext( this._currentElement._context ); ReactCurrentOwner.current = this; try { renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext(); } finally { ReactContext.current = previousContext; ReactCurrentOwner.current = null; } ("production" !== process.env.NODE_ENV ? invariant( // TODO: An `isValidNode` function would probably be more appropriate renderedComponent === null || renderedComponent === false || ReactElement.isValidElement(renderedComponent), '%s.render(): A valid ReactComponent must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', this.getName() || 'ReactCompositeComponent' ) : invariant(// TODO: An `isValidNode` function would probably be more appropriate renderedComponent === null || renderedComponent === false || ReactElement.isValidElement(renderedComponent))); 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(); var refs = inst.refs === emptyObject ? (inst.refs = {}) : inst.refs; refs[ref] = component.getPublicInstance(); }, /** * 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 React.render. Can be null for stateless * components. * * @return {ReactComponent} the public component instance. * @internal */ getPublicInstance: function() { return this._instance; }, // Stub _instantiateReactComponent: null }; ReactPerf.measureMethods( ReactCompositeComponentMixin, 'ReactCompositeComponent', { mountComponent: 'mountComponent', updateComponent: 'updateComponent', _renderValidatedComponent: '_renderValidatedComponent' } ); var ReactCompositeComponent = { Mixin: ReactCompositeComponentMixin }; module.exports = ReactCompositeComponent; }).call(this,require('_process')) },{"./Object.assign":27,"./ReactComponentEnvironment":37,"./ReactContext":39,"./ReactCurrentOwner":40,"./ReactElement":58,"./ReactElementValidator":59,"./ReactInstanceMap":68,"./ReactLifeCycle":69,"./ReactNativeComponent":74,"./ReactPerf":76,"./ReactPropTypeLocationNames":77,"./ReactPropTypeLocations":78,"./ReactReconciler":82,"./ReactUpdates":88,"./emptyObject":116,"./invariant":136,"./shouldUpdateReactComponent":152,"./warning":155,"_process":1}],39:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactContext */ 'use strict'; var assign = require("./Object.assign"); var emptyObject = require("./emptyObject"); var warning = require("./warning"); var didWarn = false; /** * Keeps track of the current context. * * The context is automatically passed down the component ownership hierarchy * and is accessible via `this.context` on ReactCompositeComponents. */ var ReactContext = { /** * @internal * @type {object} */ current: emptyObject, /** * Temporarily extends the current context while executing scopedCallback. * * A typical use case might look like * * render: function() { * var children = ReactContext.withContext({foo: 'foo'}, () => ( * * )); * return <div>{children}</div>; * } * * @param {object} newContext New context to merge into the existing context * @param {function} scopedCallback Callback to run with the new context * @return {ReactComponent|array<ReactComponent>} */ withContext: function(newContext, scopedCallback) { if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( didWarn, 'withContext is deprecated and will be removed in a future version. ' + 'Use a wrapper component with getChildContext instead.' ) : null); didWarn = true; } var result; var previousContext = ReactContext.current; ReactContext.current = assign({}, previousContext, newContext); try { result = scopedCallback(); } finally { ReactContext.current = previousContext; } return result; } }; module.exports = ReactContext; }).call(this,require('_process')) },{"./Object.assign":27,"./emptyObject":116,"./warning":155,"_process":1}],40:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCurrentOwner */ 'use strict'; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. * * The depth indicate how many composite components are above this render level. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; module.exports = ReactCurrentOwner; },{}],41:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOM * @typechecks static-only */ 'use strict'; var ReactElement = require("./ReactElement"); var ReactElementValidator = require("./ReactElementValidator"); var mapObject = require("./mapObject"); /** * Create a factory that creates HTML tag elements. * * @param {string} tag Tag name (e.g. `div`). * @private */ function createDOMFactory(tag) { if ("production" !== process.env.NODE_ENV) { 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 ReactDOM = 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', 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', defs: 'defs', ellipse: 'ellipse', g: 'g', 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 = ReactDOM; }).call(this,require('_process')) },{"./ReactElement":58,"./ReactElementValidator":59,"./mapObject":143,"_process":1}],42:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMButton */ 'use strict'; var AutoFocusMixin = require("./AutoFocusMixin"); var ReactBrowserComponentMixin = require("./ReactBrowserComponentMixin"); var ReactClass = require("./ReactClass"); var ReactElement = require("./ReactElement"); var keyMirror = require("./keyMirror"); var button = ReactElement.createFactory('button'); var mouseListenerNames = keyMirror({ onClick: true, onDoubleClick: true, onMouseDown: true, onMouseMove: true, onMouseUp: true, onClickCapture: true, onDoubleClickCapture: true, onMouseDownCapture: true, onMouseMoveCapture: true, onMouseUpCapture: true }); /** * Implements a <button> native component that does not receive mouse events * when `disabled` is set. */ var ReactDOMButton = ReactClass.createClass({ displayName: 'ReactDOMButton', tagName: 'BUTTON', mixins: [AutoFocusMixin, ReactBrowserComponentMixin], render: function() { var props = {}; // Copy the props; except the mouse listeners if we're disabled for (var key in this.props) { if (this.props.hasOwnProperty(key) && (!this.props.disabled || !mouseListenerNames[key])) { props[key] = this.props[key]; } } return button(props, this.props.children); } }); module.exports = ReactDOMButton; },{"./AutoFocusMixin":2,"./ReactBrowserComponentMixin":30,"./ReactClass":34,"./ReactElement":58,"./keyMirror":141}],43:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMComponent * @typechecks static-only */ /* global hasOwnProperty:true */ 'use strict'; var CSSPropertyOperations = require("./CSSPropertyOperations"); var DOMProperty = require("./DOMProperty"); var DOMPropertyOperations = require("./DOMPropertyOperations"); var ReactBrowserEventEmitter = require("./ReactBrowserEventEmitter"); var ReactComponentBrowserEnvironment = require("./ReactComponentBrowserEnvironment"); var ReactMount = require("./ReactMount"); var ReactMultiChild = require("./ReactMultiChild"); var ReactPerf = require("./ReactPerf"); var assign = require("./Object.assign"); var escapeTextContentForBrowser = require("./escapeTextContentForBrowser"); var invariant = require("./invariant"); var isEventSupported = require("./isEventSupported"); var keyOf = require("./keyOf"); var warning = require("./warning"); var deleteListener = ReactBrowserEventEmitter.deleteListener; var listenTo = ReactBrowserEventEmitter.listenTo; var registrationNameModules = ReactBrowserEventEmitter.registrationNameModules; // For quickly matching children type, to test if can be treated as content. var CONTENT_TYPES = {'string': true, 'number': true}; var STYLE = keyOf({style: null}); var ELEMENT_NODE_TYPE = 1; /** * Optionally injectable operations for mutating the DOM */ var BackendIDOperations = null; /** * @param {?object} props */ function assertValidProps(props) { if (!props) { return; } // Note the use of `==` which checks for null or undefined. if (props.dangerouslySetInnerHTML != null) { ("production" !== process.env.NODE_ENV ? invariant( props.children == null, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.' ) : invariant(props.children == null)); ("production" !== process.env.NODE_ENV ? invariant( props.dangerouslySetInnerHTML.__html != null, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit http://fb.me/react-invariant-dangerously-set-inner-html ' + 'for more information.' ) : invariant(props.dangerouslySetInnerHTML.__html != null)); } if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( props.innerHTML == null, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.' ) : null); ("production" !== process.env.NODE_ENV ? warning( !props.contentEditable || props.children == null, 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.' ) : null); } ("production" !== process.env.NODE_ENV ? invariant( props.style == null || typeof props.style === 'object', 'The `style` prop expects a mapping from style properties to values, ' + 'not a string. For example, style={{marginRight: spacing + \'em\'}} when ' + 'using JSX.' ) : invariant(props.style == null || typeof props.style === 'object')); } function putListener(id, registrationName, listener, transaction) { if ("production" !== process.env.NODE_ENV) { // IE8 has no API for event capturing and the `onScroll` event doesn't // bubble. ("production" !== process.env.NODE_ENV ? warning( registrationName !== 'onScroll' || isEventSupported('scroll', true), 'This browser doesn\'t support the `onScroll` event' ) : null); } var container = ReactMount.findReactContainerForID(id); if (container) { var doc = container.nodeType === ELEMENT_NODE_TYPE ? container.ownerDocument : container; listenTo(registrationName, doc); } transaction.getPutListenerQueue().enqueuePutListener( id, registrationName, listener ); } // For HTML, certain tags should omit their close tag. We keep a whitelist for // those special cased tags. var omittedCloseTags = { 'area': true, 'base': true, 'br': true, 'col': true, 'embed': true, 'hr': true, 'img': true, 'input': true, 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, 'track': true, 'wbr': true // NOTE: menuitem's close tag should be omitted, but that causes problems. }; // We accept any tag to be rendered but since this gets injected into abitrary // 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)) { ("production" !== process.env.NODE_ENV ? invariant(VALID_TAG_REGEX.test(tag), 'Invalid tag: %s', tag) : invariant(VALID_TAG_REGEX.test(tag))); validatedTagCache[tag] = true; } } /** * Creates a new React class that is idempotent and capable of containing other * React components. It accepts event listeners and DOM properties that are * valid according to `DOMProperty`. * * - Event listeners: `onClick`, `onMouseDown`, etc. * - DOM properties: `className`, `name`, `title`, etc. * * The `style` property functions differently from the DOM API. It accepts an * object mapping of style properties to values. * * @constructor ReactDOMComponent * @extends ReactMultiChild */ function ReactDOMComponent(tag) { validateDangerousTag(tag); this._tag = tag; this._renderedChildren = null; this._previousStyleCopy = null; this._rootNodeID = null; } ReactDOMComponent.displayName = 'ReactDOMComponent'; ReactDOMComponent.Mixin = { construct: function(element) { this._currentElement = element; }, /** * Generates root tag markup then recurses. This method has side effects and * is not idempotent. * * @internal * @param {string} rootID The root DOM ID for this node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {string} The computed markup. */ mountComponent: function(rootID, transaction, context) { this._rootNodeID = rootID; assertValidProps(this._currentElement.props); var closeTag = omittedCloseTags[this._tag] ? '' : '</' + this._tag + '>'; return ( this._createOpenTagMarkupAndPutListeners(transaction) + this._createContentMarkup(transaction, context) + closeTag ); }, /** * 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 * @return {string} Markup of opening tag. */ _createOpenTagMarkupAndPutListeners: function(transaction) { var props = this._currentElement.props; var ret = '<' + this._tag; for (var propKey in props) { if (!props.hasOwnProperty(propKey)) { continue; } var propValue = props[propKey]; if (propValue == null) { continue; } if (registrationNameModules.hasOwnProperty(propKey)) { putListener(this._rootNodeID, propKey, propValue, transaction); } else { if (propKey === STYLE) { if (propValue) { propValue = this._previousStyleCopy = assign({}, props.style); } propValue = CSSPropertyOperations.createMarkupForStyles(propValue); } var markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue); if (markup) { ret += ' ' + markup; } } } // For static pages, no need to put React ID and checksum. Saves lots of // bytes. if (transaction.renderToStaticMarkup) { return ret + '>'; } var markupForID = DOMPropertyOperations.createMarkupForID(this._rootNodeID); return ret + ' ' + markupForID + '>'; }, /** * Creates markup for the content between the tags. * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} context * @return {string} Content markup. */ _createContentMarkup: function(transaction, context) { var prefix = ''; if (this._tag === 'listing' || this._tag === 'pre' || this._tag === 'textarea') { // Add an initial newline because browsers ignore the first newline in // a <listing>, <pre>, or <textarea> as an "authoring convenience" -- see // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody. prefix = '\n'; } var props = this._currentElement.props; // Intentional use of != to avoid catching zero/false. var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { return prefix + innerHTML.__html; } } else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; var childrenToUse = contentToUse != null ? null : props.children; if (contentToUse != null) { return prefix + escapeTextContentForBrowser(contentToUse); } else if (childrenToUse != null) { var mountImages = this.mountChildren( childrenToUse, transaction, context ); return prefix + mountImages.join(''); } } return prefix; }, receiveComponent: function(nextElement, transaction, context) { var prevElement = this._currentElement; this._currentElement = nextElement; this.updateComponent(transaction, prevElement, nextElement, context); }, /** * Updates a native DOM component after it has already been allocated and * attached to the DOM. Reconciles the root DOM node, then recurses. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevElement * @param {ReactElement} nextElement * @internal * @overridable */ updateComponent: function(transaction, prevElement, nextElement, context) { assertValidProps(this._currentElement.props); this._updateDOMProperties(prevElement.props, transaction); this._updateDOMChildren(prevElement.props, transaction, context); }, /** * 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 {ReactReconcileTransaction} transaction */ _updateDOMProperties: function(lastProps, transaction) { var nextProps = this._currentElement.props; var propKey; var styleName; var styleUpdates; for (propKey in lastProps) { if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey)) { continue; } if (propKey === STYLE) { var lastStyle = this._previousStyleCopy; for (styleName in lastStyle) { if (lastStyle.hasOwnProperty(styleName)) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } this._previousStyleCopy = null; } else if (registrationNameModules.hasOwnProperty(propKey)) { deleteListener(this._rootNodeID, propKey); } else if ( DOMProperty.isStandardName[propKey] || DOMProperty.isCustomAttribute(propKey)) { BackendIDOperations.deletePropertyByID( this._rootNodeID, propKey ); } } for (propKey in nextProps) { var nextProp = nextProps[propKey]; var lastProp = propKey === STYLE ? this._previousStyleCopy : lastProps[propKey]; if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp) { continue; } if (propKey === STYLE) { if (nextProp) { 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)) { putListener(this._rootNodeID, propKey, nextProp, transaction); } else if ( DOMProperty.isStandardName[propKey] || DOMProperty.isCustomAttribute(propKey)) { BackendIDOperations.updatePropertyByID( this._rootNodeID, propKey, nextProp ); } } if (styleUpdates) { BackendIDOperations.updateStylesByID( this._rootNodeID, styleUpdates ); } }, /** * Reconciles the children with the various properties that affect the * children content. * * @param {object} lastProps * @param {ReactReconcileTransaction} transaction */ _updateDOMChildren: function(lastProps, transaction, context) { var nextProps = this._currentElement.props; var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null; var nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null; var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html; var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html; // Note the use of `!=` which checks for null or undefined. var lastChildren = lastContent != null ? null : lastProps.children; var nextChildren = nextContent != null ? null : nextProps.children; // If we're switching from children to content/html or vice versa, remove // the old content var lastHasContentOrHtml = lastContent != null || lastHtml != null; var nextHasContentOrHtml = nextContent != null || nextHtml != null; if (lastChildren != null && nextChildren == null) { this.updateChildren(null, transaction, context); } else if (lastHasContentOrHtml && !nextHasContentOrHtml) { this.updateTextContent(''); } if (nextContent != null) { if (lastContent !== nextContent) { this.updateTextContent('' + nextContent); } } else if (nextHtml != null) { if (lastHtml !== nextHtml) { BackendIDOperations.updateInnerHTMLByID( this._rootNodeID, nextHtml ); } } else if (nextChildren != null) { this.updateChildren(nextChildren, transaction, context); } }, /** * Destroys all event registrations for this instance. Does not remove from * the DOM. That must be done by the parent. * * @internal */ unmountComponent: function() { this.unmountChildren(); ReactBrowserEventEmitter.deleteAllListeners(this._rootNodeID); ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID); this._rootNodeID = null; } }; ReactPerf.measureMethods(ReactDOMComponent, 'ReactDOMComponent', { mountComponent: 'mountComponent', updateComponent: 'updateComponent' }); assign( ReactDOMComponent.prototype, ReactDOMComponent.Mixin, ReactMultiChild.Mixin ); ReactDOMComponent.injection = { injectIDOperations: function(IDOperations) { ReactDOMComponent.BackendIDOperations = BackendIDOperations = IDOperations; } }; module.exports = ReactDOMComponent; }).call(this,require('_process')) },{"./CSSPropertyOperations":5,"./DOMProperty":10,"./DOMPropertyOperations":11,"./Object.assign":27,"./ReactBrowserEventEmitter":31,"./ReactComponentBrowserEnvironment":36,"./ReactMount":71,"./ReactMultiChild":72,"./ReactPerf":76,"./escapeTextContentForBrowser":117,"./invariant":136,"./isEventSupported":137,"./keyOf":142,"./warning":155,"_process":1}],44:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMForm */ 'use strict'; var EventConstants = require("./EventConstants"); var LocalEventTrapMixin = require("./LocalEventTrapMixin"); var ReactBrowserComponentMixin = require("./ReactBrowserComponentMixin"); var ReactClass = require("./ReactClass"); var ReactElement = require("./ReactElement"); var form = ReactElement.createFactory('form'); /** * Since onSubmit doesn't bubble OR capture on the top level in IE8, we need * to capture it on the <form> element itself. There are lots of hacks we could * do to accomplish this, but the most reliable is to make <form> a * composite component and use `componentDidMount` to attach the event handlers. */ var ReactDOMForm = ReactClass.createClass({ displayName: 'ReactDOMForm', tagName: 'FORM', mixins: [ReactBrowserComponentMixin, LocalEventTrapMixin], render: function() { // TODO: Instead of using `ReactDOM` directly, we should use JSX. However, // `jshint` fails to parse JSX so in order for linting to work in the open // source repo, we need to just use `ReactDOM.form`. return form(this.props); }, componentDidMount: function() { this.trapBubbledEvent(EventConstants.topLevelTypes.topReset, 'reset'); this.trapBubbledEvent(EventConstants.topLevelTypes.topSubmit, 'submit'); } }); module.exports = ReactDOMForm; },{"./EventConstants":15,"./LocalEventTrapMixin":25,"./ReactBrowserComponentMixin":30,"./ReactClass":34,"./ReactElement":58}],45:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMIDOperations * @typechecks static-only */ /*jslint evil: true */ 'use strict'; var CSSPropertyOperations = require("./CSSPropertyOperations"); var DOMChildrenOperations = require("./DOMChildrenOperations"); var DOMPropertyOperations = require("./DOMPropertyOperations"); var ReactMount = require("./ReactMount"); var ReactPerf = require("./ReactPerf"); var invariant = require("./invariant"); var setInnerHTML = require("./setInnerHTML"); /** * Errors for properties that should not be updated with `updatePropertyById()`. * * @type {object} * @private */ var INVALID_PROPERTY_ERRORS = { dangerouslySetInnerHTML: '`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.', style: '`style` must be set using `updateStylesByID()`.' }; /** * Operations used to process updates to DOM nodes. This is made injectable via * `ReactDOMComponent.BackendIDOperations`. */ var ReactDOMIDOperations = { /** * Updates a DOM node with new property values. This should only be used to * update DOM properties in `DOMProperty`. * * @param {string} id ID of the node to update. * @param {string} name A valid property name, see `DOMProperty`. * @param {*} value New value of the property. * @internal */ updatePropertyByID: function(id, name, value) { var node = ReactMount.getNode(id); ("production" !== process.env.NODE_ENV ? invariant( !INVALID_PROPERTY_ERRORS.hasOwnProperty(name), 'updatePropertyByID(...): %s', INVALID_PROPERTY_ERRORS[name] ) : invariant(!INVALID_PROPERTY_ERRORS.hasOwnProperty(name))); // If we're updating to null or undefined, we should remove the property // from the DOM node instead of inadvertantly setting to a string. This // brings us in line with the same behavior we have on initial render. if (value != null) { DOMPropertyOperations.setValueForProperty(node, name, value); } else { DOMPropertyOperations.deleteValueForProperty(node, name); } }, /** * Updates a DOM node to remove a property. This should only be used to remove * DOM properties in `DOMProperty`. * * @param {string} id ID of the node to update. * @param {string} name A property name to remove, see `DOMProperty`. * @internal */ deletePropertyByID: function(id, name, value) { var node = ReactMount.getNode(id); ("production" !== process.env.NODE_ENV ? invariant( !INVALID_PROPERTY_ERRORS.hasOwnProperty(name), 'updatePropertyByID(...): %s', INVALID_PROPERTY_ERRORS[name] ) : invariant(!INVALID_PROPERTY_ERRORS.hasOwnProperty(name))); DOMPropertyOperations.deleteValueForProperty(node, name, value); }, /** * Updates a DOM node with new style values. If a value is specified as '', * the corresponding style property will be unset. * * @param {string} id ID of the node to update. * @param {object} styles Mapping from styles to values. * @internal */ updateStylesByID: function(id, styles) { var node = ReactMount.getNode(id); CSSPropertyOperations.setValueForStyles(node, styles); }, /** * Updates a DOM node's innerHTML. * * @param {string} id ID of the node to update. * @param {string} html An HTML string. * @internal */ updateInnerHTMLByID: function(id, html) { var node = ReactMount.getNode(id); setInnerHTML(node, html); }, /** * Updates a DOM node's text content set by `props.content`. * * @param {string} id ID of the node to update. * @param {string} content Text content. * @internal */ updateTextContentByID: function(id, content) { var node = ReactMount.getNode(id); DOMChildrenOperations.updateTextContent(node, content); }, /** * Replaces a DOM node that exists in the document with markup. * * @param {string} id ID of child to be replaced. * @param {string} markup Dangerous markup to inject in place of child. * @internal * @see {Danger.dangerouslyReplaceNodeWithMarkup} */ dangerouslyReplaceNodeWithMarkupByID: function(id, markup) { var node = ReactMount.getNode(id); DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup(node, markup); }, /** * Updates a component's children by processing a series of updates. * * @param {array<object>} updates List of update configurations. * @param {array<string>} markup List of markup strings. * @internal */ dangerouslyProcessChildrenUpdates: function(updates, markup) { for (var i = 0; i < updates.length; i++) { updates[i].parentNode = ReactMount.getNode(updates[i].parentID); } DOMChildrenOperations.processUpdates(updates, markup); } }; ReactPerf.measureMethods(ReactDOMIDOperations, 'ReactDOMIDOperations', { updatePropertyByID: 'updatePropertyByID', deletePropertyByID: 'deletePropertyByID', updateStylesByID: 'updateStylesByID', updateInnerHTMLByID: 'updateInnerHTMLByID', updateTextContentByID: 'updateTextContentByID', dangerouslyReplaceNodeWithMarkupByID: 'dangerouslyReplaceNodeWithMarkupByID', dangerouslyProcessChildrenUpdates: 'dangerouslyProcessChildrenUpdates' }); module.exports = ReactDOMIDOperations; }).call(this,require('_process')) },{"./CSSPropertyOperations":5,"./DOMChildrenOperations":9,"./DOMPropertyOperations":11,"./ReactMount":71,"./ReactPerf":76,"./invariant":136,"./setInnerHTML":149,"_process":1}],46:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMIframe */ 'use strict'; var EventConstants = require("./EventConstants"); var LocalEventTrapMixin = require("./LocalEventTrapMixin"); var ReactBrowserComponentMixin = require("./ReactBrowserComponentMixin"); var ReactClass = require("./ReactClass"); var ReactElement = require("./ReactElement"); var iframe = ReactElement.createFactory('iframe'); /** * Since onLoad doesn't bubble OR capture on the top level in IE8, we need to * capture it on the <iframe> element itself. There are lots of hacks we could * do to accomplish this, but the most reliable is to make <iframe> a composite * component and use `componentDidMount` to attach the event handlers. */ var ReactDOMIframe = ReactClass.createClass({ displayName: 'ReactDOMIframe', tagName: 'IFRAME', mixins: [ReactBrowserComponentMixin, LocalEventTrapMixin], render: function() { return iframe(this.props); }, componentDidMount: function() { this.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load'); } }); module.exports = ReactDOMIframe; },{"./EventConstants":15,"./LocalEventTrapMixin":25,"./ReactBrowserComponentMixin":30,"./ReactClass":34,"./ReactElement":58}],47:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMImg */ 'use strict'; var EventConstants = require("./EventConstants"); var LocalEventTrapMixin = require("./LocalEventTrapMixin"); var ReactBrowserComponentMixin = require("./ReactBrowserComponentMixin"); var ReactClass = require("./ReactClass"); var ReactElement = require("./ReactElement"); var img = ReactElement.createFactory('img'); /** * Since onLoad doesn't bubble OR capture on the top level in IE8, we need to * capture it on the <img> element itself. There are lots of hacks we could do * to accomplish this, but the most reliable is to make <img> a composite * component and use `componentDidMount` to attach the event handlers. */ var ReactDOMImg = ReactClass.createClass({ displayName: 'ReactDOMImg', tagName: 'IMG', mixins: [ReactBrowserComponentMixin, LocalEventTrapMixin], render: function() { return img(this.props); }, componentDidMount: function() { this.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load'); this.trapBubbledEvent(EventConstants.topLevelTypes.topError, 'error'); } }); module.exports = ReactDOMImg; },{"./EventConstants":15,"./LocalEventTrapMixin":25,"./ReactBrowserComponentMixin":30,"./ReactClass":34,"./ReactElement":58}],48:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMInput */ 'use strict'; var AutoFocusMixin = require("./AutoFocusMixin"); var DOMPropertyOperations = require("./DOMPropertyOperations"); var LinkedValueUtils = require("./LinkedValueUtils"); var ReactBrowserComponentMixin = require("./ReactBrowserComponentMixin"); var ReactClass = require("./ReactClass"); var ReactElement = require("./ReactElement"); var ReactMount = require("./ReactMount"); var ReactUpdates = require("./ReactUpdates"); var assign = require("./Object.assign"); var invariant = require("./invariant"); var input = ReactElement.createFactory('input'); var instancesByReactID = {}; function forceUpdateIfMounted() { /*jshint validthis:true */ if (this.isMounted()) { this.forceUpdate(); } } /** * Implements an <input> native component that allows setting these optional * props: `checked`, `value`, `defaultChecked`, and `defaultValue`. * * If `checked` or `value` are not supplied (or null/undefined), user actions * that affect the checked state or value will trigger updates to the element. * * If they are supplied (and not null/undefined), the rendered element will not * trigger updates to the element. Instead, the props must change in order for * the rendered element to be updated. * * The rendered element will be initialized as unchecked (or `defaultChecked`) * with an empty value (or `defaultValue`). * * @see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html */ var ReactDOMInput = ReactClass.createClass({ displayName: 'ReactDOMInput', tagName: 'INPUT', mixins: [AutoFocusMixin, LinkedValueUtils.Mixin, ReactBrowserComponentMixin], getInitialState: function() { var defaultValue = this.props.defaultValue; return { initialChecked: this.props.defaultChecked || false, initialValue: defaultValue != null ? defaultValue : null }; }, render: function() { // Clone `this.props` so we don't mutate the input. var props = assign({}, this.props); props.defaultChecked = null; props.defaultValue = null; var value = LinkedValueUtils.getValue(this); props.value = value != null ? value : this.state.initialValue; var checked = LinkedValueUtils.getChecked(this); props.checked = checked != null ? checked : this.state.initialChecked; props.onChange = this._handleChange; return input(props, this.props.children); }, componentDidMount: function() { var id = ReactMount.getID(this.getDOMNode()); instancesByReactID[id] = this; }, componentWillUnmount: function() { var rootNode = this.getDOMNode(); var id = ReactMount.getID(rootNode); delete instancesByReactID[id]; }, componentDidUpdate: function(prevProps, prevState, prevContext) { var rootNode = this.getDOMNode(); if (this.props.checked != null) { DOMPropertyOperations.setValueForProperty( rootNode, 'checked', this.props.checked || false ); } var value = LinkedValueUtils.getValue(this); 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. DOMPropertyOperations.setValueForProperty(rootNode, 'value', '' + value); } }, _handleChange: function(event) { var returnValue; var onChange = LinkedValueUtils.getOnChange(this); if (onChange) { returnValue = onChange.call(this, 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 = this.props.name; if (this.props.type === 'radio' && name != null) { var rootNode = this.getDOMNode(); 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, groupLen = group.length; i < groupLen; i++) { var otherNode = group[i]; if (otherNode === rootNode || otherNode.form !== rootNode.form) { continue; } var otherID = ReactMount.getID(otherNode); ("production" !== process.env.NODE_ENV ? invariant( otherID, 'ReactDOMInput: Mixing React and non-React radio inputs with the ' + 'same `name` is not supported.' ) : invariant(otherID)); var otherInstance = instancesByReactID[otherID]; ("production" !== process.env.NODE_ENV ? invariant( otherInstance, 'ReactDOMInput: Unknown radio button ID %s.', otherID ) : invariant(otherInstance)); // 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; }).call(this,require('_process')) },{"./AutoFocusMixin":2,"./DOMPropertyOperations":11,"./LinkedValueUtils":24,"./Object.assign":27,"./ReactBrowserComponentMixin":30,"./ReactClass":34,"./ReactElement":58,"./ReactMount":71,"./ReactUpdates":88,"./invariant":136,"_process":1}],49:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMOption */ 'use strict'; var ReactBrowserComponentMixin = require("./ReactBrowserComponentMixin"); var ReactClass = require("./ReactClass"); var ReactElement = require("./ReactElement"); var warning = require("./warning"); var option = ReactElement.createFactory('option'); /** * Implements an <option> native component that warns when `selected` is set. */ var ReactDOMOption = ReactClass.createClass({ displayName: 'ReactDOMOption', tagName: 'OPTION', mixins: [ReactBrowserComponentMixin], componentWillMount: function() { // TODO (yungsters): Remove support for `selected` in <option>. if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( this.props.selected == null, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.' ) : null); } }, render: function() { return option(this.props, this.props.children); } }); module.exports = ReactDOMOption; }).call(this,require('_process')) },{"./ReactBrowserComponentMixin":30,"./ReactClass":34,"./ReactElement":58,"./warning":155,"_process":1}],50:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMSelect */ 'use strict'; var AutoFocusMixin = require("./AutoFocusMixin"); var LinkedValueUtils = require("./LinkedValueUtils"); var ReactBrowserComponentMixin = require("./ReactBrowserComponentMixin"); var ReactClass = require("./ReactClass"); var ReactElement = require("./ReactElement"); var ReactUpdates = require("./ReactUpdates"); var assign = require("./Object.assign"); var select = ReactElement.createFactory('select'); function updateOptionsIfPendingUpdateAndMounted() { /*jshint validthis:true */ if (this._pendingUpdate) { this._pendingUpdate = false; var value = LinkedValueUtils.getValue(this); if (value != null && this.isMounted()) { updateOptions(this, value); } } } /** * Validation function for `value` and `defaultValue`. * @private */ function selectValueType(props, propName, componentName) { if (props[propName] == null) { return null; } if (props.multiple) { if (!Array.isArray(props[propName])) { return new Error( ("The `" + propName + "` prop supplied to <select> must be an array if ") + ("`multiple` is true.") ); } } else { if (Array.isArray(props[propName])) { return new Error( ("The `" + propName + "` prop supplied to <select> must be a scalar ") + ("value if `multiple` is false.") ); } } } /** * @param {ReactComponent} component Instance of ReactDOMSelect * @param {*} propValue A stringable (with `multiple`, a list of stringables). * @private */ function updateOptions(component, propValue) { var selectedValue, i, l; var options = component.getDOMNode().options; if (component.props.multiple) { selectedValue = {}; for (i = 0, l = propValue.length; i < l; i++) { selectedValue['' + propValue[i]] = true; } for (i = 0, l = options.length; i < l; 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, l = options.length; i < l; i++) { if (options[i].value === selectedValue) { options[i].selected = true; return; } } if (options.length) { options[0].selected = true; } } } /** * Implements a <select> native component that allows optionally setting the * props `value` and `defaultValue`. If `multiple` is false, the prop must be a * stringable. If `multiple` is true, the prop must be an array of stringables. * * If `value` is not supplied (or null/undefined), user actions that change the * selected option will trigger updates to the rendered options. * * If it is supplied (and not null/undefined), the rendered options will not * update in response to user actions. Instead, the `value` prop must change in * order for the rendered options to update. * * If `defaultValue` is provided, any options with the supplied values will be * selected. */ var ReactDOMSelect = ReactClass.createClass({ displayName: 'ReactDOMSelect', tagName: 'SELECT', mixins: [AutoFocusMixin, LinkedValueUtils.Mixin, ReactBrowserComponentMixin], propTypes: { defaultValue: selectValueType, value: selectValueType }, render: function() { // Clone `this.props` so we don't mutate the input. var props = assign({}, this.props); props.onChange = this._handleChange; props.value = null; return select(props, this.props.children); }, componentWillMount: function() { this._pendingUpdate = false; }, componentDidMount: function() { var value = LinkedValueUtils.getValue(this); if (value != null) { updateOptions(this, value); } else if (this.props.defaultValue != null) { updateOptions(this, this.props.defaultValue); } }, componentDidUpdate: function(prevProps) { var value = LinkedValueUtils.getValue(this); if (value != null) { this._pendingUpdate = false; updateOptions(this, value); } else if (!prevProps.multiple !== !this.props.multiple) { // For simplicity, reapply `defaultValue` if `multiple` is toggled. if (this.props.defaultValue != null) { updateOptions(this, this.props.defaultValue); } else { // Revert the select back to its default unselected state. updateOptions(this, this.props.multiple ? [] : ''); } } }, _handleChange: function(event) { var returnValue; var onChange = LinkedValueUtils.getOnChange(this); if (onChange) { returnValue = onChange.call(this, event); } this._pendingUpdate = true; ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this); return returnValue; } }); module.exports = ReactDOMSelect; },{"./AutoFocusMixin":2,"./LinkedValueUtils":24,"./Object.assign":27,"./ReactBrowserComponentMixin":30,"./ReactClass":34,"./ReactElement":58,"./ReactUpdates":88}],51:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMSelection */ 'use strict'; var ExecutionEnvironment = require("./ExecutionEnvironment"); var getNodeForCharacterOffset = require("./getNodeForCharacterOffset"); var getTextContentAccessor = require("./getTextContentAccessor"); /** * 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); // If the node and offset values are the same, the selection is collapsed. // `Selection.isCollapsed` is available natively, but IE sometimes gets // this value wrong. var isSelectionCollapsed = isCollapsed( selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset ); var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length; var tempRange = currentRange.cloneRange(); tempRange.selectNodeContents(node); tempRange.setEnd(currentRange.startContainer, currentRange.startOffset); var isTempRangeCollapsed = isCollapsed( tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset ); var start = isTempRangeCollapsed ? 0 : tempRange.toString().length; var end = start + rangeLength; // Detect whether the selection is backward. var detectionRange = document.createRange(); detectionRange.setStart(anchorNode, anchorOffset); detectionRange.setEnd(focusNode, focusOffset); var isBackward = detectionRange.collapsed; return { start: isBackward ? end : start, end: isBackward ? start : end }; } /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setIEOffsets(node, offsets) { var range = document.selection.createRange().duplicate(); var start, end; if (typeof offsets.end === 'undefined') { start = offsets.start; end = start; } else if (offsets.start > offsets.end) { start = offsets.end; end = offsets.start; } else { start = offsets.start; end = offsets.end; } range.moveToElementText(node); range.moveStart('character', start); range.setEndPoint('EndToStart', range); range.moveEnd('character', end - start); range.select(); } /** * In modern non-IE browsers, we can support both forward and backward * selections. * * Note: IE10+ supports the Selection object, but it does not support * the `extend` method, which means that even in modern IE, it's not possible * to programatically create a backward selection. Thus, for all IE * versions, we use the old IE API to create our selections. * * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setModernOffsets(node, offsets) { if (!window.getSelection) { return; } var selection = window.getSelection(); var length = node[getTextContentAccessor()].length; var start = Math.min(offsets.start, length); var end = typeof offsets.end === 'undefined' ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method. // Flip backward selections, so we can set with a single range. if (!selection.extend && start > end) { var temp = end; end = start; start = temp; } var startMarker = getNodeForCharacterOffset(node, start); var endMarker = getNodeForCharacterOffset(node, end); if (startMarker && endMarker) { var range = document.createRange(); range.setStart(startMarker.node, startMarker.offset); selection.removeAllRanges(); if (start > end) { selection.addRange(range); selection.extend(endMarker.node, endMarker.offset); } else { range.setEnd(endMarker.node, endMarker.offset); selection.addRange(range); } } } var useIEOffsets = ( ExecutionEnvironment.canUseDOM && 'selection' in document && !('getSelection' in window) ); var ReactDOMSelection = { /** * @param {DOMElement} node */ getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets, /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets }; module.exports = ReactDOMSelection; },{"./ExecutionEnvironment":21,"./getNodeForCharacterOffset":129,"./getTextContentAccessor":131}],52:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMTextComponent * @typechecks static-only */ 'use strict'; var DOMPropertyOperations = require("./DOMPropertyOperations"); var ReactComponentBrowserEnvironment = require("./ReactComponentBrowserEnvironment"); var ReactDOMComponent = require("./ReactDOMComponent"); var assign = require("./Object.assign"); var escapeTextContentForBrowser = require("./escapeTextContentForBrowser"); /** * Text nodes violate a couple assumptions that React makes about components: * * - When mounting text into the DOM, adjacent text nodes are merged. * - Text nodes cannot be assigned a React root ID. * * This component is used to wrap strings in elements so that they can undergo * the same reconciliation that is applied to elements. * * TODO: Investigate representing React components in the DOM with text nodes. * * @class ReactDOMTextComponent * @extends ReactComponent * @internal */ var ReactDOMTextComponent = function(props) { // This constructor and its argument is currently used by mocks. }; assign(ReactDOMTextComponent.prototype, { /** * @param {ReactText} text * @internal */ construct: function(text) { // TODO: This is really a ReactText (ReactNode), not a ReactElement this._currentElement = text; this._stringText = '' + text; // Properties this._rootNodeID = null; this._mountIndex = 0; }, /** * Creates the markup for this text node. This node is not intended to have * any features besides containing text content. * * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {string} Markup for this text node. * @internal */ mountComponent: function(rootID, transaction, context) { this._rootNodeID = rootID; var escapedText = escapeTextContentForBrowser(this._stringText); if (transaction.renderToStaticMarkup) { // Normally we'd wrap this in a `span` for the reasons stated above, but // since this is a situation where React won't take over (static pages), // we can simply return the text as it is. return escapedText; } return ( '<span ' + DOMPropertyOperations.createMarkupForID(rootID) + '>' + escapedText + '</span>' ); }, /** * Updates this component by updating the text content. * * @param {ReactText} nextText The next text content * @param {ReactReconcileTransaction} transaction * @internal */ receiveComponent: function(nextText, transaction) { if (nextText !== this._currentElement) { this._currentElement = nextText; var nextStringText = '' + nextText; if (nextStringText !== this._stringText) { // TODO: Save this as pending props and use performUpdateIfNecessary // and/or updateComponent to do the actual update for consistency with // other component types? this._stringText = nextStringText; ReactDOMComponent.BackendIDOperations.updateTextContentByID( this._rootNodeID, nextStringText ); } } }, unmountComponent: function() { ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID); } }); module.exports = ReactDOMTextComponent; },{"./DOMPropertyOperations":11,"./Object.assign":27,"./ReactComponentBrowserEnvironment":36,"./ReactDOMComponent":43,"./escapeTextContentForBrowser":117}],53:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMTextarea */ 'use strict'; var AutoFocusMixin = require("./AutoFocusMixin"); var DOMPropertyOperations = require("./DOMPropertyOperations"); var LinkedValueUtils = require("./LinkedValueUtils"); var ReactBrowserComponentMixin = require("./ReactBrowserComponentMixin"); var ReactClass = require("./ReactClass"); var ReactElement = require("./ReactElement"); var ReactUpdates = require("./ReactUpdates"); var assign = require("./Object.assign"); var invariant = require("./invariant"); var warning = require("./warning"); var textarea = ReactElement.createFactory('textarea'); function forceUpdateIfMounted() { /*jshint validthis:true */ if (this.isMounted()) { this.forceUpdate(); } } /** * Implements a <textarea> native component that allows setting `value`, and * `defaultValue`. This differs from the traditional DOM API because value is * usually set as PCDATA children. * * If `value` is not supplied (or null/undefined), user actions that affect the * value will trigger updates to the element. * * If `value` is supplied (and not null/undefined), the rendered element will * not trigger updates to the element. Instead, the `value` prop must change in * order for the rendered element to be updated. * * The rendered element will be initialized with an empty value, the prop * `defaultValue` if specified, or the children content (deprecated). */ var ReactDOMTextarea = ReactClass.createClass({ displayName: 'ReactDOMTextarea', tagName: 'TEXTAREA', mixins: [AutoFocusMixin, LinkedValueUtils.Mixin, ReactBrowserComponentMixin], getInitialState: function() { var defaultValue = this.props.defaultValue; // TODO (yungsters): Remove support for children content in <textarea>. var children = this.props.children; if (children != null) { if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.' ) : null); } ("production" !== process.env.NODE_ENV ? invariant( defaultValue == null, 'If you supply `defaultValue` on a <textarea>, do not pass children.' ) : invariant(defaultValue == null)); if (Array.isArray(children)) { ("production" !== process.env.NODE_ENV ? invariant( children.length <= 1, '<textarea> can only have at most one child.' ) : invariant(children.length <= 1)); children = children[0]; } defaultValue = '' + children; } if (defaultValue == null) { defaultValue = ''; } var value = LinkedValueUtils.getValue(this); return { // We save the initial value so that `ReactDOMComponent` doesn't update // `textContent` (unnecessary since we update value). // The initial value can be a boolean or object so that's why it's // forced to be a string. initialValue: '' + (value != null ? value : defaultValue) }; }, render: function() { // Clone `this.props` so we don't mutate the input. var props = assign({}, this.props); ("production" !== process.env.NODE_ENV ? invariant( props.dangerouslySetInnerHTML == null, '`dangerouslySetInnerHTML` does not make sense on <textarea>.' ) : invariant(props.dangerouslySetInnerHTML == null)); props.defaultValue = null; props.value = null; props.onChange = this._handleChange; // Always set children to the same thing. In IE9, the selection range will // get reset if `textContent` is mutated. return textarea(props, this.state.initialValue); }, componentDidUpdate: function(prevProps, prevState, prevContext) { var value = LinkedValueUtils.getValue(this); if (value != null) { var rootNode = this.getDOMNode(); // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. DOMPropertyOperations.setValueForProperty(rootNode, 'value', '' + value); } }, _handleChange: function(event) { var returnValue; var onChange = LinkedValueUtils.getOnChange(this); if (onChange) { returnValue = onChange.call(this, event); } ReactUpdates.asap(forceUpdateIfMounted, this); return returnValue; } }); module.exports = ReactDOMTextarea; }).call(this,require('_process')) },{"./AutoFocusMixin":2,"./DOMPropertyOperations":11,"./LinkedValueUtils":24,"./Object.assign":27,"./ReactBrowserComponentMixin":30,"./ReactClass":34,"./ReactElement":58,"./ReactUpdates":88,"./invariant":136,"./warning":155,"_process":1}],54:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultBatchingStrategy */ 'use strict'; var ReactUpdates = require("./ReactUpdates"); var Transaction = require("./Transaction"); var assign = require("./Object.assign"); var emptyFunction = require("./emptyFunction"); 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) { var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; ReactDefaultBatchingStrategy.isBatchingUpdates = true; // The code is written this way to avoid extra allocations if (alreadyBatchingUpdates) { callback(a, b, c, d); } else { transaction.perform(callback, null, a, b, c, d); } } }; module.exports = ReactDefaultBatchingStrategy; },{"./Object.assign":27,"./ReactUpdates":88,"./Transaction":104,"./emptyFunction":115}],55:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultInjection */ 'use strict'; var BeforeInputEventPlugin = require("./BeforeInputEventPlugin"); var ChangeEventPlugin = require("./ChangeEventPlugin"); var ClientReactRootIndex = require("./ClientReactRootIndex"); var DefaultEventPluginOrder = require("./DefaultEventPluginOrder"); var EnterLeaveEventPlugin = require("./EnterLeaveEventPlugin"); var ExecutionEnvironment = require("./ExecutionEnvironment"); var HTMLDOMPropertyConfig = require("./HTMLDOMPropertyConfig"); var MobileSafariClickEventPlugin = require("./MobileSafariClickEventPlugin"); var ReactBrowserComponentMixin = require("./ReactBrowserComponentMixin"); var ReactClass = require("./ReactClass"); var ReactComponentBrowserEnvironment = require("./ReactComponentBrowserEnvironment"); var ReactDefaultBatchingStrategy = require("./ReactDefaultBatchingStrategy"); var ReactDOMComponent = require("./ReactDOMComponent"); var ReactDOMButton = require("./ReactDOMButton"); var ReactDOMForm = require("./ReactDOMForm"); var ReactDOMImg = require("./ReactDOMImg"); var ReactDOMIDOperations = require("./ReactDOMIDOperations"); var ReactDOMIframe = require("./ReactDOMIframe"); var ReactDOMInput = require("./ReactDOMInput"); var ReactDOMOption = require("./ReactDOMOption"); var ReactDOMSelect = require("./ReactDOMSelect"); var ReactDOMTextarea = require("./ReactDOMTextarea"); var ReactDOMTextComponent = require("./ReactDOMTextComponent"); var ReactElement = require("./ReactElement"); var ReactEventListener = require("./ReactEventListener"); var ReactInjection = require("./ReactInjection"); var ReactInstanceHandles = require("./ReactInstanceHandles"); var ReactMount = require("./ReactMount"); var ReactReconcileTransaction = require("./ReactReconcileTransaction"); var SelectEventPlugin = require("./SelectEventPlugin"); var ServerReactRootIndex = require("./ServerReactRootIndex"); var SimpleEventPlugin = require("./SimpleEventPlugin"); var SVGDOMPropertyConfig = require("./SVGDOMPropertyConfig"); var createFullPageComponent = require("./createFullPageComponent"); function autoGenerateWrapperClass(type) { return ReactClass.createClass({ tagName: type.toUpperCase(), render: function() { return new ReactElement( type, null, null, null, null, this.props ); } }); } function inject() { ReactInjection.EventEmitter.injectReactEventListener( ReactEventListener ); /** * Inject modules for resolving DOM hierarchy and plugin ordering. */ ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder); ReactInjection.EventPluginHub.injectInstanceHandle(ReactInstanceHandles); ReactInjection.EventPluginHub.injectMount(ReactMount); /** * Some important event plugins included by default (without having to require * them). */ ReactInjection.EventPluginHub.injectEventPluginsByName({ SimpleEventPlugin: SimpleEventPlugin, EnterLeaveEventPlugin: EnterLeaveEventPlugin, ChangeEventPlugin: ChangeEventPlugin, MobileSafariClickEventPlugin: MobileSafariClickEventPlugin, SelectEventPlugin: SelectEventPlugin, BeforeInputEventPlugin: BeforeInputEventPlugin }); ReactInjection.NativeComponent.injectGenericComponentClass( ReactDOMComponent ); ReactInjection.NativeComponent.injectTextComponentClass( ReactDOMTextComponent ); ReactInjection.NativeComponent.injectAutoWrapper( autoGenerateWrapperClass ); // This needs to happen before createFullPageComponent() otherwise the mixin // won't be included. ReactInjection.Class.injectMixin(ReactBrowserComponentMixin); ReactInjection.NativeComponent.injectComponentClasses({ 'button': ReactDOMButton, 'form': ReactDOMForm, 'iframe': ReactDOMIframe, 'img': ReactDOMImg, 'input': ReactDOMInput, 'option': ReactDOMOption, 'select': ReactDOMSelect, 'textarea': ReactDOMTextarea, 'html': createFullPageComponent('html'), 'head': createFullPageComponent('head'), 'body': createFullPageComponent('body') }); ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig); ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig); ReactInjection.EmptyComponent.injectEmptyComponent('noscript'); ReactInjection.Updates.injectReconcileTransaction( ReactReconcileTransaction ); ReactInjection.Updates.injectBatchingStrategy( ReactDefaultBatchingStrategy ); ReactInjection.RootIndex.injectCreateReactRootIndex( ExecutionEnvironment.canUseDOM ? ClientReactRootIndex.createReactRootIndex : ServerReactRootIndex.createReactRootIndex ); ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment); ReactInjection.DOMComponent.injectIDOperations(ReactDOMIDOperations); if ("production" !== process.env.NODE_ENV) { var url = (ExecutionEnvironment.canUseDOM && window.location.href) || ''; if ((/[?&]react_perf\b/).test(url)) { var ReactDefaultPerf = require("./ReactDefaultPerf"); ReactDefaultPerf.start(); } } } module.exports = { inject: inject }; }).call(this,require('_process')) },{"./BeforeInputEventPlugin":3,"./ChangeEventPlugin":7,"./ClientReactRootIndex":8,"./DefaultEventPluginOrder":13,"./EnterLeaveEventPlugin":14,"./ExecutionEnvironment":21,"./HTMLDOMPropertyConfig":23,"./MobileSafariClickEventPlugin":26,"./ReactBrowserComponentMixin":30,"./ReactClass":34,"./ReactComponentBrowserEnvironment":36,"./ReactDOMButton":42,"./ReactDOMComponent":43,"./ReactDOMForm":44,"./ReactDOMIDOperations":45,"./ReactDOMIframe":46,"./ReactDOMImg":47,"./ReactDOMInput":48,"./ReactDOMOption":49,"./ReactDOMSelect":50,"./ReactDOMTextComponent":52,"./ReactDOMTextarea":53,"./ReactDefaultBatchingStrategy":54,"./ReactDefaultPerf":56,"./ReactElement":58,"./ReactEventListener":63,"./ReactInjection":65,"./ReactInstanceHandles":67,"./ReactMount":71,"./ReactReconcileTransaction":81,"./SVGDOMPropertyConfig":89,"./SelectEventPlugin":90,"./ServerReactRootIndex":91,"./SimpleEventPlugin":92,"./createFullPageComponent":112,"_process":1}],56:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultPerf * @typechecks static-only */ 'use strict'; var DOMProperty = require("./DOMProperty"); var ReactDefaultPerfAnalysis = require("./ReactDefaultPerfAnalysis"); var ReactMount = require("./ReactMount"); var ReactPerf = require("./ReactPerf"); var performanceNow = require("./performanceNow"); function roundFloat(val) { return Math.floor(val * 100) / 100; } function addValue(obj, key, val) { obj[key] = (obj[key] || 0) + val; } var ReactDefaultPerf = { _allMeasurements: [], // last item in the list is the current one _mountStack: [0], _injected: false, start: function() { if (!ReactDefaultPerf._injected) { ReactPerf.injection.injectMeasure(ReactDefaultPerf.measure); } ReactDefaultPerf._allMeasurements.length = 0; ReactPerf.enableMeasure = true; }, stop: function() { ReactPerf.enableMeasure = false; }, getLastMeasurements: function() { return ReactDefaultPerf._allMeasurements; }, printExclusive: function(measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; var summary = ReactDefaultPerfAnalysis.getExclusiveSummary(measurements); console.table(summary.map(function(item) { return { 'Component class name': item.componentName, 'Total inclusive time (ms)': roundFloat(item.inclusive), 'Exclusive mount time (ms)': roundFloat(item.exclusive), 'Exclusive render time (ms)': roundFloat(item.render), 'Mount time per instance (ms)': roundFloat(item.exclusive / item.count), 'Render time per instance (ms)': roundFloat(item.render / item.count), 'Instances': item.count }; })); // TODO: ReactDefaultPerfAnalysis.getTotalTime() does not return the correct // number. }, printInclusive: function(measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements); console.table(summary.map(function(item) { return { 'Owner > component': item.componentName, 'Inclusive time (ms)': roundFloat(item.time), 'Instances': item.count }; })); console.log( 'Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms' ); }, getMeasurementsSummaryMap: function(measurements) { var summary = ReactDefaultPerfAnalysis.getInclusiveSummary( measurements, true ); return summary.map(function(item) { return { 'Owner > component': item.componentName, 'Wasted time (ms)': item.time, 'Instances': item.count }; }); }, printWasted: function(measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; console.table(ReactDefaultPerf.getMeasurementsSummaryMap(measurements)); console.log( 'Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms' ); }, printDOM: function(measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; var summary = ReactDefaultPerfAnalysis.getDOMSummary(measurements); console.table(summary.map(function(item) { var result = {}; result[DOMProperty.ID_ATTRIBUTE_NAME] = item.id; result['type'] = item.type; result['args'] = JSON.stringify(item.args); return result; })); console.log( 'Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms' ); }, _recordWrite: function(id, fnName, totalTime, args) { // TODO: totalTime isn't that useful since it doesn't count paints/reflows var writes = ReactDefaultPerf ._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1] .writes; writes[id] = writes[id] || []; writes[id].push({ type: fnName, time: totalTime, args: args }); }, measure: function(moduleName, fnName, func) { return function() {for (var args=[],$__0=0,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]); var totalTime; var rv; var start; if (fnName === '_renderNewRootComponent' || fnName === 'flushBatchedUpdates') { // A "measurement" is a set of metrics recorded for each flush. We want // to group the metrics for a given flush together so we can look at the // components that rendered and the DOM operations that actually // happened to determine the amount of "wasted work" performed. ReactDefaultPerf._allMeasurements.push({ exclusive: {}, inclusive: {}, render: {}, counts: {}, writes: {}, displayNames: {}, totalTime: 0 }); start = performanceNow(); rv = func.apply(this, args); ReactDefaultPerf._allMeasurements[ ReactDefaultPerf._allMeasurements.length - 1 ].totalTime = performanceNow() - start; return rv; } else if (fnName === '_mountImageIntoNode' || moduleName === 'ReactDOMIDOperations') { start = performanceNow(); rv = func.apply(this, args); totalTime = performanceNow() - start; if (fnName === '_mountImageIntoNode') { var mountID = ReactMount.getID(args[1]); ReactDefaultPerf._recordWrite(mountID, fnName, totalTime, args[0]); } else if (fnName === 'dangerouslyProcessChildrenUpdates') { // special format args[0].forEach(function(update) { var writeArgs = {}; if (update.fromIndex !== null) { writeArgs.fromIndex = update.fromIndex; } if (update.toIndex !== null) { writeArgs.toIndex = update.toIndex; } if (update.textContent !== null) { writeArgs.textContent = update.textContent; } if (update.markupIndex !== null) { writeArgs.markup = args[1][update.markupIndex]; } ReactDefaultPerf._recordWrite( update.parentID, update.type, totalTime, writeArgs ); }); } else { // basic format ReactDefaultPerf._recordWrite( args[0], fnName, totalTime, Array.prototype.slice.call(args, 1) ); } return rv; } else if (moduleName === 'ReactCompositeComponent' && ( (// TODO: receiveComponent()? (fnName === 'mountComponent' || fnName === 'updateComponent' || fnName === '_renderValidatedComponent')))) { if (typeof this._currentElement.type === 'string') { return func.apply(this, args); } var rootNodeID = fnName === 'mountComponent' ? args[0] : this._rootNodeID; var isRender = fnName === '_renderValidatedComponent'; var isMount = fnName === 'mountComponent'; var mountStack = ReactDefaultPerf._mountStack; var entry = ReactDefaultPerf._allMeasurements[ ReactDefaultPerf._allMeasurements.length - 1 ]; if (isRender) { addValue(entry.counts, rootNodeID, 1); } else if (isMount) { mountStack.push(0); } start = performanceNow(); rv = func.apply(this, args); totalTime = performanceNow() - start; if (isRender) { addValue(entry.render, rootNodeID, totalTime); } else if (isMount) { var subMountTime = mountStack.pop(); mountStack[mountStack.length - 1] += totalTime; addValue(entry.exclusive, rootNodeID, totalTime - subMountTime); addValue(entry.inclusive, rootNodeID, totalTime); } else { addValue(entry.inclusive, rootNodeID, totalTime); } entry.displayNames[rootNodeID] = { current: this.getName(), owner: this._currentElement._owner ? this._currentElement._owner.getName() : '<root>' }; return rv; } else { return func.apply(this, args); } }; } }; module.exports = ReactDefaultPerf; },{"./DOMProperty":10,"./ReactDefaultPerfAnalysis":57,"./ReactMount":71,"./ReactPerf":76,"./performanceNow":147}],57:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultPerfAnalysis */ var assign = require("./Object.assign"); // Don't try to save users less than 1.2ms (a number I made up) var DONT_CARE_THRESHOLD = 1.2; var DOM_OPERATION_TYPES = { '_mountImageIntoNode': 'set innerHTML', INSERT_MARKUP: 'set innerHTML', MOVE_EXISTING: 'move', REMOVE_NODE: 'remove', TEXT_CONTENT: 'set textContent', 'updatePropertyByID': 'update attribute', 'deletePropertyByID': 'delete attribute', 'updateStylesByID': 'update styles', 'updateInnerHTMLByID': 'set innerHTML', 'dangerouslyReplaceNodeWithMarkupByID': 'replace' }; function getTotalTime(measurements) { // TODO: return number of DOM ops? could be misleading. // TODO: measure dropped frames after reconcile? // TODO: log total time of each reconcile and the top-level component // class that triggered it. var totalTime = 0; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; totalTime += measurement.totalTime; } return totalTime; } function getDOMSummary(measurements) { var items = []; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; var id; for (id in measurement.writes) { measurement.writes[id].forEach(function(write) { items.push({ id: id, type: DOM_OPERATION_TYPES[write.type] || write.type, args: write.args }); }); } } return items; } function getExclusiveSummary(measurements) { var candidates = {}; var displayName; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; var allIDs = assign( {}, measurement.exclusive, measurement.inclusive ); for (var id in allIDs) { displayName = measurement.displayNames[id].current; candidates[displayName] = candidates[displayName] || { componentName: displayName, inclusive: 0, exclusive: 0, render: 0, count: 0 }; if (measurement.render[id]) { candidates[displayName].render += measurement.render[id]; } if (measurement.exclusive[id]) { candidates[displayName].exclusive += measurement.exclusive[id]; } if (measurement.inclusive[id]) { candidates[displayName].inclusive += measurement.inclusive[id]; } if (measurement.counts[id]) { candidates[displayName].count += measurement.counts[id]; } } } // Now make a sorted array with the results. var arr = []; for (displayName in candidates) { if (candidates[displayName].exclusive >= DONT_CARE_THRESHOLD) { arr.push(candidates[displayName]); } } arr.sort(function(a, b) { return b.exclusive - a.exclusive; }); return arr; } function getInclusiveSummary(measurements, onlyClean) { var candidates = {}; var inclusiveKey; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; var allIDs = assign( {}, measurement.exclusive, measurement.inclusive ); var cleanComponents; if (onlyClean) { cleanComponents = getUnchangedComponents(measurement); } for (var id in allIDs) { if (onlyClean && !cleanComponents[id]) { continue; } var displayName = measurement.displayNames[id]; // Inclusive time is not useful for many components without knowing where // they are instantiated. So we aggregate inclusive time with both the // owner and current displayName as the key. inclusiveKey = displayName.owner + ' > ' + displayName.current; candidates[inclusiveKey] = candidates[inclusiveKey] || { componentName: inclusiveKey, time: 0, count: 0 }; if (measurement.inclusive[id]) { candidates[inclusiveKey].time += measurement.inclusive[id]; } if (measurement.counts[id]) { candidates[inclusiveKey].count += measurement.counts[id]; } } } // Now make a sorted array with the results. var arr = []; for (inclusiveKey in candidates) { if (candidates[inclusiveKey].time >= DONT_CARE_THRESHOLD) { arr.push(candidates[inclusiveKey]); } } arr.sort(function(a, b) { return b.time - a.time; }); return arr; } function getUnchangedComponents(measurement) { // For a given reconcile, look at which components did not actually // render anything to the DOM and return a mapping of their ID to // the amount of time it took to render the entire subtree. var cleanComponents = {}; var dirtyLeafIDs = Object.keys(measurement.writes); var allIDs = assign({}, measurement.exclusive, measurement.inclusive); for (var id in allIDs) { var isDirty = false; // For each component that rendered, see if a component that triggered // a DOM op is in its subtree. for (var i = 0; i < dirtyLeafIDs.length; i++) { if (dirtyLeafIDs[i].indexOf(id) === 0) { isDirty = true; break; } } if (!isDirty && measurement.counts[id] > 0) { cleanComponents[id] = true; } } return cleanComponents; } var ReactDefaultPerfAnalysis = { getExclusiveSummary: getExclusiveSummary, getInclusiveSummary: getInclusiveSummary, getDOMSummary: getDOMSummary, getTotalTime: getTotalTime }; module.exports = ReactDefaultPerfAnalysis; },{"./Object.assign":27}],58:[function(require,module,exports){ (function (process){ /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactElement */ 'use strict'; var ReactContext = require("./ReactContext"); var ReactCurrentOwner = require("./ReactCurrentOwner"); var assign = require("./Object.assign"); var warning = require("./warning"); var RESERVED_PROPS = { key: true, ref: true }; /** * Warn for mutations. * * @internal * @param {object} object * @param {string} key */ function defineWarningProperty(object, key) { Object.defineProperty(object, key, { configurable: false, enumerable: true, get: function() { if (!this._store) { return null; } return this._store[key]; }, set: function(value) { ("production" !== process.env.NODE_ENV ? warning( false, 'Don\'t set the %s property of the React element. Instead, ' + 'specify the correct value when initially creating the element.', key ) : null); this._store[key] = value; } }); } /** * This is updated to true if the membrane is successfully created. */ var useMutationMembrane = false; /** * Warn for mutations. * * @internal * @param {object} element */ function defineMutationMembrane(prototype) { try { var pseudoFrozenProperties = { props: true }; for (var key in pseudoFrozenProperties) { defineWarningProperty(prototype, key); } useMutationMembrane = true; } catch (x) { // IE will fail on defineProperty } } /** * Base constructor for all React elements. This is only used to make this * work with a dynamic instanceof check. Nothing should live on this prototype. * * @param {*} type * @param {string|object} ref * @param {*} key * @param {*} props * @internal */ var ReactElement = function(type, key, ref, owner, context, props) { // Built-in properties that belong on the element this.type = type; this.key = key; this.ref = ref; // Record the component responsible for creating this element. this._owner = owner; // TODO: Deprecate withContext, and then the context becomes accessible // through the owner. this._context = context; if ("production" !== process.env.NODE_ENV) { // The validation flag and props are currently mutative. We put them 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. this._store = {props: props, originalProps: assign({}, props)}; // 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. try { Object.defineProperty(this._store, 'validated', { configurable: false, enumerable: false, writable: true }); } catch (x) { } this._store.validated = false; // We're not allowed to set props directly on the object so we early // return and rely on the prototype membrane to forward to the backing // store. if (useMutationMembrane) { Object.freeze(this); return; } } this.props = props; }; // We intentionally don't expose the function on the constructor property. // ReactElement should be indistinguishable from a plain object. ReactElement.prototype = { _isReactElement: true }; if ("production" !== process.env.NODE_ENV) { defineMutationMembrane(ReactElement.prototype); } ReactElement.createElement = function(type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; if (config != null) { ref = config.ref === undefined ? null : config.ref; key = config.key === undefined ? null : '' + config.key; // Remaining properties are added to a new props object for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (typeof props[propName] === 'undefined') { props[propName] = defaultProps[propName]; } } } return new ReactElement( type, key, ref, ReactCurrentOwner.current, ReactContext.current, props ); }; ReactElement.createFactory = function(type) { var factory = ReactElement.createElement.bind(null, type); // Expose the type on the factory and the prototype so that it can be // easily accessed on elements. E.g. <Foo />.type === Foo.type. // 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.cloneAndReplaceProps = function(oldElement, newProps) { var newElement = new ReactElement( oldElement.type, oldElement.key, oldElement.ref, oldElement._owner, oldElement._context, newProps ); if ("production" !== process.env.NODE_ENV) { // If the key on the original is valid, then the clone is valid newElement._store.validated = oldElement._store.validated; } return newElement; }; ReactElement.cloneElement = function(element, config, children) { var propName; // Original props are copied var props = assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if (config.ref !== undefined) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (config.key !== undefined) { key = '' + config.key; } // Remaining properties override existing props for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return new ReactElement( element.type, key, ref, owner, element._context, props ); }; /** * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactElement.isValidElement = function(object) { // ReactTestUtils is often used outside of beforeEach where as React is // within it. This leads to two different instances of React on the same // page. To identify a element from a different React instance we use // a flag instead of an instanceof check. var isElement = !!(object && object._isReactElement); // if (isElement && !(object instanceof ReactElement)) { // This is an indicator that you're using multiple versions of React at the // same time. This will screw with ownership and stuff. Fix it, please. // TODO: We could possibly warn here. // } return isElement; }; module.exports = ReactElement; }).call(this,require('_process')) },{"./Object.assign":27,"./ReactContext":39,"./ReactCurrentOwner":40,"./warning":155,"_process":1}],59:[function(require,module,exports){ (function (process){ /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactElementValidator */ /** * ReactElementValidator provides a wrapper around a element factory * which validates the props passed to the element. This is intended to be * used only in DEV and could be replaced by a static type checker for languages * that support it. */ 'use strict'; var ReactElement = require("./ReactElement"); var ReactFragment = require("./ReactFragment"); var ReactPropTypeLocations = require("./ReactPropTypeLocations"); var ReactPropTypeLocationNames = require("./ReactPropTypeLocationNames"); var ReactCurrentOwner = require("./ReactCurrentOwner"); var ReactNativeComponent = require("./ReactNativeComponent"); var getIteratorFn = require("./getIteratorFn"); var invariant = require("./invariant"); var warning = require("./warning"); function getDeclarationErrorAddendum() { if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = {}; var loggedTypeFailures = {}; var NUMERIC_PROPERTY_REGEX = /^\d+$/; /** * Gets the instance's name for use in warnings. * * @internal * @return {?string} Display name or undefined */ function getName(instance) { var publicInstance = instance && instance.getPublicInstance(); if (!publicInstance) { return undefined; } var constructor = publicInstance.constructor; if (!constructor) { return undefined; } return constructor.displayName || constructor.name || undefined; } /** * Gets the current owner's displayName for use in warnings. * * @internal * @return {?string} Display name or undefined */ function getCurrentOwnerDisplayName() { var current = ReactCurrentOwner.current; return ( current && getName(current) || undefined ); } /** * Warn if the element doesn't have an explicit key assigned to it. * This element is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { if (element._store.validated || element.key != null) { return; } element._store.validated = true; warnAndMonitorForKeyUse( 'Each child in an array or iterator should have a unique "key" prop.', element, parentType ); } /** * Warn if the key is being defined as an object property but has an incorrect * value. * * @internal * @param {string} name Property name of the key. * @param {ReactElement} element Component that requires a key. * @param {*} parentType element's parent's type. */ function validatePropertyKey(name, element, parentType) { if (!NUMERIC_PROPERTY_REGEX.test(name)) { return; } warnAndMonitorForKeyUse( 'Child objects should have non-numeric keys so ordering is preserved.', element, parentType ); } /** * Shared warning and monitoring code for the key warnings. * * @internal * @param {string} message The base warning that gets output. * @param {ReactElement} element Component that requires a key. * @param {*} parentType element's parent's type. */ function warnAndMonitorForKeyUse(message, element, parentType) { var ownerName = getCurrentOwnerDisplayName(); var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; var useName = ownerName || parentName; var memoizer = ownerHasKeyUseWarning[message] || ( (ownerHasKeyUseWarning[message] = {}) ); if (memoizer.hasOwnProperty(useName)) { return; } memoizer[useName] = true; var parentOrOwnerAddendum = ownerName ? (" Check the render method of " + ownerName + ".") : parentName ? (" Check the React.render call using <" + parentName + ">.") : ''; // 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 childOwnerAddendum = ''; if (element && element._owner && element._owner !== ReactCurrentOwner.current) { // Name of the component that originally created this child. var childOwnerName = getName(element._owner); childOwnerAddendum = (" It was passed a child from " + childOwnerName + "."); } ("production" !== process.env.NODE_ENV ? warning( false, message + '%s%s See http://fb.me/react-warning-keys for more information.', parentOrOwnerAddendum, childOwnerAddendum ) : null); } /** * 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 (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. 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); } } } } else if (typeof node === 'object') { var fragment = ReactFragment.extractIfFragment(node); for (var key in fragment) { if (fragment.hasOwnProperty(key)) { validatePropertyKey(key, fragment[key], parentType); } } } } } /** * Assert that the props are valid * * @param {string} componentName Name of the component for error messages. * @param {object} propTypes Map of prop name to a ReactPropType * @param {object} props * @param {string} location e.g. "prop", "context", "child context" * @private */ function checkPropTypes(componentName, propTypes, props, location) { for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. ("production" !== process.env.NODE_ENV ? invariant( typeof propTypes[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName ) : invariant(typeof propTypes[propName] === 'function')); error = propTypes[propName](props, propName, componentName, location); } catch (ex) { error = ex; } 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(this); ("production" !== process.env.NODE_ENV ? warning(false, 'Failed propType: %s%s', error.message, addendum) : null); } } } } var warnedPropsMutations = {}; /** * Warn about mutating props when setting `propName` on `element`. * * @param {string} propName The string key within props that was set * @param {ReactElement} element */ function warnForPropsMutation(propName, element) { var type = element.type; var elementName = typeof type === 'string' ? type : type.displayName; var ownerName = element._owner ? element._owner.getPublicInstance().constructor.displayName : null; var warningKey = propName + '|' + elementName + '|' + ownerName; if (warnedPropsMutations.hasOwnProperty(warningKey)) { return; } warnedPropsMutations[warningKey] = true; var elementInfo = ''; if (elementName) { elementInfo = ' <' + elementName + ' />'; } var ownerInfo = ''; if (ownerName) { ownerInfo = ' The element was created by ' + ownerName + '.'; } ("production" !== process.env.NODE_ENV ? warning( false, 'Don\'t set .props.%s of the React component%s. Instead, specify the ' + 'correct value when initially creating the element or use ' + 'React.cloneElement to make a new element with updated props.%s', propName, elementInfo, ownerInfo ) : null); } // Inline Object.is polyfill function is(a, b) { if (a !== a) { // NaN return b !== b; } if (a === 0 && b === 0) { // +-0 return 1 / a === 1 / b; } return a === b; } /** * Given an element, check if its props have been mutated since element * creation (or the last call to this function). In particular, check if any * new props have been added, which we can't directly catch by defining warning * properties on the props object. * * @param {ReactElement} element */ function checkAndWarnForMutatedProps(element) { if (!element._store) { // Element was created using `new ReactElement` directly or with // `ReactElement.createElement`; skip mutation checking return; } var originalProps = element._store.originalProps; var props = element.props; for (var propName in props) { if (props.hasOwnProperty(propName)) { if (!originalProps.hasOwnProperty(propName) || !is(originalProps[propName], props[propName])) { warnForPropsMutation(propName, element); // Copy over the new value so that the two props objects match again originalProps[propName] = props[propName]; } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { if (element.type == null) { // This has already warned. Don't throw. return; } // Extract the component class from the element. Converts string types // to a composite class which may have propTypes. // TODO: Validating a string's propTypes is not decoupled from the // rendering target which is problematic. var componentClass = ReactNativeComponent.getComponentClassForElement( element ); var name = componentClass.displayName || componentClass.name; if (componentClass.propTypes) { checkPropTypes( name, componentClass.propTypes, element.props, ReactPropTypeLocations.prop ); } if (typeof componentClass.getDefaultProps === 'function') { ("production" !== process.env.NODE_ENV ? warning( componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.' ) : null); } } var ReactElementValidator = { checkAndWarnForMutatedProps: checkAndWarnForMutatedProps, createElement: function(type, props, children) { // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. ("production" !== process.env.NODE_ENV ? warning( type != null, 'React.createElement: type should not be null or undefined. It should ' + 'be a string (for DOM elements) or a ReactClass (for composite ' + 'components).' ) : null); 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; } 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 ("production" !== process.env.NODE_ENV) { try { Object.defineProperty( validatedFactory, 'type', { enumerable: false, get: function() { ("production" !== process.env.NODE_ENV ? warning( false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.' ) : null); Object.defineProperty(this, 'type', { value: type }); return type; } } ); } catch (x) { // IE will fail on defineProperty (es5-shim/sham too) } } 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; }).call(this,require('_process')) },{"./ReactCurrentOwner":40,"./ReactElement":58,"./ReactFragment":64,"./ReactNativeComponent":74,"./ReactPropTypeLocationNames":77,"./ReactPropTypeLocations":78,"./getIteratorFn":127,"./invariant":136,"./warning":155,"_process":1}],60:[function(require,module,exports){ (function (process){ /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEmptyComponent */ 'use strict'; var ReactElement = require("./ReactElement"); var ReactInstanceMap = require("./ReactInstanceMap"); var invariant = require("./invariant"); var component; // This registry keeps track of the React IDs of the components that rendered to // `null` (in reality a placeholder such as `noscript`) var nullComponentIDsRegistry = {}; var ReactEmptyComponentInjection = { injectEmptyComponent: function(emptyComponent) { component = ReactElement.createFactory(emptyComponent); } }; var ReactEmptyComponentType = function() {}; ReactEmptyComponentType.prototype.componentDidMount = function() { var internalInstance = ReactInstanceMap.get(this); // TODO: Make sure we run these methods in the correct order, we shouldn't // need this check. We're going to assume if we're here it means we ran // componentWillUnmount already so there is no internal instance (it gets // removed as part of the unmounting process). if (!internalInstance) { return; } registerNullComponentID(internalInstance._rootNodeID); }; ReactEmptyComponentType.prototype.componentWillUnmount = function() { var internalInstance = ReactInstanceMap.get(this); // TODO: Get rid of this check. See TODO in componentDidMount. if (!internalInstance) { return; } deregisterNullComponentID(internalInstance._rootNodeID); }; ReactEmptyComponentType.prototype.render = function() { ("production" !== process.env.NODE_ENV ? invariant( component, 'Trying to return null from a render, but no null placeholder component ' + 'was injected.' ) : invariant(component)); return component(); }; var emptyElement = ReactElement.createElement(ReactEmptyComponentType); /** * Mark the component as having rendered to null. * @param {string} id Component's `_rootNodeID`. */ function registerNullComponentID(id) { nullComponentIDsRegistry[id] = true; } /** * Unmark the component as having rendered to null: it renders to something now. * @param {string} id Component's `_rootNodeID`. */ function deregisterNullComponentID(id) { delete nullComponentIDsRegistry[id]; } /** * @param {string} id Component's `_rootNodeID`. * @return {boolean} True if the component is rendered to null. */ function isNullComponentID(id) { return !!nullComponentIDsRegistry[id]; } var ReactEmptyComponent = { emptyElement: emptyElement, injection: ReactEmptyComponentInjection, isNullComponentID: isNullComponentID }; module.exports = ReactEmptyComponent; }).call(this,require('_process')) },{"./ReactElement":58,"./ReactInstanceMap":68,"./invariant":136,"_process":1}],61:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactErrorUtils * @typechecks */ "use strict"; var ReactErrorUtils = { /** * Creates a guarded version of a function. This is supposed to make debugging * of event handlers easier. To aid debugging with the browser's debugger, * this currently simply returns the original function. * * @param {function} func Function to be executed * @param {string} name The name of the guard * @return {function} */ guard: function(func, name) { return func; } }; module.exports = ReactErrorUtils; },{}],62:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEventEmitterMixin */ 'use strict'; var EventPluginHub = require("./EventPluginHub"); function runEventQueueInBatch(events) { EventPluginHub.enqueueEvents(events); EventPluginHub.processEventQueue(); } var ReactEventEmitterMixin = { /** * Streams a fired top-level event to `EventPluginHub` where plugins have the * opportunity to create `ReactEvent`s to be dispatched. * * @param {string} topLevelType Record from `EventConstants`. * @param {object} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native environment event. */ handleTopLevel: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var events = EventPluginHub.extractEvents( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent ); runEventQueueInBatch(events); } }; module.exports = ReactEventEmitterMixin; },{"./EventPluginHub":17}],63:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEventListener * @typechecks static-only */ 'use strict'; var EventListener = require("./EventListener"); var ExecutionEnvironment = require("./ExecutionEnvironment"); var PooledClass = require("./PooledClass"); var ReactInstanceHandles = require("./ReactInstanceHandles"); var ReactMount = require("./ReactMount"); var ReactUpdates = require("./ReactUpdates"); var assign = require("./Object.assign"); var getEventTarget = require("./getEventTarget"); var getUnboundedScrollPosition = require("./getUnboundedScrollPosition"); /** * Finds the parent React component of `node`. * * @param {*} node * @return {?DOMEventTarget} Parent container, or `null` if the specified node * is not nested. */ function findParent(node) { // TODO: It may be a good idea to cache this to prevent unnecessary DOM // traversal, but caching is difficult to do correctly without using a // mutation observer to listen for all DOM changes. var nodeID = ReactMount.getID(node); var rootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID); var container = ReactMount.findReactContainerForID(rootID); var parent = ReactMount.getFirstReactDOM(container); return parent; } // Used to store ancestor hierarchy in top level callback function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) { this.topLevelType = topLevelType; this.nativeEvent = nativeEvent; this.ancestors = []; } assign(TopLevelCallbackBookKeeping.prototype, { destructor: function() { this.topLevelType = null; this.nativeEvent = null; this.ancestors.length = 0; } }); PooledClass.addPoolingTo( TopLevelCallbackBookKeeping, PooledClass.twoArgumentPooler ); function handleTopLevelImpl(bookKeeping) { var topLevelTarget = ReactMount.getFirstReactDOM( getEventTarget(bookKeeping.nativeEvent) ) || window; // Loop through the hierarchy, in case there's any nested components. // It's important that we build the array of ancestors before calling any // event handlers, because event handlers can modify the DOM, leading to // inconsistencies with ReactMount's node cache. See #1105. var ancestor = topLevelTarget; while (ancestor) { bookKeeping.ancestors.push(ancestor); ancestor = findParent(ancestor); } for (var i = 0, l = bookKeeping.ancestors.length; i < l; i++) { topLevelTarget = bookKeeping.ancestors[i]; var topLevelTargetID = ReactMount.getID(topLevelTarget) || ''; ReactEventListener._handleTopLevel( bookKeeping.topLevelType, topLevelTarget, topLevelTargetID, 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; },{"./EventListener":16,"./ExecutionEnvironment":21,"./Object.assign":27,"./PooledClass":28,"./ReactInstanceHandles":67,"./ReactMount":71,"./ReactUpdates":88,"./getEventTarget":126,"./getUnboundedScrollPosition":132}],64:[function(require,module,exports){ (function (process){ /** * Copyright 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactFragment */ 'use strict'; var ReactElement = require("./ReactElement"); var warning = require("./warning"); /** * We used to allow keyed objects to serve as a collection of ReactElements, * or nested sets. This allowed us a way to explicitly key a set a fragment of * components. This is now being replaced with an opaque data structure. * The upgrade path is to call React.addons.createFragment({ key: value }) to * create a keyed fragment. The resulting data structure is opaque, for now. */ if ("production" !== process.env.NODE_ENV) { var fragmentKey = '_reactFragment'; var didWarnKey = '_reactDidWarn'; var canWarnForReactFragment = false; try { // Feature test. Don't even try to issue this warning if we can't use // enumerable: false. var dummy = function() { return 1; }; Object.defineProperty( {}, fragmentKey, {enumerable: false, value: true} ); Object.defineProperty( {}, 'key', {enumerable: true, get: dummy} ); canWarnForReactFragment = true; } catch (x) { } var proxyPropertyAccessWithWarning = function(obj, key) { Object.defineProperty(obj, key, { enumerable: true, get: function() { ("production" !== process.env.NODE_ENV ? warning( this[didWarnKey], 'A ReactFragment is an opaque type. Accessing any of its ' + 'properties is deprecated. Pass it to one of the React.Children ' + 'helpers.' ) : null); this[didWarnKey] = true; return this[fragmentKey][key]; }, set: function(value) { ("production" !== process.env.NODE_ENV ? warning( this[didWarnKey], 'A ReactFragment is an immutable opaque type. Mutating its ' + 'properties is deprecated.' ) : null); this[didWarnKey] = true; this[fragmentKey][key] = value; } }); }; var issuedWarnings = {}; var didWarnForFragment = function(fragment) { // We use the keys and the type of the value as a heuristic to dedupe the // warning to avoid spamming too much. var fragmentCacheKey = ''; for (var key in fragment) { fragmentCacheKey += key + ':' + (typeof fragment[key]) + ','; } var alreadyWarnedOnce = !!issuedWarnings[fragmentCacheKey]; issuedWarnings[fragmentCacheKey] = true; return alreadyWarnedOnce; }; } var ReactFragment = { // Wrap a keyed object in an opaque proxy that warns you if you access any // of its properties. create: function(object) { if ("production" !== process.env.NODE_ENV) { if (typeof object !== 'object' || !object || Array.isArray(object)) { ("production" !== process.env.NODE_ENV ? warning( false, 'React.addons.createFragment only accepts a single object.', object ) : null); return object; } if (ReactElement.isValidElement(object)) { ("production" !== process.env.NODE_ENV ? warning( false, 'React.addons.createFragment does not accept a ReactElement ' + 'without a wrapper object.' ) : null); return object; } if (canWarnForReactFragment) { var proxy = {}; Object.defineProperty(proxy, fragmentKey, { enumerable: false, value: object }); Object.defineProperty(proxy, didWarnKey, { writable: true, enumerable: false, value: false }); for (var key in object) { proxyPropertyAccessWithWarning(proxy, key); } Object.preventExtensions(proxy); return proxy; } } return object; }, // Extract the original keyed object from the fragment opaque type. Warn if // a plain object is passed here. extract: function(fragment) { if ("production" !== process.env.NODE_ENV) { if (canWarnForReactFragment) { if (!fragment[fragmentKey]) { ("production" !== process.env.NODE_ENV ? warning( didWarnForFragment(fragment), 'Any use of a keyed object should be wrapped in ' + 'React.addons.createFragment(object) before being passed as a ' + 'child.' ) : null); return fragment; } return fragment[fragmentKey]; } } return fragment; }, // Check if this is a fragment and if so, extract the keyed object. If it // is a fragment-like object, warn that it should be wrapped. Ignore if we // can't determine what kind of object this is. extractIfFragment: function(fragment) { if ("production" !== process.env.NODE_ENV) { if (canWarnForReactFragment) { // If it is the opaque type, return the keyed object. if (fragment[fragmentKey]) { return fragment[fragmentKey]; } // Otherwise, check each property if it has an element, if it does // it is probably meant as a fragment, so we can warn early. Defer, // the warning to extract. for (var key in fragment) { if (fragment.hasOwnProperty(key) && ReactElement.isValidElement(fragment[key])) { // This looks like a fragment object, we should provide an // early warning. return ReactFragment.extract(fragment); } } } } return fragment; } }; module.exports = ReactFragment; }).call(this,require('_process')) },{"./ReactElement":58,"./warning":155,"_process":1}],65:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInjection */ 'use strict'; var DOMProperty = require("./DOMProperty"); var EventPluginHub = require("./EventPluginHub"); var ReactComponentEnvironment = require("./ReactComponentEnvironment"); var ReactClass = require("./ReactClass"); var ReactEmptyComponent = require("./ReactEmptyComponent"); var ReactBrowserEventEmitter = require("./ReactBrowserEventEmitter"); var ReactNativeComponent = require("./ReactNativeComponent"); var ReactDOMComponent = require("./ReactDOMComponent"); var ReactPerf = require("./ReactPerf"); var ReactRootIndex = require("./ReactRootIndex"); var ReactUpdates = require("./ReactUpdates"); var ReactInjection = { Component: ReactComponentEnvironment.injection, Class: ReactClass.injection, DOMComponent: ReactDOMComponent.injection, DOMProperty: DOMProperty.injection, EmptyComponent: ReactEmptyComponent.injection, EventPluginHub: EventPluginHub.injection, EventEmitter: ReactBrowserEventEmitter.injection, NativeComponent: ReactNativeComponent.injection, Perf: ReactPerf.injection, RootIndex: ReactRootIndex.injection, Updates: ReactUpdates.injection }; module.exports = ReactInjection; },{"./DOMProperty":10,"./EventPluginHub":17,"./ReactBrowserEventEmitter":31,"./ReactClass":34,"./ReactComponentEnvironment":37,"./ReactDOMComponent":43,"./ReactEmptyComponent":60,"./ReactNativeComponent":74,"./ReactPerf":76,"./ReactRootIndex":84,"./ReactUpdates":88}],66:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInputSelection */ 'use strict'; var ReactDOMSelection = require("./ReactDOMSelection"); var containsNode = require("./containsNode"); var focusNode = require("./focusNode"); var getActiveElement = require("./getActiveElement"); 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) { return elem && ( ((elem.nodeName === 'INPUT' && elem.type === 'text') || elem.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') { // IE8 input. var range = document.selection.createRange(); // There can only be one selection per document in IE, so it must // be in our element. if (range.parentElement() === input) { selection = { start: -range.moveStart('character', -input.value.length), end: -range.moveEnd('character', -input.value.length) }; } } else { // Content editable or old IE textarea. selection = ReactDOMSelection.getOffsets(input); } return selection || {start: 0, end: 0}; }, /** * @setSelection: Sets the selection bounds of a textarea or input and focuses * the input. * -@input Set selection bounds of this input or textarea * -@offsets Object of same form that is returned from get* */ setSelection: function(input, offsets) { var start = offsets.start; var end = offsets.end; if (typeof end === 'undefined') { end = start; } if ('selectionStart' in input) { input.selectionStart = start; input.selectionEnd = Math.min(end, input.value.length); } else if (document.selection && input.nodeName === 'INPUT') { 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; },{"./ReactDOMSelection":51,"./containsNode":110,"./focusNode":120,"./getActiveElement":122}],67:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInstanceHandles * @typechecks static-only */ 'use strict'; var ReactRootIndex = require("./ReactRootIndex"); var invariant = require("./invariant"); var SEPARATOR = '.'; var SEPARATOR_LENGTH = SEPARATOR.length; /** * Maximum depth of traversals before we consider the possibility of a bad ID. */ var MAX_TREE_DEPTH = 100; /** * Creates a DOM ID prefix to use when mounting React components. * * @param {number} index A unique integer * @return {string} React root ID. * @internal */ function getReactRootIDString(index) { return SEPARATOR + index.toString(36); } /** * Checks if a character in the supplied ID is a separator or the end. * * @param {string} id A React DOM ID. * @param {number} index Index of the character to check. * @return {boolean} True if the character is a separator or end of the ID. * @private */ function isBoundary(id, index) { return id.charAt(index) === SEPARATOR || index === id.length; } /** * Checks if the supplied string is a valid React DOM ID. * * @param {string} id A React DOM ID, maybe. * @return {boolean} True if the string is a valid React DOM ID. * @private */ function isValidID(id) { return id === '' || ( id.charAt(0) === SEPARATOR && id.charAt(id.length - 1) !== SEPARATOR ); } /** * Checks if the first ID is an ancestor of or equal to the second ID. * * @param {string} ancestorID * @param {string} descendantID * @return {boolean} True if `ancestorID` is an ancestor of `descendantID`. * @internal */ function isAncestorIDOf(ancestorID, descendantID) { return ( descendantID.indexOf(ancestorID) === 0 && isBoundary(descendantID, ancestorID.length) ); } /** * Gets the parent ID of the supplied React DOM ID, `id`. * * @param {string} id ID of a component. * @return {string} ID of the parent, or an empty string. * @private */ function getParentID(id) { return id ? id.substr(0, id.lastIndexOf(SEPARATOR)) : ''; } /** * Gets the next DOM ID on the tree path from the supplied `ancestorID` to the * supplied `destinationID`. If they are equal, the ID is returned. * * @param {string} ancestorID ID of an ancestor node of `destinationID`. * @param {string} destinationID ID of the destination node. * @return {string} Next ID on the path from `ancestorID` to `destinationID`. * @private */ function getNextDescendantID(ancestorID, destinationID) { ("production" !== process.env.NODE_ENV ? invariant( isValidID(ancestorID) && isValidID(destinationID), 'getNextDescendantID(%s, %s): Received an invalid React DOM ID.', ancestorID, destinationID ) : invariant(isValidID(ancestorID) && isValidID(destinationID))); ("production" !== process.env.NODE_ENV ? invariant( isAncestorIDOf(ancestorID, destinationID), 'getNextDescendantID(...): React has made an invalid assumption about ' + 'the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.', ancestorID, destinationID ) : invariant(isAncestorIDOf(ancestorID, destinationID))); if (ancestorID === destinationID) { return ancestorID; } // Skip over the ancestor and the immediate separator. Traverse until we hit // another separator or we reach the end of `destinationID`. var start = ancestorID.length + SEPARATOR_LENGTH; var i; for (i = start; i < destinationID.length; i++) { if (isBoundary(destinationID, i)) { break; } } return destinationID.substr(0, i); } /** * Gets the nearest common ancestor ID of two IDs. * * Using this ID scheme, the nearest common ancestor ID is the longest common * prefix of the two IDs that immediately preceded a "marker" in both strings. * * @param {string} oneID * @param {string} twoID * @return {string} Nearest common ancestor ID, or the empty string if none. * @private */ function getFirstCommonAncestorID(oneID, twoID) { var minLength = Math.min(oneID.length, twoID.length); if (minLength === 0) { return ''; } var lastCommonMarkerIndex = 0; // Use `<=` to traverse until the "EOL" of the shorter string. for (var i = 0; i <= minLength; i++) { if (isBoundary(oneID, i) && isBoundary(twoID, i)) { lastCommonMarkerIndex = i; } else if (oneID.charAt(i) !== twoID.charAt(i)) { break; } } var longestCommonID = oneID.substr(0, lastCommonMarkerIndex); ("production" !== process.env.NODE_ENV ? invariant( isValidID(longestCommonID), 'getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s', oneID, twoID, longestCommonID ) : invariant(isValidID(longestCommonID))); return longestCommonID; } /** * Traverses the parent path between two IDs (either up or down). The IDs must * not be the same, and there must exist a parent path between them. If the * callback returns `false`, traversal is stopped. * * @param {?string} start ID at which to start traversal. * @param {?string} stop ID at which to end traversal. * @param {function} cb Callback to invoke each ID with. * @param {?boolean} skipFirst Whether or not to skip the first node. * @param {?boolean} skipLast Whether or not to skip the last node. * @private */ function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) { start = start || ''; stop = stop || ''; ("production" !== process.env.NODE_ENV ? invariant( start !== stop, 'traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.', start ) : invariant(start !== stop)); var traverseUp = isAncestorIDOf(stop, start); ("production" !== process.env.NODE_ENV ? invariant( traverseUp || isAncestorIDOf(start, stop), 'traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do ' + 'not have a parent path.', start, stop ) : invariant(traverseUp || isAncestorIDOf(start, stop))); // Traverse from `start` to `stop` one depth at a time. var depth = 0; var traverse = traverseUp ? getParentID : getNextDescendantID; for (var id = start; /* until break */; id = traverse(id, stop)) { var ret; if ((!skipFirst || id !== start) && (!skipLast || id !== stop)) { ret = cb(id, traverseUp, arg); } if (ret === false || id === stop) { // Only break //after// visiting `stop`. break; } ("production" !== process.env.NODE_ENV ? invariant( depth++ < MAX_TREE_DEPTH, 'traverseParentPath(%s, %s, ...): Detected an infinite loop while ' + 'traversing the React DOM ID tree. This may be due to malformed IDs: %s', start, stop ) : invariant(depth++ < MAX_TREE_DEPTH)); } } /** * Manages the IDs assigned to DOM representations of React components. This * uses a specific scheme in order to traverse the DOM efficiently (e.g. in * order to simulate events). * * @internal */ var ReactInstanceHandles = { /** * Constructs a React root ID * @return {string} A React root ID. */ createReactRootID: function() { return getReactRootIDString(ReactRootIndex.createReactRootIndex()); }, /** * Constructs a React ID by joining a root ID with a name. * * @param {string} rootID Root ID of a parent component. * @param {string} name A component's name (as flattened children). * @return {string} A React ID. * @internal */ createReactID: function(rootID, name) { return rootID + name; }, /** * Gets the DOM ID of the React component that is the root of the tree that * contains the React component with the supplied DOM ID. * * @param {string} id DOM ID of a React component. * @return {?string} DOM ID of the React component that is the root. * @internal */ getReactRootIDFromNodeID: function(id) { if (id && id.charAt(0) === SEPARATOR && id.length > 1) { var index = id.indexOf(SEPARATOR, 1); return index > -1 ? id.substr(0, index) : id; } return null; }, /** * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that * should would receive a `mouseEnter` or `mouseLeave` event. * * NOTE: Does not invoke the callback on the nearest common ancestor because * nothing "entered" or "left" that element. * * @param {string} leaveID ID being left. * @param {string} enterID ID being entered. * @param {function} cb Callback to invoke on each entered/left ID. * @param {*} upArg Argument to invoke the callback with on left IDs. * @param {*} downArg Argument to invoke the callback with on entered IDs. * @internal */ traverseEnterLeave: function(leaveID, enterID, cb, upArg, downArg) { var ancestorID = getFirstCommonAncestorID(leaveID, enterID); if (ancestorID !== leaveID) { traverseParentPath(leaveID, ancestorID, cb, upArg, false, true); } if (ancestorID !== enterID) { traverseParentPath(ancestorID, enterID, cb, downArg, true, false); } }, /** * Simulates the traversal of a two-phase, capture/bubble event dispatch. * * NOTE: This traversal happens on IDs without touching the DOM. * * @param {string} targetID ID of the target node. * @param {function} cb Callback to invoke. * @param {*} arg Argument to invoke the callback with. * @internal */ traverseTwoPhase: function(targetID, cb, arg) { if (targetID) { traverseParentPath('', targetID, cb, arg, true, false); traverseParentPath(targetID, '', cb, arg, false, true); } }, /** * Traverse a node ID, calling the supplied `cb` for each ancestor ID. For * example, passing `.0.$row-0.1` would result in `cb` getting called * with `.0`, `.0.$row-0`, and `.0.$row-0.1`. * * NOTE: This traversal happens on IDs without touching the DOM. * * @param {string} targetID ID of the target node. * @param {function} cb Callback to invoke. * @param {*} arg Argument to invoke the callback with. * @internal */ traverseAncestors: function(targetID, cb, arg) { traverseParentPath('', targetID, cb, arg, true, false); }, /** * Exposed for unit testing. * @private */ _getFirstCommonAncestorID: getFirstCommonAncestorID, /** * Exposed for unit testing. * @private */ _getNextDescendantID: getNextDescendantID, isAncestorIDOf: isAncestorIDOf, SEPARATOR: SEPARATOR }; module.exports = ReactInstanceHandles; }).call(this,require('_process')) },{"./ReactRootIndex":84,"./invariant":136,"_process":1}],68:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInstanceMap */ 'use strict'; /** * `ReactInstanceMap` maintains a mapping from a public facing stateful * instance (key) and the internal representation (value). This allows public * methods to accept the user facing instance as an argument and map them back * to internal methods. */ // TODO: Replace this with ES6: var ReactInstanceMap = new Map(); var ReactInstanceMap = { /** * This API should be called `delete` but we'd have to make sure to always * transform these to strings for IE support. When this transform is fully * supported we can rename it. */ remove: function(key) { key._reactInternalInstance = undefined; }, get: function(key) { return key._reactInternalInstance; }, has: function(key) { return key._reactInternalInstance !== undefined; }, set: function(key, value) { key._reactInternalInstance = value; } }; module.exports = ReactInstanceMap; },{}],69:[function(require,module,exports){ /** * Copyright 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactLifeCycle */ 'use strict'; /** * This module manages the bookkeeping when a component is in the process * of being mounted or being unmounted. This is used as a way to enforce * invariants (or warnings) when it is not recommended to call * setState/forceUpdate. * * currentlyMountingInstance: During the construction phase, it is not possible * to trigger an update since the instance is not fully mounted yet. However, we * currently allow this as a convenience for mutating the initial state. * * currentlyUnmountingInstance: During the unmounting phase, the instance is * still mounted and can therefore schedule an update. However, this is not * recommended and probably an error since it's about to be unmounted. * Therefore we still want to trigger in an error for that case. */ var ReactLifeCycle = { currentlyMountingInstance: null, currentlyUnmountingInstance: null }; module.exports = ReactLifeCycle; },{}],70:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMarkupChecksum */ 'use strict'; var adler32 = require("./adler32"); 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); return markup.replace( '>', ' ' + 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; },{"./adler32":107}],71:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMount */ 'use strict'; var DOMProperty = require("./DOMProperty"); var ReactBrowserEventEmitter = require("./ReactBrowserEventEmitter"); var ReactCurrentOwner = require("./ReactCurrentOwner"); var ReactElement = require("./ReactElement"); var ReactElementValidator = require("./ReactElementValidator"); var ReactEmptyComponent = require("./ReactEmptyComponent"); var ReactInstanceHandles = require("./ReactInstanceHandles"); var ReactInstanceMap = require("./ReactInstanceMap"); var ReactMarkupChecksum = require("./ReactMarkupChecksum"); var ReactPerf = require("./ReactPerf"); var ReactReconciler = require("./ReactReconciler"); var ReactUpdateQueue = require("./ReactUpdateQueue"); var ReactUpdates = require("./ReactUpdates"); var emptyObject = require("./emptyObject"); var containsNode = require("./containsNode"); var getReactRootElementInContainer = require("./getReactRootElementInContainer"); var instantiateReactComponent = require("./instantiateReactComponent"); var invariant = require("./invariant"); var setInnerHTML = require("./setInnerHTML"); var shouldUpdateReactComponent = require("./shouldUpdateReactComponent"); var warning = require("./warning"); var SEPARATOR = ReactInstanceHandles.SEPARATOR; var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME; var nodeCache = {}; var ELEMENT_NODE_TYPE = 1; var DOC_NODE_TYPE = 9; /** Mapping from reactRootID to React component instance. */ var instancesByReactRootID = {}; /** Mapping from reactRootID to `container` nodes. */ var containersByReactRootID = {}; if ("production" !== process.env.NODE_ENV) { /** __DEV__-only mapping from reactRootID to root elements. */ var rootElementsByReactRootID = {}; } // Used to store breadth-first search state in findComponentRoot. var findComponentRootReusableArray = []; /** * Finds the index of the first character * that's not common between the two given strings. * * @return {number} the index of the character where the strings diverge */ function firstDifferenceIndex(string1, string2) { var minLen = Math.min(string1.length, string2.length); for (var i = 0; i < minLen; i++) { if (string1.charAt(i) !== string2.charAt(i)) { return i; } } return string1.length === string2.length ? -1 : minLen; } /** * @param {DOMElement} container DOM element that may contain a React component. * @return {?string} A "reactRoot" ID, if a React component is rendered. */ function getReactRootID(container) { var rootElement = getReactRootElementInContainer(container); return rootElement && ReactMount.getID(rootElement); } /** * Accessing node[ATTR_NAME] or calling getAttribute(ATTR_NAME) on a form * element can return its control whose name or ID equals ATTR_NAME. All * DOM nodes support `getAttributeNode` but this can also get called on * other objects so just return '' if we're given something other than a * DOM node (such as window). * * @param {?DOMElement|DOMWindow|DOMDocument|DOMTextNode} node DOM node. * @return {string} ID of the supplied `domNode`. */ function getID(node) { var id = internalGetID(node); if (id) { if (nodeCache.hasOwnProperty(id)) { var cached = nodeCache[id]; if (cached !== node) { ("production" !== process.env.NODE_ENV ? invariant( !isValid(cached, id), 'ReactMount: Two valid but unequal nodes with the same `%s`: %s', ATTR_NAME, id ) : invariant(!isValid(cached, id))); nodeCache[id] = node; } } else { nodeCache[id] = node; } } return id; } function internalGetID(node) { // If node is something like a window, document, or text node, none of // which support attributes or a .getAttribute method, gracefully return // the empty string, as if the attribute were missing. return node && node.getAttribute && node.getAttribute(ATTR_NAME) || ''; } /** * Sets the React-specific ID of the given node. * * @param {DOMElement} node The DOM node whose ID will be set. * @param {string} id The value of the ID attribute. */ function setID(node, id) { var oldID = internalGetID(node); if (oldID !== id) { delete nodeCache[oldID]; } node.setAttribute(ATTR_NAME, id); nodeCache[id] = node; } /** * Finds the node with the supplied React-generated DOM ID. * * @param {string} id A React-generated DOM ID. * @return {DOMElement} DOM node with the suppled `id`. * @internal */ function getNode(id) { if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) { nodeCache[id] = ReactMount.findReactNodeByID(id); } return nodeCache[id]; } /** * Finds the node with the supplied public React instance. * * @param {*} instance A public React instance. * @return {?DOMElement} DOM node with the suppled `id`. * @internal */ function getNodeFromInstance(instance) { var id = ReactInstanceMap.get(instance)._rootNodeID; if (ReactEmptyComponent.isNullComponentID(id)) { return null; } if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) { nodeCache[id] = ReactMount.findReactNodeByID(id); } return nodeCache[id]; } /** * A node is "valid" if it is contained by a currently mounted container. * * This means that the node does not have to be contained by a document in * order to be considered valid. * * @param {?DOMElement} node The candidate DOM node. * @param {string} id The expected ID of the node. * @return {boolean} Whether the node is contained by a mounted container. */ function isValid(node, id) { if (node) { ("production" !== process.env.NODE_ENV ? invariant( internalGetID(node) === id, 'ReactMount: Unexpected modification of `%s`', ATTR_NAME ) : invariant(internalGetID(node) === id)); var container = ReactMount.findReactContainerForID(id); if (container && containsNode(container, node)) { return true; } } return false; } /** * Causes the cache to forget about one React-specific ID. * * @param {string} id The ID to forget. */ function purgeID(id) { delete nodeCache[id]; } var deepestNodeSoFar = null; function findDeepestCachedAncestorImpl(ancestorID) { var ancestor = nodeCache[ancestorID]; if (ancestor && isValid(ancestor, ancestorID)) { deepestNodeSoFar = ancestor; } else { // This node isn't populated in the cache, so presumably none of its // descendants are. Break out of the loop. return false; } } /** * Return the deepest cached node whose ID is a prefix of `targetID`. */ function findDeepestCachedAncestor(targetID) { deepestNodeSoFar = null; ReactInstanceHandles.traverseAncestors( targetID, findDeepestCachedAncestorImpl ); var foundNode = deepestNodeSoFar; deepestNodeSoFar = null; return foundNode; } /** * Mounts this component and inserts it into the DOM. * * @param {ReactComponent} componentInstance The instance to mount. * @param {string} rootID DOM ID of the root node. * @param {DOMElement} container DOM element to mount into. * @param {ReactReconcileTransaction} transaction * @param {boolean} shouldReuseMarkup If true, do not insert markup */ function mountComponentIntoNode( componentInstance, rootID, container, transaction, shouldReuseMarkup) { var markup = ReactReconciler.mountComponent( componentInstance, rootID, transaction, emptyObject ); componentInstance._isTopLevel = true; ReactMount._mountImageIntoNode(markup, container, shouldReuseMarkup); } /** * Batched mount. * * @param {ReactComponent} componentInstance The instance to mount. * @param {string} rootID DOM ID of the root node. * @param {DOMElement} container DOM element to mount into. * @param {boolean} shouldReuseMarkup If true, do not insert markup */ function batchedMountComponentIntoNode( componentInstance, rootID, container, shouldReuseMarkup) { var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(); transaction.perform( mountComponentIntoNode, null, componentInstance, rootID, container, transaction, shouldReuseMarkup ); ReactUpdates.ReactReconcileTransaction.release(transaction); } /** * 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 = { /** Exposed for debugging purposes **/ _instancesByReactRootID: instancesByReactRootID, /** * This is a hook provided to support rendering React components while * ensuring that the apparent scroll position of its `container` does not * change. * * @param {DOMElement} container The `container` being rendered into. * @param {function} renderCallback This must be called once to do the render. */ scrollMonitor: function(container, renderCallback) { renderCallback(); }, /** * Take a component that's already mounted into the DOM and replace its props * @param {ReactComponent} prevComponent component instance already in the DOM * @param {ReactElement} nextElement component instance to render * @param {DOMElement} container container to render into * @param {?function} callback function triggered on completion */ _updateRootComponent: function( prevComponent, nextElement, container, callback) { if ("production" !== process.env.NODE_ENV) { ReactElementValidator.checkAndWarnForMutatedProps(nextElement); } ReactMount.scrollMonitor(container, function() { ReactUpdateQueue.enqueueElementInternal(prevComponent, nextElement); if (callback) { ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback); } }); if ("production" !== process.env.NODE_ENV) { // Record the root element in case it later gets transplanted. rootElementsByReactRootID[getReactRootID(container)] = getReactRootElementInContainer(container); } return prevComponent; }, /** * Register a component into the instance map and starts scroll value * monitoring * @param {ReactComponent} nextComponent component instance to render * @param {DOMElement} container container to render into * @return {string} reactRoot ID prefix */ _registerComponent: function(nextComponent, container) { ("production" !== process.env.NODE_ENV ? invariant( container && ( (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE) ), '_registerComponent(...): Target container is not a DOM element.' ) : invariant(container && ( (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE) ))); ReactBrowserEventEmitter.ensureScrollValueMonitoring(); var reactRootID = ReactMount.registerContainer(container); instancesByReactRootID[reactRootID] = nextComponent; return reactRootID; }, /** * Render a new component into the DOM. * @param {ReactElement} nextElement element to render * @param {DOMElement} container container to render into * @param {boolean} shouldReuseMarkup if we should skip the markup insertion * @return {ReactComponent} nextComponent */ _renderNewRootComponent: function( nextElement, container, shouldReuseMarkup ) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. ("production" !== process.env.NODE_ENV ? 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.' ) : null); var componentInstance = instantiateReactComponent(nextElement, null); var reactRootID = ReactMount._registerComponent( componentInstance, container ); // The initial render is synchronous but any updates that happen during // rendering, in componentWillMount or componentDidMount, will be batched // according to the current batching strategy. ReactUpdates.batchedUpdates( batchedMountComponentIntoNode, componentInstance, reactRootID, container, shouldReuseMarkup ); if ("production" !== process.env.NODE_ENV) { // Record the root element in case it later gets transplanted. rootElementsByReactRootID[reactRootID] = getReactRootElementInContainer(container); } return componentInstance; }, /** * Renders a React component into the DOM in the supplied `container`. * * If the React component was previously rendered into `container`, this will * perform an update on it and only mutate the DOM as necessary to reflect the * latest React component. * * @param {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) { ("production" !== process.env.NODE_ENV ? invariant( ReactElement.isValidElement(nextElement), 'React.render(): Invalid component element.%s', ( typeof nextElement === 'string' ? ' Instead of passing an element string, make sure to instantiate ' + 'it by passing it to React.createElement.' : typeof nextElement === 'function' ? ' Instead of passing a component class, make sure to instantiate ' + 'it by passing it to React.createElement.' : // Check if it quacks like an element nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '' ) ) : invariant(ReactElement.isValidElement(nextElement))); var prevComponent = instancesByReactRootID[getReactRootID(container)]; if (prevComponent) { var prevElement = prevComponent._currentElement; if (shouldUpdateReactComponent(prevElement, nextElement)) { return ReactMount._updateRootComponent( prevComponent, nextElement, container, callback ).getPublicInstance(); } else { ReactMount.unmountComponentAtNode(container); } } var reactRootElement = getReactRootElementInContainer(container); var containerHasReactMarkup = reactRootElement && ReactMount.isRenderedByReact(reactRootElement); if ("production" !== process.env.NODE_ENV) { if (!containerHasReactMarkup || reactRootElement.nextSibling) { var rootElementSibling = reactRootElement; while (rootElementSibling) { if (ReactMount.isRenderedByReact(rootElementSibling)) { ("production" !== process.env.NODE_ENV ? 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.' ) : null); break; } rootElementSibling = rootElementSibling.nextSibling; } } } var shouldReuseMarkup = containerHasReactMarkup && !prevComponent; var component = ReactMount._renderNewRootComponent( nextElement, container, shouldReuseMarkup ).getPublicInstance(); if (callback) { callback.call(component); } return component; }, /** * Constructs a component instance of `constructor` with `initialProps` and * renders it into the supplied `container`. * * @param {function} constructor React component constructor. * @param {?object} props Initial props of the component instance. * @param {DOMElement} container DOM element to render into. * @return {ReactComponent} Component instance rendered in `container`. */ constructAndRenderComponent: function(constructor, props, container) { var element = ReactElement.createElement(constructor, props); return ReactMount.render(element, container); }, /** * Constructs a component instance of `constructor` with `initialProps` and * renders it into a container node identified by supplied `id`. * * @param {function} componentConstructor React component constructor * @param {?object} props Initial props of the component instance. * @param {string} id ID of the DOM element to render into. * @return {ReactComponent} Component instance rendered in the container node. */ constructAndRenderComponentByID: function(constructor, props, id) { var domNode = document.getElementById(id); ("production" !== process.env.NODE_ENV ? invariant( domNode, 'Tried to get element with id of "%s" but it is not present on the page.', id ) : invariant(domNode)); return ReactMount.constructAndRenderComponent(constructor, props, domNode); }, /** * Registers a container node into which React components will be rendered. * This also creates the "reactRoot" ID that will be assigned to the element * rendered within. * * @param {DOMElement} container DOM element to register as a container. * @return {string} The "reactRoot" ID of elements rendered within. */ registerContainer: function(container) { var reactRootID = getReactRootID(container); if (reactRootID) { // If one exists, make sure it is a valid "reactRoot" ID. reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID); } if (!reactRootID) { // No valid "reactRoot" ID found, create one. reactRootID = ReactInstanceHandles.createReactRootID(); } containersByReactRootID[reactRootID] = container; return reactRootID; }, /** * Unmounts and destroys the React component rendered in the `container`. * * @param {DOMElement} container DOM element containing a React component. * @return {boolean} True if a component was found in and unmounted from * `container` */ unmountComponentAtNode: function(container) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (Strictly speaking, unmounting won't cause a // render but we still don't expect to be in a render call here.) ("production" !== process.env.NODE_ENV ? 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.' ) : null); ("production" !== process.env.NODE_ENV ? invariant( container && ( (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE) ), 'unmountComponentAtNode(...): Target container is not a DOM element.' ) : invariant(container && ( (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE) ))); var reactRootID = getReactRootID(container); var component = instancesByReactRootID[reactRootID]; if (!component) { return false; } ReactMount.unmountComponentFromNode(component, container); delete instancesByReactRootID[reactRootID]; delete containersByReactRootID[reactRootID]; if ("production" !== process.env.NODE_ENV) { delete rootElementsByReactRootID[reactRootID]; } return true; }, /** * 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} */ unmountComponentFromNode: function(instance, container) { ReactReconciler.unmountComponent(instance); if (container.nodeType === DOC_NODE_TYPE) { container = container.documentElement; } // http://jsperf.com/emptying-a-node while (container.lastChild) { container.removeChild(container.lastChild); } }, /** * Finds the container DOM element that contains React component to which the * supplied DOM `id` belongs. * * @param {string} id The ID of an element rendered by a React component. * @return {?DOMElement} DOM element that contains the `id`. */ findReactContainerForID: function(id) { var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(id); var container = containersByReactRootID[reactRootID]; if ("production" !== process.env.NODE_ENV) { var rootElement = rootElementsByReactRootID[reactRootID]; if (rootElement && rootElement.parentNode !== container) { ("production" !== process.env.NODE_ENV ? invariant( // Call internalGetID here because getID calls isValid which calls // findReactContainerForID (this function). internalGetID(rootElement) === reactRootID, 'ReactMount: Root element ID differed from reactRootID.' ) : invariant(// Call internalGetID here because getID calls isValid which calls // findReactContainerForID (this function). internalGetID(rootElement) === reactRootID)); var containerChild = container.firstChild; if (containerChild && reactRootID === internalGetID(containerChild)) { // If the container has a new child with the same ID as the old // root element, then rootElementsByReactRootID[reactRootID] is // just stale and needs to be updated. The case that deserves a // warning is when the container is empty. rootElementsByReactRootID[reactRootID] = containerChild; } else { ("production" !== process.env.NODE_ENV ? warning( false, 'ReactMount: Root element has been removed from its original ' + 'container. New container:', rootElement.parentNode ) : null); } } } return container; }, /** * Finds an element rendered by React with the supplied ID. * * @param {string} id ID of a DOM node in the React component. * @return {DOMElement} Root DOM node of the React component. */ findReactNodeByID: function(id) { var reactRoot = ReactMount.findReactContainerForID(id); return ReactMount.findComponentRoot(reactRoot, id); }, /** * True if the supplied `node` is rendered by React. * * @param {*} node DOM Element to check. * @return {boolean} True if the DOM Element appears to be rendered by React. * @internal */ isRenderedByReact: function(node) { if (node.nodeType !== 1) { // Not a DOMElement, therefore not a React component return false; } var id = ReactMount.getID(node); return id ? id.charAt(0) === SEPARATOR : false; }, /** * Traverses up the ancestors of the supplied node to find a node that is a * DOM representation of a React component. * * @param {*} node * @return {?DOMEventTarget} * @internal */ getFirstReactDOM: function(node) { var current = node; while (current && current.parentNode !== current) { if (ReactMount.isRenderedByReact(current)) { return current; } current = current.parentNode; } return null; }, /** * Finds a node with the supplied `targetID` inside of the supplied * `ancestorNode`. Exploits the ID naming scheme to perform the search * quickly. * * @param {DOMEventTarget} ancestorNode Search from this root. * @pararm {string} targetID ID of the DOM representation of the component. * @return {DOMEventTarget} DOM node with the supplied `targetID`. * @internal */ findComponentRoot: function(ancestorNode, targetID) { var firstChildren = findComponentRootReusableArray; var childIndex = 0; var deepestAncestor = findDeepestCachedAncestor(targetID) || ancestorNode; firstChildren[0] = deepestAncestor.firstChild; firstChildren.length = 1; while (childIndex < firstChildren.length) { var child = firstChildren[childIndex++]; var targetChild; while (child) { var childID = ReactMount.getID(child); if (childID) { // Even if we find the node we're looking for, we finish looping // through its siblings to ensure they're cached so that we don't have // to revisit this node again. Otherwise, we make n^2 calls to getID // when visiting the many children of a single node in order. if (targetID === childID) { targetChild = child; } else if (ReactInstanceHandles.isAncestorIDOf(childID, targetID)) { // If we find a child whose ID is an ancestor of the given ID, // then we can be sure that we only want to search the subtree // rooted at this child, so we can throw out the rest of the // search state. firstChildren.length = childIndex = 0; firstChildren.push(child.firstChild); } } else { // If this child had no ID, then there's a chance that it was // injected automatically by the browser, as when a `<table>` // element sprouts an extra `<tbody>` child as a side effect of // `.innerHTML` parsing. Optimistically continue down this // branch, but not before examining the other siblings. firstChildren.push(child.firstChild); } child = child.nextSibling; } if (targetChild) { // Emptying firstChildren/findComponentRootReusableArray is // not necessary for correctness, but it helps the GC reclaim // any nodes that were left at the end of the search. firstChildren.length = 0; return targetChild; } } firstChildren.length = 0; ("production" !== process.env.NODE_ENV ? invariant( false, 'findComponentRoot(..., %s): Unable to find element. This probably ' + 'means the DOM was unexpectedly mutated (e.g., by the browser), ' + 'usually due to forgetting a <tbody> when using tables, nesting tags ' + 'like <form>, <p>, or <a>, or using non-SVG elements in an <svg> ' + 'parent. ' + 'Try inspecting the child nodes of the element with React ID `%s`.', targetID, ReactMount.getID(ancestorNode) ) : invariant(false)); }, _mountImageIntoNode: function(markup, container, shouldReuseMarkup) { ("production" !== process.env.NODE_ENV ? invariant( container && ( (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE) ), 'mountComponentIntoNode(...): Target container is not valid.' ) : invariant(container && ( (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE) ))); if (shouldReuseMarkup) { var rootElement = getReactRootElementInContainer(container); if (ReactMarkupChecksum.canReuseMarkup(markup, rootElement)) { return; } else { var checksum = rootElement.getAttribute( ReactMarkupChecksum.CHECKSUM_ATTR_NAME ); rootElement.removeAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); var rootMarkup = rootElement.outerHTML; rootElement.setAttribute( ReactMarkupChecksum.CHECKSUM_ATTR_NAME, checksum ); var diffIndex = firstDifferenceIndex(markup, rootMarkup); var difference = ' (client) ' + markup.substring(diffIndex - 20, diffIndex + 20) + '\n (server) ' + rootMarkup.substring(diffIndex - 20, diffIndex + 20); ("production" !== process.env.NODE_ENV ? invariant( container.nodeType !== DOC_NODE_TYPE, 'You\'re trying to render a component to the document using ' + 'server rendering but the checksum was invalid. This usually ' + 'means you rendered a different component type or props on ' + 'the client from the one on the server, or your render() ' + 'methods are impure. React cannot handle this case due to ' + 'cross-browser quirks by rendering at the document root. You ' + 'should look for environment dependent code in your components ' + 'and ensure the props are the same client and server side:\n%s', difference ) : invariant(container.nodeType !== DOC_NODE_TYPE)); if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? 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 ) : null); } } } ("production" !== process.env.NODE_ENV ? invariant( container.nodeType !== DOC_NODE_TYPE, 'You\'re trying to render a component to the document but ' + 'you didn\'t use server rendering. We can\'t do this ' + 'without using server rendering due to cross-browser quirks. ' + 'See React.renderToString() for server rendering.' ) : invariant(container.nodeType !== DOC_NODE_TYPE)); setInnerHTML(container, markup); }, /** * React ID utilities. */ getReactRootID: getReactRootID, getID: getID, setID: setID, getNode: getNode, getNodeFromInstance: getNodeFromInstance, purgeID: purgeID }; ReactPerf.measureMethods(ReactMount, 'ReactMount', { _renderNewRootComponent: '_renderNewRootComponent', _mountImageIntoNode: '_mountImageIntoNode' }); module.exports = ReactMount; }).call(this,require('_process')) },{"./DOMProperty":10,"./ReactBrowserEventEmitter":31,"./ReactCurrentOwner":40,"./ReactElement":58,"./ReactElementValidator":59,"./ReactEmptyComponent":60,"./ReactInstanceHandles":67,"./ReactInstanceMap":68,"./ReactMarkupChecksum":70,"./ReactPerf":76,"./ReactReconciler":82,"./ReactUpdateQueue":87,"./ReactUpdates":88,"./containsNode":110,"./emptyObject":116,"./getReactRootElementInContainer":130,"./instantiateReactComponent":135,"./invariant":136,"./setInnerHTML":149,"./shouldUpdateReactComponent":152,"./warning":155,"_process":1}],72:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMultiChild * @typechecks static-only */ 'use strict'; var ReactComponentEnvironment = require("./ReactComponentEnvironment"); var ReactMultiChildUpdateTypes = require("./ReactMultiChildUpdateTypes"); var ReactReconciler = require("./ReactReconciler"); var ReactChildReconciler = require("./ReactChildReconciler"); /** * Updating children of a component may trigger recursive updates. The depth is * used to batch recursive updates to render markup more efficiently. * * @type {number} * @private */ var updateDepth = 0; /** * Queue of update configuration objects. * * Each object has a `type` property that is in `ReactMultiChildUpdateTypes`. * * @type {array<object>} * @private */ var updateQueue = []; /** * Queue of markup to be rendered. * * @type {array<string>} * @private */ var markupQueue = []; /** * Enqueues markup to be rendered and inserted at a supplied index. * * @param {string} parentID ID of the parent component. * @param {string} markup Markup that renders into an element. * @param {number} toIndex Destination index. * @private */ function enqueueMarkup(parentID, markup, toIndex) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.INSERT_MARKUP, markupIndex: markupQueue.push(markup) - 1, textContent: null, fromIndex: null, toIndex: toIndex }); } /** * Enqueues moving an existing element to another index. * * @param {string} parentID ID of the parent component. * @param {number} fromIndex Source index of the existing element. * @param {number} toIndex Destination index of the element. * @private */ function enqueueMove(parentID, fromIndex, toIndex) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.MOVE_EXISTING, markupIndex: null, textContent: null, fromIndex: fromIndex, toIndex: toIndex }); } /** * Enqueues removing an element at an index. * * @param {string} parentID ID of the parent component. * @param {number} fromIndex Index of the element to remove. * @private */ function enqueueRemove(parentID, fromIndex) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.REMOVE_NODE, markupIndex: null, textContent: null, fromIndex: fromIndex, toIndex: null }); } /** * Enqueues setting the text content. * * @param {string} parentID ID of the parent component. * @param {string} textContent Text content to set. * @private */ function enqueueTextContent(parentID, textContent) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.TEXT_CONTENT, markupIndex: null, textContent: textContent, fromIndex: null, toIndex: null }); } /** * Processes any enqueued updates. * * @private */ function processQueue() { if (updateQueue.length) { ReactComponentEnvironment.processChildrenUpdates( updateQueue, markupQueue ); clearQueue(); } } /** * Clears any enqueued updates. * * @private */ function clearQueue() { updateQueue.length = 0; markupQueue.length = 0; } /** * ReactMultiChild are capable of reconciling multiple children. * * @class ReactMultiChild * @internal */ var ReactMultiChild = { /** * Provides common functionality for components that must reconcile multiple * children. This is used by `ReactDOMComponent` to mount, update, and * unmount child components. * * @lends {ReactMultiChild.prototype} */ Mixin: { /** * 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 = ReactChildReconciler.instantiateChildren( nestedChildren, transaction, context ); this._renderedChildren = children; var mountImages = []; var index = 0; for (var name in children) { if (children.hasOwnProperty(name)) { var child = children[name]; // Inlined for performance, see `ReactInstanceHandles.createReactID`. var rootID = this._rootNodeID + name; var mountImage = ReactReconciler.mountComponent( child, rootID, transaction, context ); child._mountIndex = index; mountImages.push(mountImage); index++; } } return mountImages; }, /** * Replaces any rendered children with a text content string. * * @param {string} nextContent String of content. * @internal */ updateTextContent: function(nextContent) { updateDepth++; var errorThrown = true; try { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren); // TODO: The setTextContent operation should be enough for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { this._unmountChildByName(prevChildren[name], name); } } // Set new text content. this.setTextContent(nextContent); errorThrown = false; } finally { updateDepth--; if (!updateDepth) { if (errorThrown) { clearQueue(); } else { processQueue(); } } } }, /** * Updates the rendered children with new children. * * @param {?object} nextNestedChildren Nested child maps. * @param {ReactReconcileTransaction} transaction * @internal */ updateChildren: function(nextNestedChildren, transaction, context) { updateDepth++; var errorThrown = true; try { this._updateChildren(nextNestedChildren, transaction, context); errorThrown = false; } finally { updateDepth--; if (!updateDepth) { if (errorThrown) { clearQueue(); } else { processQueue(); } } } }, /** * Improve performance by isolating this hot code path from the try/catch * block in `updateChildren`. * * @param {?object} nextNestedChildren Nested child maps. * @param {ReactReconcileTransaction} transaction * @final * @protected */ _updateChildren: function(nextNestedChildren, transaction, context) { var prevChildren = this._renderedChildren; var nextChildren = ReactChildReconciler.updateChildren( prevChildren, nextNestedChildren, transaction, context ); this._renderedChildren = nextChildren; if (!nextChildren && !prevChildren) { return; } var name; // `nextIndex` will increment for each child in `nextChildren`, but // `lastIndex` will be the last index visited in `prevChildren`. var lastIndex = 0; var nextIndex = 0; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } var prevChild = prevChildren && prevChildren[name]; var nextChild = nextChildren[name]; if (prevChild === nextChild) { this.moveChild(prevChild, nextIndex, lastIndex); lastIndex = Math.max(prevChild._mountIndex, lastIndex); prevChild._mountIndex = nextIndex; } else { if (prevChild) { // Update `lastIndex` before `_mountIndex` gets unset by unmounting. lastIndex = Math.max(prevChild._mountIndex, lastIndex); this._unmountChildByName(prevChild, name); } // The child must be instantiated before it's mounted. this._mountChildByNameAtIndex( nextChild, name, nextIndex, transaction, context ); } nextIndex++; } // Remove children that are no longer present. for (name in prevChildren) { if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) { this._unmountChildByName(prevChildren[name], name); } } }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. * * @internal */ unmountChildren: function() { var renderedChildren = this._renderedChildren; ReactChildReconciler.unmountChildren(renderedChildren); this._renderedChildren = null; }, /** * Moves a child component to the supplied index. * * @param {ReactComponent} child Component to move. * @param {number} toIndex Destination index of the element. * @param {number} lastIndex Last index visited of the siblings of `child`. * @protected */ moveChild: function(child, toIndex, lastIndex) { // If the index of `child` is less than `lastIndex`, then it needs to // be moved. Otherwise, we do not need to move it because a child will be // inserted or moved before `child`. if (child._mountIndex < lastIndex) { enqueueMove(this._rootNodeID, child._mountIndex, toIndex); } }, /** * Creates a child component. * * @param {ReactComponent} child Component to create. * @param {string} mountImage Markup to insert. * @protected */ createChild: function(child, mountImage) { enqueueMarkup(this._rootNodeID, mountImage, child._mountIndex); }, /** * Removes a child component. * * @param {ReactComponent} child Child to remove. * @protected */ removeChild: function(child) { enqueueRemove(this._rootNodeID, child._mountIndex); }, /** * Sets this text content string. * * @param {string} textContent Text content to set. * @protected */ setTextContent: function(textContent) { enqueueTextContent(this._rootNodeID, textContent); }, /** * Mounts a child with the supplied name. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to mount. * @param {string} name Name of the child. * @param {number} index Index at which to insert the child. * @param {ReactReconcileTransaction} transaction * @private */ _mountChildByNameAtIndex: function( child, name, index, transaction, context) { // Inlined for performance, see `ReactInstanceHandles.createReactID`. var rootID = this._rootNodeID + name; var mountImage = ReactReconciler.mountComponent( child, rootID, transaction, context ); child._mountIndex = index; this.createChild(child, mountImage); }, /** * Unmounts a rendered child by name. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to unmount. * @param {string} name Name of the child in `this._renderedChildren`. * @private */ _unmountChildByName: function(child, name) { this.removeChild(child); child._mountIndex = null; } } }; module.exports = ReactMultiChild; },{"./ReactChildReconciler":32,"./ReactComponentEnvironment":37,"./ReactMultiChildUpdateTypes":73,"./ReactReconciler":82}],73:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMultiChildUpdateTypes */ 'use strict'; var keyMirror = require("./keyMirror"); /** * 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, TEXT_CONTENT: null }); module.exports = ReactMultiChildUpdateTypes; },{"./keyMirror":141}],74:[function(require,module,exports){ (function (process){ /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactNativeComponent */ 'use strict'; var assign = require("./Object.assign"); var invariant = require("./invariant"); var autoGenerateWrapperClass = null; var genericComponentClass = null; // This registry keeps track of wrapper classes around native tags var tagToComponentClass = {}; var textComponentClass = null; var ReactNativeComponentInjection = { // This accepts a class that receives the tag string. This is a catch all // that can render any kind of tag. injectGenericComponentClass: function(componentClass) { genericComponentClass = componentClass; }, // This accepts a text component class that takes the text string to be // rendered as props. injectTextComponentClass: function(componentClass) { textComponentClass = componentClass; }, // This accepts a keyed object with classes as values. Each key represents a // tag. That particular tag will use this class instead of the generic one. injectComponentClasses: function(componentClasses) { assign(tagToComponentClass, componentClasses); }, // Temporary hack since we expect DOM refs to behave like composites, // for this release. injectAutoWrapper: function(wrapperFactory) { autoGenerateWrapperClass = wrapperFactory; } }; /** * Get a composite component wrapper class for a specific tag. * * @param {ReactElement} element The tag for which to get the class. * @return {function} The React class constructor function. */ function getComponentClassForElement(element) { if (typeof element.type === 'function') { return element.type; } var tag = element.type; var componentClass = tagToComponentClass[tag]; if (componentClass == null) { tagToComponentClass[tag] = componentClass = autoGenerateWrapperClass(tag); } return componentClass; } /** * Get a native internal component class for a specific tag. * * @param {ReactElement} element The element to create. * @return {function} The internal class constructor function. */ function createInternalComponent(element) { ("production" !== process.env.NODE_ENV ? invariant( genericComponentClass, 'There is no registered component for the tag %s', element.type ) : invariant(genericComponentClass)); return new genericComponentClass(element.type, element.props); } /** * @param {ReactText} text * @return {ReactComponent} */ function createInstanceForText(text) { return new textComponentClass(text); } /** * @param {ReactComponent} component * @return {boolean} */ function isTextComponent(component) { return component instanceof textComponentClass; } var ReactNativeComponent = { getComponentClassForElement: getComponentClassForElement, createInternalComponent: createInternalComponent, createInstanceForText: createInstanceForText, isTextComponent: isTextComponent, injection: ReactNativeComponentInjection }; module.exports = ReactNativeComponent; }).call(this,require('_process')) },{"./Object.assign":27,"./invariant":136,"_process":1}],75:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactOwner */ 'use strict'; var invariant = require("./invariant"); /** * 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) { ("production" !== process.env.NODE_ENV ? invariant( ReactOwner.isValidOwner(owner), 'addComponentAsRefTo(...): Only a ReactOwner can have refs. This ' + 'usually means that you\'re trying to add a ref to a component that ' + 'doesn\'t have an owner (that is, was not created inside of another ' + 'component\'s `render` method). Try rendering this component inside of ' + 'a new top-level component which will hold the ref.' ) : invariant(ReactOwner.isValidOwner(owner))); 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) { ("production" !== process.env.NODE_ENV ? invariant( ReactOwner.isValidOwner(owner), 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. This ' + 'usually means that you\'re trying to remove a ref to a component that ' + 'doesn\'t have an owner (that is, was not created inside of another ' + 'component\'s `render` method). Try rendering this component inside of ' + 'a new top-level component which will hold the ref.' ) : invariant(ReactOwner.isValidOwner(owner))); // Check that `component` is still the current ref because we do not want to // detach the ref if another component stole it. if (owner.getPublicInstance().refs[ref] === component.getPublicInstance()) { owner.detachRef(ref); } } }; module.exports = ReactOwner; }).call(this,require('_process')) },{"./invariant":136,"_process":1}],76:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPerf * @typechecks static-only */ 'use strict'; /** * ReactPerf is a general AOP system designed to measure performance. This * module only has the hooks: see ReactDefaultPerf for the analysis tool. */ var ReactPerf = { /** * Boolean to enable/disable measurement. Set to false by default to prevent * accidental logging and perf loss. */ enableMeasure: false, /** * Holds onto the measure function in use. By default, don't measure * anything, but we'll override this if we inject a measure function. */ storedMeasure: _noMeasure, /** * @param {object} object * @param {string} objectName * @param {object<string>} methodNames */ measureMethods: function(object, objectName, methodNames) { if ("production" !== process.env.NODE_ENV) { for (var key in methodNames) { if (!methodNames.hasOwnProperty(key)) { continue; } object[key] = ReactPerf.measure( objectName, methodNames[key], object[key] ); } } }, /** * Use this to wrap methods you want to measure. Zero overhead in production. * * @param {string} objName * @param {string} fnName * @param {function} func * @return {function} */ measure: function(objName, fnName, func) { if ("production" !== process.env.NODE_ENV) { var measuredFunc = null; var wrapper = function() { if (ReactPerf.enableMeasure) { if (!measuredFunc) { measuredFunc = ReactPerf.storedMeasure(objName, fnName, func); } return measuredFunc.apply(this, arguments); } return func.apply(this, arguments); }; wrapper.displayName = objName + '_' + fnName; return wrapper; } return func; }, injection: { /** * @param {function} measure */ injectMeasure: function(measure) { ReactPerf.storedMeasure = measure; } } }; /** * Simply passes through the measured function, without measuring it. * * @param {string} objName * @param {string} fnName * @param {function} func * @return {function} */ function _noMeasure(objName, fnName, func) { return func; } module.exports = ReactPerf; }).call(this,require('_process')) },{"_process":1}],77:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypeLocationNames */ 'use strict'; var ReactPropTypeLocationNames = {}; if ("production" !== process.env.NODE_ENV) { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } module.exports = ReactPropTypeLocationNames; }).call(this,require('_process')) },{"_process":1}],78:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypeLocations */ 'use strict'; var keyMirror = require("./keyMirror"); var ReactPropTypeLocations = keyMirror({ prop: null, context: null, childContext: null }); module.exports = ReactPropTypeLocations; },{"./keyMirror":141}],79:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypes */ 'use strict'; var ReactElement = require("./ReactElement"); var ReactFragment = require("./ReactFragment"); var ReactPropTypeLocationNames = require("./ReactPropTypeLocationNames"); var emptyFunction = require("./emptyFunction"); /** * 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 elementTypeChecker = createElementTypeChecker(); var nodeTypeChecker = createNodeChecker(); var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: elementTypeChecker, instanceOf: createInstanceTypeChecker, node: nodeTypeChecker, objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker }; function createChainableTypeChecker(validate) { function checkType(isRequired, props, propName, componentName, location) { componentName = componentName || ANONYMOUS; if (props[propName] == null) { var locationName = ReactPropTypeLocationNames[location]; if (isRequired) { return new Error( ("Required " + locationName + " `" + propName + "` was not specified in ") + ("`" + componentName + "`.") ); } return null; } else { return validate(props, propName, componentName, location); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location) { 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 + " `" + propName + "` 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) { var propValue = props[propName]; if (!Array.isArray(propValue)) { var locationName = ReactPropTypeLocationNames[location]; var propType = getPropType(propValue); return new Error( ("Invalid " + locationName + " `" + propName + "` of type ") + ("`" + propType + "` supplied to `" + componentName + "`, expected an array.") ); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location) { if (!ReactElement.isValidElement(props[propName])) { var locationName = ReactPropTypeLocationNames[location]; return new Error( ("Invalid " + locationName + " `" + propName + "` supplied to ") + ("`" + componentName + "`, expected a ReactElement.") ); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location) { if (!(props[propName] instanceof expectedClass)) { var locationName = ReactPropTypeLocationNames[location]; var expectedClassName = expectedClass.name || ANONYMOUS; return new Error( ("Invalid " + locationName + " `" + propName + "` supplied to ") + ("`" + componentName + "`, expected instance of `" + expectedClassName + "`.") ); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { function validate(props, propName, componentName, location) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (propValue === expectedValues[i]) { return null; } } var locationName = ReactPropTypeLocationNames[location]; var valuesString = JSON.stringify(expectedValues); return new Error( ("Invalid " + locationName + " `" + propName + "` of value `" + propValue + "` ") + ("supplied to `" + componentName + "`, expected one of " + valuesString + ".") ); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new Error( ("Invalid " + locationName + " `" + propName + "` 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); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { function validate(props, propName, componentName, location) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location) == null) { return null; } } var locationName = ReactPropTypeLocationNames[location]; return new Error( ("Invalid " + locationName + " `" + propName + "` supplied to ") + ("`" + componentName + "`.") ); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location) { if (!isNode(props[propName])) { var locationName = ReactPropTypeLocationNames[location]; return new Error( ("Invalid " + locationName + " `" + propName + "` supplied to ") + ("`" + componentName + "`, expected a ReactNode.") ); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new Error( ("Invalid " + locationName + " `" + propName + "` 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); 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; } propValue = ReactFragment.extractIfFragment(propValue); for (var k in propValue) { if (!isNode(propValue[k])) { return false; } } return true; default: return false; } } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } module.exports = ReactPropTypes; },{"./ReactElement":58,"./ReactFragment":64,"./ReactPropTypeLocationNames":77,"./emptyFunction":115}],80:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPutListenerQueue */ 'use strict'; var PooledClass = require("./PooledClass"); var ReactBrowserEventEmitter = require("./ReactBrowserEventEmitter"); var assign = require("./Object.assign"); function ReactPutListenerQueue() { this.listenersToPut = []; } assign(ReactPutListenerQueue.prototype, { enqueuePutListener: function(rootNodeID, propKey, propValue) { this.listenersToPut.push({ rootNodeID: rootNodeID, propKey: propKey, propValue: propValue }); }, putListeners: function() { for (var i = 0; i < this.listenersToPut.length; i++) { var listenerToPut = this.listenersToPut[i]; ReactBrowserEventEmitter.putListener( listenerToPut.rootNodeID, listenerToPut.propKey, listenerToPut.propValue ); } }, reset: function() { this.listenersToPut.length = 0; }, destructor: function() { this.reset(); } }); PooledClass.addPoolingTo(ReactPutListenerQueue); module.exports = ReactPutListenerQueue; },{"./Object.assign":27,"./PooledClass":28,"./ReactBrowserEventEmitter":31}],81:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactReconcileTransaction * @typechecks static-only */ 'use strict'; var CallbackQueue = require("./CallbackQueue"); var PooledClass = require("./PooledClass"); var ReactBrowserEventEmitter = require("./ReactBrowserEventEmitter"); var ReactInputSelection = require("./ReactInputSelection"); var ReactPutListenerQueue = require("./ReactPutListenerQueue"); var Transaction = require("./Transaction"); var assign = require("./Object.assign"); /** * 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 occured. `close` * restores the previous value. */ close: function(previouslyEnabled) { ReactBrowserEventEmitter.setEnabled(previouslyEnabled); } }; /** * Provides a queue for collecting `componentDidMount` and * `componentDidUpdate` callbacks during the the transaction. */ var ON_DOM_READY_QUEUEING = { /** * Initializes the internal `onDOMReady` queue. */ initialize: function() { this.reactMountReady.reset(); }, /** * After DOM is flushed, invoke all registered `onDOMReady` callbacks. */ close: function() { this.reactMountReady.notifyAll(); } }; var PUT_LISTENER_QUEUEING = { initialize: function() { this.putListenerQueue.reset(); }, close: function() { this.putListenerQueue.putListeners(); } }; /** * 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 = [ PUT_LISTENER_QUEUEING, SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING ]; /** * Currently: * - The order that these are listed in the transaction is critical: * - Suppresses events. * - Restores selection range. * * Future: * - Restore document/overflow scroll positions that were unintentionally * modified via DOM insertions above the top viewport boundary. * - Implement/integrate with customized constraint based layout system and keep * track of which dimensions must be remeasured. * * @class ReactReconcileTransaction */ function ReactReconcileTransaction() { this.reinitializeTransaction(); // Only server-side rendering really needs this option (see // `ReactServerRendering`), but server-side uses // `ReactServerRenderingTransaction` instead. This option is here so that it's // accessible and defaults to false when `ReactDOMComponent` and // `ReactTextComponent` checks it in `mountComponent`.` this.renderToStaticMarkup = false; this.reactMountReady = CallbackQueue.getPooled(null); this.putListenerQueue = ReactPutListenerQueue.getPooled(); } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array<object>} List of operation wrap proceedures. * TODO: convert to array<TransactionWrapper> */ getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function() { return this.reactMountReady; }, getPutListenerQueue: function() { return this.putListenerQueue; }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be resused. */ destructor: function() { CallbackQueue.release(this.reactMountReady); this.reactMountReady = null; ReactPutListenerQueue.release(this.putListenerQueue); this.putListenerQueue = null; } }; assign(ReactReconcileTransaction.prototype, Transaction.Mixin, Mixin); PooledClass.addPoolingTo(ReactReconcileTransaction); module.exports = ReactReconcileTransaction; },{"./CallbackQueue":6,"./Object.assign":27,"./PooledClass":28,"./ReactBrowserEventEmitter":31,"./ReactInputSelection":66,"./ReactPutListenerQueue":80,"./Transaction":104}],82:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactReconciler */ 'use strict'; var ReactRef = require("./ReactRef"); var ReactElementValidator = require("./ReactElementValidator"); /** * Helper to call ReactRef.attachRefs with this composite component, split out * to avoid allocations in the transaction mount-ready queue. */ function attachRefs() { ReactRef.attachRefs(this, this._currentElement); } var ReactReconciler = { /** * Initializes the component, renders markup, and registers event listeners. * * @param {ReactComponent} internalInstance * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function(internalInstance, rootID, transaction, context) { var markup = internalInstance.mountComponent(rootID, transaction, context); if ("production" !== process.env.NODE_ENV) { ReactElementValidator.checkAndWarnForMutatedProps( internalInstance._currentElement ); } transaction.getReactMountReady().enqueue(attachRefs, internalInstance); return markup; }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function(internalInstance) { ReactRef.detachRefs(internalInstance, internalInstance._currentElement); internalInstance.unmountComponent(); }, /** * Update a component using a new element. * * @param {ReactComponent} internalInstance * @param {ReactElement} nextElement * @param {ReactReconcileTransaction} transaction * @param {object} context * @internal */ receiveComponent: function( internalInstance, nextElement, transaction, context ) { var prevElement = internalInstance._currentElement; if (nextElement === prevElement && nextElement._owner != null) { // 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. return; } if ("production" !== process.env.NODE_ENV) { ReactElementValidator.checkAndWarnForMutatedProps(nextElement); } var refsChanged = ReactRef.shouldUpdateRefs( prevElement, nextElement ); if (refsChanged) { ReactRef.detachRefs(internalInstance, prevElement); } internalInstance.receiveComponent(nextElement, transaction, context); if (refsChanged) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } }, /** * Flush any dirty changes in a component. * * @param {ReactComponent} internalInstance * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function( internalInstance, transaction ) { internalInstance.performUpdateIfNecessary(transaction); } }; module.exports = ReactReconciler; }).call(this,require('_process')) },{"./ReactElementValidator":59,"./ReactRef":83,"_process":1}],83:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactRef */ 'use strict'; var ReactOwner = require("./ReactOwner"); 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) { 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. return ( nextElement._owner !== prevElement._owner || nextElement.ref !== prevElement.ref ); }; ReactRef.detachRefs = function(instance, element) { var ref = element.ref; if (ref != null) { detachRef(ref, instance, element._owner); } }; module.exports = ReactRef; },{"./ReactOwner":75}],84:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactRootIndex * @typechecks */ 'use strict'; var ReactRootIndexInjection = { /** * @param {function} _createReactRootIndex */ injectCreateReactRootIndex: function(_createReactRootIndex) { ReactRootIndex.createReactRootIndex = _createReactRootIndex; } }; var ReactRootIndex = { createReactRootIndex: null, injection: ReactRootIndexInjection }; module.exports = ReactRootIndex; },{}],85:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks static-only * @providesModule ReactServerRendering */ 'use strict'; var ReactElement = require("./ReactElement"); var ReactInstanceHandles = require("./ReactInstanceHandles"); var ReactMarkupChecksum = require("./ReactMarkupChecksum"); var ReactServerRenderingTransaction = require("./ReactServerRenderingTransaction"); var emptyObject = require("./emptyObject"); var instantiateReactComponent = require("./instantiateReactComponent"); var invariant = require("./invariant"); /** * @param {ReactElement} element * @return {string} the HTML markup */ function renderToString(element) { ("production" !== process.env.NODE_ENV ? invariant( ReactElement.isValidElement(element), 'renderToString(): You must pass a valid ReactElement.' ) : invariant(ReactElement.isValidElement(element))); var transaction; try { var id = ReactInstanceHandles.createReactRootID(); transaction = ReactServerRenderingTransaction.getPooled(false); return transaction.perform(function() { var componentInstance = instantiateReactComponent(element, null); var markup = componentInstance.mountComponent(id, transaction, emptyObject); return ReactMarkupChecksum.addChecksumToMarkup(markup); }, null); } finally { ReactServerRenderingTransaction.release(transaction); } } /** * @param {ReactElement} element * @return {string} the HTML markup, without the extra React ID and checksum * (for generating static pages) */ function renderToStaticMarkup(element) { ("production" !== process.env.NODE_ENV ? invariant( ReactElement.isValidElement(element), 'renderToStaticMarkup(): You must pass a valid ReactElement.' ) : invariant(ReactElement.isValidElement(element))); var transaction; try { var id = ReactInstanceHandles.createReactRootID(); transaction = ReactServerRenderingTransaction.getPooled(true); return transaction.perform(function() { var componentInstance = instantiateReactComponent(element, null); return componentInstance.mountComponent(id, transaction, emptyObject); }, null); } finally { ReactServerRenderingTransaction.release(transaction); } } module.exports = { renderToString: renderToString, renderToStaticMarkup: renderToStaticMarkup }; }).call(this,require('_process')) },{"./ReactElement":58,"./ReactInstanceHandles":67,"./ReactMarkupChecksum":70,"./ReactServerRenderingTransaction":86,"./emptyObject":116,"./instantiateReactComponent":135,"./invariant":136,"_process":1}],86:[function(require,module,exports){ /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactServerRenderingTransaction * @typechecks */ 'use strict'; var PooledClass = require("./PooledClass"); var CallbackQueue = require("./CallbackQueue"); var ReactPutListenerQueue = require("./ReactPutListenerQueue"); var Transaction = require("./Transaction"); var assign = require("./Object.assign"); var emptyFunction = require("./emptyFunction"); /** * Provides a `CallbackQueue` queue for collecting `onDOMReady` callbacks * during the performing of the transaction. */ var ON_DOM_READY_QUEUEING = { /** * Initializes the internal `onDOMReady` queue. */ initialize: function() { this.reactMountReady.reset(); }, close: emptyFunction }; var PUT_LISTENER_QUEUEING = { initialize: function() { this.putListenerQueue.reset(); }, close: emptyFunction }; /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = [ PUT_LISTENER_QUEUEING, ON_DOM_READY_QUEUEING ]; /** * @class ReactServerRenderingTransaction * @param {boolean} renderToStaticMarkup */ function ReactServerRenderingTransaction(renderToStaticMarkup) { this.reinitializeTransaction(); this.renderToStaticMarkup = renderToStaticMarkup; this.reactMountReady = CallbackQueue.getPooled(null); this.putListenerQueue = ReactPutListenerQueue.getPooled(); } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array} Empty list of operation wrap proceedures. */ getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function() { return this.reactMountReady; }, getPutListenerQueue: function() { return this.putListenerQueue; }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be resused. */ destructor: function() { CallbackQueue.release(this.reactMountReady); this.reactMountReady = null; ReactPutListenerQueue.release(this.putListenerQueue); this.putListenerQueue = null; } }; assign( ReactServerRenderingTransaction.prototype, Transaction.Mixin, Mixin ); PooledClass.addPoolingTo(ReactServerRenderingTransaction); module.exports = ReactServerRenderingTransaction; },{"./CallbackQueue":6,"./Object.assign":27,"./PooledClass":28,"./ReactPutListenerQueue":80,"./Transaction":104,"./emptyFunction":115}],87:[function(require,module,exports){ (function (process){ /** * Copyright 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactUpdateQueue */ 'use strict'; var ReactLifeCycle = require("./ReactLifeCycle"); var ReactCurrentOwner = require("./ReactCurrentOwner"); var ReactElement = require("./ReactElement"); var ReactInstanceMap = require("./ReactInstanceMap"); var ReactUpdates = require("./ReactUpdates"); var assign = require("./Object.assign"); var invariant = require("./invariant"); var warning = require("./warning"); function enqueueUpdate(internalInstance) { if (internalInstance !== ReactLifeCycle.currentlyMountingInstance) { // If we're in a componentWillMount handler, don't enqueue a rerender // because ReactUpdates assumes we're in a browser context (which is // wrong for server rendering) and we're about to do a render anyway. // See bug in #1740. ReactUpdates.enqueueUpdate(internalInstance); } } function getInternalInstanceReadyForUpdate(publicInstance, callerName) { ("production" !== process.env.NODE_ENV ? invariant( ReactCurrentOwner.current == null, '%s(...): Cannot update during an existing state transition ' + '(such as within `render`). Render methods should be a pure function ' + 'of props and state.', callerName ) : invariant(ReactCurrentOwner.current == null)); var internalInstance = ReactInstanceMap.get(publicInstance); if (!internalInstance) { if ("production" !== process.env.NODE_ENV) { // 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. ("production" !== process.env.NODE_ENV ? 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.', callerName, callerName ) : null); } return null; } if (internalInstance === ReactLifeCycle.currentlyUnmountingInstance) { return null; } return internalInstance; } /** * ReactUpdateQueue allows for state updates to be scheduled into a later * reconciliation step. */ var ReactUpdateQueue = { /** * 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) { ("production" !== process.env.NODE_ENV ? invariant( typeof callback === 'function', 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.' ) : invariant(typeof callback === 'function')); 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 || internalInstance === ReactLifeCycle.currentlyMountingInstance) { 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) { ("production" !== process.env.NODE_ENV ? invariant( typeof callback === 'function', 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.' ) : invariant(typeof callback === 'function')); 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 `shouldUpdateComponent`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ enqueueForceUpdate: function(publicInstance) { var internalInstance = getInternalInstanceReadyForUpdate( publicInstance, 'forceUpdate' ); if (!internalInstance) { return; } internalInstance._pendingForceUpdate = true; enqueueUpdate(internalInstance); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @internal */ enqueueReplaceState: function(publicInstance, completeState) { var internalInstance = getInternalInstanceReadyForUpdate( publicInstance, 'replaceState' ); if (!internalInstance) { return; } internalInstance._pendingStateQueue = [completeState]; internalInstance._pendingReplaceState = true; enqueueUpdate(internalInstance); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @internal */ enqueueSetState: function(publicInstance, partialState) { var internalInstance = getInternalInstanceReadyForUpdate( publicInstance, 'setState' ); if (!internalInstance) { return; } var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []); queue.push(partialState); enqueueUpdate(internalInstance); }, /** * Sets a subset of the props. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialProps Subset of the next props. * @internal */ enqueueSetProps: function(publicInstance, partialProps) { var internalInstance = getInternalInstanceReadyForUpdate( publicInstance, 'setProps' ); if (!internalInstance) { return; } ("production" !== process.env.NODE_ENV ? invariant( internalInstance._isTopLevel, 'setProps(...): You called `setProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.' ) : invariant(internalInstance._isTopLevel)); // Merge with the pending element if it exists, otherwise with existing // element props. var element = internalInstance._pendingElement || internalInstance._currentElement; var props = assign({}, element.props, partialProps); internalInstance._pendingElement = ReactElement.cloneAndReplaceProps( element, props ); enqueueUpdate(internalInstance); }, /** * Replaces all of the props. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} props New props. * @internal */ enqueueReplaceProps: function(publicInstance, props) { var internalInstance = getInternalInstanceReadyForUpdate( publicInstance, 'replaceProps' ); if (!internalInstance) { return; } ("production" !== process.env.NODE_ENV ? invariant( internalInstance._isTopLevel, 'replaceProps(...): You called `replaceProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.' ) : invariant(internalInstance._isTopLevel)); // Merge with the pending element if it exists, otherwise with existing // element props. var element = internalInstance._pendingElement || internalInstance._currentElement; internalInstance._pendingElement = ReactElement.cloneAndReplaceProps( element, props ); enqueueUpdate(internalInstance); }, enqueueElementInternal: function(internalInstance, newElement) { internalInstance._pendingElement = newElement; enqueueUpdate(internalInstance); } }; module.exports = ReactUpdateQueue; }).call(this,require('_process')) },{"./Object.assign":27,"./ReactCurrentOwner":40,"./ReactElement":58,"./ReactInstanceMap":68,"./ReactLifeCycle":69,"./ReactUpdates":88,"./invariant":136,"./warning":155,"_process":1}],88:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactUpdates */ 'use strict'; var CallbackQueue = require("./CallbackQueue"); var PooledClass = require("./PooledClass"); var ReactCurrentOwner = require("./ReactCurrentOwner"); var ReactPerf = require("./ReactPerf"); var ReactReconciler = require("./ReactReconciler"); var Transaction = require("./Transaction"); var assign = require("./Object.assign"); var invariant = require("./invariant"); var warning = require("./warning"); var dirtyComponents = []; var asapCallbackQueue = CallbackQueue.getPooled(); var asapEnqueued = false; var batchingStrategy = null; function ensureInjected() { ("production" !== process.env.NODE_ENV ? invariant( ReactUpdates.ReactReconcileTransaction && batchingStrategy, 'ReactUpdates: must inject a reconcile transaction class and batching ' + 'strategy' ) : invariant(ReactUpdates.ReactReconcileTransaction && batchingStrategy)); } 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(); } 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) { ensureInjected(); batchingStrategy.batchedUpdates(callback, a, b, c, d); } /** * 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; ("production" !== process.env.NODE_ENV ? invariant( len === dirtyComponents.length, 'Expected flush transaction\'s stored dirty-components length (%s) to ' + 'match dirty-components array length (%s).', len, dirtyComponents.length ) : invariant(len === dirtyComponents.length)); // Since reconciling a component higher in the owner hierarchy usually (not // always -- see shouldComponentUpdate()) will reconcile children, reconcile // them before their children by sorting the array. dirtyComponents.sort(mountOrderComparator); for (var i = 0; i < len; i++) { // If a component is unmounted before pending changes apply, it will still // be here, but we assume that it has cleared its _pendingCallbacks and // that performUpdateIfNecessary is a noop. var component = dirtyComponents[i]; // If performUpdateIfNecessary happens to enqueue any new updates, we // shouldn't execute the callbacks until the next render happens, so // stash the callbacks first var callbacks = component._pendingCallbacks; component._pendingCallbacks = null; ReactReconciler.performUpdateIfNecessary( component, transaction.reconcileTransaction ); if (callbacks) { for (var j = 0; j < callbacks.length; j++) { transaction.callbackQueue.enqueue( callbacks[j], component.getPublicInstance() ); } } } } var flushBatchedUpdates = function() { // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents // array and perform any updates enqueued by mount-ready handlers (i.e., // componentDidUpdate) but we need to check here too in order to catch // updates enqueued by setState callbacks and asap calls. while (dirtyComponents.length || asapEnqueued) { if (dirtyComponents.length) { var transaction = ReactUpdatesFlushTransaction.getPooled(); transaction.perform(runBatchedUpdates, null, transaction); ReactUpdatesFlushTransaction.release(transaction); } if (asapEnqueued) { asapEnqueued = false; var queue = asapCallbackQueue; asapCallbackQueue = CallbackQueue.getPooled(); queue.notifyAll(); CallbackQueue.release(queue); } } }; flushBatchedUpdates = ReactPerf.measure( 'ReactUpdates', 'flushBatchedUpdates', flushBatchedUpdates ); /** * Mark a component as needing a rerender, adding an optional callback to a * list of functions which will be executed once the rerender occurs. */ function enqueueUpdate(component) { ensureInjected(); // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (This is called by each top-level update // function, like setProps, setState, forceUpdate, etc.; creation and // destruction of top-level components is guarded in ReactMount.) ("production" !== process.env.NODE_ENV ? warning( ReactCurrentOwner.current == null, 'enqueueUpdate(): 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.' ) : null); if (!batchingStrategy.isBatchingUpdates) { batchingStrategy.batchedUpdates(enqueueUpdate, component); return; } dirtyComponents.push(component); } /** * Enqueue a callback to be run at the end of the current batching cycle. Throws * if no updates are currently being performed. */ function asap(callback, context) { ("production" !== process.env.NODE_ENV ? invariant( batchingStrategy.isBatchingUpdates, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context where' + 'updates are not being batched.' ) : invariant(batchingStrategy.isBatchingUpdates)); asapCallbackQueue.enqueue(callback, context); asapEnqueued = true; } var ReactUpdatesInjection = { injectReconcileTransaction: function(ReconcileTransaction) { ("production" !== process.env.NODE_ENV ? invariant( ReconcileTransaction, 'ReactUpdates: must provide a reconcile transaction class' ) : invariant(ReconcileTransaction)); ReactUpdates.ReactReconcileTransaction = ReconcileTransaction; }, injectBatchingStrategy: function(_batchingStrategy) { ("production" !== process.env.NODE_ENV ? invariant( _batchingStrategy, 'ReactUpdates: must provide a batching strategy' ) : invariant(_batchingStrategy)); ("production" !== process.env.NODE_ENV ? invariant( typeof _batchingStrategy.batchedUpdates === 'function', 'ReactUpdates: must provide a batchedUpdates() function' ) : invariant(typeof _batchingStrategy.batchedUpdates === 'function')); ("production" !== process.env.NODE_ENV ? invariant( typeof _batchingStrategy.isBatchingUpdates === 'boolean', 'ReactUpdates: must provide an isBatchingUpdates boolean attribute' ) : invariant(typeof _batchingStrategy.isBatchingUpdates === 'boolean')); 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; }).call(this,require('_process')) },{"./CallbackQueue":6,"./Object.assign":27,"./PooledClass":28,"./ReactCurrentOwner":40,"./ReactPerf":76,"./ReactReconciler":82,"./Transaction":104,"./invariant":136,"./warning":155,"_process":1}],89:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SVGDOMPropertyConfig */ /*jslint bitwise: true*/ 'use strict'; var DOMProperty = require("./DOMProperty"); var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE; var SVGDOMPropertyConfig = { Properties: { cx: MUST_USE_ATTRIBUTE, cy: MUST_USE_ATTRIBUTE, d: MUST_USE_ATTRIBUTE, dx: MUST_USE_ATTRIBUTE, dy: MUST_USE_ATTRIBUTE, fill: MUST_USE_ATTRIBUTE, fillOpacity: MUST_USE_ATTRIBUTE, fontFamily: MUST_USE_ATTRIBUTE, fontSize: MUST_USE_ATTRIBUTE, fx: MUST_USE_ATTRIBUTE, fy: MUST_USE_ATTRIBUTE, gradientTransform: MUST_USE_ATTRIBUTE, gradientUnits: MUST_USE_ATTRIBUTE, markerEnd: MUST_USE_ATTRIBUTE, markerMid: MUST_USE_ATTRIBUTE, markerStart: MUST_USE_ATTRIBUTE, offset: MUST_USE_ATTRIBUTE, opacity: MUST_USE_ATTRIBUTE, patternContentUnits: MUST_USE_ATTRIBUTE, patternUnits: MUST_USE_ATTRIBUTE, points: MUST_USE_ATTRIBUTE, preserveAspectRatio: MUST_USE_ATTRIBUTE, r: MUST_USE_ATTRIBUTE, rx: MUST_USE_ATTRIBUTE, ry: MUST_USE_ATTRIBUTE, spreadMethod: MUST_USE_ATTRIBUTE, stopColor: MUST_USE_ATTRIBUTE, stopOpacity: MUST_USE_ATTRIBUTE, stroke: MUST_USE_ATTRIBUTE, strokeDasharray: MUST_USE_ATTRIBUTE, strokeLinecap: MUST_USE_ATTRIBUTE, strokeOpacity: MUST_USE_ATTRIBUTE, strokeWidth: MUST_USE_ATTRIBUTE, textAnchor: MUST_USE_ATTRIBUTE, transform: MUST_USE_ATTRIBUTE, version: MUST_USE_ATTRIBUTE, viewBox: MUST_USE_ATTRIBUTE, x1: MUST_USE_ATTRIBUTE, x2: MUST_USE_ATTRIBUTE, x: MUST_USE_ATTRIBUTE, y1: MUST_USE_ATTRIBUTE, y2: MUST_USE_ATTRIBUTE, y: MUST_USE_ATTRIBUTE }, DOMAttributeNames: { fillOpacity: 'fill-opacity', fontFamily: 'font-family', fontSize: 'font-size', gradientTransform: 'gradientTransform', gradientUnits: 'gradientUnits', markerEnd: 'marker-end', markerMid: 'marker-mid', markerStart: 'marker-start', patternContentUnits: 'patternContentUnits', patternUnits: 'patternUnits', preserveAspectRatio: 'preserveAspectRatio', spreadMethod: 'spreadMethod', stopColor: 'stop-color', stopOpacity: 'stop-opacity', strokeDasharray: 'stroke-dasharray', strokeLinecap: 'stroke-linecap', strokeOpacity: 'stroke-opacity', strokeWidth: 'stroke-width', textAnchor: 'text-anchor', viewBox: 'viewBox' } }; module.exports = SVGDOMPropertyConfig; },{"./DOMProperty":10}],90:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SelectEventPlugin */ 'use strict'; var EventConstants = require("./EventConstants"); var EventPropagators = require("./EventPropagators"); var ReactInputSelection = require("./ReactInputSelection"); var SyntheticEvent = require("./SyntheticEvent"); var getActiveElement = require("./getActiveElement"); var isTextInputElement = require("./isTextInputElement"); var keyOf = require("./keyOf"); var shallowEqual = require("./shallowEqual"); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { select: { phasedRegistrationNames: { bubbled: keyOf({onSelect: null}), captured: keyOf({onSelectCapture: null}) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topContextMenu, topLevelTypes.topFocus, topLevelTypes.topKeyDown, topLevelTypes.topMouseDown, topLevelTypes.topMouseUp, topLevelTypes.topSelectionChange ] } }; var activeElement = null; var activeElementID = null; var lastSelection = null; var mouseDown = false; /** * 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 * @param {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) { // Ensure we have the right element, and that the user is not dragging a // selection (this matches native `select` event behavior). In HTML5, select // fires only on input and textarea thus if there's no focused element we // won't dispatch. if (mouseDown || activeElement == null || activeElement !== getActiveElement()) { return null; } // Only fire when selection has actually changed. var currentSelection = getSelection(activeElement); if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { lastSelection = currentSelection; var syntheticEvent = SyntheticEvent.getPooled( eventTypes.select, activeElementID, nativeEvent ); syntheticEvent.type = 'select'; syntheticEvent.target = activeElement; EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent); return syntheticEvent; } } /** * This plugin creates an `onSelect` event that normalizes select events * across form elements. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - contentEditable * * This differs from native browser implementations in the following ways: * - Fires on contentEditable fields as well as inputs. * - Fires for collapsed selection. * - Fires after user input. */ var SelectEventPlugin = { eventTypes: eventTypes, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { switch (topLevelType) { // Track the input node that has focus. case topLevelTypes.topFocus: if (isTextInputElement(topLevelTarget) || topLevelTarget.contentEditable === 'true') { activeElement = topLevelTarget; activeElementID = topLevelTargetID; lastSelection = null; } break; case topLevelTypes.topBlur: activeElement = null; activeElementID = null; lastSelection = null; break; // Don't fire the event while the user is dragging. This matches the // semantics of the native select event. case topLevelTypes.topMouseDown: mouseDown = true; break; case topLevelTypes.topContextMenu: case topLevelTypes.topMouseUp: mouseDown = false; return constructSelectEvent(nativeEvent); // Chrome and IE fire non-standard event when selection is changed (and // sometimes when it hasn't). // 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. case topLevelTypes.topSelectionChange: case topLevelTypes.topKeyDown: case topLevelTypes.topKeyUp: return constructSelectEvent(nativeEvent); } } }; module.exports = SelectEventPlugin; },{"./EventConstants":15,"./EventPropagators":20,"./ReactInputSelection":66,"./SyntheticEvent":96,"./getActiveElement":122,"./isTextInputElement":139,"./keyOf":142,"./shallowEqual":151}],91:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ServerReactRootIndex * @typechecks */ 'use strict'; /** * Size of the reactRoot ID space. We generate random numbers for React root * IDs and if there's a collision the events and DOM update system will * get confused. In the future we need a way to generate GUIDs but for * now this will work on a smaller scale. */ var GLOBAL_MOUNT_POINT_MAX = Math.pow(2, 53); var ServerReactRootIndex = { createReactRootIndex: function() { return Math.ceil(Math.random() * GLOBAL_MOUNT_POINT_MAX); } }; module.exports = ServerReactRootIndex; },{}],92:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SimpleEventPlugin */ 'use strict'; var EventConstants = require("./EventConstants"); var EventPluginUtils = require("./EventPluginUtils"); var EventPropagators = require("./EventPropagators"); var SyntheticClipboardEvent = require("./SyntheticClipboardEvent"); var SyntheticEvent = require("./SyntheticEvent"); var SyntheticFocusEvent = require("./SyntheticFocusEvent"); var SyntheticKeyboardEvent = require("./SyntheticKeyboardEvent"); var SyntheticMouseEvent = require("./SyntheticMouseEvent"); var SyntheticDragEvent = require("./SyntheticDragEvent"); var SyntheticTouchEvent = require("./SyntheticTouchEvent"); var SyntheticUIEvent = require("./SyntheticUIEvent"); var SyntheticWheelEvent = require("./SyntheticWheelEvent"); var getEventCharCode = require("./getEventCharCode"); var invariant = require("./invariant"); var keyOf = require("./keyOf"); var warning = require("./warning"); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { blur: { phasedRegistrationNames: { bubbled: keyOf({onBlur: true}), captured: keyOf({onBlurCapture: 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}) } }, focus: { phasedRegistrationNames: { bubbled: keyOf({onFocus: true}), captured: keyOf({onFocusCapture: true}) } }, input: { phasedRegistrationNames: { bubbled: keyOf({onInput: true}), captured: keyOf({onInputCapture: true}) } }, keyDown: { phasedRegistrationNames: { bubbled: keyOf({onKeyDown: true}), captured: keyOf({onKeyDownCapture: true}) } }, keyPress: { phasedRegistrationNames: { bubbled: keyOf({onKeyPress: true}), captured: keyOf({onKeyPressCapture: true}) } }, keyUp: { phasedRegistrationNames: { bubbled: keyOf({onKeyUp: true}), captured: keyOf({onKeyUpCapture: true}) } }, load: { phasedRegistrationNames: { bubbled: keyOf({onLoad: true}), captured: keyOf({onLoadCapture: true}) } }, error: { phasedRegistrationNames: { bubbled: keyOf({onError: true}), captured: keyOf({onErrorCapture: 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}) } }, reset: { phasedRegistrationNames: { bubbled: keyOf({onReset: true}), captured: keyOf({onResetCapture: true}) } }, scroll: { phasedRegistrationNames: { bubbled: keyOf({onScroll: true}), captured: keyOf({onScrollCapture: true}) } }, submit: { phasedRegistrationNames: { bubbled: keyOf({onSubmit: true}), captured: keyOf({onSubmitCapture: 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}) } }, wheel: { phasedRegistrationNames: { bubbled: keyOf({onWheel: true}), captured: keyOf({onWheelCapture: true}) } } }; var topLevelEventsToDispatchConfig = { topBlur: eventTypes.blur, 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, topError: eventTypes.error, topFocus: eventTypes.focus, topInput: eventTypes.input, topKeyDown: eventTypes.keyDown, topKeyPress: eventTypes.keyPress, topKeyUp: eventTypes.keyUp, topLoad: eventTypes.load, topMouseDown: eventTypes.mouseDown, topMouseMove: eventTypes.mouseMove, topMouseOut: eventTypes.mouseOut, topMouseOver: eventTypes.mouseOver, topMouseUp: eventTypes.mouseUp, topPaste: eventTypes.paste, topReset: eventTypes.reset, topScroll: eventTypes.scroll, topSubmit: eventTypes.submit, topTouchCancel: eventTypes.touchCancel, topTouchEnd: eventTypes.touchEnd, topTouchMove: eventTypes.touchMove, topTouchStart: eventTypes.touchStart, topWheel: eventTypes.wheel }; for (var type in topLevelEventsToDispatchConfig) { topLevelEventsToDispatchConfig[type].dependencies = [type]; } var SimpleEventPlugin = { eventTypes: eventTypes, /** * Same as the default implementation, except cancels the event when return * value is false. This behavior will be disabled in a future release. * * @param {object} Event to be dispatched. * @param {function} Application-level callback. * @param {string} domID DOM ID to pass to the callback. */ executeDispatch: function(event, listener, domID) { var returnValue = EventPluginUtils.executeDispatch(event, listener, domID); ("production" !== process.env.NODE_ENV ? warning( typeof returnValue !== 'boolean', 'Returning `false` from an event handler is deprecated and will be ' + 'ignored in a future release. Instead, manually call ' + 'e.stopPropagation() or e.preventDefault(), as appropriate.' ) : null); if (returnValue === false) { event.stopPropagation(); event.preventDefault(); } }, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType]; if (!dispatchConfig) { return null; } var EventConstructor; switch (topLevelType) { case topLevelTypes.topInput: case topLevelTypes.topLoad: case topLevelTypes.topError: case topLevelTypes.topReset: case topLevelTypes.topSubmit: // HTML Events // @see http://www.w3.org/TR/html5/index.html#events-0 EventConstructor = SyntheticEvent; break; case topLevelTypes.topKeyPress: // FireFox creates a keypress event for function keys too. This removes // the unwanted keypress events. Enter is however both printable and // non-printable. One would expect Tab to be as well (but it isn't). if (getEventCharCode(nativeEvent) === 0) { return null; } /* falls through */ case topLevelTypes.topKeyDown: case topLevelTypes.topKeyUp: EventConstructor = SyntheticKeyboardEvent; break; case topLevelTypes.topBlur: case topLevelTypes.topFocus: EventConstructor = SyntheticFocusEvent; break; case topLevelTypes.topClick: // Firefox creates a click event on right mouse clicks. This removes the // unwanted click events. if (nativeEvent.button === 2) { return null; } /* falls through */ case topLevelTypes.topContextMenu: case topLevelTypes.topDoubleClick: case topLevelTypes.topMouseDown: case topLevelTypes.topMouseMove: case topLevelTypes.topMouseOut: case topLevelTypes.topMouseOver: case topLevelTypes.topMouseUp: EventConstructor = SyntheticMouseEvent; break; case topLevelTypes.topDrag: case topLevelTypes.topDragEnd: case topLevelTypes.topDragEnter: case topLevelTypes.topDragExit: case topLevelTypes.topDragLeave: case topLevelTypes.topDragOver: case topLevelTypes.topDragStart: case topLevelTypes.topDrop: EventConstructor = SyntheticDragEvent; break; case topLevelTypes.topTouchCancel: case topLevelTypes.topTouchEnd: case topLevelTypes.topTouchMove: case topLevelTypes.topTouchStart: EventConstructor = SyntheticTouchEvent; break; case topLevelTypes.topScroll: EventConstructor = SyntheticUIEvent; break; case topLevelTypes.topWheel: EventConstructor = SyntheticWheelEvent; break; case topLevelTypes.topCopy: case topLevelTypes.topCut: case topLevelTypes.topPaste: EventConstructor = SyntheticClipboardEvent; break; } ("production" !== process.env.NODE_ENV ? invariant( EventConstructor, 'SimpleEventPlugin: Unhandled event type, `%s`.', topLevelType ) : invariant(EventConstructor)); var event = EventConstructor.getPooled( dispatchConfig, topLevelTargetID, nativeEvent ); EventPropagators.accumulateTwoPhaseDispatches(event); return event; } }; module.exports = SimpleEventPlugin; }).call(this,require('_process')) },{"./EventConstants":15,"./EventPluginUtils":19,"./EventPropagators":20,"./SyntheticClipboardEvent":93,"./SyntheticDragEvent":95,"./SyntheticEvent":96,"./SyntheticFocusEvent":97,"./SyntheticKeyboardEvent":99,"./SyntheticMouseEvent":100,"./SyntheticTouchEvent":101,"./SyntheticUIEvent":102,"./SyntheticWheelEvent":103,"./getEventCharCode":123,"./invariant":136,"./keyOf":142,"./warning":155,"_process":1}],93:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticClipboardEvent * @typechecks static-only */ 'use strict'; var SyntheticEvent = require("./SyntheticEvent"); /** * @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) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface); module.exports = SyntheticClipboardEvent; },{"./SyntheticEvent":96}],94:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticCompositionEvent * @typechecks static-only */ 'use strict'; var SyntheticEvent = require("./SyntheticEvent"); /** * @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) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticEvent.augmentClass( SyntheticCompositionEvent, CompositionEventInterface ); module.exports = SyntheticCompositionEvent; },{"./SyntheticEvent":96}],95:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticDragEvent * @typechecks static-only */ 'use strict'; var SyntheticMouseEvent = require("./SyntheticMouseEvent"); /** * @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) { SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface); module.exports = SyntheticDragEvent; },{"./SyntheticMouseEvent":100}],96:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticEvent * @typechecks static-only */ 'use strict'; var PooledClass = require("./PooledClass"); var assign = require("./Object.assign"); var emptyFunction = require("./emptyFunction"); var getEventTarget = require("./getEventTarget"); /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var EventInterface = { type: null, target: getEventTarget, // currentTarget is set when dispatching; no use in copying it here currentTarget: emptyFunction.thatReturnsNull, eventPhase: null, bubbles: null, cancelable: null, timeStamp: function(event) { return event.timeStamp || Date.now(); }, defaultPrevented: null, isTrusted: null }; /** * Synthetic events are dispatched by event plugins, typically in response to a * top-level event delegation handler. * * These systems should generally use pooling to reduce the frequency of garbage * collection. The system should check `isPersistent` to determine whether the * event should be released into the pool after being dispatched. Users that * need a persisted event should invoke `persist`. * * Synthetic events (and subclasses) implement the DOM Level 3 Events API by * normalizing browser quirks. Subclasses do not necessarily have to implement a * DOM interface; custom application-specific events can also subclass this. * * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. */ function SyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent) { this.dispatchConfig = dispatchConfig; this.dispatchMarker = dispatchMarker; this.nativeEvent = nativeEvent; var Interface = this.constructor.Interface; for (var propName in Interface) { if (!Interface.hasOwnProperty(propName)) { continue; } var normalize = Interface[propName]; if (normalize) { this[propName] = normalize(nativeEvent); } else { this[propName] = nativeEvent[propName]; } } var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; if (defaultPrevented) { this.isDefaultPrevented = emptyFunction.thatReturnsTrue; } else { this.isDefaultPrevented = emptyFunction.thatReturnsFalse; } this.isPropagationStopped = emptyFunction.thatReturnsFalse; } assign(SyntheticEvent.prototype, { preventDefault: function() { this.defaultPrevented = true; var event = this.nativeEvent; if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } this.isDefaultPrevented = emptyFunction.thatReturnsTrue; }, stopPropagation: function() { var event = this.nativeEvent; if (event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubble = true; } this.isPropagationStopped = emptyFunction.thatReturnsTrue; }, /** * We release all dispatched `SyntheticEvent`s after each event loop, adding * them back into the pool. This allows a way to hold onto a reference that * won't be added back into the pool. */ persist: function() { this.isPersistent = emptyFunction.thatReturnsTrue; }, /** * Checks if this event should be released back into the pool. * * @return {boolean} True if this should not be released, false otherwise. */ isPersistent: emptyFunction.thatReturnsFalse, /** * `PooledClass` looks for `destructor` on each instance it releases. */ destructor: function() { var Interface = this.constructor.Interface; for (var propName in Interface) { this[propName] = null; } this.dispatchConfig = null; this.dispatchMarker = null; this.nativeEvent = null; } }); SyntheticEvent.Interface = EventInterface; /** * Helper to reduce boilerplate when creating subclasses. * * @param {function} Class * @param {?object} Interface */ SyntheticEvent.augmentClass = function(Class, Interface) { var Super = this; var prototype = Object.create(Super.prototype); assign(prototype, Class.prototype); Class.prototype = prototype; Class.prototype.constructor = Class; Class.Interface = assign({}, Super.Interface, Interface); Class.augmentClass = Super.augmentClass; PooledClass.addPoolingTo(Class, PooledClass.threeArgumentPooler); }; PooledClass.addPoolingTo(SyntheticEvent, PooledClass.threeArgumentPooler); module.exports = SyntheticEvent; },{"./Object.assign":27,"./PooledClass":28,"./emptyFunction":115,"./getEventTarget":126}],97:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticFocusEvent * @typechecks static-only */ 'use strict'; var SyntheticUIEvent = require("./SyntheticUIEvent"); /** * @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) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface); module.exports = SyntheticFocusEvent; },{"./SyntheticUIEvent":102}],98:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticInputEvent * @typechecks static-only */ 'use strict'; var SyntheticEvent = require("./SyntheticEvent"); /** * @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) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticEvent.augmentClass( SyntheticInputEvent, InputEventInterface ); module.exports = SyntheticInputEvent; },{"./SyntheticEvent":96}],99:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticKeyboardEvent * @typechecks static-only */ 'use strict'; var SyntheticUIEvent = require("./SyntheticUIEvent"); var getEventCharCode = require("./getEventCharCode"); var getEventKey = require("./getEventKey"); var getEventModifierState = require("./getEventModifierState"); /** * @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) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface); module.exports = SyntheticKeyboardEvent; },{"./SyntheticUIEvent":102,"./getEventCharCode":123,"./getEventKey":124,"./getEventModifierState":125}],100:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticMouseEvent * @typechecks static-only */ 'use strict'; var SyntheticUIEvent = require("./SyntheticUIEvent"); var ViewportMetrics = require("./ViewportMetrics"); var getEventModifierState = require("./getEventModifierState"); /** * @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) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface); module.exports = SyntheticMouseEvent; },{"./SyntheticUIEvent":102,"./ViewportMetrics":105,"./getEventModifierState":125}],101:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticTouchEvent * @typechecks static-only */ 'use strict'; var SyntheticUIEvent = require("./SyntheticUIEvent"); var getEventModifierState = require("./getEventModifierState"); /** * @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) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface); module.exports = SyntheticTouchEvent; },{"./SyntheticUIEvent":102,"./getEventModifierState":125}],102:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticUIEvent * @typechecks static-only */ 'use strict'; var SyntheticEvent = require("./SyntheticEvent"); var getEventTarget = require("./getEventTarget"); /** * @interface UIEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var UIEventInterface = { view: function(event) { if (event.view) { return event.view; } var target = getEventTarget(event); if (target != null && target.window === target) { // target is a window object return target; } var doc = target.ownerDocument; // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. if (doc) { return doc.defaultView || doc.parentWindow; } else { return window; } }, detail: function(event) { return event.detail || 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface); module.exports = SyntheticUIEvent; },{"./SyntheticEvent":96,"./getEventTarget":126}],103:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticWheelEvent * @typechecks static-only */ 'use strict'; var SyntheticMouseEvent = require("./SyntheticMouseEvent"); /** * @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) { SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface); module.exports = SyntheticWheelEvent; },{"./SyntheticMouseEvent":100}],104:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Transaction */ 'use strict'; var invariant = require("./invariant"); /** * `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 = []; } else { this.wrapperInitData.length = 0; } 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. * * @param {function} method Member of scope to call. * @param {Object} scope Scope to invoke from. * @param {Object?=} args... Arguments to pass to the method (optional). * Helps prevent need to bind in many cases. * @return Return value from `method`. */ perform: function(method, scope, a, b, c, d, e, f) { ("production" !== process.env.NODE_ENV ? invariant( !this.isInTransaction(), 'Transaction.perform(...): Cannot initialize a transaction when there ' + 'is already an outstanding transaction.' ) : invariant(!this.isInTransaction())); 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) { ("production" !== process.env.NODE_ENV ? invariant( this.isInTransaction(), 'Transaction.closeAll(): Cannot close transaction when none are open.' ) : invariant(this.isInTransaction())); 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 occured. */ OBSERVED_ERROR: {} }; module.exports = Transaction; }).call(this,require('_process')) },{"./invariant":136,"_process":1}],105:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ViewportMetrics */ 'use strict'; var ViewportMetrics = { currentScrollLeft: 0, currentScrollTop: 0, refreshScrollValues: function(scrollPosition) { ViewportMetrics.currentScrollLeft = scrollPosition.x; ViewportMetrics.currentScrollTop = scrollPosition.y; } }; module.exports = ViewportMetrics; },{}],106:[function(require,module,exports){ (function (process){ /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule accumulateInto */ 'use strict'; var invariant = require("./invariant"); /** * * 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) { ("production" !== process.env.NODE_ENV ? invariant( next != null, 'accumulateInto(...): Accumulated items must not be null or undefined.' ) : invariant(next != null)); if (current == null) { return next; } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). var currentIsArray = Array.isArray(current); var nextIsArray = Array.isArray(next); if (currentIsArray && nextIsArray) { current.push.apply(current, next); return current; } if (currentIsArray) { current.push(next); return current; } if (nextIsArray) { // A bit too dangerous to mutate `next`. return [current].concat(next); } return [current, next]; } module.exports = accumulateInto; }).call(this,require('_process')) },{"./invariant":136,"_process":1}],107:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule adler32 */ /* jslint bitwise:true */ 'use strict'; var MOD = 65521; // This is a clean-room implementation of adler32 designed for detecting // if markup is not what we expect it to be. It does not need to be // cryptographically strong, only reasonably good at detecting if markup // generated on the server is different than that on the client. function adler32(data) { var a = 1; var b = 0; for (var i = 0; i < data.length; i++) { a = (a + data.charCodeAt(i)) % MOD; b = (b + a) % MOD; } return a | (b << 16); } module.exports = adler32; },{}],108:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule camelize * @typechecks */ 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; },{}],109:[function(require,module,exports){ /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule camelizeStyleName * @typechecks */ "use strict"; var camelize = require("./camelize"); 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; },{"./camelize":108}],110:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule containsNode * @typechecks */ var isTextNode = require("./isTextNode"); /*jslint bitwise:true */ /** * Checks if a given DOM node contains or is another DOM node. * * @param {?DOMNode} outerNode Outer DOM node. * @param {?DOMNode} innerNode Inner DOM node. * @return {boolean} True if `outerNode` contains or is `innerNode`. */ function containsNode(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 (outerNode.contains) { return outerNode.contains(innerNode); } else if (outerNode.compareDocumentPosition) { return !!(outerNode.compareDocumentPosition(innerNode) & 16); } else { return false; } } module.exports = containsNode; },{"./isTextNode":140}],111:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule createArrayFromMixed * @typechecks */ var toArray = require("./toArray"); /** * 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 (// HTMLCollection/NodeList (Array.isArray(obj) || // arguments ('callee' in obj) || '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; },{"./toArray":153}],112:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule createFullPageComponent * @typechecks */ 'use strict'; // Defeat circular references by requiring this directly. var ReactClass = require("./ReactClass"); var ReactElement = require("./ReactElement"); var invariant = require("./invariant"); /** * Create a component that will throw an exception when unmounted. * * 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. * * @param {string} tag The tag to wrap * @return {function} convenience constructor of new component */ function createFullPageComponent(tag) { var elementFactory = ReactElement.createFactory(tag); var FullPageComponent = ReactClass.createClass({ tagName: tag.toUpperCase(), displayName: 'ReactFullPageComponent' + tag, componentWillUnmount: function() { ("production" !== process.env.NODE_ENV ? 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.constructor.displayName ) : invariant(false)); }, render: function() { return elementFactory(this.props); } }); return FullPageComponent; } module.exports = createFullPageComponent; }).call(this,require('_process')) },{"./ReactClass":34,"./ReactElement":58,"./invariant":136,"_process":1}],113:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule createNodesFromMarkup * @typechecks */ /*jslint evil: true, sub: true */ var ExecutionEnvironment = require("./ExecutionEnvironment"); var createArrayFromMixed = require("./createArrayFromMixed"); var getMarkupWrap = require("./getMarkupWrap"); var invariant = require("./invariant"); /** * 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; ("production" !== process.env.NODE_ENV ? invariant(!!dummyNode, 'createNodesFromMarkup dummy not initialized') : invariant(!!dummyNode)); 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) { ("production" !== process.env.NODE_ENV ? invariant( handleScript, 'createNodesFromMarkup(...): Unexpected <script> element rendered.' ) : invariant(handleScript)); createArrayFromMixed(scripts).forEach(handleScript); } var nodes = createArrayFromMixed(node.childNodes); while (node.lastChild) { node.removeChild(node.lastChild); } return nodes; } module.exports = createNodesFromMarkup; }).call(this,require('_process')) },{"./ExecutionEnvironment":21,"./createArrayFromMixed":111,"./getMarkupWrap":128,"./invariant":136,"_process":1}],114:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule dangerousStyleValue * @typechecks static-only */ 'use strict'; var CSSProperty = require("./CSSProperty"); var isUnitlessNumber = CSSProperty.isUnitlessNumber; /** * Convert a value into the proper css writable value. The style name `name` * should be logical (no hyphens), as specified * in `CSSProperty.isUnitlessNumber`. * * @param {string} name CSS property name such as `topMargin`. * @param {*} value CSS property value such as `10px`. * @return {string} Normalized style value with dimensions applied. */ function dangerousStyleValue(name, value) { // Note that we've removed escapeTextForBrowser() calls here since the // whole string will be escaped when the attribute is injected into // the markup. If you provide unsafe user data here they can inject // arbitrary CSS which may be problematic (I couldn't repro this): // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/ // This is not an XSS hole but instead a potential CSS injection issue // which has lead to a greater discussion about how we're going to // trust URLs moving forward. See #2115901 var isEmpty = value == null || typeof value === 'boolean' || value === ''; if (isEmpty) { return ''; } var isNonNumeric = isNaN(value); if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) { return '' + value; // cast to string } if (typeof value === 'string') { value = value.trim(); } return value + 'px'; } module.exports = dangerousStyleValue; },{"./CSSProperty":4}],115:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule emptyFunction */ function makeEmptyFunction(arg) { return function() { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ function emptyFunction() {} emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function() { return this; }; emptyFunction.thatReturnsArgument = function(arg) { return arg; }; module.exports = emptyFunction; },{}],116:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule emptyObject */ "use strict"; var emptyObject = {}; if ("production" !== process.env.NODE_ENV) { Object.freeze(emptyObject); } module.exports = emptyObject; }).call(this,require('_process')) },{"_process":1}],117:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule escapeTextContentForBrowser */ 'use strict'; var ESCAPE_LOOKUP = { '&': '&amp;', '>': '&gt;', '<': '&lt;', '"': '&quot;', '\'': '&#x27;' }; var ESCAPE_REGEX = /[&><"']/g; function escaper(match) { return ESCAPE_LOOKUP[match]; } /** * Escapes text to prevent scripting attacks. * * @param {*} text Text value to escape. * @return {string} An escaped string. */ function escapeTextContentForBrowser(text) { return ('' + text).replace(ESCAPE_REGEX, escaper); } module.exports = escapeTextContentForBrowser; },{}],118:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule findDOMNode * @typechecks static-only */ 'use strict'; var ReactCurrentOwner = require("./ReactCurrentOwner"); var ReactInstanceMap = require("./ReactInstanceMap"); var ReactMount = require("./ReactMount"); var invariant = require("./invariant"); var isNode = require("./isNode"); var warning = require("./warning"); /** * Returns the DOM node rendered by this element. * * @param {ReactComponent|DOMElement} componentOrElement * @return {DOMElement} The root node of this element. */ function findDOMNode(componentOrElement) { if ("production" !== process.env.NODE_ENV) { var owner = ReactCurrentOwner.current; if (owner !== null) { ("production" !== process.env.NODE_ENV ? warning( owner._warnedAboutRefsInRender, '%s is accessing getDOMNode or findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component' ) : null); owner._warnedAboutRefsInRender = true; } } if (componentOrElement == null) { return null; } if (isNode(componentOrElement)) { return componentOrElement; } if (ReactInstanceMap.has(componentOrElement)) { return ReactMount.getNodeFromInstance(componentOrElement); } ("production" !== process.env.NODE_ENV ? invariant( componentOrElement.render == null || typeof componentOrElement.render !== 'function', 'Component (with keys: %s) contains `render` method ' + 'but is not mounted in the DOM', Object.keys(componentOrElement) ) : invariant(componentOrElement.render == null || typeof componentOrElement.render !== 'function')); ("production" !== process.env.NODE_ENV ? invariant( false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement) ) : invariant(false)); } module.exports = findDOMNode; }).call(this,require('_process')) },{"./ReactCurrentOwner":40,"./ReactInstanceMap":68,"./ReactMount":71,"./invariant":136,"./isNode":138,"./warning":155,"_process":1}],119:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule flattenChildren */ 'use strict'; var traverseAllChildren = require("./traverseAllChildren"); var warning = require("./warning"); /** * @param {function} traverseContext Context passed through traversal. * @param {?ReactComponent} child React child component. * @param {!string} name String name of key path to child. */ function flattenSingleChildIntoContext(traverseContext, child, name) { // We found a component instance. var result = traverseContext; var keyUnique = !result.hasOwnProperty(name); if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name ) : null); } if (keyUnique && child != null) { result[name] = child; } } /** * Flattens children that are typically specified as `props.children`. Any null * children will not be included in the resulting object. * @return {!object} flattened children keyed by name. */ function flattenChildren(children) { if (children == null) { return children; } var result = {}; traverseAllChildren(children, flattenSingleChildIntoContext, result); return result; } module.exports = flattenChildren; }).call(this,require('_process')) },{"./traverseAllChildren":154,"./warning":155,"_process":1}],120:[function(require,module,exports){ /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule focusNode */ "use strict"; /** * @param {DOMElement} node input/textarea to focus */ function focusNode(node) { // IE8 can throw "Can't move focus to the control because it is invisible, // not enabled, or of a type that does not accept the focus." for all kinds of // reasons that are too expensive and fragile to test. try { node.focus(); } catch(e) { } } module.exports = focusNode; },{}],121:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule forEachAccumulated */ 'use strict'; /** * @param {array} an "accumulation" of items which is either an Array or * a single item. Useful when paired with the `accumulate` module. This is a * simple utility that allows us to reason about a collection of items, but * handling the case when there is exactly one item (and we do not need to * allocate an array). */ var forEachAccumulated = function(arr, cb, scope) { if (Array.isArray(arr)) { arr.forEach(cb, scope); } else if (arr) { cb.call(scope, arr); } }; module.exports = forEachAccumulated; },{}],122:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getActiveElement * @typechecks */ /** * Same as document.activeElement but wraps in a try-catch block. In IE it is * not safe to call document.activeElement if there is nothing focused. * * The activeElement will be null only if the document body is not yet defined. */ function getActiveElement() /*?DOMElement*/ { try { return document.activeElement || document.body; } catch (e) { return document.body; } } module.exports = getActiveElement; },{}],123:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventCharCode * @typechecks static-only */ 'use strict'; /** * `charCode` represents the actual "character code" and is safe to use with * `String.fromCharCode`. As such, only keys that correspond to printable * characters produce a valid `charCode`, the only exception to this is Enter. * The Tab-key is considered non-printable and does not have a `charCode`, * presumably because it does not produce a tab-character in browsers. * * @param {object} nativeEvent Native browser event. * @return {string} 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; },{}],124:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventKey * @typechecks static-only */ 'use strict'; var getEventCharCode = require("./getEventCharCode"); /** * 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; },{"./getEventCharCode":123}],125:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventModifierState * @typechecks static-only */ 'use strict'; /** * Translation from modifier key to the associated property in the event. * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers */ var modifierKeyToProp = { 'Alt': 'altKey', 'Control': 'ctrlKey', 'Meta': 'metaKey', 'Shift': 'shiftKey' }; // IE8 does not implement getModifierState so we simply map it to the only // modifier keys exposed by the event itself, does not support Lock-keys. // Currently, all major browsers except Chrome seems to support Lock-keys. function modifierStateGetter(keyArg) { /*jshint validthis:true */ 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; },{}],126:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventTarget * @typechecks static-only */ 'use strict'; /** * Gets the target node from a native browser event by accounting for * inconsistencies in browser DOM APIs. * * @param {object} nativeEvent Native browser event. * @return {DOMEventTarget} Target node. */ function getEventTarget(nativeEvent) { var target = nativeEvent.target || nativeEvent.srcElement || window; // Safari may fire events on text nodes (Node.TEXT_NODE is 3). // @see http://www.quirksmode.org/js/events_properties.html return target.nodeType === 3 ? target.parentNode : target; } module.exports = getEventTarget; },{}],127:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getIteratorFn * @typechecks static-only */ 'use strict'; /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && ( (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]) ); if (typeof iteratorFn === 'function') { return iteratorFn; } } module.exports = getIteratorFn; },{}],128:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getMarkupWrap */ var ExecutionEnvironment = require("./ExecutionEnvironment"); var invariant = require("./invariant"); /** * 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 = { // Force wrapping for SVG elements because if they get created inside a <div>, // they will be initialized in the wrong namespace (and will not display). 'circle': true, 'defs': true, 'ellipse': true, 'g': true, 'line': true, 'linearGradient': true, 'path': true, 'polygon': true, 'polyline': true, 'radialGradient': true, 'rect': true, 'stop': true, 'text': true }; 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>', '</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, 'circle': svgWrap, 'defs': svgWrap, 'ellipse': svgWrap, 'g': svgWrap, 'line': svgWrap, 'linearGradient': svgWrap, 'path': svgWrap, 'polygon': svgWrap, 'polyline': svgWrap, 'radialGradient': svgWrap, 'rect': svgWrap, 'stop': svgWrap, 'text': svgWrap }; /** * 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) { ("production" !== process.env.NODE_ENV ? invariant(!!dummyNode, 'Markup wrapping node not initialized') : invariant(!!dummyNode)); 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; }).call(this,require('_process')) },{"./ExecutionEnvironment":21,"./invariant":136,"_process":1}],129:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getNodeForCharacterOffset */ 'use strict'; /** * Given any node return the first leaf node without children. * * @param {DOMElement|DOMTextNode} node * @return {DOMElement|DOMTextNode} */ function getLeafNode(node) { while (node && node.firstChild) { node = node.firstChild; } return node; } /** * Get the next sibling within a container. This will walk up the * DOM if a node's siblings have been exhausted. * * @param {DOMElement|DOMTextNode} node * @return {?DOMElement|DOMTextNode} */ function getSiblingNode(node) { while (node) { if (node.nextSibling) { return node.nextSibling; } node = node.parentNode; } } /** * Get object describing the nodes which contain characters at offset. * * @param {DOMElement|DOMTextNode} root * @param {number} offset * @return {?object} */ function getNodeForCharacterOffset(root, offset) { var node = getLeafNode(root); var nodeStart = 0; var nodeEnd = 0; while (node) { if (node.nodeType === 3) { nodeEnd = nodeStart + node.textContent.length; if (nodeStart <= offset && nodeEnd >= offset) { return { node: node, offset: offset - nodeStart }; } nodeStart = nodeEnd; } node = getLeafNode(getSiblingNode(node)); } } module.exports = getNodeForCharacterOffset; },{}],130:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getReactRootElementInContainer */ 'use strict'; var DOC_NODE_TYPE = 9; /** * @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; } } module.exports = getReactRootElementInContainer; },{}],131:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getTextContentAccessor */ 'use strict'; var ExecutionEnvironment = require("./ExecutionEnvironment"); 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; },{"./ExecutionEnvironment":21}],132:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getUnboundedScrollPosition * @typechecks */ "use strict"; /** * Gets the scroll position of the supplied element or window. * * The return values are unbounded, unlike `getScrollPosition`. This means they * may be negative or exceed the element boundaries (which is possible using * inertial scrolling). * * @param {DOMWindow|DOMElement} scrollable * @return {object} Map with `x` and `y` keys. */ function getUnboundedScrollPosition(scrollable) { if (scrollable === window) { return { x: window.pageXOffset || document.documentElement.scrollLeft, y: window.pageYOffset || document.documentElement.scrollTop }; } return { x: scrollable.scrollLeft, y: scrollable.scrollTop }; } module.exports = getUnboundedScrollPosition; },{}],133:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule hyphenate * @typechecks */ 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; },{}],134:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule hyphenateStyleName * @typechecks */ "use strict"; var hyphenate = require("./hyphenate"); 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; },{"./hyphenate":133}],135:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule instantiateReactComponent * @typechecks static-only */ 'use strict'; var ReactCompositeComponent = require("./ReactCompositeComponent"); var ReactEmptyComponent = require("./ReactEmptyComponent"); var ReactNativeComponent = require("./ReactNativeComponent"); var assign = require("./Object.assign"); var invariant = require("./invariant"); var warning = require("./warning"); // To avoid a cyclic dependency, we create the final class in this module var ReactCompositeComponentWrapper = function() { }; assign( ReactCompositeComponentWrapper.prototype, ReactCompositeComponent.Mixin, { _instantiateReactComponent: instantiateReactComponent } ); /** * Check if the type reference is a known internal type. I.e. not a user * provided composite type. * * @param {function} type * @return {boolean} Returns true if this is a valid internal type. */ function isInternalComponentType(type) { return ( typeof type === 'function' && typeof type.prototype !== 'undefined' && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function' ); } /** * Given a ReactNode, create an instance that will actually be mounted. * * @param {ReactNode} node * @param {*} parentCompositeType The composite type that resolved this. * @return {object} A new instance of the element's constructor. * @protected */ function instantiateReactComponent(node, parentCompositeType) { var instance; if (node === null || node === false) { node = ReactEmptyComponent.emptyElement; } if (typeof node === 'object') { var element = node; if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( element && (typeof element.type === 'function' || typeof element.type === 'string'), 'Only functions or strings can be mounted as React components.' ) : null); } // Special case string values if (parentCompositeType === element.type && typeof element.type === 'string') { // Avoid recursion if the wrapper renders itself. instance = ReactNativeComponent.createInternalComponent(element); // All native components are currently wrapped in a composite so we're // safe to assume that this is what we should instantiate. } else if (isInternalComponentType(element.type)) { // This is temporarily available for custom components that are not string // represenations. I.e. ART. Once those are updated to use the string // representation, we can drop this code path. instance = new element.type(element); } else { instance = new ReactCompositeComponentWrapper(); } } else if (typeof node === 'string' || typeof node === 'number') { instance = ReactNativeComponent.createInstanceForText(node); } else { ("production" !== process.env.NODE_ENV ? invariant( false, 'Encountered invalid React node of type %s', typeof node ) : invariant(false)); } if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( typeof instance.construct === 'function' && typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.' ) : null); } // Sets up the instance. This can probably just move into the constructor now. instance.construct(node); // These two fields are used by the DOM and ART diffing algorithms // respectively. Instead of using expandos on components, we should be // storing the state needed by the diffing algorithms elsewhere. instance._mountIndex = 0; instance._mountImage = null; if ("production" !== process.env.NODE_ENV) { instance._isOwnerNecessary = false; instance._warnedAboutRefsInRender = false; } // Internal instances should fully constructed at this point, so they should // not get any new fields added to them at this point. if ("production" !== process.env.NODE_ENV) { if (Object.preventExtensions) { Object.preventExtensions(instance); } } return instance; } module.exports = instantiateReactComponent; }).call(this,require('_process')) },{"./Object.assign":27,"./ReactCompositeComponent":38,"./ReactEmptyComponent":60,"./ReactNativeComponent":74,"./invariant":136,"./warning":155,"_process":1}],136:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule invariant */ "use strict"; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var invariant = function(condition, format, a, b, c, d, e, f) { if ("production" !== process.env.NODE_ENV) { 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( 'Invariant Violation: ' + format.replace(/%s/g, function() { return args[argIndex++]; }) ); } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; module.exports = invariant; }).call(this,require('_process')) },{"_process":1}],137:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isEventSupported */ 'use strict'; var ExecutionEnvironment = require("./ExecutionEnvironment"); 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; },{"./ExecutionEnvironment":21}],138:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isNode * @typechecks */ /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM node. */ 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; },{}],139:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isTextInputElement */ 'use strict'; /** * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary */ var supportedInputTypes = { 'color': true, 'date': true, 'datetime': true, 'datetime-local': true, 'email': true, 'month': true, 'number': true, 'password': true, 'range': true, 'search': true, 'tel': true, 'text': true, 'time': true, 'url': true, 'week': true }; function isTextInputElement(elem) { return elem && ( (elem.nodeName === 'INPUT' && supportedInputTypes[elem.type] || elem.nodeName === 'TEXTAREA') ); } module.exports = isTextInputElement; },{}],140:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isTextNode * @typechecks */ var isNode = require("./isNode"); /** * @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; },{"./isNode":138}],141:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule keyMirror * @typechecks static-only */ 'use strict'; var invariant = require("./invariant"); /** * Constructs an enumeration with keys equal to their value. * * For example: * * var COLORS = keyMirror({blue: null, red: null}); * var myColor = COLORS.blue; * var isColorValid = !!COLORS[myColor]; * * The last line could not be performed if the values of the generated enum were * not equal to their keys. * * Input: {key1: val1, key2: val2} * Output: {key1: key1, key2: key2} * * @param {object} obj * @return {object} */ var keyMirror = function(obj) { var ret = {}; var key; ("production" !== process.env.NODE_ENV ? invariant( obj instanceof Object && !Array.isArray(obj), 'keyMirror(...): Argument must be an object.' ) : invariant(obj instanceof Object && !Array.isArray(obj))); for (key in obj) { if (!obj.hasOwnProperty(key)) { continue; } ret[key] = key; } return ret; }; module.exports = keyMirror; }).call(this,require('_process')) },{"./invariant":136,"_process":1}],142:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule keyOf */ /** * Allows extraction of a minified key. Let's the build system minify keys * without loosing 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(oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }; module.exports = keyOf; },{}],143:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule mapObject */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Executes the provided `callback` once for each enumerable own property in the * object and constructs a new object from the results. The `callback` is * invoked with three arguments: * * - the property value * - the property name * - the object being traversed * * Properties that are added after the call to `mapObject` will not be visited * by `callback`. If the values of existing properties are changed, the value * passed to `callback` will be the value at the time `mapObject` visits them. * Properties that are deleted before being visited are not visited. * * @grep function objectMap() * @grep function objMap() * * @param {?object} object * @param {function} callback * @param {*} context * @return {?object} */ function mapObject(object, callback, context) { if (!object) { return null; } var result = {}; for (var name in object) { if (hasOwnProperty.call(object, name)) { result[name] = callback.call(context, object[name], name, object); } } return result; } module.exports = mapObject; },{}],144:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule memoizeStringOnly * @typechecks static-only */ 'use strict'; /** * Memoizes the return value of a function that accepts one string argument. * * @param {function} callback * @return {function} */ function memoizeStringOnly(callback) { var cache = {}; return function(string) { if (!cache.hasOwnProperty(string)) { cache[string] = callback.call(this, string); } return cache[string]; }; } module.exports = memoizeStringOnly; },{}],145:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule onlyChild */ 'use strict'; var ReactElement = require("./ReactElement"); var invariant = require("./invariant"); /** * Returns the first child in a collection of children and verifies that there * is only one child in the collection. The current implementation of this * function assumes that a single child gets passed without a wrapper, but the * purpose of this helper function is to abstract away the particular structure * of children. * * @param {?object} children Child collection structure. * @return {ReactComponent} The first and only `ReactComponent` contained in the * structure. */ function onlyChild(children) { ("production" !== process.env.NODE_ENV ? invariant( ReactElement.isValidElement(children), 'onlyChild must be passed a children with exactly one child.' ) : invariant(ReactElement.isValidElement(children))); return children; } module.exports = onlyChild; }).call(this,require('_process')) },{"./ReactElement":58,"./invariant":136,"_process":1}],146:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule performance * @typechecks */ "use strict"; var ExecutionEnvironment = require("./ExecutionEnvironment"); var performance; if (ExecutionEnvironment.canUseDOM) { performance = window.performance || window.msPerformance || window.webkitPerformance; } module.exports = performance || {}; },{"./ExecutionEnvironment":21}],147:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule performanceNow * @typechecks */ var performance = require("./performance"); /** * 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 || !performance.now) { performance = Date; } var performanceNow = performance.now.bind(performance); module.exports = performanceNow; },{"./performance":146}],148:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule quoteAttributeValueForBrowser */ 'use strict'; var escapeTextContentForBrowser = require("./escapeTextContentForBrowser"); /** * 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; },{"./escapeTextContentForBrowser":117}],149:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule setInnerHTML */ /* globals MSApp */ 'use strict'; var ExecutionEnvironment = require("./ExecutionEnvironment"); var WHITESPACE_TEST = /^[ \r\n\t\f]/; var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/; /** * Set the innerHTML property of a node, ensuring that whitespace is preserved * even in IE8. * * @param {DOMElement} node * @param {string} html * @internal */ var setInnerHTML = function(node, html) { node.innerHTML = html; }; // Win8 apps: Allow all html to be inserted if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) { setInnerHTML = function(node, html) { MSApp.execUnsafeLocalFunction(function() { node.innerHTML = html; }); }; } if (ExecutionEnvironment.canUseDOM) { // IE8: When updating a just created node with innerHTML only leading // whitespace is removed. When updating an existing node with innerHTML // whitespace in root TextNodes is also collapsed. // @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html // Feature detection; only IE8 is known to behave improperly like this. var testElement = document.createElement('div'); testElement.innerHTML = ' '; if (testElement.innerHTML === '') { setInnerHTML = function(node, html) { // Magic theory: IE8 supposedly differentiates between added and updated // nodes when processing innerHTML, innerHTML on updated nodes suffers // from worse whitespace behavior. Re-adding a node like this triggers // the initial and more favorable whitespace behavior. // TODO: What to do on a detached node? if (node.parentNode) { node.parentNode.replaceChild(node, node); } // We also implement a workaround for non-visible tags disappearing into // thin air on IE8, this only happens if there is no visible text // in-front of the non-visible tags. Piggyback on the whitespace fix // and simply check if any non-visible tags appear in the source. if (WHITESPACE_TEST.test(html) || html[0] === '<' && NONVISIBLE_TEST.test(html)) { // Recover leading whitespace by temporarily prepending any character. // \uFEFF has the potential advantage of being zero-width/invisible. node.innerHTML = '\uFEFF' + html; // deleteData leaves an empty `TextNode` which offsets the index of all // children. Definitely want to avoid this. var textNode = node.firstChild; if (textNode.data.length === 1) { node.removeChild(textNode); } else { textNode.deleteData(0, 1); } } else { node.innerHTML = html; } }; } } module.exports = setInnerHTML; },{"./ExecutionEnvironment":21}],150:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule setTextContent */ 'use strict'; var ExecutionEnvironment = require("./ExecutionEnvironment"); var escapeTextContentForBrowser = require("./escapeTextContentForBrowser"); var setInnerHTML = require("./setInnerHTML"); /** * Set the textContent property of a node, ensuring that whitespace is preserved * even in IE8. innerText is a poor substitute for textContent and, among many * issues, inserts <br> instead of the literal newline chars. innerHTML behaves * as it should. * * @param {DOMElement} node * @param {string} text * @internal */ var setTextContent = function(node, text) { node.textContent = text; }; if (ExecutionEnvironment.canUseDOM) { if (!('textContent' in document.documentElement)) { setTextContent = function(node, text) { setInnerHTML(node, escapeTextContentForBrowser(text)); }; } } module.exports = setTextContent; },{"./ExecutionEnvironment":21,"./escapeTextContentForBrowser":117,"./setInnerHTML":149}],151:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule shallowEqual */ 'use strict'; /** * Performs equality by iterating through keys on an object and returning * false when any key has values which are not strictly equal between * objA and objB. Returns true when the values of all keys are strictly equal. * * @return {boolean} */ function shallowEqual(objA, objB) { if (objA === objB) { return true; } var key; // Test for A's keys different from B. for (key in objA) { if (objA.hasOwnProperty(key) && (!objB.hasOwnProperty(key) || objA[key] !== objB[key])) { return false; } } // Test for B's keys missing from A. for (key in objB) { if (objB.hasOwnProperty(key) && !objA.hasOwnProperty(key)) { return false; } } return true; } module.exports = shallowEqual; },{}],152:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule shouldUpdateReactComponent * @typechecks static-only */ 'use strict'; var warning = require("./warning"); /** * 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) { if (prevElement != null && nextElement != null) { var prevType = typeof prevElement; var nextType = typeof nextElement; if (prevType === 'string' || prevType === 'number') { return (nextType === 'string' || nextType === 'number'); } else { if (nextType === 'object' && prevElement.type === nextElement.type && prevElement.key === nextElement.key) { var ownersMatch = prevElement._owner === nextElement._owner; var prevName = null; var nextName = null; var nextDisplayName = null; if ("production" !== process.env.NODE_ENV) { if (!ownersMatch) { if (prevElement._owner != null && prevElement._owner.getPublicInstance() != null && prevElement._owner.getPublicInstance().constructor != null) { prevName = prevElement._owner.getPublicInstance().constructor.displayName; } if (nextElement._owner != null && nextElement._owner.getPublicInstance() != null && nextElement._owner.getPublicInstance().constructor != null) { nextName = nextElement._owner.getPublicInstance().constructor.displayName; } if (nextElement.type != null && nextElement.type.displayName != null) { nextDisplayName = nextElement.type.displayName; } if (nextElement.type != null && typeof nextElement.type === 'string') { nextDisplayName = nextElement.type; } if (typeof nextElement.type !== 'string' || nextElement.type === 'input' || nextElement.type === 'textarea') { if ((prevElement._owner != null && prevElement._owner._isOwnerNecessary === false) || (nextElement._owner != null && nextElement._owner._isOwnerNecessary === false)) { if (prevElement._owner != null) { prevElement._owner._isOwnerNecessary = true; } if (nextElement._owner != null) { nextElement._owner._isOwnerNecessary = true; } ("production" !== process.env.NODE_ENV ? warning( false, '<%s /> is being rendered by both %s and %s using the same ' + 'key (%s) in the same place. Currently, this means that ' + 'they don\'t preserve state. This behavior should be very ' + 'rare so we\'re considering deprecating it. Please contact ' + 'the React team and explain your use case so that we can ' + 'take that into consideration.', nextDisplayName || 'Unknown Component', prevName || '[Unknown]', nextName || '[Unknown]', prevElement.key ) : null); } } } } return ownersMatch; } } } return false; } module.exports = shouldUpdateReactComponent; }).call(this,require('_process')) },{"./warning":155,"_process":1}],153:[function(require,module,exports){ (function (process){ /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule toArray * @typechecks */ var invariant = require("./invariant"); /** * Convert array-like objects to arrays. * * This API assumes the caller knows the contents of the data type. For less * well defined inputs use createArrayFromMixed. * * @param {object|function|filelist} obj * @return {array} */ function toArray(obj) { var length = obj.length; // Some browse builtin objects can report typeof 'function' (e.g. NodeList in // old versions of Safari). ("production" !== process.env.NODE_ENV ? invariant( !Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function'), 'toArray: Array-like object expected' ) : invariant(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function'))); ("production" !== process.env.NODE_ENV ? invariant( typeof length === 'number', 'toArray: Object needs a length property' ) : invariant(typeof length === 'number')); ("production" !== process.env.NODE_ENV ? invariant( length === 0 || (length - 1) in obj, 'toArray: Object should have keys for indices' ) : invariant(length === 0 || (length - 1) in obj)); // Old IE doesn't give collections access to hasOwnProperty. Assume inputs // without method will throw during the slice call and skip straight to the // fallback. if (obj.hasOwnProperty) { try { return Array.prototype.slice.call(obj); } catch (e) { // IE < 9 does not support Array#slice on collections objects } } // Fall back to copying key by key. This assumes all keys have a value, // so will not preserve sparsely populated inputs. var ret = Array(length); for (var ii = 0; ii < length; ii++) { ret[ii] = obj[ii]; } return ret; } module.exports = toArray; }).call(this,require('_process')) },{"./invariant":136,"_process":1}],154:[function(require,module,exports){ (function (process){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule traverseAllChildren */ 'use strict'; var ReactElement = require("./ReactElement"); var ReactFragment = require("./ReactFragment"); var ReactInstanceHandles = require("./ReactInstanceHandles"); var getIteratorFn = require("./getIteratorFn"); var invariant = require("./invariant"); var warning = require("./warning"); var SEPARATOR = ReactInstanceHandles.SEPARATOR; var SUBSEPARATOR = ':'; /** * TODO: Test that a single child and an array with one item have the same key * pattern. */ var userProvidedKeyEscaperLookup = { '=': '=0', '.': '=1', ':': '=2' }; var userProvidedKeyEscapeRegex = /[=.:]/g; var didWarnAboutMaps = false; function userProvidedKeyEscaper(match) { return userProvidedKeyEscaperLookup[match]; } /** * Generate a key string that identifies a component within a set. * * @param {*} component A component that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getComponentKey(component, index) { if (component && component.key != null) { // Explicit key return wrapUserProvidedKey(component.key); } // Implicit key determined by the index in the set return index.toString(36); } /** * Escape a component key so that it is safe to use in a reactid. * * @param {*} key Component key to be escaped. * @return {string} An escaped string. */ function escapeUserProvidedKey(text) { return ('' + text).replace( userProvidedKeyEscapeRegex, userProvidedKeyEscaper ); } /** * Wrap a `key` value explicitly provided by the user to distinguish it from * implicitly-generated keys generated by a component's index in its parent. * * @param {string} key Value of a user-provided `key` attribute * @return {string} */ function wrapUserProvidedKey(key) { return '$' + escapeUserProvidedKey(key); } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @param {!number} indexSoFar Number of children encountered until this point. * @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, indexSoFar, 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, indexSoFar ); return 1; } var child, nextName, nextIndex; var subtreeCount = 0; // Count of children found in the current subtree. if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = ( (nameSoFar !== '' ? nameSoFar + SUBSEPARATOR : SEPARATOR) + getComponentKey(child, i) ); nextIndex = indexSoFar + subtreeCount; subtreeCount += traverseAllChildrenImpl( child, nextName, nextIndex, 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 = ( (nameSoFar !== '' ? nameSoFar + SUBSEPARATOR : SEPARATOR) + getComponentKey(child, ii++) ); nextIndex = indexSoFar + subtreeCount; subtreeCount += traverseAllChildrenImpl( child, nextName, nextIndex, callback, traverseContext ); } } else { if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? 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.' ) : null); 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 = ( (nameSoFar !== '' ? nameSoFar + SUBSEPARATOR : SEPARATOR) + wrapUserProvidedKey(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0) ); nextIndex = indexSoFar + subtreeCount; subtreeCount += traverseAllChildrenImpl( child, nextName, nextIndex, callback, traverseContext ); } } } } else if (type === 'object') { ("production" !== process.env.NODE_ENV ? invariant( children.nodeType !== 1, 'traverseAllChildren(...): Encountered an invalid child; DOM ' + 'elements are not valid children of React components.' ) : invariant(children.nodeType !== 1)); var fragment = ReactFragment.extract(children); for (var key in fragment) { if (fragment.hasOwnProperty(key)) { child = fragment[key]; nextName = ( (nameSoFar !== '' ? nameSoFar + SUBSEPARATOR : SEPARATOR) + wrapUserProvidedKey(key) + SUBSEPARATOR + getComponentKey(child, 0) ); nextIndex = indexSoFar + subtreeCount; subtreeCount += traverseAllChildrenImpl( child, nextName, nextIndex, callback, traverseContext ); } } } } 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, '', 0, callback, traverseContext); } module.exports = traverseAllChildren; }).call(this,require('_process')) },{"./ReactElement":58,"./ReactFragment":64,"./ReactInstanceHandles":67,"./getIteratorFn":127,"./invariant":136,"./warning":155,"_process":1}],155:[function(require,module,exports){ (function (process){ /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule warning */ "use strict"; var emptyFunction = require("./emptyFunction"); /** * 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 ("production" !== process.env.NODE_ENV) { warning = function(condition, format ) {for (var args=[],$__0=2,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]); if (format === undefined) { throw new Error( '`warning(condition, format, ...args)` requires a warning ' + 'message argument' ); } if (format.length < 10 || /^[s\W]*$/.test(format)) { throw new Error( 'The warning format should be able to uniquely identify this ' + 'warning. Please, use a more descriptive format than: ' + format ); } 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++];}); console.warn(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; }).call(this,require('_process')) },{"./emptyFunction":115,"_process":1}],156:[function(require,module,exports){ module.exports = require('./lib/React'); },{"./lib/React":29}],157:[function(require,module,exports){ /** * Module dependencies. */ var Emitter = require('emitter'); var reduce = require('reduce'); /** * Root reference for iframes. */ var root = 'undefined' == typeof window ? (this || self) : window; /** * Noop. */ function noop(){}; /** * Check if `obj` is a host object, * we don't want to serialize these :) * * TODO: future proof, move to compoent land * * @param {Object} obj * @return {Boolean} * @api private */ function isHost(obj) { var str = {}.toString.call(obj); switch (str) { case '[object File]': case '[object Blob]': case '[object FormData]': return true; default: return false; } } /** * Determine XHR. */ request.getXHR = function () { if (root.XMLHttpRequest && (!root.location || 'file:' != root.location.protocol || !root.ActiveXObject)) { return new XMLHttpRequest; } else { try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {} try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {} try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {} try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {} } return false; }; /** * Removes leading and trailing whitespace, added to support IE. * * @param {String} s * @return {String} * @api private */ var trim = ''.trim ? function(s) { return s.trim(); } : function(s) { return s.replace(/(^\s*|\s*$)/g, ''); }; /** * Check if `obj` is an object. * * @param {Object} obj * @return {Boolean} * @api private */ function isObject(obj) { return obj === Object(obj); } /** * Serialize the given `obj`. * * @param {Object} obj * @return {String} * @api private */ function serialize(obj) { if (!isObject(obj)) return obj; var pairs = []; for (var key in obj) { if (null != obj[key]) { pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key])); } } return pairs.join('&'); } /** * Expose serialization method. */ request.serializeObject = serialize; /** * Parse the given x-www-form-urlencoded `str`. * * @param {String} str * @return {Object} * @api private */ function parseString(str) { var obj = {}; var pairs = str.split('&'); var parts; var pair; for (var i = 0, len = pairs.length; i < len; ++i) { pair = pairs[i]; parts = pair.split('='); obj[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]); } return obj; } /** * Expose parser. */ request.parseString = parseString; /** * Default MIME type map. * * superagent.types.xml = 'application/xml'; * */ request.types = { html: 'text/html', json: 'application/json', xml: 'application/xml', urlencoded: 'application/x-www-form-urlencoded', 'form': 'application/x-www-form-urlencoded', 'form-data': 'application/x-www-form-urlencoded' }; /** * Default serialization map. * * superagent.serialize['application/xml'] = function(obj){ * return 'generated xml here'; * }; * */ request.serialize = { 'application/x-www-form-urlencoded': serialize, 'application/json': JSON.stringify }; /** * Default parsers. * * superagent.parse['application/xml'] = function(str){ * return { object parsed from str }; * }; * */ request.parse = { 'application/x-www-form-urlencoded': parseString, 'application/json': JSON.parse }; /** * Parse the given header `str` into * an object containing the mapped fields. * * @param {String} str * @return {Object} * @api private */ function parseHeader(str) { var lines = str.split(/\r?\n/); var fields = {}; var index; var line; var field; var val; lines.pop(); // trailing CRLF for (var i = 0, len = lines.length; i < len; ++i) { line = lines[i]; index = line.indexOf(':'); field = line.slice(0, index).toLowerCase(); val = trim(line.slice(index + 1)); fields[field] = val; } return fields; } /** * Return the mime type for the given `str`. * * @param {String} str * @return {String} * @api private */ function type(str){ return str.split(/ *; */).shift(); }; /** * Return header field parameters. * * @param {String} str * @return {Object} * @api private */ function params(str){ return reduce(str.split(/ *; */), function(obj, str){ var parts = str.split(/ *= */) , key = parts.shift() , val = parts.shift(); if (key && val) obj[key] = val; return obj; }, {}); }; /** * Initialize a new `Response` with the given `xhr`. * * - set flags (.ok, .error, etc) * - parse header * * Examples: * * Aliasing `superagent` as `request` is nice: * * request = superagent; * * We can use the promise-like API, or pass callbacks: * * request.get('/').end(function(res){}); * request.get('/', function(res){}); * * Sending data can be chained: * * request * .post('/user') * .send({ name: 'tj' }) * .end(function(res){}); * * Or passed to `.send()`: * * request * .post('/user') * .send({ name: 'tj' }, function(res){}); * * Or passed to `.post()`: * * request * .post('/user', { name: 'tj' }) * .end(function(res){}); * * Or further reduced to a single call for simple cases: * * request * .post('/user', { name: 'tj' }, function(res){}); * * @param {XMLHTTPRequest} xhr * @param {Object} options * @api private */ function Response(req, options) { options = options || {}; this.req = req; this.xhr = this.req.xhr; // responseText is accessible only if responseType is '' or 'text' and on older browsers this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined') ? this.xhr.responseText : null; this.statusText = this.req.xhr.statusText; this.setStatusProperties(this.xhr.status); this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders()); // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but // getResponseHeader still works. so we get content-type even if getting // other headers fails. this.header['content-type'] = this.xhr.getResponseHeader('content-type'); this.setHeaderProperties(this.header); this.body = this.req.method != 'HEAD' ? this.parseBody(this.text ? this.text : this.xhr.response) : null; } /** * Get case-insensitive `field` value. * * @param {String} field * @return {String} * @api public */ Response.prototype.get = function(field){ return this.header[field.toLowerCase()]; }; /** * Set header related properties: * * - `.type` the content type without params * * A response of "Content-Type: text/plain; charset=utf-8" * will provide you with a `.type` of "text/plain". * * @param {Object} header * @api private */ Response.prototype.setHeaderProperties = function(header){ // content-type var ct = this.header['content-type'] || ''; this.type = type(ct); // params var obj = params(ct); for (var key in obj) this[key] = obj[key]; }; /** * Parse the given body `str`. * * Used for auto-parsing of bodies. Parsers * are defined on the `superagent.parse` object. * * @param {String} str * @return {Mixed} * @api private */ Response.prototype.parseBody = function(str){ var parse = request.parse[this.type]; return parse && str && (str.length || str instanceof Object) ? parse(str) : null; }; /** * Set flags such as `.ok` based on `status`. * * For example a 2xx response will give you a `.ok` of __true__ * whereas 5xx will be __false__ and `.error` will be __true__. The * `.clientError` and `.serverError` are also available to be more * specific, and `.statusType` is the class of error ranging from 1..5 * sometimes useful for mapping respond colors etc. * * "sugar" properties are also defined for common cases. Currently providing: * * - .noContent * - .badRequest * - .unauthorized * - .notAcceptable * - .notFound * * @param {Number} status * @api private */ Response.prototype.setStatusProperties = function(status){ // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request if (status === 1223) { status = 204; } var type = status / 100 | 0; // status / class this.status = status; this.statusType = type; // basics this.info = 1 == type; this.ok = 2 == type; this.clientError = 4 == type; this.serverError = 5 == type; this.error = (4 == type || 5 == type) ? this.toError() : false; // sugar this.accepted = 202 == status; this.noContent = 204 == status; this.badRequest = 400 == status; this.unauthorized = 401 == status; this.notAcceptable = 406 == status; this.notFound = 404 == status; this.forbidden = 403 == status; }; /** * Return an `Error` representative of this response. * * @return {Error} * @api public */ Response.prototype.toError = function(){ var req = this.req; var method = req.method; var url = req.url; var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')'; var err = new Error(msg); err.status = this.status; err.method = method; err.url = url; return err; }; /** * Expose `Response`. */ request.Response = Response; /** * Initialize a new `Request` with the given `method` and `url`. * * @param {String} method * @param {String} url * @api public */ function Request(method, url) { var self = this; Emitter.call(this); this._query = this._query || []; this.method = method; this.url = url; this.header = {}; this._header = {}; this.on('end', function(){ var err = null; var res = null; try { res = new Response(self); } catch(e) { err = new Error('Parser is unable to parse the response'); err.parse = true; err.original = e; return self.callback(err); } self.emit('response', res); if (err) { return self.callback(err, res); } if (res.status >= 200 && res.status < 300) { return self.callback(err, res); } var new_err = new Error(res.statusText || 'Unsuccessful HTTP response'); new_err.original = err; new_err.response = res; new_err.status = res.status; self.callback(err || new_err, res); }); } /** * Mixin `Emitter`. */ Emitter(Request.prototype); /** * Allow for extension */ Request.prototype.use = function(fn) { fn(this); return this; } /** * Set timeout to `ms`. * * @param {Number} ms * @return {Request} for chaining * @api public */ Request.prototype.timeout = function(ms){ this._timeout = ms; return this; }; /** * Clear previous timeout. * * @return {Request} for chaining * @api public */ Request.prototype.clearTimeout = function(){ this._timeout = 0; clearTimeout(this._timer); return this; }; /** * Abort the request, and clear potential timeout. * * @return {Request} * @api public */ Request.prototype.abort = function(){ if (this.aborted) return; this.aborted = true; this.xhr.abort(); this.clearTimeout(); this.emit('abort'); return this; }; /** * Set header `field` to `val`, or multiple fields with one object. * * Examples: * * req.get('/') * .set('Accept', 'application/json') * .set('X-API-Key', 'foobar') * .end(callback); * * req.get('/') * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' }) * .end(callback); * * @param {String|Object} field * @param {String} val * @return {Request} for chaining * @api public */ Request.prototype.set = function(field, val){ if (isObject(field)) { for (var key in field) { this.set(key, field[key]); } return this; } this._header[field.toLowerCase()] = val; this.header[field] = val; return this; }; /** * Remove header `field`. * * Example: * * req.get('/') * .unset('User-Agent') * .end(callback); * * @param {String} field * @return {Request} for chaining * @api public */ Request.prototype.unset = function(field){ delete this._header[field.toLowerCase()]; delete this.header[field]; return this; }; /** * Get case-insensitive header `field` value. * * @param {String} field * @return {String} * @api private */ Request.prototype.getHeader = function(field){ return this._header[field.toLowerCase()]; }; /** * Set Content-Type to `type`, mapping values from `request.types`. * * Examples: * * superagent.types.xml = 'application/xml'; * * request.post('/') * .type('xml') * .send(xmlstring) * .end(callback); * * request.post('/') * .type('application/xml') * .send(xmlstring) * .end(callback); * * @param {String} type * @return {Request} for chaining * @api public */ Request.prototype.type = function(type){ this.set('Content-Type', request.types[type] || type); return this; }; /** * Set Accept to `type`, mapping values from `request.types`. * * Examples: * * superagent.types.json = 'application/json'; * * request.get('/agent') * .accept('json') * .end(callback); * * request.get('/agent') * .accept('application/json') * .end(callback); * * @param {String} accept * @return {Request} for chaining * @api public */ Request.prototype.accept = function(type){ this.set('Accept', request.types[type] || type); return this; }; /** * Set Authorization field value with `user` and `pass`. * * @param {String} user * @param {String} pass * @return {Request} for chaining * @api public */ Request.prototype.auth = function(user, pass){ var str = btoa(user + ':' + pass); this.set('Authorization', 'Basic ' + str); return this; }; /** * Add query-string `val`. * * Examples: * * request.get('/shoes') * .query('size=10') * .query({ color: 'blue' }) * * @param {Object|String} val * @return {Request} for chaining * @api public */ Request.prototype.query = function(val){ if ('string' != typeof val) val = serialize(val); if (val) this._query.push(val); return this; }; /** * Write the field `name` and `val` for "multipart/form-data" * request bodies. * * ``` js * request.post('/upload') * .field('foo', 'bar') * .end(callback); * ``` * * @param {String} name * @param {String|Blob|File} val * @return {Request} for chaining * @api public */ Request.prototype.field = function(name, val){ if (!this._formData) this._formData = new root.FormData(); this._formData.append(name, val); return this; }; /** * Queue the given `file` as an attachment to the specified `field`, * with optional `filename`. * * ``` js * request.post('/upload') * .attach(new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"})) * .end(callback); * ``` * * @param {String} field * @param {Blob|File} file * @param {String} filename * @return {Request} for chaining * @api public */ Request.prototype.attach = function(field, file, filename){ if (!this._formData) this._formData = new root.FormData(); this._formData.append(field, file, filename); return this; }; /** * Send `data`, defaulting the `.type()` to "json" when * an object is given. * * Examples: * * // querystring * request.get('/search') * .end(callback) * * // multiple data "writes" * request.get('/search') * .send({ search: 'query' }) * .send({ range: '1..5' }) * .send({ order: 'desc' }) * .end(callback) * * // manual json * request.post('/user') * .type('json') * .send('{"name":"tj"}) * .end(callback) * * // auto json * request.post('/user') * .send({ name: 'tj' }) * .end(callback) * * // manual x-www-form-urlencoded * request.post('/user') * .type('form') * .send('name=tj') * .end(callback) * * // auto x-www-form-urlencoded * request.post('/user') * .type('form') * .send({ name: 'tj' }) * .end(callback) * * // defaults to x-www-form-urlencoded * request.post('/user') * .send('name=tobi') * .send('species=ferret') * .end(callback) * * @param {String|Object} data * @return {Request} for chaining * @api public */ Request.prototype.send = function(data){ var obj = isObject(data); var type = this.getHeader('Content-Type'); // merge if (obj && isObject(this._data)) { for (var key in data) { this._data[key] = data[key]; } } else if ('string' == typeof data) { if (!type) this.type('form'); type = this.getHeader('Content-Type'); if ('application/x-www-form-urlencoded' == type) { this._data = this._data ? this._data + '&' + data : data; } else { this._data = (this._data || '') + data; } } else { this._data = data; } if (!obj || isHost(data)) return this; if (!type) this.type('json'); return this; }; /** * Invoke the callback with `err` and `res` * and handle arity check. * * @param {Error} err * @param {Response} res * @api private */ Request.prototype.callback = function(err, res){ var fn = this._callback; this.clearTimeout(); fn(err, res); }; /** * Invoke callback with x-domain error. * * @api private */ Request.prototype.crossDomainError = function(){ var err = new Error('Origin is not allowed by Access-Control-Allow-Origin'); err.crossDomain = true; this.callback(err); }; /** * Invoke callback with timeout error. * * @api private */ Request.prototype.timeoutError = function(){ var timeout = this._timeout; var err = new Error('timeout of ' + timeout + 'ms exceeded'); err.timeout = timeout; this.callback(err); }; /** * Enable transmission of cookies with x-domain requests. * * Note that for this to work the origin must not be * using "Access-Control-Allow-Origin" with a wildcard, * and also must set "Access-Control-Allow-Credentials" * to "true". * * @api public */ Request.prototype.withCredentials = function(){ this._withCredentials = true; return this; }; /** * Initiate request, invoking callback `fn(res)` * with an instanceof `Response`. * * @param {Function} fn * @return {Request} for chaining * @api public */ Request.prototype.end = function(fn){ var self = this; var xhr = this.xhr = request.getXHR(); var query = this._query.join('&'); var timeout = this._timeout; var data = this._formData || this._data; // store callback this._callback = fn || noop; // state change xhr.onreadystatechange = function(){ if (4 != xhr.readyState) return; // In IE9, reads to any property (e.g. status) off of an aborted XHR will // result in the error "Could not complete the operation due to error c00c023f" var status; try { status = xhr.status } catch(e) { status = 0; } if (0 == status) { if (self.timedout) return self.timeoutError(); if (self.aborted) return; return self.crossDomainError(); } self.emit('end'); }; // progress var handleProgress = function(e){ if (e.total > 0) { e.percent = e.loaded / e.total * 100; } self.emit('progress', e); }; if (this.hasListeners('progress')) { xhr.onprogress = handleProgress; } try { if (xhr.upload && this.hasListeners('progress')) { xhr.upload.onprogress = handleProgress; } } catch(e) { // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist. // Reported here: // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context } // timeout if (timeout && !this._timer) { this._timer = setTimeout(function(){ self.timedout = true; self.abort(); }, timeout); } // querystring if (query) { query = request.serializeObject(query); this.url += ~this.url.indexOf('?') ? '&' + query : '?' + query; } // initiate request xhr.open(this.method, this.url, true); // CORS if (this._withCredentials) xhr.withCredentials = true; // body if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !isHost(data)) { // serialize stuff var serialize = request.serialize[this.getHeader('Content-Type')]; if (serialize) data = serialize(data); } // set header fields for (var field in this.header) { if (null == this.header[field]) continue; xhr.setRequestHeader(field, this.header[field]); } // send stuff this.emit('request', this); xhr.send(data); return this; }; /** * Expose `Request`. */ request.Request = Request; /** * Issue a request: * * Examples: * * request('GET', '/users').end(callback) * request('/users').end(callback) * request('/users', callback) * * @param {String} method * @param {String|Function} url or callback * @return {Request} * @api public */ function request(method, url) { // callback if ('function' == typeof url) { return new Request('GET', method).end(url); } // url first if (1 == arguments.length) { return new Request('GET', method); } return new Request(method, url); } /** * GET `url` with optional callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} data or fn * @param {Function} fn * @return {Request} * @api public */ request.get = function(url, data, fn){ var req = request('GET', url); if ('function' == typeof data) fn = data, data = null; if (data) req.query(data); if (fn) req.end(fn); return req; }; /** * HEAD `url` with optional callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} data or fn * @param {Function} fn * @return {Request} * @api public */ request.head = function(url, data, fn){ var req = request('HEAD', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * DELETE `url` with optional callback `fn(res)`. * * @param {String} url * @param {Function} fn * @return {Request} * @api public */ request.del = function(url, fn){ var req = request('DELETE', url); if (fn) req.end(fn); return req; }; /** * PATCH `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed} data * @param {Function} fn * @return {Request} * @api public */ request.patch = function(url, data, fn){ var req = request('PATCH', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * POST `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed} data * @param {Function} fn * @return {Request} * @api public */ request.post = function(url, data, fn){ var req = request('POST', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * PUT `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} data or fn * @param {Function} fn * @return {Request} * @api public */ request.put = function(url, data, fn){ var req = request('PUT', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * Expose `request`. */ module.exports = request; },{"emitter":158,"reduce":159}],158:[function(require,module,exports){ /** * Expose `Emitter`. */ module.exports = Emitter; /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks[event] = this._callbacks[event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ var self = this; this._callbacks = this._callbacks || {}; function on() { self.off(event, on); fn.apply(this, arguments); } on.fn = fn; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks[event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks[event]; return this; } // remove specific handler var cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks[event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks[event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; },{}],159:[function(require,module,exports){ /** * Reduce `arr` with `fn`. * * @param {Array} arr * @param {Function} fn * @param {Mixed} initial * * TODO: combatible error handling? */ module.exports = function(arr, fn, initial){ var idx = 0; var len = arr.length; var curr = arguments.length == 3 ? initial : arr[idx++]; while (idx < len) { curr = fn.call(null, curr, arr[idx], ++idx, arr); } return curr; }; },{}],160:[function(require,module,exports){ /** @license MIT License (c) copyright B Cavalier & J Hann */ /** * cancelable.js * @deprecated * * Decorator that makes a deferred "cancelable". It adds a cancel() method that * will call a special cancel handler function and then reject the deferred. The * cancel handler can be used to do resource cleanup, or anything else that should * be done before any other rejection handlers are executed. * * Usage: * * var cancelableDeferred = cancelable(when.defer(), myCancelHandler); * * @author [email protected] */ (function(define) { define(function() { /** * Makes deferred cancelable, adding a cancel() method. * @deprecated * * @param deferred {Deferred} the {@link Deferred} to make cancelable * @param canceler {Function} cancel handler function to execute when this deferred * is canceled. This is guaranteed to run before all other rejection handlers. * The canceler will NOT be executed if the deferred is rejected in the standard * way, i.e. deferred.reject(). It ONLY executes if the deferred is canceled, * i.e. deferred.cancel() * * @returns deferred, with an added cancel() method. */ return function(deferred, canceler) { // Add a cancel method to the deferred to reject the delegate // with the special canceled indicator. deferred.cancel = function() { try { deferred.reject(canceler(deferred)); } catch(e) { deferred.reject(e); } return deferred.promise; }; return deferred; }; }); })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(); }); },{}],161:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function (require) { var makePromise = require('./makePromise'); var Scheduler = require('./Scheduler'); var async = require('./env').asap; return makePromise({ scheduler: new Scheduler(async) }); }); })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); }); },{"./Scheduler":162,"./env":174,"./makePromise":176}],162:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { // Credit to Twisol (https://github.com/Twisol) for suggesting // this type of extensible queue + trampoline approach for next-tick conflation. /** * Async task scheduler * @param {function} async function to schedule a single async function * @constructor */ function Scheduler(async) { this._async = async; this._running = false; this._queue = this; this._queueLen = 0; this._afterQueue = {}; this._afterQueueLen = 0; var self = this; this.drain = function() { self._drain(); }; } /** * Enqueue a task * @param {{ run:function }} task */ Scheduler.prototype.enqueue = function(task) { this._queue[this._queueLen++] = task; this.run(); }; /** * Enqueue a task to run after the main task queue * @param {{ run:function }} task */ Scheduler.prototype.afterQueue = function(task) { this._afterQueue[this._afterQueueLen++] = task; this.run(); }; Scheduler.prototype.run = function() { if (!this._running) { this._running = true; this._async(this.drain); } }; /** * Drain the handler queue entirely, and then the after queue */ Scheduler.prototype._drain = function() { var i = 0; for (; i < this._queueLen; ++i) { this._queue[i].run(); this._queue[i] = void 0; } this._queueLen = 0; this._running = false; for (i = 0; i < this._afterQueueLen; ++i) { this._afterQueue[i].run(); this._afterQueue[i] = void 0; } this._afterQueueLen = 0; }; return Scheduler; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],163:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { /** * Custom error type for promises rejected by promise.timeout * @param {string} message * @constructor */ function TimeoutError (message) { Error.call(this); this.message = message; this.name = TimeoutError.name; if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, TimeoutError); } } TimeoutError.prototype = Object.create(Error.prototype); TimeoutError.prototype.constructor = TimeoutError; return TimeoutError; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],164:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { makeApply.tryCatchResolve = tryCatchResolve; return makeApply; function makeApply(Promise, call) { if(arguments.length < 2) { call = tryCatchResolve; } return apply; function apply(f, thisArg, args) { var p = Promise._defer(); var l = args.length; var params = new Array(l); callAndResolve({ f:f, thisArg:thisArg, args:args, params:params, i:l-1, call:call }, p._handler); return p; } function callAndResolve(c, h) { if(c.i < 0) { return call(c.f, c.thisArg, c.params, h); } var handler = Promise._handler(c.args[c.i]); handler.fold(callAndResolveNext, c, void 0, h); } function callAndResolveNext(c, x, h) { c.params[c.i] = x; c.i -= 1; callAndResolve(c, h); } } function tryCatchResolve(f, thisArg, args, resolver) { try { resolver.resolve(f.apply(thisArg, args)); } catch(e) { resolver.reject(e); } } }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],165:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function(require) { var state = require('../state'); var applier = require('../apply'); return function array(Promise) { var applyFold = applier(Promise); var toPromise = Promise.resolve; var all = Promise.all; var ar = Array.prototype.reduce; var arr = Array.prototype.reduceRight; var slice = Array.prototype.slice; // Additional array combinators Promise.any = any; Promise.some = some; Promise.settle = settle; Promise.map = map; Promise.filter = filter; Promise.reduce = reduce; Promise.reduceRight = reduceRight; /** * When this promise fulfills with an array, do * onFulfilled.apply(void 0, array) * @param {function} onFulfilled function to apply * @returns {Promise} promise for the result of applying onFulfilled */ Promise.prototype.spread = function(onFulfilled) { return this.then(all).then(function(array) { return onFulfilled.apply(this, array); }); }; return Promise; /** * One-winner competitive race. * Return a promise that will fulfill when one of the promises * in the input array fulfills, or will reject when all promises * have rejected. * @param {array} promises * @returns {Promise} promise for the first fulfilled value */ function any(promises) { var p = Promise._defer(); var resolver = p._handler; var l = promises.length>>>0; var pending = l; var errors = []; for (var h, x, i = 0; i < l; ++i) { x = promises[i]; if(x === void 0 && !(i in promises)) { --pending; continue; } h = Promise._handler(x); if(h.state() > 0) { resolver.become(h); Promise._visitRemaining(promises, i, h); break; } else { h.visit(resolver, handleFulfill, handleReject); } } if(pending === 0) { resolver.reject(new RangeError('any(): array must not be empty')); } return p; function handleFulfill(x) { /*jshint validthis:true*/ errors = null; this.resolve(x); // this === resolver } function handleReject(e) { /*jshint validthis:true*/ if(this.resolved) { // this === resolver return; } errors.push(e); if(--pending === 0) { this.reject(errors); } } } /** * N-winner competitive race * Return a promise that will fulfill when n input promises have * fulfilled, or will reject when it becomes impossible for n * input promises to fulfill (ie when promises.length - n + 1 * have rejected) * @param {array} promises * @param {number} n * @returns {Promise} promise for the earliest n fulfillment values * * @deprecated */ function some(promises, n) { /*jshint maxcomplexity:7*/ var p = Promise._defer(); var resolver = p._handler; var results = []; var errors = []; var l = promises.length>>>0; var nFulfill = 0; var nReject; var x, i; // reused in both for() loops // First pass: count actual array items for(i=0; i<l; ++i) { x = promises[i]; if(x === void 0 && !(i in promises)) { continue; } ++nFulfill; } // Compute actual goals n = Math.max(n, 0); nReject = (nFulfill - n + 1); nFulfill = Math.min(n, nFulfill); if(n > nFulfill) { resolver.reject(new RangeError('some(): array must contain at least ' + n + ' item(s), but had ' + nFulfill)); } else if(nFulfill === 0) { resolver.resolve(results); } // Second pass: observe each array item, make progress toward goals for(i=0; i<l; ++i) { x = promises[i]; if(x === void 0 && !(i in promises)) { continue; } Promise._handler(x).visit(resolver, fulfill, reject, resolver.notify); } return p; function fulfill(x) { /*jshint validthis:true*/ if(this.resolved) { // this === resolver return; } results.push(x); if(--nFulfill === 0) { errors = null; this.resolve(results); } } function reject(e) { /*jshint validthis:true*/ if(this.resolved) { // this === resolver return; } errors.push(e); if(--nReject === 0) { results = null; this.reject(errors); } } } /** * Apply f to the value of each promise in a list of promises * and return a new list containing the results. * @param {array} promises * @param {function(x:*, index:Number):*} f mapping function * @returns {Promise} */ function map(promises, f) { return Promise._traverse(f, promises); } /** * Filter the provided array of promises using the provided predicate. Input may * contain promises and values * @param {Array} promises array of promises and values * @param {function(x:*, index:Number):boolean} predicate filtering predicate. * Must return truthy (or promise for truthy) for items to retain. * @returns {Promise} promise that will fulfill with an array containing all items * for which predicate returned truthy. */ function filter(promises, predicate) { var a = slice.call(promises); return Promise._traverse(predicate, a).then(function(keep) { return filterSync(a, keep); }); } function filterSync(promises, keep) { // Safe because we know all promises have fulfilled if we've made it this far var l = keep.length; var filtered = new Array(l); for(var i=0, j=0; i<l; ++i) { if(keep[i]) { filtered[j++] = Promise._handler(promises[i]).value; } } filtered.length = j; return filtered; } /** * Return a promise that will always fulfill with an array containing * the outcome states of all input promises. The returned promise * will never reject. * @param {Array} promises * @returns {Promise} promise for array of settled state descriptors */ function settle(promises) { return all(promises.map(settleOne)); } function settleOne(p) { var h = Promise._handler(p); if(h.state() === 0) { return toPromise(p).then(state.fulfilled, state.rejected); } h._unreport(); return state.inspect(h); } /** * Traditional reduce function, similar to `Array.prototype.reduce()`, but * input may contain promises and/or values, and reduceFunc * may return either a value or a promise, *and* initialValue may * be a promise for the starting value. * @param {Array|Promise} promises array or promise for an array of anything, * may contain a mix of promises and values. * @param {function(accumulated:*, x:*, index:Number):*} f reduce function * @returns {Promise} that will resolve to the final reduced value */ function reduce(promises, f /*, initialValue */) { return arguments.length > 2 ? ar.call(promises, liftCombine(f), arguments[2]) : ar.call(promises, liftCombine(f)); } /** * Traditional reduce function, similar to `Array.prototype.reduceRight()`, but * input may contain promises and/or values, and reduceFunc * may return either a value or a promise, *and* initialValue may * be a promise for the starting value. * @param {Array|Promise} promises array or promise for an array of anything, * may contain a mix of promises and values. * @param {function(accumulated:*, x:*, index:Number):*} f reduce function * @returns {Promise} that will resolve to the final reduced value */ function reduceRight(promises, f /*, initialValue */) { return arguments.length > 2 ? arr.call(promises, liftCombine(f), arguments[2]) : arr.call(promises, liftCombine(f)); } function liftCombine(f) { return function(z, x, i) { return applyFold(f, void 0, [z,x,i]); }; } }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); })); },{"../apply":164,"../state":177}],166:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return function flow(Promise) { var resolve = Promise.resolve; var reject = Promise.reject; var origCatch = Promise.prototype['catch']; /** * Handle the ultimate fulfillment value or rejection reason, and assume * responsibility for all errors. If an error propagates out of result * or handleFatalError, it will be rethrown to the host, resulting in a * loud stack track on most platforms and a crash on some. * @param {function?} onResult * @param {function?} onError * @returns {undefined} */ Promise.prototype.done = function(onResult, onError) { this._handler.visit(this._handler.receiver, onResult, onError); }; /** * Add Error-type and predicate matching to catch. Examples: * promise.catch(TypeError, handleTypeError) * .catch(predicate, handleMatchedErrors) * .catch(handleRemainingErrors) * @param onRejected * @returns {*} */ Promise.prototype['catch'] = Promise.prototype.otherwise = function(onRejected) { if (arguments.length < 2) { return origCatch.call(this, onRejected); } if(typeof onRejected !== 'function') { return this.ensure(rejectInvalidPredicate); } return origCatch.call(this, createCatchFilter(arguments[1], onRejected)); }; /** * Wraps the provided catch handler, so that it will only be called * if the predicate evaluates truthy * @param {?function} handler * @param {function} predicate * @returns {function} conditional catch handler */ function createCatchFilter(handler, predicate) { return function(e) { return evaluatePredicate(e, predicate) ? handler.call(this, e) : reject(e); }; } /** * Ensures that onFulfilledOrRejected will be called regardless of whether * this promise is fulfilled or rejected. onFulfilledOrRejected WILL NOT * receive the promises' value or reason. Any returned value will be disregarded. * onFulfilledOrRejected may throw or return a rejected promise to signal * an additional error. * @param {function} handler handler to be called regardless of * fulfillment or rejection * @returns {Promise} */ Promise.prototype['finally'] = Promise.prototype.ensure = function(handler) { if(typeof handler !== 'function') { return this; } return this.then(function(x) { return runSideEffect(handler, this, identity, x); }, function(e) { return runSideEffect(handler, this, reject, e); }); }; function runSideEffect (handler, thisArg, propagate, value) { var result = handler.call(thisArg); return maybeThenable(result) ? propagateValue(result, propagate, value) : propagate(value); } function propagateValue (result, propagate, x) { return resolve(result).then(function () { return propagate(x); }); } /** * Recover from a failure by returning a defaultValue. If defaultValue * is a promise, it's fulfillment value will be used. If defaultValue is * a promise that rejects, the returned promise will reject with the * same reason. * @param {*} defaultValue * @returns {Promise} new promise */ Promise.prototype['else'] = Promise.prototype.orElse = function(defaultValue) { return this.then(void 0, function() { return defaultValue; }); }; /** * Shortcut for .then(function() { return value; }) * @param {*} value * @return {Promise} a promise that: * - is fulfilled if value is not a promise, or * - if value is a promise, will fulfill with its value, or reject * with its reason. */ Promise.prototype['yield'] = function(value) { return this.then(function() { return value; }); }; /** * Runs a side effect when this promise fulfills, without changing the * fulfillment value. * @param {function} onFulfilledSideEffect * @returns {Promise} */ Promise.prototype.tap = function(onFulfilledSideEffect) { return this.then(onFulfilledSideEffect)['yield'](this); }; return Promise; }; function rejectInvalidPredicate() { throw new TypeError('catch predicate must be a function'); } function evaluatePredicate(e, predicate) { return isError(predicate) ? e instanceof predicate : predicate(e); } function isError(predicate) { return predicate === Error || (predicate != null && predicate.prototype instanceof Error); } function maybeThenable(x) { return (typeof x === 'object' || typeof x === 'function') && x !== null; } function identity(x) { return x; } }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],167:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ /** @author Jeff Escalante */ (function(define) { 'use strict'; define(function() { return function fold(Promise) { Promise.prototype.fold = function(f, z) { var promise = this._beget(); this._handler.fold(function(z, x, to) { Promise._handler(z).fold(function(x, z, to) { to.resolve(f.call(this, z, x)); }, x, this, to); }, z, promise._handler.receiver, promise._handler); return promise; }; return Promise; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],168:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function(require) { var inspect = require('../state').inspect; return function inspection(Promise) { Promise.prototype.inspect = function() { return inspect(Promise._handler(this)); }; return Promise; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); })); },{"../state":177}],169:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return function generate(Promise) { var resolve = Promise.resolve; Promise.iterate = iterate; Promise.unfold = unfold; return Promise; /** * @deprecated Use github.com/cujojs/most streams and most.iterate * Generate a (potentially infinite) stream of promised values: * x, f(x), f(f(x)), etc. until condition(x) returns true * @param {function} f function to generate a new x from the previous x * @param {function} condition function that, given the current x, returns * truthy when the iterate should stop * @param {function} handler function to handle the value produced by f * @param {*|Promise} x starting value, may be a promise * @return {Promise} the result of the last call to f before * condition returns true */ function iterate(f, condition, handler, x) { return unfold(function(x) { return [x, f(x)]; }, condition, handler, x); } /** * @deprecated Use github.com/cujojs/most streams and most.unfold * Generate a (potentially infinite) stream of promised values * by applying handler(generator(seed)) iteratively until * condition(seed) returns true. * @param {function} unspool function that generates a [value, newSeed] * given a seed. * @param {function} condition function that, given the current seed, returns * truthy when the unfold should stop * @param {function} handler function to handle the value produced by unspool * @param x {*|Promise} starting value, may be a promise * @return {Promise} the result of the last value produced by unspool before * condition returns true */ function unfold(unspool, condition, handler, x) { return resolve(x).then(function(seed) { return resolve(condition(seed)).then(function(done) { return done ? seed : resolve(unspool(seed)).spread(next); }); }); function next(item, newSeed) { return resolve(handler(item)).then(function() { return unfold(unspool, condition, handler, newSeed); }); } } }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],170:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return function progress(Promise) { /** * @deprecated * Register a progress handler for this promise * @param {function} onProgress * @returns {Promise} */ Promise.prototype.progress = function(onProgress) { return this.then(void 0, void 0, onProgress); }; return Promise; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],171:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function(require) { var env = require('../env'); var TimeoutError = require('../TimeoutError'); function setTimeout(f, ms, x, y) { return env.setTimer(function() { f(x, y, ms); }, ms); } return function timed(Promise) { /** * Return a new promise whose fulfillment value is revealed only * after ms milliseconds * @param {number} ms milliseconds * @returns {Promise} */ Promise.prototype.delay = function(ms) { var p = this._beget(); this._handler.fold(handleDelay, ms, void 0, p._handler); return p; }; function handleDelay(ms, x, h) { setTimeout(resolveDelay, ms, x, h); } function resolveDelay(x, h) { h.resolve(x); } /** * Return a new promise that rejects after ms milliseconds unless * this promise fulfills earlier, in which case the returned promise * fulfills with the same value. * @param {number} ms milliseconds * @param {Error|*=} reason optional rejection reason to use, defaults * to a TimeoutError if not provided * @returns {Promise} */ Promise.prototype.timeout = function(ms, reason) { var p = this._beget(); var h = p._handler; var t = setTimeout(onTimeout, ms, reason, p._handler); this._handler.visit(h, function onFulfill(x) { env.clearTimer(t); this.resolve(x); // this = h }, function onReject(x) { env.clearTimer(t); this.reject(x); // this = h }, h.notify); return p; }; function onTimeout(reason, h, ms) { var e = typeof reason === 'undefined' ? new TimeoutError('timed out after ' + ms + 'ms') : reason; h.reject(e); } return Promise; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); })); },{"../TimeoutError":163,"../env":174}],172:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function(require) { var setTimer = require('../env').setTimer; var format = require('../format'); return function unhandledRejection(Promise) { var logError = noop; var logInfo = noop; var localConsole; if(typeof console !== 'undefined') { // Alias console to prevent things like uglify's drop_console option from // removing console.log/error. Unhandled rejections fall into the same // category as uncaught exceptions, and build tools shouldn't silence them. localConsole = console; logError = typeof localConsole.error !== 'undefined' ? function (e) { localConsole.error(e); } : function (e) { localConsole.log(e); }; logInfo = typeof localConsole.info !== 'undefined' ? function (e) { localConsole.info(e); } : function (e) { localConsole.log(e); }; } Promise.onPotentiallyUnhandledRejection = function(rejection) { enqueue(report, rejection); }; Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) { enqueue(unreport, rejection); }; Promise.onFatalRejection = function(rejection) { enqueue(throwit, rejection.value); }; var tasks = []; var reported = []; var running = null; function report(r) { if(!r.handled) { reported.push(r); logError('Potentially unhandled rejection [' + r.id + '] ' + format.formatError(r.value)); } } function unreport(r) { var i = reported.indexOf(r); if(i >= 0) { reported.splice(i, 1); logInfo('Handled previous rejection [' + r.id + '] ' + format.formatObject(r.value)); } } function enqueue(f, x) { tasks.push(f, x); if(running === null) { running = setTimer(flush, 0); } } function flush() { running = null; while(tasks.length > 0) { tasks.shift()(tasks.shift()); } } return Promise; }; function throwit(e) { throw e; } function noop() {} }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); })); },{"../env":174,"../format":175}],173:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return function addWith(Promise) { /** * Returns a promise whose handlers will be called with `this` set to * the supplied receiver. Subsequent promises derived from the * returned promise will also have their handlers called with receiver * as `this`. Calling `with` with undefined or no arguments will return * a promise whose handlers will again be called in the usual Promises/A+ * way (no `this`) thus safely undoing any previous `with` in the * promise chain. * * WARNING: Promises returned from `with`/`withThis` are NOT Promises/A+ * compliant, specifically violating 2.2.5 (http://promisesaplus.com/#point-41) * * @param {object} receiver `this` value for all handlers attached to * the returned promise. * @returns {Promise} */ Promise.prototype['with'] = Promise.prototype.withThis = function(receiver) { var p = this._beget(); var child = p._handler; child.receiver = receiver; this._handler.chain(child, receiver); return p; }; return Promise; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],174:[function(require,module,exports){ (function (process){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ /*global process,document,setTimeout,clearTimeout,MutationObserver,WebKitMutationObserver*/ (function(define) { 'use strict'; define(function(require) { /*jshint maxcomplexity:6*/ // Sniff "best" async scheduling option // Prefer process.nextTick or MutationObserver, then check for // setTimeout, and finally vertx, since its the only env that doesn't // have setTimeout var MutationObs; var capturedSetTimeout = typeof setTimeout !== 'undefined' && setTimeout; // Default env var setTimer = function(f, ms) { return setTimeout(f, ms); }; var clearTimer = function(t) { return clearTimeout(t); }; var asap = function (f) { return capturedSetTimeout(f, 0); }; // Detect specific env if (isNode()) { // Node asap = function (f) { return process.nextTick(f); }; } else if (MutationObs = hasMutationObserver()) { // Modern browser asap = initMutationObserver(MutationObs); } else if (!capturedSetTimeout) { // vert.x var vertxRequire = require; var vertx = vertxRequire('vertx'); setTimer = function (f, ms) { return vertx.setTimer(ms, f); }; clearTimer = vertx.cancelTimer; asap = vertx.runOnLoop || vertx.runOnContext; } return { setTimer: setTimer, clearTimer: clearTimer, asap: asap }; function isNode () { return typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]'; } function hasMutationObserver () { return (typeof MutationObserver === 'function' && MutationObserver) || (typeof WebKitMutationObserver === 'function' && WebKitMutationObserver); } function initMutationObserver(MutationObserver) { var scheduled; var node = document.createTextNode(''); var o = new MutationObserver(run); o.observe(node, { characterData: true }); function run() { var f = scheduled; scheduled = void 0; f(); } var i = 0; return function (f) { scheduled = f; node.data = (i ^= 1); }; } }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); })); }).call(this,require('_process')) },{"_process":1}],175:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return { formatError: formatError, formatObject: formatObject, tryStringify: tryStringify }; /** * Format an error into a string. If e is an Error and has a stack property, * it's returned. Otherwise, e is formatted using formatObject, with a * warning added about e not being a proper Error. * @param {*} e * @returns {String} formatted string, suitable for output to developers */ function formatError(e) { var s = typeof e === 'object' && e !== null && e.stack ? e.stack : formatObject(e); return e instanceof Error ? s : s + ' (WARNING: non-Error used)'; } /** * Format an object, detecting "plain" objects and running them through * JSON.stringify if possible. * @param {Object} o * @returns {string} */ function formatObject(o) { var s = String(o); if(s === '[object Object]' && typeof JSON !== 'undefined') { s = tryStringify(o, s); } return s; } /** * Try to return the result of JSON.stringify(x). If that fails, return * defaultValue * @param {*} x * @param {*} defaultValue * @returns {String|*} JSON.stringify(x) or defaultValue */ function tryStringify(x, defaultValue) { try { return JSON.stringify(x); } catch(e) { return defaultValue; } } }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],176:[function(require,module,exports){ (function (process){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return function makePromise(environment) { var tasks = environment.scheduler; var emitRejection = initEmitRejection(); var objectCreate = Object.create || function(proto) { function Child() {} Child.prototype = proto; return new Child(); }; /** * Create a promise whose fate is determined by resolver * @constructor * @returns {Promise} promise * @name Promise */ function Promise(resolver, handler) { this._handler = resolver === Handler ? handler : init(resolver); } /** * Run the supplied resolver * @param resolver * @returns {Pending} */ function init(resolver) { var handler = new Pending(); try { resolver(promiseResolve, promiseReject, promiseNotify); } catch (e) { promiseReject(e); } return handler; /** * Transition from pre-resolution state to post-resolution state, notifying * all listeners of the ultimate fulfillment or rejection * @param {*} x resolution value */ function promiseResolve (x) { handler.resolve(x); } /** * Reject this promise with reason, which will be used verbatim * @param {Error|*} reason rejection reason, strongly suggested * to be an Error type */ function promiseReject (reason) { handler.reject(reason); } /** * @deprecated * Issue a progress event, notifying all progress listeners * @param {*} x progress event payload to pass to all listeners */ function promiseNotify (x) { handler.notify(x); } } // Creation Promise.resolve = resolve; Promise.reject = reject; Promise.never = never; Promise._defer = defer; Promise._handler = getHandler; /** * Returns a trusted promise. If x is already a trusted promise, it is * returned, otherwise returns a new trusted Promise which follows x. * @param {*} x * @return {Promise} promise */ function resolve(x) { return isPromise(x) ? x : new Promise(Handler, new Async(getHandler(x))); } /** * Return a reject promise with x as its reason (x is used verbatim) * @param {*} x * @returns {Promise} rejected promise */ function reject(x) { return new Promise(Handler, new Async(new Rejected(x))); } /** * Return a promise that remains pending forever * @returns {Promise} forever-pending promise. */ function never() { return foreverPendingPromise; // Should be frozen } /** * Creates an internal {promise, resolver} pair * @private * @returns {Promise} */ function defer() { return new Promise(Handler, new Pending()); } // Transformation and flow control /** * Transform this promise's fulfillment value, returning a new Promise * for the transformed result. If the promise cannot be fulfilled, onRejected * is called with the reason. onProgress *may* be called with updates toward * this promise's fulfillment. * @param {function=} onFulfilled fulfillment handler * @param {function=} onRejected rejection handler * @param {function=} onProgress @deprecated progress handler * @return {Promise} new promise */ Promise.prototype.then = function(onFulfilled, onRejected, onProgress) { var parent = this._handler; var state = parent.join().state(); if ((typeof onFulfilled !== 'function' && state > 0) || (typeof onRejected !== 'function' && state < 0)) { // Short circuit: value will not change, simply share handler return new this.constructor(Handler, parent); } var p = this._beget(); var child = p._handler; parent.chain(child, parent.receiver, onFulfilled, onRejected, onProgress); return p; }; /** * If this promise cannot be fulfilled due to an error, call onRejected to * handle the error. Shortcut for .then(undefined, onRejected) * @param {function?} onRejected * @return {Promise} */ Promise.prototype['catch'] = function(onRejected) { return this.then(void 0, onRejected); }; /** * Creates a new, pending promise of the same type as this promise * @private * @returns {Promise} */ Promise.prototype._beget = function() { return begetFrom(this._handler, this.constructor); }; function begetFrom(parent, Promise) { var child = new Pending(parent.receiver, parent.join().context); return new Promise(Handler, child); } // Array combinators Promise.all = all; Promise.race = race; Promise._traverse = traverse; /** * Return a promise that will fulfill when all promises in the * input array have fulfilled, or will reject when one of the * promises rejects. * @param {array} promises array of promises * @returns {Promise} promise for array of fulfillment values */ function all(promises) { return traverseWith(snd, null, promises); } /** * Array<Promise<X>> -> Promise<Array<f(X)>> * @private * @param {function} f function to apply to each promise's value * @param {Array} promises array of promises * @returns {Promise} promise for transformed values */ function traverse(f, promises) { return traverseWith(tryCatch2, f, promises); } function traverseWith(tryMap, f, promises) { var handler = typeof f === 'function' ? mapAt : settleAt; var resolver = new Pending(); var pending = promises.length >>> 0; var results = new Array(pending); for (var i = 0, x; i < promises.length && !resolver.resolved; ++i) { x = promises[i]; if (x === void 0 && !(i in promises)) { --pending; continue; } traverseAt(promises, handler, i, x, resolver); } if(pending === 0) { resolver.become(new Fulfilled(results)); } return new Promise(Handler, resolver); function mapAt(i, x, resolver) { if(!resolver.resolved) { traverseAt(promises, settleAt, i, tryMap(f, x, i), resolver); } } function settleAt(i, x, resolver) { results[i] = x; if(--pending === 0) { resolver.become(new Fulfilled(results)); } } } function traverseAt(promises, handler, i, x, resolver) { if (maybeThenable(x)) { var h = getHandlerMaybeThenable(x); var s = h.state(); if (s === 0) { h.fold(handler, i, void 0, resolver); } else if (s > 0) { handler(i, h.value, resolver); } else { resolver.become(h); visitRemaining(promises, i+1, h); } } else { handler(i, x, resolver); } } Promise._visitRemaining = visitRemaining; function visitRemaining(promises, start, handler) { for(var i=start; i<promises.length; ++i) { markAsHandled(getHandler(promises[i]), handler); } } function markAsHandled(h, handler) { if(h === handler) { return; } var s = h.state(); if(s === 0) { h.visit(h, void 0, h._unreport); } else if(s < 0) { h._unreport(); } } /** * Fulfill-reject competitive race. Return a promise that will settle * to the same state as the earliest input promise to settle. * * WARNING: The ES6 Promise spec requires that race()ing an empty array * must return a promise that is pending forever. This implementation * returns a singleton forever-pending promise, the same singleton that is * returned by Promise.never(), thus can be checked with === * * @param {array} promises array of promises to race * @returns {Promise} if input is non-empty, a promise that will settle * to the same outcome as the earliest input promise to settle. if empty * is empty, returns a promise that will never settle. */ function race(promises) { if(typeof promises !== 'object' || promises === null) { return reject(new TypeError('non-iterable passed to race()')); } // Sigh, race([]) is untestable unless we return *something* // that is recognizable without calling .then() on it. return promises.length === 0 ? never() : promises.length === 1 ? resolve(promises[0]) : runRace(promises); } function runRace(promises) { var resolver = new Pending(); var i, x, h; for(i=0; i<promises.length; ++i) { x = promises[i]; if (x === void 0 && !(i in promises)) { continue; } h = getHandler(x); if(h.state() !== 0) { resolver.become(h); visitRemaining(promises, i+1, h); break; } else { h.visit(resolver, resolver.resolve, resolver.reject); } } return new Promise(Handler, resolver); } // Promise internals // Below this, everything is @private /** * Get an appropriate handler for x, without checking for cycles * @param {*} x * @returns {object} handler */ function getHandler(x) { if(isPromise(x)) { return x._handler.join(); } return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x); } /** * Get a handler for thenable x. * NOTE: You must only call this if maybeThenable(x) == true * @param {object|function|Promise} x * @returns {object} handler */ function getHandlerMaybeThenable(x) { return isPromise(x) ? x._handler.join() : getHandlerUntrusted(x); } /** * Get a handler for potentially untrusted thenable x * @param {*} x * @returns {object} handler */ function getHandlerUntrusted(x) { try { var untrustedThen = x.then; return typeof untrustedThen === 'function' ? new Thenable(untrustedThen, x) : new Fulfilled(x); } catch(e) { return new Rejected(e); } } /** * Handler for a promise that is pending forever * @constructor */ function Handler() {} Handler.prototype.when = Handler.prototype.become = Handler.prototype.notify // deprecated = Handler.prototype.fail = Handler.prototype._unreport = Handler.prototype._report = noop; Handler.prototype._state = 0; Handler.prototype.state = function() { return this._state; }; /** * Recursively collapse handler chain to find the handler * nearest to the fully resolved value. * @returns {object} handler nearest the fully resolved value */ Handler.prototype.join = function() { var h = this; while(h.handler !== void 0) { h = h.handler; } return h; }; Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) { this.when({ resolver: to, receiver: receiver, fulfilled: fulfilled, rejected: rejected, progress: progress }); }; Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) { this.chain(failIfRejected, receiver, fulfilled, rejected, progress); }; Handler.prototype.fold = function(f, z, c, to) { this.when(new Fold(f, z, c, to)); }; /** * Handler that invokes fail() on any handler it becomes * @constructor */ function FailIfRejected() {} inherit(Handler, FailIfRejected); FailIfRejected.prototype.become = function(h) { h.fail(); }; var failIfRejected = new FailIfRejected(); /** * Handler that manages a queue of consumers waiting on a pending promise * @constructor */ function Pending(receiver, inheritedContext) { Promise.createContext(this, inheritedContext); this.consumers = void 0; this.receiver = receiver; this.handler = void 0; this.resolved = false; } inherit(Handler, Pending); Pending.prototype._state = 0; Pending.prototype.resolve = function(x) { this.become(getHandler(x)); }; Pending.prototype.reject = function(x) { if(this.resolved) { return; } this.become(new Rejected(x)); }; Pending.prototype.join = function() { if (!this.resolved) { return this; } var h = this; while (h.handler !== void 0) { h = h.handler; if (h === this) { return this.handler = cycle(); } } return h; }; Pending.prototype.run = function() { var q = this.consumers; var handler = this.handler; this.handler = this.handler.join(); this.consumers = void 0; for (var i = 0; i < q.length; ++i) { handler.when(q[i]); } }; Pending.prototype.become = function(handler) { if(this.resolved) { return; } this.resolved = true; this.handler = handler; if(this.consumers !== void 0) { tasks.enqueue(this); } if(this.context !== void 0) { handler._report(this.context); } }; Pending.prototype.when = function(continuation) { if(this.resolved) { tasks.enqueue(new ContinuationTask(continuation, this.handler)); } else { if(this.consumers === void 0) { this.consumers = [continuation]; } else { this.consumers.push(continuation); } } }; /** * @deprecated */ Pending.prototype.notify = function(x) { if(!this.resolved) { tasks.enqueue(new ProgressTask(x, this)); } }; Pending.prototype.fail = function(context) { var c = typeof context === 'undefined' ? this.context : context; this.resolved && this.handler.join().fail(c); }; Pending.prototype._report = function(context) { this.resolved && this.handler.join()._report(context); }; Pending.prototype._unreport = function() { this.resolved && this.handler.join()._unreport(); }; /** * Wrap another handler and force it into a future stack * @param {object} handler * @constructor */ function Async(handler) { this.handler = handler; } inherit(Handler, Async); Async.prototype.when = function(continuation) { tasks.enqueue(new ContinuationTask(continuation, this)); }; Async.prototype._report = function(context) { this.join()._report(context); }; Async.prototype._unreport = function() { this.join()._unreport(); }; /** * Handler that wraps an untrusted thenable and assimilates it in a future stack * @param {function} then * @param {{then: function}} thenable * @constructor */ function Thenable(then, thenable) { Pending.call(this); tasks.enqueue(new AssimilateTask(then, thenable, this)); } inherit(Pending, Thenable); /** * Handler for a fulfilled promise * @param {*} x fulfillment value * @constructor */ function Fulfilled(x) { Promise.createContext(this); this.value = x; } inherit(Handler, Fulfilled); Fulfilled.prototype._state = 1; Fulfilled.prototype.fold = function(f, z, c, to) { runContinuation3(f, z, this, c, to); }; Fulfilled.prototype.when = function(cont) { runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver); }; var errorId = 0; /** * Handler for a rejected promise * @param {*} x rejection reason * @constructor */ function Rejected(x) { Promise.createContext(this); this.id = ++errorId; this.value = x; this.handled = false; this.reported = false; this._report(); } inherit(Handler, Rejected); Rejected.prototype._state = -1; Rejected.prototype.fold = function(f, z, c, to) { to.become(this); }; Rejected.prototype.when = function(cont) { if(typeof cont.rejected === 'function') { this._unreport(); } runContinuation1(cont.rejected, this, cont.receiver, cont.resolver); }; Rejected.prototype._report = function(context) { tasks.afterQueue(new ReportTask(this, context)); }; Rejected.prototype._unreport = function() { if(this.handled) { return; } this.handled = true; tasks.afterQueue(new UnreportTask(this)); }; Rejected.prototype.fail = function(context) { this.reported = true; emitRejection('unhandledRejection', this); Promise.onFatalRejection(this, context === void 0 ? this.context : context); }; function ReportTask(rejection, context) { this.rejection = rejection; this.context = context; } ReportTask.prototype.run = function() { if(!this.rejection.handled && !this.rejection.reported) { this.rejection.reported = true; emitRejection('unhandledRejection', this.rejection) || Promise.onPotentiallyUnhandledRejection(this.rejection, this.context); } }; function UnreportTask(rejection) { this.rejection = rejection; } UnreportTask.prototype.run = function() { if(this.rejection.reported) { emitRejection('rejectionHandled', this.rejection) || Promise.onPotentiallyUnhandledRejectionHandled(this.rejection); } }; // Unhandled rejection hooks // By default, everything is a noop Promise.createContext = Promise.enterContext = Promise.exitContext = Promise.onPotentiallyUnhandledRejection = Promise.onPotentiallyUnhandledRejectionHandled = Promise.onFatalRejection = noop; // Errors and singletons var foreverPendingHandler = new Handler(); var foreverPendingPromise = new Promise(Handler, foreverPendingHandler); function cycle() { return new Rejected(new TypeError('Promise cycle')); } // Task runners /** * Run a single consumer * @constructor */ function ContinuationTask(continuation, handler) { this.continuation = continuation; this.handler = handler; } ContinuationTask.prototype.run = function() { this.handler.join().when(this.continuation); }; /** * Run a queue of progress handlers * @constructor */ function ProgressTask(value, handler) { this.handler = handler; this.value = value; } ProgressTask.prototype.run = function() { var q = this.handler.consumers; if(q === void 0) { return; } for (var c, i = 0; i < q.length; ++i) { c = q[i]; runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver); } }; /** * Assimilate a thenable, sending it's value to resolver * @param {function} then * @param {object|function} thenable * @param {object} resolver * @constructor */ function AssimilateTask(then, thenable, resolver) { this._then = then; this.thenable = thenable; this.resolver = resolver; } AssimilateTask.prototype.run = function() { var h = this.resolver; tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify); function _resolve(x) { h.resolve(x); } function _reject(x) { h.reject(x); } function _notify(x) { h.notify(x); } }; function tryAssimilate(then, thenable, resolve, reject, notify) { try { then.call(thenable, resolve, reject, notify); } catch (e) { reject(e); } } /** * Fold a handler value with z * @constructor */ function Fold(f, z, c, to) { this.f = f; this.z = z; this.c = c; this.to = to; this.resolver = failIfRejected; this.receiver = this; } Fold.prototype.fulfilled = function(x) { this.f.call(this.c, this.z, x, this.to); }; Fold.prototype.rejected = function(x) { this.to.reject(x); }; Fold.prototype.progress = function(x) { this.to.notify(x); }; // Other helpers /** * @param {*} x * @returns {boolean} true iff x is a trusted Promise */ function isPromise(x) { return x instanceof Promise; } /** * Test just enough to rule out primitives, in order to take faster * paths in some code * @param {*} x * @returns {boolean} false iff x is guaranteed *not* to be a thenable */ function maybeThenable(x) { return (typeof x === 'object' || typeof x === 'function') && x !== null; } function runContinuation1(f, h, receiver, next) { if(typeof f !== 'function') { return next.become(h); } Promise.enterContext(h); tryCatchReject(f, h.value, receiver, next); Promise.exitContext(); } function runContinuation3(f, x, h, receiver, next) { if(typeof f !== 'function') { return next.become(h); } Promise.enterContext(h); tryCatchReject3(f, x, h.value, receiver, next); Promise.exitContext(); } /** * @deprecated */ function runNotify(f, x, h, receiver, next) { if(typeof f !== 'function') { return next.notify(x); } Promise.enterContext(h); tryCatchReturn(f, x, receiver, next); Promise.exitContext(); } function tryCatch2(f, a, b) { try { return f(a, b); } catch(e) { return reject(e); } } /** * Return f.call(thisArg, x), or if it throws return a rejected promise for * the thrown exception */ function tryCatchReject(f, x, thisArg, next) { try { next.become(getHandler(f.call(thisArg, x))); } catch(e) { next.become(new Rejected(e)); } } /** * Same as above, but includes the extra argument parameter. */ function tryCatchReject3(f, x, y, thisArg, next) { try { f.call(thisArg, x, y, next); } catch(e) { next.become(new Rejected(e)); } } /** * @deprecated * Return f.call(thisArg, x), or if it throws, *return* the exception */ function tryCatchReturn(f, x, thisArg, next) { try { next.notify(f.call(thisArg, x)); } catch(e) { next.notify(e); } } function inherit(Parent, Child) { Child.prototype = objectCreate(Parent.prototype); Child.prototype.constructor = Child; } function snd(x, y) { return y; } function noop() {} function initEmitRejection() { /*global process, self, CustomEvent*/ if(typeof process !== 'undefined' && process !== null && typeof process.emit === 'function') { // Returning falsy here means to call the default // onPotentiallyUnhandledRejection API. This is safe even in // browserify since process.emit always returns falsy in browserify: // https://github.com/defunctzombie/node-process/blob/master/browser.js#L40-L46 return function(type, rejection) { return type === 'unhandledRejection' ? process.emit(type, rejection.value, rejection) : process.emit(type, rejection); }; } else if(typeof self !== 'undefined' && typeof CustomEvent === 'function') { return (function(noop, self, CustomEvent) { var hasCustomEvent = false; try { var ev = new CustomEvent('unhandledRejection'); hasCustomEvent = ev instanceof CustomEvent; } catch (e) {} return !hasCustomEvent ? noop : function(type, rejection) { var ev = new CustomEvent(type, { detail: { reason: rejection.value, key: rejection }, bubbles: false, cancelable: true }); return !self.dispatchEvent(ev); }; }(noop, self, CustomEvent)); } return noop; } return Promise; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); }).call(this,require('_process')) },{"_process":1}],177:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return { pending: toPendingState, fulfilled: toFulfilledState, rejected: toRejectedState, inspect: inspect }; function toPendingState() { return { state: 'pending' }; } function toRejectedState(e) { return { state: 'rejected', reason: e }; } function toFulfilledState(x) { return { state: 'fulfilled', value: x }; } function inspect(handler) { var state = handler.state(); return state === 0 ? toPendingState() : state > 0 ? toFulfilledState(handler.value) : toRejectedState(handler.value); } }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],178:[function(require,module,exports){ /** @license MIT License (c) copyright 2012-2013 original author or authors */ /** * poll.js * * Helper that polls until cancelled or for a condition to become true. * * @author Scott Andrews */ (function (define) { 'use strict'; define(function(require) { var when = require('./when'); var attempt = when['try']; var cancelable = require('./cancelable'); /** * Periodically execute the task function on the msec delay. The result of * the task may be verified by watching for a condition to become true. The * returned deferred is cancellable if the polling needs to be cancelled * externally before reaching a resolved state. * * The next vote is scheduled after the results of the current vote are * verified and rejected. * * Polling may be terminated by the verifier returning a truthy value, * invoking cancel() on the returned promise, or the task function returning * a rejected promise. * * Usage: * * var count = 0; * function doSomething() { return count++ } * * // poll until cancelled * var p = poll(doSomething, 1000); * ... * p.cancel(); * * // poll until condition is met * poll(doSomething, 1000, function(result) { return result > 10 }) * .then(function(result) { assert result == 10 }); * * // delay first vote * poll(doSomething, 1000, anyFunc, true); * * @param task {Function} function that is executed after every timeout * @param interval {number|Function} timeout in milliseconds * @param [verifier] {Function} function to evaluate the result of the vote. * May return a {Promise} or a {Boolean}. Rejecting the promise or a * falsey value will schedule the next vote. * @param [delayInitialTask] {boolean} if truthy, the first vote is scheduled * instead of immediate * * @returns {Promise} */ return function poll(task, interval, verifier, delayInitialTask) { var deferred, canceled, reject; canceled = false; deferred = cancelable(when.defer(), function () { canceled = true; }); reject = deferred.reject; verifier = verifier || function () { return false; }; if (typeof interval !== 'function') { interval = (function (interval) { return function () { return when().delay(interval); }; })(interval); } function certify(result) { deferred.resolve(result); } function schedule(result) { attempt(interval).then(vote, reject); if (result !== void 0) { deferred.notify(result); } } function vote() { if (canceled) { return; } when(task(), function (result) { when(verifier(result), function (verification) { return verification ? certify(result) : schedule(result); }, function () { schedule(result); } ); }, reject ); } if (delayInitialTask) { schedule(); } else { // if task() is blocking, vote will also block vote(); } // make the promise cancelable deferred.promise = Object.create(deferred.promise); deferred.promise.cancel = deferred.cancel; return deferred.promise; }; }); })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); }); },{"./cancelable":160,"./when":179}],179:[function(require,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** * Promises/A+ and when() implementation * when is part of the cujoJS family of libraries (http://cujojs.com/) * @author Brian Cavalier * @author John Hann */ (function(define) { 'use strict'; define(function (require) { var timed = require('./lib/decorators/timed'); var array = require('./lib/decorators/array'); var flow = require('./lib/decorators/flow'); var fold = require('./lib/decorators/fold'); var inspect = require('./lib/decorators/inspect'); var generate = require('./lib/decorators/iterate'); var progress = require('./lib/decorators/progress'); var withThis = require('./lib/decorators/with'); var unhandledRejection = require('./lib/decorators/unhandledRejection'); var TimeoutError = require('./lib/TimeoutError'); var Promise = [array, flow, fold, generate, progress, inspect, withThis, timed, unhandledRejection] .reduce(function(Promise, feature) { return feature(Promise); }, require('./lib/Promise')); var apply = require('./lib/apply')(Promise); // Public API when.promise = promise; // Create a pending promise when.resolve = Promise.resolve; // Create a resolved promise when.reject = Promise.reject; // Create a rejected promise when.lift = lift; // lift a function to return promises when['try'] = attempt; // call a function and return a promise when.attempt = attempt; // alias for when.try when.iterate = Promise.iterate; // DEPRECATED (use cujojs/most streams) Generate a stream of promises when.unfold = Promise.unfold; // DEPRECATED (use cujojs/most streams) Generate a stream of promises when.join = join; // Join 2 or more promises when.all = all; // Resolve a list of promises when.settle = settle; // Settle a list of promises when.any = lift(Promise.any); // One-winner race when.some = lift(Promise.some); // Multi-winner race when.race = lift(Promise.race); // First-to-settle race when.map = map; // Array.map() for promises when.filter = filter; // Array.filter() for promises when.reduce = lift(Promise.reduce); // Array.reduce() for promises when.reduceRight = lift(Promise.reduceRight); // Array.reduceRight() for promises when.isPromiseLike = isPromiseLike; // Is something promise-like, aka thenable when.Promise = Promise; // Promise constructor when.defer = defer; // Create a {promise, resolve, reject} tuple // Error types when.TimeoutError = TimeoutError; /** * Get a trusted promise for x, or by transforming x with onFulfilled * * @param {*} x * @param {function?} onFulfilled callback to be called when x is * successfully fulfilled. If promiseOrValue is an immediate value, callback * will be invoked immediately. * @param {function?} onRejected callback to be called when x is * rejected. * @param {function?} onProgress callback to be called when progress updates * are issued for x. @deprecated * @returns {Promise} a new promise that will fulfill with the return * value of callback or errback or the completion value of promiseOrValue if * callback and/or errback is not supplied. */ function when(x, onFulfilled, onRejected, onProgress) { var p = Promise.resolve(x); if (arguments.length < 2) { return p; } return p.then(onFulfilled, onRejected, onProgress); } /** * Creates a new promise whose fate is determined by resolver. * @param {function} resolver function(resolve, reject, notify) * @returns {Promise} promise whose fate is determine by resolver */ function promise(resolver) { return new Promise(resolver); } /** * Lift the supplied function, creating a version of f that returns * promises, and accepts promises as arguments. * @param {function} f * @returns {Function} version of f that returns promises */ function lift(f) { return function() { for(var i=0, l=arguments.length, a=new Array(l); i<l; ++i) { a[i] = arguments[i]; } return apply(f, this, a); }; } /** * Call f in a future turn, with the supplied args, and return a promise * for the result. * @param {function} f * @returns {Promise} */ function attempt(f /*, args... */) { /*jshint validthis:true */ for(var i=0, l=arguments.length-1, a=new Array(l); i<l; ++i) { a[i] = arguments[i+1]; } return apply(f, this, a); } /** * Creates a {promise, resolver} pair, either or both of which * may be given out safely to consumers. * @return {{promise: Promise, resolve: function, reject: function, notify: function}} */ function defer() { return new Deferred(); } function Deferred() { var p = Promise._defer(); function resolve(x) { p._handler.resolve(x); } function reject(x) { p._handler.reject(x); } function notify(x) { p._handler.notify(x); } this.promise = p; this.resolve = resolve; this.reject = reject; this.notify = notify; this.resolver = { resolve: resolve, reject: reject, notify: notify }; } /** * Determines if x is promise-like, i.e. a thenable object * NOTE: Will return true for *any thenable object*, and isn't truly * safe, since it may attempt to access the `then` property of x (i.e. * clever/malicious getters may do weird things) * @param {*} x anything * @returns {boolean} true if x is promise-like */ function isPromiseLike(x) { return x && typeof x.then === 'function'; } /** * Return a promise that will resolve only once all the supplied arguments * have resolved. The resolution value of the returned promise will be an array * containing the resolution values of each of the arguments. * @param {...*} arguments may be a mix of promises and values * @returns {Promise} */ function join(/* ...promises */) { return Promise.all(arguments); } /** * Return a promise that will fulfill once all input promises have * fulfilled, or reject when any one input promise rejects. * @param {array|Promise} promises array (or promise for an array) of promises * @returns {Promise} */ function all(promises) { return when(promises, Promise.all); } /** * Return a promise that will always fulfill with an array containing * the outcome states of all input promises. The returned promise * will only reject if `promises` itself is a rejected promise. * @param {array|Promise} promises array (or promise for an array) of promises * @returns {Promise} promise for array of settled state descriptors */ function settle(promises) { return when(promises, Promise.settle); } /** * Promise-aware array map function, similar to `Array.prototype.map()`, * but input array may contain promises or values. * @param {Array|Promise} promises array of anything, may contain promises and values * @param {function(x:*, index:Number):*} mapFunc map function which may * return a promise or value * @returns {Promise} promise that will fulfill with an array of mapped values * or reject if any input promise rejects. */ function map(promises, mapFunc) { return when(promises, function(promises) { return Promise.map(promises, mapFunc); }); } /** * Filter the provided array of promises using the provided predicate. Input may * contain promises and values * @param {Array|Promise} promises array of promises and values * @param {function(x:*, index:Number):boolean} predicate filtering predicate. * Must return truthy (or promise for truthy) for items to retain. * @returns {Promise} promise that will fulfill with an array containing all items * for which predicate returned truthy. */ function filter(promises, predicate) { return when(promises, function(promises) { return Promise.filter(promises, predicate); }); } return when; }); })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); }); },{"./lib/Promise":161,"./lib/TimeoutError":163,"./lib/apply":164,"./lib/decorators/array":165,"./lib/decorators/flow":166,"./lib/decorators/fold":167,"./lib/decorators/inspect":168,"./lib/decorators/iterate":169,"./lib/decorators/progress":170,"./lib/decorators/timed":171,"./lib/decorators/unhandledRejection":172,"./lib/decorators/with":173}],180:[function(require,module,exports){ var React = require('react'); var request = require('superagent'); var poll = require('when/poll'); var Clip = React.createClass({displayName: "Clip", render: function() { return ( React.createElement("div", {class: "clip"}, React.createElement("h2", null, this.props.title), React.createElement("video", {controls: true}, React.createElement("source", {src: this.props.uri}) ) ) ); } }); var MythTvStatus = React.createClass({displayName: "MythTvStatus", getInitialState: function() { return { title: '', subtitle: '' } }, componentDidMount: function(e) { request .get('/api/mythtv/status') .set('Accept', 'application/json') .end(function(err, result) { if(err==null) { console.log(result); this.setState(result); } else { console.log(err); } }); }, render: function() { return ( React.createElement("div", {className: "mythtv-status"}, React.createElement("div", {className: "mythtv-title"}, React.createElement("h2", {className: "title"}, this.state.title ) ), React.createElement("div", {className: "mythtv-subtitle"}, React.createElement("h2", {className: "title"}, this.state.subtitle ) ) ) ); } }); var ClipMakerForm = React.createClass({displayName: "ClipMakerForm", pollClipStatus: function(id) { var pollingIntervalId; pollingIntervalId = setInterval(function() { request .get('/api/mythtv/clip/' + id) .end(function(err, result) { if(err==null) { var clipData = JSON.parse(result.text); console.log(clipData); var title = clipData.title; var uri = clipData.uri; clearInterval(pollingIntervalId); React.render( React.createElement(Clip, {title: title, uri: uri}), document.getElementById("clip") ); } }) }, 5000); }, handleSubmit: function(e) { e.preventDefault(); var duration = e.target.duration.value; var self = this; request .post('/api/mythtv/clip') .send({duration: duration}) .set('Accept', 'application/json') .end(function(err, result) { if(err==null) { var clipData = JSON.parse(result.text); self.pollClipStatus(clipData.id); } else { console.log(err); } }); }, render: function() { console.log("rendering"); return ( React.createElement("div", null, React.createElement("form", {onSubmit: this.handleSubmit}, React.createElement("input", {type: "text", name: "duration"}), React.createElement("input", {type: "submit"}) ) ) ); } }); React.render( React.createElement(MythTvStatus, null), document.getElementById("mythtv-ffmpeg-tumblr-clip") ); },{"react":156,"superagent":157,"when/poll":178}]},{},[180]);
davidrice/mythtv-ffmpeg-tumblr-clip
public/build/mythtv-ffmpeg-tumblr-clip.js
JavaScript
apache-2.0
719,858
'use strict'; var path = require('path'); var conf = require('./gulp/conf'); var _ = require('lodash'); var wiredep = require('wiredep'); var pathSrcHtml = [ path.join(conf.paths.src, '/**/*.html') ]; function listFiles() { var wiredepOptions = _.extend({}, conf.wiredep, { dependencies: true, devDependencies: true }); var patterns = wiredep(wiredepOptions).js .concat([ path.join(conf.paths.src, '/app/**/*.module.js'), path.join(conf.paths.src, '/app/**/*.js'), path.join(conf.paths.src, '/**/*.spec.js'), path.join(conf.paths.src, '/**/*.mock.js'), ]) .concat(pathSrcHtml); var files = patterns.map(function(pattern) { return { pattern: pattern }; }); files.push({ pattern: path.join(conf.paths.src, '/assets/**/*'), included: false, served: true, watched: false }); return files; } module.exports = function(config) { var configuration = { files: listFiles(), singleRun: true, autoWatch: false, ngHtml2JsPreprocessor: { stripPrefix: conf.paths.src + '/', moduleName: 'vector' }, logLevel: 'WARN', frameworks: ['phantomjs-shim', 'jasmine', 'angular-filesort'], angularFilesort: { whitelist: [path.join(conf.paths.src, '/**/!(*.html|*.spec|*.mock).js')] }, browsers : ['PhantomJS'], plugins : [ 'karma-phantomjs-launcher', 'karma-angular-filesort', 'karma-phantomjs-shim', 'karma-coverage', 'karma-jasmine', 'karma-ng-html2js-preprocessor' ], coverageReporter: { type : 'html', dir : 'coverage/' }, reporters: ['progress'], proxies: { '/assets/': path.join('/base/', conf.paths.src, '/assets/') } }; // This is the default preprocessors configuration for a usage with Karma cli // The coverage preprocessor is added in gulp/unit-test.js only for single tests // It was not possible to do it there because karma doesn't let us now if we are // running a single test or not configuration.preprocessors = {}; pathSrcHtml.forEach(function(path) { configuration.preprocessors[path] = ['ng-html2js']; }); // This block is needed to execute Chrome on Travis // If you ever plan to use Chrome and Travis, you can keep it // If not, you can safely remove it // https://github.com/karma-runner/karma/issues/1144#issuecomment-53633076 if(configuration.browsers[0] === 'Chrome' && process.env.TRAVIS) { configuration.customLaunchers = { 'chrome-travis-ci': { base: 'Chrome', flags: ['--no-sandbox'] } }; configuration.browsers = ['chrome-travis-ci']; } config.set(configuration); };
brendangregg/vector
karma.conf.js
JavaScript
apache-2.0
2,704
var utils = require('../../utils').common; var _ = require('underscore'); /** Adds pagerduty field to devops if pagerduty related api is present * @param {string} devops_filename the filename of the devopsjson file relative to the fixtures directory * @param {fn} request_maker A function that takes two arguments, options and on_end_cb: * options an options dict for making an XHR, such as would be used by http.request * on_end_cb a callback that gets called with the XHR response data */ module.exports = { name: 'pager_duty', poll_interval: 10 * 60 * 1000, related_apis: ['pager_duty'], priority: 1, worker: function(payload) { var api_config = payload.get_config(); // PagerDuty requires the date range for all requests. var now, until, options; now = new Date(); until = new Date(); until.setDate(now.getDate() + 4); now = now.toISOString().split('T')[0]; until = until.toISOString().split('T')[0]; options = { port: api_config.port, host: api_config.subdomain + '.pagerduty.com', path: ['/api/v1/schedules/', api_config.schedule_id, '/entries?since=', now, '&until=', until].join(''), method: 'GET', auth: api_config.auth, headers: { 'Content-Type': 'application/json' } }; utils.request_maker( options, function(err, data) { var parsed_data; if(err){ payload.set_data(err); return; } try{ parsed_data = JSON.parse(data.data); } catch (e){ payload.set_data(e); return; } payload.set_data(null, parsed_data); } ); } };
racker/gutsy
lib/web/plugins/pager_duty.js
JavaScript
apache-2.0
1,738
// // Autogenerated by Thrift // // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING // YahooWoeType = { 'UNKNOWN' : 0 ,'TOWN' : 7 ,'ADMIN1' : 8 ,'ADMIN2' : 9 ,'ADMIN3' : 10 ,'POSTAL_CODE' : 11 ,'COUNTRY' : 12 ,'ISLAND' : 13 ,'AIRPORT' : 14 ,'DRAINAGE' : 15 ,'PARK' : 16 ,'POI' : 20 ,'SUBURB' : 22 ,'SPORT' : 23 ,'COLLOQUIAL' : 24 ,'ZONE' : 25 ,'HISTORICAL_STATE' : 26 ,'HISTORICAL_COUNTY' : 27 ,'CONTINENT' : 29 ,'TIMEZONE' : 31 ,'HISTORICAL_TOWN' : 35 ,'STREET' : 100 } FeatureNameFlags = { 'PREFERRED' : 1 ,'ABBREVIATION' : 2 ,'DEACCENT' : 4 ,'ALIAS' : 8 ,'LOCAL_LANG' : 16 ,'ALT_NAME' : 32 ,'COLLOQUIAL' : 64 ,'SHORT_NAME' : 128 ,'NEVER_DISPLAY' : 256 ,'LOW_QUALITY' : 512 ,'HISTORIC' : 1024 } GeocodeRelationType = { 'PARENT' : 1 ,'HIERARCHY' : 2 } NeighborhoodType = { 'MACRO' : 2 ,'NEIGHBORHOOD' : 3 ,'SUB' : 4 } ResponseIncludes = { 'EVERYTHING' : 0 ,'PARENTS' : 1 ,'ALL_NAMES' : 2 ,'PARENT_ALL_NAMES' : 3 ,'WKB_GEOMETRY' : 4 ,'WKT_GEOMETRY' : 5 ,'REVGEO_COVERAGE' : 6 ,'DISPLAY_NAME' : 7 ,'WKB_GEOMETRY_SIMPLIFIED' : 8 ,'WKT_GEOMETRY_SIMPLIFIED' : 9 } GeocodePoint = function(args){ this.lat = 0.0 this.lng = 0.0 if( args != null ){if (null != args.lat) this.lat = args.lat if (null != args.lng) this.lng = args.lng }} GeocodePoint.prototype = {} GeocodePoint.prototype.read = function(input){ var ret = input.readStructBegin() while (1) { var ret = input.readFieldBegin() var fname = ret.fname var ftype = ret.ftype var fid = ret.fid if (ftype == Thrift.Type.STOP) break switch(fid) { case 1: if (ftype == Thrift.Type.DOUBLE) { var rtmp = input.readDouble() this.lat = rtmp.value } else { input.skip(ftype) } break case 2: if (ftype == Thrift.Type.DOUBLE) { var rtmp = input.readDouble() this.lng = rtmp.value } else { input.skip(ftype) } break default: input.skip(ftype) } input.readFieldEnd() } input.readStructEnd() return } GeocodePoint.prototype.write = function(output){ output.writeStructBegin('GeocodePoint') if (null != this.lat) { output.writeFieldBegin('lat', Thrift.Type.DOUBLE, 1) output.writeDouble(this.lat) output.writeFieldEnd() } if (null != this.lng) { output.writeFieldBegin('lng', Thrift.Type.DOUBLE, 2) output.writeDouble(this.lng) output.writeFieldEnd() } output.writeFieldStop() output.writeStructEnd() return } GeocodeBoundingBox = function(args){ this.ne = new GeocodePoint() this.sw = new GeocodePoint() if( args != null ){if (null != args.ne) this.ne = args.ne if (null != args.sw) this.sw = args.sw }} GeocodeBoundingBox.prototype = {} GeocodeBoundingBox.prototype.read = function(input){ var ret = input.readStructBegin() while (1) { var ret = input.readFieldBegin() var fname = ret.fname var ftype = ret.ftype var fid = ret.fid if (ftype == Thrift.Type.STOP) break switch(fid) { case 1: if (ftype == Thrift.Type.STRUCT) { this.ne = new GeocodePoint() this.ne.read(input) } else { input.skip(ftype) } break case 2: if (ftype == Thrift.Type.STRUCT) { this.sw = new GeocodePoint() this.sw.read(input) } else { input.skip(ftype) } break default: input.skip(ftype) } input.readFieldEnd() } input.readStructEnd() return } GeocodeBoundingBox.prototype.write = function(output){ output.writeStructBegin('GeocodeBoundingBox') if (null != this.ne) { output.writeFieldBegin('ne', Thrift.Type.STRUCT, 1) this.ne.write(output) output.writeFieldEnd() } if (null != this.sw) { output.writeFieldBegin('sw', Thrift.Type.STRUCT, 2) this.sw.write(output) output.writeFieldEnd() } output.writeFieldStop() output.writeStructEnd() return } FeatureId = function(args){ this.source = '' this.id = '' if( args != null ){if (null != args.source) this.source = args.source if (null != args.id) this.id = args.id }} FeatureId.prototype = {} FeatureId.prototype.read = function(input){ var ret = input.readStructBegin() while (1) { var ret = input.readFieldBegin() var fname = ret.fname var ftype = ret.ftype var fid = ret.fid if (ftype == Thrift.Type.STOP) break switch(fid) { case 1:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.source = rtmp.value } else { input.skip(ftype) } break case 2:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.id = rtmp.value } else { input.skip(ftype) } break default: input.skip(ftype) } input.readFieldEnd() } input.readStructEnd() return } FeatureId.prototype.write = function(output){ output.writeStructBegin('FeatureId') if (null != this.source) { output.writeFieldBegin('source', Thrift.Type.STRING, 1) output.writeString(this.source) output.writeFieldEnd() } if (null != this.id) { output.writeFieldBegin('id', Thrift.Type.STRING, 2) output.writeString(this.id) output.writeFieldEnd() } output.writeFieldStop() output.writeStructEnd() return } FeatureName = function(args){ this.name = '' this.lang = '' this.flags = [] this.highlightedName = '' if( args != null ){if (null != args.name) this.name = args.name if (null != args.lang) this.lang = args.lang if (null != args.flags) this.flags = args.flags if (null != args.highlightedName) this.highlightedName = args.highlightedName }} FeatureName.prototype = {} FeatureName.prototype.read = function(input){ var ret = input.readStructBegin() while (1) { var ret = input.readFieldBegin() var fname = ret.fname var ftype = ret.ftype var fid = ret.fid if (ftype == Thrift.Type.STOP) break switch(fid) { case 1:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.name = rtmp.value } else { input.skip(ftype) } break case 2:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.lang = rtmp.value } else { input.skip(ftype) } break case 3:if (ftype == Thrift.Type.LIST) { { var _size0 = 0 var rtmp3 this.flags = [] var _etype3 = 0 rtmp3 = input.readListBegin() _etype3 = rtmp3.etype _size0 = rtmp3.size for (var _i4 = 0; _i4 < _size0; ++_i4) { var elem5 = null var rtmp = input.readI32() elem5 = rtmp.value this.flags.push(elem5) } input.readListEnd() } } else { input.skip(ftype) } break case 4:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.highlightedName = rtmp.value } else { input.skip(ftype) } break default: input.skip(ftype) } input.readFieldEnd() } input.readStructEnd() return } FeatureName.prototype.write = function(output){ output.writeStructBegin('FeatureName') if (null != this.name) { output.writeFieldBegin('name', Thrift.Type.STRING, 1) output.writeString(this.name) output.writeFieldEnd() } if (null != this.lang) { output.writeFieldBegin('lang', Thrift.Type.STRING, 2) output.writeString(this.lang) output.writeFieldEnd() } if (null != this.flags) { output.writeFieldBegin('flags', Thrift.Type.LIST, 3) { output.writeListBegin(Thrift.Type.I32, this.flags.length) { for(var iter6 in this.flags) { iter6=this.flags[iter6] output.writeI32(iter6) } } output.writeListEnd() } output.writeFieldEnd() } if (null != this.highlightedName) { output.writeFieldBegin('highlightedName', Thrift.Type.STRING, 4) output.writeString(this.highlightedName) output.writeFieldEnd() } output.writeFieldStop() output.writeStructEnd() return } FeatureGeometry = function(args){ this.center = new GeocodePoint() this.bounds = new GeocodeBoundingBox() this.wkbGeometry = '' this.wktGeometry = '' this.wkbGeometrySimplified = '' this.wktGeometrySimplified = '' this.displayBounds = new GeocodeBoundingBox() if( args != null ){if (null != args.center) this.center = args.center if (null != args.bounds) this.bounds = args.bounds if (null != args.wkbGeometry) this.wkbGeometry = args.wkbGeometry if (null != args.wktGeometry) this.wktGeometry = args.wktGeometry if (null != args.wkbGeometrySimplified) this.wkbGeometrySimplified = args.wkbGeometrySimplified if (null != args.wktGeometrySimplified) this.wktGeometrySimplified = args.wktGeometrySimplified if (null != args.displayBounds) this.displayBounds = args.displayBounds }} FeatureGeometry.prototype = {} FeatureGeometry.prototype.read = function(input){ var ret = input.readStructBegin() while (1) { var ret = input.readFieldBegin() var fname = ret.fname var ftype = ret.ftype var fid = ret.fid if (ftype == Thrift.Type.STOP) break switch(fid) { case 1:if (ftype == Thrift.Type.STRUCT) { this.center = new GeocodePoint() this.center.read(input) } else { input.skip(ftype) } break case 2:if (ftype == Thrift.Type.STRUCT) { this.bounds = new GeocodeBoundingBox() this.bounds.read(input) } else { input.skip(ftype) } break case 3:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.wkbGeometry = rtmp.value } else { input.skip(ftype) } break case 4:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.wktGeometry = rtmp.value } else { input.skip(ftype) } break case 5:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.wkbGeometrySimplified = rtmp.value } else { input.skip(ftype) } break case 6:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.wktGeometrySimplified = rtmp.value } else { input.skip(ftype) } break case 7:if (ftype == Thrift.Type.STRUCT) { this.displayBounds = new GeocodeBoundingBox() this.displayBounds.read(input) } else { input.skip(ftype) } break default: input.skip(ftype) } input.readFieldEnd() } input.readStructEnd() return } FeatureGeometry.prototype.write = function(output){ output.writeStructBegin('FeatureGeometry') if (null != this.center) { output.writeFieldBegin('center', Thrift.Type.STRUCT, 1) this.center.write(output) output.writeFieldEnd() } if (null != this.bounds) { output.writeFieldBegin('bounds', Thrift.Type.STRUCT, 2) this.bounds.write(output) output.writeFieldEnd() } if (null != this.wkbGeometry) { output.writeFieldBegin('wkbGeometry', Thrift.Type.STRING, 3) output.writeString(this.wkbGeometry) output.writeFieldEnd() } if (null != this.wktGeometry) { output.writeFieldBegin('wktGeometry', Thrift.Type.STRING, 4) output.writeString(this.wktGeometry) output.writeFieldEnd() } if (null != this.wkbGeometrySimplified) { output.writeFieldBegin('wkbGeometrySimplified', Thrift.Type.STRING, 5) output.writeString(this.wkbGeometrySimplified) output.writeFieldEnd() } if (null != this.wktGeometrySimplified) { output.writeFieldBegin('wktGeometrySimplified', Thrift.Type.STRING, 6) output.writeString(this.wktGeometrySimplified) output.writeFieldEnd() } if (null != this.displayBounds) { output.writeFieldBegin('displayBounds', Thrift.Type.STRUCT, 7) this.displayBounds.write(output) output.writeFieldEnd() } output.writeFieldStop() output.writeStructEnd() return } GeocodeRelation = function(args){ this.relationType = 0 this.relatedId = '' if( args != null ){if (null != args.relationType) this.relationType = args.relationType if (null != args.relatedId) this.relatedId = args.relatedId }} GeocodeRelation.prototype = {} GeocodeRelation.prototype.read = function(input){ var ret = input.readStructBegin() while (1) { var ret = input.readFieldBegin() var fname = ret.fname var ftype = ret.ftype var fid = ret.fid if (ftype == Thrift.Type.STOP) break switch(fid) { case 1:if (ftype == Thrift.Type.I32) { var rtmp = input.readI32() this.relationType = rtmp.value } else { input.skip(ftype) } break case 2:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.relatedId = rtmp.value } else { input.skip(ftype) } break default: input.skip(ftype) } input.readFieldEnd() } input.readStructEnd() return } GeocodeRelation.prototype.write = function(output){ output.writeStructBegin('GeocodeRelation') if (null != this.relationType) { output.writeFieldBegin('relationType', Thrift.Type.I32, 1) output.writeI32(this.relationType) output.writeFieldEnd() } if (null != this.relatedId) { output.writeFieldBegin('relatedId', Thrift.Type.STRING, 2) output.writeString(this.relatedId) output.writeFieldEnd() } output.writeFieldStop() output.writeStructEnd() return } GeocodeFeatureAttributes = function(args){ this.adm0cap = false this.adm1cap = false this.scalerank = 20 this.labelrank = 0 this.natscale = 0 this.population = 0 this.sociallyRelevant = false this.neighborhoodType = 0 if( args != null ){if (null != args.adm0cap) this.adm0cap = args.adm0cap if (null != args.adm1cap) this.adm1cap = args.adm1cap if (null != args.scalerank) this.scalerank = args.scalerank if (null != args.labelrank) this.labelrank = args.labelrank if (null != args.natscale) this.natscale = args.natscale if (null != args.population) this.population = args.population if (null != args.sociallyRelevant) this.sociallyRelevant = args.sociallyRelevant if (null != args.neighborhoodType) this.neighborhoodType = args.neighborhoodType }} GeocodeFeatureAttributes.prototype = {} GeocodeFeatureAttributes.prototype.read = function(input){ var ret = input.readStructBegin() while (1) { var ret = input.readFieldBegin() var fname = ret.fname var ftype = ret.ftype var fid = ret.fid if (ftype == Thrift.Type.STOP) break switch(fid) { case 1:if (ftype == Thrift.Type.BOOL) { var rtmp = input.readBool() this.adm0cap = rtmp.value } else { input.skip(ftype) } break case 2:if (ftype == Thrift.Type.BOOL) { var rtmp = input.readBool() this.adm1cap = rtmp.value } else { input.skip(ftype) } break case 3:if (ftype == Thrift.Type.I32) { var rtmp = input.readI32() this.scalerank = rtmp.value } else { input.skip(ftype) } break case 4:if (ftype == Thrift.Type.I32) { var rtmp = input.readI32() this.labelrank = rtmp.value } else { input.skip(ftype) } break case 5:if (ftype == Thrift.Type.I32) { var rtmp = input.readI32() this.natscale = rtmp.value } else { input.skip(ftype) } break case 6:if (ftype == Thrift.Type.I32) { var rtmp = input.readI32() this.population = rtmp.value } else { input.skip(ftype) } break case 7:if (ftype == Thrift.Type.BOOL) { var rtmp = input.readBool() this.sociallyRelevant = rtmp.value } else { input.skip(ftype) } break case 8:if (ftype == Thrift.Type.I32) { var rtmp = input.readI32() this.neighborhoodType = rtmp.value } else { input.skip(ftype) } break default: input.skip(ftype) } input.readFieldEnd() } input.readStructEnd() return } GeocodeFeatureAttributes.prototype.write = function(output){ output.writeStructBegin('GeocodeFeatureAttributes') if (null != this.adm0cap) { output.writeFieldBegin('adm0cap', Thrift.Type.BOOL, 1) output.writeBool(this.adm0cap) output.writeFieldEnd() } if (null != this.adm1cap) { output.writeFieldBegin('adm1cap', Thrift.Type.BOOL, 2) output.writeBool(this.adm1cap) output.writeFieldEnd() } if (null != this.scalerank) { output.writeFieldBegin('scalerank', Thrift.Type.I32, 3) output.writeI32(this.scalerank) output.writeFieldEnd() } if (null != this.labelrank) { output.writeFieldBegin('labelrank', Thrift.Type.I32, 4) output.writeI32(this.labelrank) output.writeFieldEnd() } if (null != this.natscale) { output.writeFieldBegin('natscale', Thrift.Type.I32, 5) output.writeI32(this.natscale) output.writeFieldEnd() } if (null != this.population) { output.writeFieldBegin('population', Thrift.Type.I32, 6) output.writeI32(this.population) output.writeFieldEnd() } if (null != this.sociallyRelevant) { output.writeFieldBegin('sociallyRelevant', Thrift.Type.BOOL, 7) output.writeBool(this.sociallyRelevant) output.writeFieldEnd() } if (null != this.neighborhoodType) { output.writeFieldBegin('neighborhoodType', Thrift.Type.I32, 8) output.writeI32(this.neighborhoodType) output.writeFieldEnd() } output.writeFieldStop() output.writeStructEnd() return } ScoringFeatures = function(args){ this.population = 0 this.boost = 0 this.parentIds = [] this.canGeocode = true this.hasPoly = false this.DEPRECATED_parents = [] if( args != null ){if (null != args.population) this.population = args.population if (null != args.boost) this.boost = args.boost if (null != args.parentIds) this.parentIds = args.parentIds if (null != args.canGeocode) this.canGeocode = args.canGeocode if (null != args.hasPoly) this.hasPoly = args.hasPoly if (null != args.DEPRECATED_parents) this.DEPRECATED_parents = args.DEPRECATED_parents }} ScoringFeatures.prototype = {} ScoringFeatures.prototype.read = function(input){ var ret = input.readStructBegin() while (1) { var ret = input.readFieldBegin() var fname = ret.fname var ftype = ret.ftype var fid = ret.fid if (ftype == Thrift.Type.STOP) break switch(fid) { case 1:if (ftype == Thrift.Type.I32) { var rtmp = input.readI32() this.population = rtmp.value } else { input.skip(ftype) } break case 2:if (ftype == Thrift.Type.I32) { var rtmp = input.readI32() this.boost = rtmp.value } else { input.skip(ftype) } break case 6:if (ftype == Thrift.Type.LIST) { { var _size7 = 0 var rtmp3 this.parentIds = [] var _etype10 = 0 rtmp3 = input.readListBegin() _etype10 = rtmp3.etype _size7 = rtmp3.size for (var _i11 = 0; _i11 < _size7; ++_i11) { var elem12 = null var rtmp = input.readI64() elem12 = rtmp.value this.parentIds.push(elem12) } input.readListEnd() } } else { input.skip(ftype) } break case 5:if (ftype == Thrift.Type.BOOL) { var rtmp = input.readBool() this.canGeocode = rtmp.value } else { input.skip(ftype) } break case 7:if (ftype == Thrift.Type.BOOL) { var rtmp = input.readBool() this.hasPoly = rtmp.value } else { input.skip(ftype) } break case 3:if (ftype == Thrift.Type.LIST) { { var _size13 = 0 var rtmp3 this.DEPRECATED_parents = [] var _etype16 = 0 rtmp3 = input.readListBegin() _etype16 = rtmp3.etype _size13 = rtmp3.size for (var _i17 = 0; _i17 < _size13; ++_i17) { var elem18 = null var rtmp = input.readString() elem18 = rtmp.value this.DEPRECATED_parents.push(elem18) } input.readListEnd() } } else { input.skip(ftype) } break default: input.skip(ftype) } input.readFieldEnd() } input.readStructEnd() return } ScoringFeatures.prototype.write = function(output){ output.writeStructBegin('ScoringFeatures') if (null != this.population) { output.writeFieldBegin('population', Thrift.Type.I32, 1) output.writeI32(this.population) output.writeFieldEnd() } if (null != this.boost) { output.writeFieldBegin('boost', Thrift.Type.I32, 2) output.writeI32(this.boost) output.writeFieldEnd() } if (null != this.parentIds) { output.writeFieldBegin('parentIds', Thrift.Type.LIST, 6) { output.writeListBegin(Thrift.Type.I64, this.parentIds.length) { for(var iter19 in this.parentIds) { iter19=this.parentIds[iter19] output.writeI64(iter19) } } output.writeListEnd() } output.writeFieldEnd() } if (null != this.canGeocode) { output.writeFieldBegin('canGeocode', Thrift.Type.BOOL, 5) output.writeBool(this.canGeocode) output.writeFieldEnd() } if (null != this.hasPoly) { output.writeFieldBegin('hasPoly', Thrift.Type.BOOL, 7) output.writeBool(this.hasPoly) output.writeFieldEnd() } if (null != this.DEPRECATED_parents) { output.writeFieldBegin('DEPRECATED_parents', Thrift.Type.LIST, 3) { output.writeListBegin(Thrift.Type.STRING, this.DEPRECATED_parents.length) { for(var iter20 in this.DEPRECATED_parents) { iter20=this.DEPRECATED_parents[iter20] output.writeString(iter20) } } output.writeListEnd() } output.writeFieldEnd() } output.writeFieldStop() output.writeStructEnd() return } GeocodeFeature = function(args){ this.cc = '' this.geometry = new FeatureGeometry() this.name = '' this.displayName = '' this.woeType = 0 this.ids = [] this.names = [] this.attribution = [] this.timezones = [] this.highlightedName = '' this.matchedName = '' this.slug = '' this.id = '' this.attributes = new GeocodeFeatureAttributes() this.longId = 0 this.longIds = [] if( args != null ){if (null != args.cc) this.cc = args.cc if (null != args.geometry) this.geometry = args.geometry if (null != args.name) this.name = args.name if (null != args.displayName) this.displayName = args.displayName if (null != args.woeType) this.woeType = args.woeType if (null != args.ids) this.ids = args.ids if (null != args.names) this.names = args.names if (null != args.attribution) this.attribution = args.attribution if (null != args.timezones) this.timezones = args.timezones if (null != args.highlightedName) this.highlightedName = args.highlightedName if (null != args.matchedName) this.matchedName = args.matchedName if (null != args.slug) this.slug = args.slug if (null != args.id) this.id = args.id if (null != args.attributes) this.attributes = args.attributes if (null != args.longId) this.longId = args.longId if (null != args.longIds) this.longIds = args.longIds }} GeocodeFeature.prototype = {} GeocodeFeature.prototype.read = function(input){ var ret = input.readStructBegin() while (1) { var ret = input.readFieldBegin() var fname = ret.fname var ftype = ret.ftype var fid = ret.fid if (ftype == Thrift.Type.STOP) break switch(fid) { case 1:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.cc = rtmp.value } else { input.skip(ftype) } break case 2:if (ftype == Thrift.Type.STRUCT) { this.geometry = new FeatureGeometry() this.geometry.read(input) } else { input.skip(ftype) } break case 3:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.name = rtmp.value } else { input.skip(ftype) } break case 4:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.displayName = rtmp.value } else { input.skip(ftype) } break case 5:if (ftype == Thrift.Type.I32) { var rtmp = input.readI32() this.woeType = rtmp.value } else { input.skip(ftype) } break case 6:if (ftype == Thrift.Type.LIST) { { var _size21 = 0 var rtmp3 this.ids = [] var _etype24 = 0 rtmp3 = input.readListBegin() _etype24 = rtmp3.etype _size21 = rtmp3.size for (var _i25 = 0; _i25 < _size21; ++_i25) { var elem26 = null elem26 = new FeatureId() elem26.read(input) this.ids.push(elem26) } input.readListEnd() } } else { input.skip(ftype) } break case 7:if (ftype == Thrift.Type.LIST) { { var _size27 = 0 var rtmp3 this.names = [] var _etype30 = 0 rtmp3 = input.readListBegin() _etype30 = rtmp3.etype _size27 = rtmp3.size for (var _i31 = 0; _i31 < _size27; ++_i31) { var elem32 = null elem32 = new FeatureName() elem32.read(input) this.names.push(elem32) } input.readListEnd() } } else { input.skip(ftype) } break case 8:if (ftype == Thrift.Type.LIST) { { var _size33 = 0 var rtmp3 this.attribution = [] var _etype36 = 0 rtmp3 = input.readListBegin() _etype36 = rtmp3.etype _size33 = rtmp3.size for (var _i37 = 0; _i37 < _size33; ++_i37) { var elem38 = null var rtmp = input.readString() elem38 = rtmp.value this.attribution.push(elem38) } input.readListEnd() } } else { input.skip(ftype) } break case 9:if (ftype == Thrift.Type.LIST) { { var _size39 = 0 var rtmp3 this.timezones = [] var _etype42 = 0 rtmp3 = input.readListBegin() _etype42 = rtmp3.etype _size39 = rtmp3.size for (var _i43 = 0; _i43 < _size39; ++_i43) { var elem44 = null var rtmp = input.readString() elem44 = rtmp.value this.timezones.push(elem44) } input.readListEnd() } } else { input.skip(ftype) } break case 11:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.highlightedName = rtmp.value } else { input.skip(ftype) } break case 12:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.matchedName = rtmp.value } else { input.skip(ftype) } break case 13:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.slug = rtmp.value } else { input.skip(ftype) } break case 14:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.id = rtmp.value } else { input.skip(ftype) } break case 15:if (ftype == Thrift.Type.STRUCT) { this.attributes = new GeocodeFeatureAttributes() this.attributes.read(input) } else { input.skip(ftype) } break case 16:if (ftype == Thrift.Type.I64) { var rtmp = input.readI64() this.longId = rtmp.value } else { input.skip(ftype) } break case 17:if (ftype == Thrift.Type.LIST) { { var _size45 = 0 var rtmp3 this.longIds = [] var _etype48 = 0 rtmp3 = input.readListBegin() _etype48 = rtmp3.etype _size45 = rtmp3.size for (var _i49 = 0; _i49 < _size45; ++_i49) { var elem50 = null var rtmp = input.readI64() elem50 = rtmp.value this.longIds.push(elem50) } input.readListEnd() } } else { input.skip(ftype) } break default: input.skip(ftype) } input.readFieldEnd() } input.readStructEnd() return } GeocodeFeature.prototype.write = function(output){ output.writeStructBegin('GeocodeFeature') if (null != this.cc) { output.writeFieldBegin('cc', Thrift.Type.STRING, 1) output.writeString(this.cc) output.writeFieldEnd() } if (null != this.geometry) { output.writeFieldBegin('geometry', Thrift.Type.STRUCT, 2) this.geometry.write(output) output.writeFieldEnd() } if (null != this.name) { output.writeFieldBegin('name', Thrift.Type.STRING, 3) output.writeString(this.name) output.writeFieldEnd() } if (null != this.displayName) { output.writeFieldBegin('displayName', Thrift.Type.STRING, 4) output.writeString(this.displayName) output.writeFieldEnd() } if (null != this.woeType) { output.writeFieldBegin('woeType', Thrift.Type.I32, 5) output.writeI32(this.woeType) output.writeFieldEnd() } if (null != this.ids) { output.writeFieldBegin('ids', Thrift.Type.LIST, 6) { output.writeListBegin(Thrift.Type.STRUCT, this.ids.length) { for(var iter51 in this.ids) { iter51=this.ids[iter51] iter51.write(output) } } output.writeListEnd() } output.writeFieldEnd() } if (null != this.names) { output.writeFieldBegin('names', Thrift.Type.LIST, 7) { output.writeListBegin(Thrift.Type.STRUCT, this.names.length) { for(var iter52 in this.names) { iter52=this.names[iter52] iter52.write(output) } } output.writeListEnd() } output.writeFieldEnd() } if (null != this.attribution) { output.writeFieldBegin('attribution', Thrift.Type.LIST, 8) { output.writeListBegin(Thrift.Type.STRING, this.attribution.length) { for(var iter53 in this.attribution) { iter53=this.attribution[iter53] output.writeString(iter53) } } output.writeListEnd() } output.writeFieldEnd() } if (null != this.timezones) { output.writeFieldBegin('timezones', Thrift.Type.LIST, 9) { output.writeListBegin(Thrift.Type.STRING, this.timezones.length) { for(var iter54 in this.timezones) { iter54=this.timezones[iter54] output.writeString(iter54) } } output.writeListEnd() } output.writeFieldEnd() } if (null != this.highlightedName) { output.writeFieldBegin('highlightedName', Thrift.Type.STRING, 11) output.writeString(this.highlightedName) output.writeFieldEnd() } if (null != this.matchedName) { output.writeFieldBegin('matchedName', Thrift.Type.STRING, 12) output.writeString(this.matchedName) output.writeFieldEnd() } if (null != this.slug) { output.writeFieldBegin('slug', Thrift.Type.STRING, 13) output.writeString(this.slug) output.writeFieldEnd() } if (null != this.id) { output.writeFieldBegin('id', Thrift.Type.STRING, 14) output.writeString(this.id) output.writeFieldEnd() } if (null != this.attributes) { output.writeFieldBegin('attributes', Thrift.Type.STRUCT, 15) this.attributes.write(output) output.writeFieldEnd() } if (null != this.longId) { output.writeFieldBegin('longId', Thrift.Type.I64, 16) output.writeI64(this.longId) output.writeFieldEnd() } if (null != this.longIds) { output.writeFieldBegin('longIds', Thrift.Type.LIST, 17) { output.writeListBegin(Thrift.Type.I64, this.longIds.length) { for(var iter55 in this.longIds) { iter55=this.longIds[iter55] output.writeI64(iter55) } } output.writeListEnd() } output.writeFieldEnd() } output.writeFieldStop() output.writeStructEnd() return } GeocodeServingFeature = function(args){ this.longId = 0 this.scoringFeatures = new ScoringFeatures() this.feature = new GeocodeFeature() this.parents = [] this.DEPRECATED_id = '' if( args != null ){if (null != args.longId) this.longId = args.longId if (null != args.scoringFeatures) this.scoringFeatures = args.scoringFeatures if (null != args.feature) this.feature = args.feature if (null != args.parents) this.parents = args.parents if (null != args.DEPRECATED_id) this.DEPRECATED_id = args.DEPRECATED_id }} GeocodeServingFeature.prototype = {} GeocodeServingFeature.prototype.read = function(input){ var ret = input.readStructBegin() while (1) { var ret = input.readFieldBegin() var fname = ret.fname var ftype = ret.ftype var fid = ret.fid if (ftype == Thrift.Type.STOP) break switch(fid) { case 5:if (ftype == Thrift.Type.I64) { var rtmp = input.readI64() this.longId = rtmp.value } else { input.skip(ftype) } break case 2:if (ftype == Thrift.Type.STRUCT) { this.scoringFeatures = new ScoringFeatures() this.scoringFeatures.read(input) } else { input.skip(ftype) } break case 3:if (ftype == Thrift.Type.STRUCT) { this.feature = new GeocodeFeature() this.feature.read(input) } else { input.skip(ftype) } break case 4:if (ftype == Thrift.Type.LIST) { { var _size56 = 0 var rtmp3 this.parents = [] var _etype59 = 0 rtmp3 = input.readListBegin() _etype59 = rtmp3.etype _size56 = rtmp3.size for (var _i60 = 0; _i60 < _size56; ++_i60) { var elem61 = null elem61 = new GeocodeFeature() elem61.read(input) this.parents.push(elem61) } input.readListEnd() } } else { input.skip(ftype) } break case 1:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.DEPRECATED_id = rtmp.value } else { input.skip(ftype) } break default: input.skip(ftype) } input.readFieldEnd() } input.readStructEnd() return } GeocodeServingFeature.prototype.write = function(output){ output.writeStructBegin('GeocodeServingFeature') if (null != this.longId) { output.writeFieldBegin('longId', Thrift.Type.I64, 5) output.writeI64(this.longId) output.writeFieldEnd() } if (null != this.scoringFeatures) { output.writeFieldBegin('scoringFeatures', Thrift.Type.STRUCT, 2) this.scoringFeatures.write(output) output.writeFieldEnd() } if (null != this.feature) { output.writeFieldBegin('feature', Thrift.Type.STRUCT, 3) this.feature.write(output) output.writeFieldEnd() } if (null != this.parents) { output.writeFieldBegin('parents', Thrift.Type.LIST, 4) { output.writeListBegin(Thrift.Type.STRUCT, this.parents.length) { for(var iter62 in this.parents) { iter62=this.parents[iter62] iter62.write(output) } } output.writeListEnd() } output.writeFieldEnd() } if (null != this.DEPRECATED_id) { output.writeFieldBegin('DEPRECATED_id', Thrift.Type.STRING, 1) output.writeString(this.DEPRECATED_id) output.writeFieldEnd() } output.writeFieldStop() output.writeStructEnd() return } InterpretationScoringFeatures = function(args){ this.percentOfRequestCovered = 0 this.percentOfFeatureCovered = 0 if( args != null ){if (null != args.percentOfRequestCovered) this.percentOfRequestCovered = args.percentOfRequestCovered if (null != args.percentOfFeatureCovered) this.percentOfFeatureCovered = args.percentOfFeatureCovered }} InterpretationScoringFeatures.prototype = {} InterpretationScoringFeatures.prototype.read = function(input){ var ret = input.readStructBegin() while (1) { var ret = input.readFieldBegin() var fname = ret.fname var ftype = ret.ftype var fid = ret.fid if (ftype == Thrift.Type.STOP) break switch(fid) { case 2:if (ftype == Thrift.Type.DOUBLE) { var rtmp = input.readDouble() this.percentOfRequestCovered = rtmp.value } else { input.skip(ftype) } break case 3:if (ftype == Thrift.Type.DOUBLE) { var rtmp = input.readDouble() this.percentOfFeatureCovered = rtmp.value } else { input.skip(ftype) } break default: input.skip(ftype) } input.readFieldEnd() } input.readStructEnd() return } InterpretationScoringFeatures.prototype.write = function(output){ output.writeStructBegin('InterpretationScoringFeatures') if (null != this.percentOfRequestCovered) { output.writeFieldBegin('percentOfRequestCovered', Thrift.Type.DOUBLE, 2) output.writeDouble(this.percentOfRequestCovered) output.writeFieldEnd() } if (null != this.percentOfFeatureCovered) { output.writeFieldBegin('percentOfFeatureCovered', Thrift.Type.DOUBLE, 3) output.writeDouble(this.percentOfFeatureCovered) output.writeFieldEnd() } output.writeFieldStop() output.writeStructEnd() return } DebugScoreComponent = function(args){ this.key = '' this.value = 0 if( args != null ){if (null != args.key) this.key = args.key if (null != args.value) this.value = args.value }} DebugScoreComponent.prototype = {} DebugScoreComponent.prototype.read = function(input){ var ret = input.readStructBegin() while (1) { var ret = input.readFieldBegin() var fname = ret.fname var ftype = ret.ftype var fid = ret.fid if (ftype == Thrift.Type.STOP) break switch(fid) { case 1:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.key = rtmp.value } else { input.skip(ftype) } break case 2:if (ftype == Thrift.Type.I32) { var rtmp = input.readI32() this.value = rtmp.value } else { input.skip(ftype) } break default: input.skip(ftype) } input.readFieldEnd() } input.readStructEnd() return } DebugScoreComponent.prototype.write = function(output){ output.writeStructBegin('DebugScoreComponent') if (null != this.key) { output.writeFieldBegin('key', Thrift.Type.STRING, 1) output.writeString(this.key) output.writeFieldEnd() } if (null != this.value) { output.writeFieldBegin('value', Thrift.Type.I32, 2) output.writeI32(this.value) output.writeFieldEnd() } output.writeFieldStop() output.writeStructEnd() return } InterpretationDebugInfo = function(args){ this.scoreComponents = [] this.finalScore = 0 if( args != null ){if (null != args.scoreComponents) this.scoreComponents = args.scoreComponents if (null != args.finalScore) this.finalScore = args.finalScore }} InterpretationDebugInfo.prototype = {} InterpretationDebugInfo.prototype.read = function(input){ var ret = input.readStructBegin() while (1) { var ret = input.readFieldBegin() var fname = ret.fname var ftype = ret.ftype var fid = ret.fid if (ftype == Thrift.Type.STOP) break switch(fid) { case 1:if (ftype == Thrift.Type.LIST) { { var _size63 = 0 var rtmp3 this.scoreComponents = [] var _etype66 = 0 rtmp3 = input.readListBegin() _etype66 = rtmp3.etype _size63 = rtmp3.size for (var _i67 = 0; _i67 < _size63; ++_i67) { var elem68 = null elem68 = new DebugScoreComponent() elem68.read(input) this.scoreComponents.push(elem68) } input.readListEnd() } } else { input.skip(ftype) } break case 2:if (ftype == Thrift.Type.I32) { var rtmp = input.readI32() this.finalScore = rtmp.value } else { input.skip(ftype) } break default: input.skip(ftype) } input.readFieldEnd() } input.readStructEnd() return } InterpretationDebugInfo.prototype.write = function(output){ output.writeStructBegin('InterpretationDebugInfo') if (null != this.scoreComponents) { output.writeFieldBegin('scoreComponents', Thrift.Type.LIST, 1) { output.writeListBegin(Thrift.Type.STRUCT, this.scoreComponents.length) { for(var iter69 in this.scoreComponents) { iter69=this.scoreComponents[iter69] iter69.write(output) } } output.writeListEnd() } output.writeFieldEnd() } if (null != this.finalScore) { output.writeFieldBegin('finalScore', Thrift.Type.I32, 2) output.writeI32(this.finalScore) output.writeFieldEnd() } output.writeFieldStop() output.writeStructEnd() return } GeocodeInterpretation = function(args){ this.what = '' this.where = '' this.feature = new GeocodeFeature() this.parents = [] this.scoringFeatures_DEPRECATED = new ScoringFeatures() this.scores = new InterpretationScoringFeatures() this.debugInfo = new InterpretationDebugInfo() this.parentLongIds = [] if( args != null ){if (null != args.what) this.what = args.what if (null != args.where) this.where = args.where if (null != args.feature) this.feature = args.feature if (null != args.parents) this.parents = args.parents if (null != args.scoringFeatures_DEPRECATED) this.scoringFeatures_DEPRECATED = args.scoringFeatures_DEPRECATED if (null != args.scores) this.scores = args.scores if (null != args.debugInfo) this.debugInfo = args.debugInfo if (null != args.parentLongIds) this.parentLongIds = args.parentLongIds }} GeocodeInterpretation.prototype = {} GeocodeInterpretation.prototype.read = function(input){ var ret = input.readStructBegin() while (1) { var ret = input.readFieldBegin() var fname = ret.fname var ftype = ret.ftype var fid = ret.fid if (ftype == Thrift.Type.STOP) break switch(fid) { case 1:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.what = rtmp.value } else { input.skip(ftype) } break case 2:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.where = rtmp.value } else { input.skip(ftype) } break case 3:if (ftype == Thrift.Type.STRUCT) { this.feature = new GeocodeFeature() this.feature.read(input) } else { input.skip(ftype) } break case 4:if (ftype == Thrift.Type.LIST) { { var _size70 = 0 var rtmp3 this.parents = [] var _etype73 = 0 rtmp3 = input.readListBegin() _etype73 = rtmp3.etype _size70 = rtmp3.size for (var _i74 = 0; _i74 < _size70; ++_i74) { var elem75 = null elem75 = new GeocodeFeature() elem75.read(input) this.parents.push(elem75) } input.readListEnd() } } else { input.skip(ftype) } break case 5:if (ftype == Thrift.Type.STRUCT) { this.scoringFeatures_DEPRECATED = new ScoringFeatures() this.scoringFeatures_DEPRECATED.read(input) } else { input.skip(ftype) } break case 6:if (ftype == Thrift.Type.STRUCT) { this.scores = new InterpretationScoringFeatures() this.scores.read(input) } else { input.skip(ftype) } break case 7:if (ftype == Thrift.Type.STRUCT) { this.debugInfo = new InterpretationDebugInfo() this.debugInfo.read(input) } else { input.skip(ftype) } break case 8:if (ftype == Thrift.Type.LIST) { { var _size76 = 0 var rtmp3 this.parentLongIds = [] var _etype79 = 0 rtmp3 = input.readListBegin() _etype79 = rtmp3.etype _size76 = rtmp3.size for (var _i80 = 0; _i80 < _size76; ++_i80) { var elem81 = null var rtmp = input.readI64() elem81 = rtmp.value this.parentLongIds.push(elem81) } input.readListEnd() } } else { input.skip(ftype) } break default: input.skip(ftype) } input.readFieldEnd() } input.readStructEnd() return } GeocodeInterpretation.prototype.write = function(output){ output.writeStructBegin('GeocodeInterpretation') if (null != this.what) { output.writeFieldBegin('what', Thrift.Type.STRING, 1) output.writeString(this.what) output.writeFieldEnd() } if (null != this.where) { output.writeFieldBegin('where', Thrift.Type.STRING, 2) output.writeString(this.where) output.writeFieldEnd() } if (null != this.feature) { output.writeFieldBegin('feature', Thrift.Type.STRUCT, 3) this.feature.write(output) output.writeFieldEnd() } if (null != this.parents) { output.writeFieldBegin('parents', Thrift.Type.LIST, 4) { output.writeListBegin(Thrift.Type.STRUCT, this.parents.length) { for(var iter82 in this.parents) { iter82=this.parents[iter82] iter82.write(output) } } output.writeListEnd() } output.writeFieldEnd() } if (null != this.scoringFeatures_DEPRECATED) { output.writeFieldBegin('scoringFeatures_DEPRECATED', Thrift.Type.STRUCT, 5) this.scoringFeatures_DEPRECATED.write(output) output.writeFieldEnd() } if (null != this.scores) { output.writeFieldBegin('scores', Thrift.Type.STRUCT, 6) this.scores.write(output) output.writeFieldEnd() } if (null != this.debugInfo) { output.writeFieldBegin('debugInfo', Thrift.Type.STRUCT, 7) this.debugInfo.write(output) output.writeFieldEnd() } if (null != this.parentLongIds) { output.writeFieldBegin('parentLongIds', Thrift.Type.LIST, 8) { output.writeListBegin(Thrift.Type.I64, this.parentLongIds.length) { for(var iter83 in this.parentLongIds) { iter83=this.parentLongIds[iter83] output.writeI64(iter83) } } output.writeListEnd() } output.writeFieldEnd() } output.writeFieldStop() output.writeStructEnd() return } GeocodeResponse = function(args){ this.interpretations = [] this.debugLines = [] this.requestWktGeometry = '' if( args != null ){if (null != args.interpretations) this.interpretations = args.interpretations if (null != args.debugLines) this.debugLines = args.debugLines if (null != args.requestWktGeometry) this.requestWktGeometry = args.requestWktGeometry }} GeocodeResponse.prototype = {} GeocodeResponse.prototype.read = function(input){ var ret = input.readStructBegin() while (1) { var ret = input.readFieldBegin() var fname = ret.fname var ftype = ret.ftype var fid = ret.fid if (ftype == Thrift.Type.STOP) break switch(fid) { case 1:if (ftype == Thrift.Type.LIST) { { var _size84 = 0 var rtmp3 this.interpretations = [] var _etype87 = 0 rtmp3 = input.readListBegin() _etype87 = rtmp3.etype _size84 = rtmp3.size for (var _i88 = 0; _i88 < _size84; ++_i88) { var elem89 = null elem89 = new GeocodeInterpretation() elem89.read(input) this.interpretations.push(elem89) } input.readListEnd() } } else { input.skip(ftype) } break case 2:if (ftype == Thrift.Type.LIST) { { var _size90 = 0 var rtmp3 this.debugLines = [] var _etype93 = 0 rtmp3 = input.readListBegin() _etype93 = rtmp3.etype _size90 = rtmp3.size for (var _i94 = 0; _i94 < _size90; ++_i94) { var elem95 = null var rtmp = input.readString() elem95 = rtmp.value this.debugLines.push(elem95) } input.readListEnd() } } else { input.skip(ftype) } break case 3:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.requestWktGeometry = rtmp.value } else { input.skip(ftype) } break default: input.skip(ftype) } input.readFieldEnd() } input.readStructEnd() return } GeocodeResponse.prototype.write = function(output){ output.writeStructBegin('GeocodeResponse') if (null != this.interpretations) { output.writeFieldBegin('interpretations', Thrift.Type.LIST, 1) { output.writeListBegin(Thrift.Type.STRUCT, this.interpretations.length) { for(var iter96 in this.interpretations) { iter96=this.interpretations[iter96] iter96.write(output) } } output.writeListEnd() } output.writeFieldEnd() } if (null != this.debugLines) { output.writeFieldBegin('debugLines', Thrift.Type.LIST, 2) { output.writeListBegin(Thrift.Type.STRING, this.debugLines.length) { for(var iter97 in this.debugLines) { iter97=this.debugLines[iter97] output.writeString(iter97) } } output.writeListEnd() } output.writeFieldEnd() } if (null != this.requestWktGeometry) { output.writeFieldBegin('requestWktGeometry', Thrift.Type.STRING, 3) output.writeString(this.requestWktGeometry) output.writeFieldEnd() } output.writeFieldStop() output.writeStructEnd() return } GeocodeRequest = function(args){ this.query = '' this.cc = '' this.lang = 'en' this.ll = new GeocodePoint() this.full_DEPRECATED = false this.debug = 0 this.autocomplete = false this.woeHint = [] this.woeRestrict = [] this.bounds = new GeocodeBoundingBox() this.slug = '' this.includePolygon_DEPRECATED = false this.radius = 0 this.maxInterpretations = 0 this.allowedSources = [] this.responseIncludes = [] if( args != null ){if (null != args.query) this.query = args.query if (null != args.cc) this.cc = args.cc if (null != args.lang) this.lang = args.lang if (null != args.ll) this.ll = args.ll if (null != args.full_DEPRECATED) this.full_DEPRECATED = args.full_DEPRECATED if (null != args.debug) this.debug = args.debug if (null != args.autocomplete) this.autocomplete = args.autocomplete if (null != args.woeHint) this.woeHint = args.woeHint if (null != args.woeRestrict) this.woeRestrict = args.woeRestrict if (null != args.bounds) this.bounds = args.bounds if (null != args.slug) this.slug = args.slug if (null != args.includePolygon_DEPRECATED) this.includePolygon_DEPRECATED = args.includePolygon_DEPRECATED if (null != args.radius) this.radius = args.radius if (null != args.maxInterpretations) this.maxInterpretations = args.maxInterpretations if (null != args.allowedSources) this.allowedSources = args.allowedSources if (null != args.responseIncludes) this.responseIncludes = args.responseIncludes }} GeocodeRequest.prototype = {} GeocodeRequest.prototype.read = function(input){ var ret = input.readStructBegin() while (1) { var ret = input.readFieldBegin() var fname = ret.fname var ftype = ret.ftype var fid = ret.fid if (ftype == Thrift.Type.STOP) break switch(fid) { case 1:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.query = rtmp.value } else { input.skip(ftype) } break case 2:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.cc = rtmp.value } else { input.skip(ftype) } break case 3:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.lang = rtmp.value } else { input.skip(ftype) } break case 4:if (ftype == Thrift.Type.STRUCT) { this.ll = new GeocodePoint() this.ll.read(input) } else { input.skip(ftype) } break case 5:if (ftype == Thrift.Type.BOOL) { var rtmp = input.readBool() this.full_DEPRECATED = rtmp.value } else { input.skip(ftype) } break case 6:if (ftype == Thrift.Type.I32) { var rtmp = input.readI32() this.debug = rtmp.value } else { input.skip(ftype) } break case 7:if (ftype == Thrift.Type.BOOL) { var rtmp = input.readBool() this.autocomplete = rtmp.value } else { input.skip(ftype) } break case 8:if (ftype == Thrift.Type.LIST) { { var _size98 = 0 var rtmp3 this.woeHint = [] var _etype101 = 0 rtmp3 = input.readListBegin() _etype101 = rtmp3.etype _size98 = rtmp3.size for (var _i102 = 0; _i102 < _size98; ++_i102) { var elem103 = null var rtmp = input.readI32() elem103 = rtmp.value this.woeHint.push(elem103) } input.readListEnd() } } else { input.skip(ftype) } break case 9:if (ftype == Thrift.Type.LIST) { { var _size104 = 0 var rtmp3 this.woeRestrict = [] var _etype107 = 0 rtmp3 = input.readListBegin() _etype107 = rtmp3.etype _size104 = rtmp3.size for (var _i108 = 0; _i108 < _size104; ++_i108) { var elem109 = null var rtmp = input.readI32() elem109 = rtmp.value this.woeRestrict.push(elem109) } input.readListEnd() } } else { input.skip(ftype) } break case 10:if (ftype == Thrift.Type.STRUCT) { this.bounds = new GeocodeBoundingBox() this.bounds.read(input) } else { input.skip(ftype) } break case 11:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.slug = rtmp.value } else { input.skip(ftype) } break case 12:if (ftype == Thrift.Type.BOOL) { var rtmp = input.readBool() this.includePolygon_DEPRECATED = rtmp.value } else { input.skip(ftype) } break case 14:if (ftype == Thrift.Type.I32) { var rtmp = input.readI32() this.radius = rtmp.value } else { input.skip(ftype) } break case 16:if (ftype == Thrift.Type.I32) { var rtmp = input.readI32() this.maxInterpretations = rtmp.value } else { input.skip(ftype) } break case 17:if (ftype == Thrift.Type.LIST) { { var _size110 = 0 var rtmp3 this.allowedSources = [] var _etype113 = 0 rtmp3 = input.readListBegin() _etype113 = rtmp3.etype _size110 = rtmp3.size for (var _i114 = 0; _i114 < _size110; ++_i114) { var elem115 = null var rtmp = input.readString() elem115 = rtmp.value this.allowedSources.push(elem115) } input.readListEnd() } } else { input.skip(ftype) } break case 18:if (ftype == Thrift.Type.LIST) { { var _size116 = 0 var rtmp3 this.responseIncludes = [] var _etype119 = 0 rtmp3 = input.readListBegin() _etype119 = rtmp3.etype _size116 = rtmp3.size for (var _i120 = 0; _i120 < _size116; ++_i120) { var elem121 = null var rtmp = input.readI32() elem121 = rtmp.value this.responseIncludes.push(elem121) } input.readListEnd() } } else { input.skip(ftype) } break default: input.skip(ftype) } input.readFieldEnd() } input.readStructEnd() return } GeocodeRequest.prototype.write = function(output){ output.writeStructBegin('GeocodeRequest') if (null != this.query) { output.writeFieldBegin('query', Thrift.Type.STRING, 1) output.writeString(this.query) output.writeFieldEnd() } if (null != this.cc) { output.writeFieldBegin('cc', Thrift.Type.STRING, 2) output.writeString(this.cc) output.writeFieldEnd() } if (null != this.lang) { output.writeFieldBegin('lang', Thrift.Type.STRING, 3) output.writeString(this.lang) output.writeFieldEnd() } if (null != this.ll) { output.writeFieldBegin('ll', Thrift.Type.STRUCT, 4) this.ll.write(output) output.writeFieldEnd() } if (null != this.full_DEPRECATED) { output.writeFieldBegin('full_DEPRECATED', Thrift.Type.BOOL, 5) output.writeBool(this.full_DEPRECATED) output.writeFieldEnd() } if (null != this.debug) { output.writeFieldBegin('debug', Thrift.Type.I32, 6) output.writeI32(this.debug) output.writeFieldEnd() } if (null != this.autocomplete) { output.writeFieldBegin('autocomplete', Thrift.Type.BOOL, 7) output.writeBool(this.autocomplete) output.writeFieldEnd() } if (null != this.woeHint) { output.writeFieldBegin('woeHint', Thrift.Type.LIST, 8) { output.writeListBegin(Thrift.Type.I32, this.woeHint.length) { for(var iter122 in this.woeHint) { iter122=this.woeHint[iter122] output.writeI32(iter122) } } output.writeListEnd() } output.writeFieldEnd() } if (null != this.woeRestrict) { output.writeFieldBegin('woeRestrict', Thrift.Type.LIST, 9) { output.writeListBegin(Thrift.Type.I32, this.woeRestrict.length) { for(var iter123 in this.woeRestrict) { iter123=this.woeRestrict[iter123] output.writeI32(iter123) } } output.writeListEnd() } output.writeFieldEnd() } if (null != this.bounds) { output.writeFieldBegin('bounds', Thrift.Type.STRUCT, 10) this.bounds.write(output) output.writeFieldEnd() } if (null != this.slug) { output.writeFieldBegin('slug', Thrift.Type.STRING, 11) output.writeString(this.slug) output.writeFieldEnd() } if (null != this.includePolygon_DEPRECATED) { output.writeFieldBegin('includePolygon_DEPRECATED', Thrift.Type.BOOL, 12) output.writeBool(this.includePolygon_DEPRECATED) output.writeFieldEnd() } if (null != this.radius) { output.writeFieldBegin('radius', Thrift.Type.I32, 14) output.writeI32(this.radius) output.writeFieldEnd() } if (null != this.maxInterpretations) { output.writeFieldBegin('maxInterpretations', Thrift.Type.I32, 16) output.writeI32(this.maxInterpretations) output.writeFieldEnd() } if (null != this.allowedSources) { output.writeFieldBegin('allowedSources', Thrift.Type.LIST, 17) { output.writeListBegin(Thrift.Type.STRING, this.allowedSources.length) { for(var iter124 in this.allowedSources) { iter124=this.allowedSources[iter124] output.writeString(iter124) } } output.writeListEnd() } output.writeFieldEnd() } if (null != this.responseIncludes) { output.writeFieldBegin('responseIncludes', Thrift.Type.LIST, 18) { output.writeListBegin(Thrift.Type.I32, this.responseIncludes.length) { for(var iter125 in this.responseIncludes) { iter125=this.responseIncludes[iter125] output.writeI32(iter125) } } output.writeListEnd() } output.writeFieldEnd() } output.writeFieldStop() output.writeStructEnd() return } CommonGeocodeRequestParams = function(args){ this.debug = 0 this.woeHint = [] this.woeRestrict = [] this.cc = '' this.lang = 'en' this.responseIncludes = [] this.allowedSources = [] this.llHint = new GeocodePoint() this.bounds = new GeocodeBoundingBox() this.maxInterpretations = 0 if( args != null ){if (null != args.debug) this.debug = args.debug if (null != args.woeHint) this.woeHint = args.woeHint if (null != args.woeRestrict) this.woeRestrict = args.woeRestrict if (null != args.cc) this.cc = args.cc if (null != args.lang) this.lang = args.lang if (null != args.responseIncludes) this.responseIncludes = args.responseIncludes if (null != args.allowedSources) this.allowedSources = args.allowedSources if (null != args.llHint) this.llHint = args.llHint if (null != args.bounds) this.bounds = args.bounds if (null != args.maxInterpretations) this.maxInterpretations = args.maxInterpretations }} CommonGeocodeRequestParams.prototype = {} CommonGeocodeRequestParams.prototype.read = function(input){ var ret = input.readStructBegin() while (1) { var ret = input.readFieldBegin() var fname = ret.fname var ftype = ret.ftype var fid = ret.fid if (ftype == Thrift.Type.STOP) break switch(fid) { case 1:if (ftype == Thrift.Type.I32) { var rtmp = input.readI32() this.debug = rtmp.value } else { input.skip(ftype) } break case 2:if (ftype == Thrift.Type.LIST) { { var _size126 = 0 var rtmp3 this.woeHint = [] var _etype129 = 0 rtmp3 = input.readListBegin() _etype129 = rtmp3.etype _size126 = rtmp3.size for (var _i130 = 0; _i130 < _size126; ++_i130) { var elem131 = null var rtmp = input.readI32() elem131 = rtmp.value this.woeHint.push(elem131) } input.readListEnd() } } else { input.skip(ftype) } break case 3:if (ftype == Thrift.Type.LIST) { { var _size132 = 0 var rtmp3 this.woeRestrict = [] var _etype135 = 0 rtmp3 = input.readListBegin() _etype135 = rtmp3.etype _size132 = rtmp3.size for (var _i136 = 0; _i136 < _size132; ++_i136) { var elem137 = null var rtmp = input.readI32() elem137 = rtmp.value this.woeRestrict.push(elem137) } input.readListEnd() } } else { input.skip(ftype) } break case 4:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.cc = rtmp.value } else { input.skip(ftype) } break case 5:if (ftype == Thrift.Type.STRING) { var rtmp = input.readString() this.lang = rtmp.value } else { input.skip(ftype) } break case 6:if (ftype == Thrift.Type.LIST) { { var _size138 = 0 var rtmp3 this.responseIncludes = [] var _etype141 = 0 rtmp3 = input.readListBegin() _etype141 = rtmp3.etype _size138 = rtmp3.size for (var _i142 = 0; _i142 < _size138; ++_i142) { var elem143 = null var rtmp = input.readI32() elem143 = rtmp.value this.responseIncludes.push(elem143) } input.readListEnd() } } else { input.skip(ftype) } break case 7:if (ftype == Thrift.Type.LIST) { { var _size144 = 0 var rtmp3 this.allowedSources = [] var _etype147 = 0 rtmp3 = input.readListBegin() _etype147 = rtmp3.etype _size144 = rtmp3.size for (var _i148 = 0; _i148 < _size144; ++_i148) { var elem149 = null var rtmp = input.readString() elem149 = rtmp.value this.allowedSources.push(elem149) } input.readListEnd() } } else { input.skip(ftype) } break case 8:if (ftype == Thrift.Type.STRUCT) { this.llHint = new GeocodePoint() this.llHint.read(input) } else { input.skip(ftype) } break case 9:if (ftype == Thrift.Type.STRUCT) { this.bounds = new GeocodeBoundingBox() this.bounds.read(input) } else { input.skip(ftype) } break case 10:if (ftype == Thrift.Type.I32) { var rtmp = input.readI32() this.maxInterpretations = rtmp.value } else { input.skip(ftype) } break default: input.skip(ftype) } input.readFieldEnd() } input.readStructEnd() return } CommonGeocodeRequestParams.prototype.write = function(output){ output.writeStructBegin('CommonGeocodeRequestParams') if (null != this.debug) { output.writeFieldBegin('debug', Thrift.Type.I32, 1) output.writeI32(this.debug) output.writeFieldEnd() } if (null != this.woeHint) { output.writeFieldBegin('woeHint', Thrift.Type.LIST, 2) { output.writeListBegin(Thrift.Type.I32, this.woeHint.length) { for(var iter150 in this.woeHint) { iter150=this.woeHint[iter150] output.writeI32(iter150) } } output.writeListEnd() } output.writeFieldEnd() } if (null != this.woeRestrict) { output.writeFieldBegin('woeRestrict', Thrift.Type.LIST, 3) { output.writeListBegin(Thrift.Type.I32, this.woeRestrict.length) { for(var iter151 in this.woeRestrict) { iter151=this.woeRestrict[iter151] output.writeI32(iter151) } } output.writeListEnd() } output.writeFieldEnd() } if (null != this.cc) { output.writeFieldBegin('cc', Thrift.Type.STRING, 4) output.writeString(this.cc) output.writeFieldEnd() } if (null != this.lang) { output.writeFieldBegin('lang', Thrift.Type.STRING, 5) output.writeString(this.lang) output.writeFieldEnd() } if (null != this.responseIncludes) { output.writeFieldBegin('responseIncludes', Thrift.Type.LIST, 6) { output.writeListBegin(Thrift.Type.I32, this.responseIncludes.length) { for(var iter152 in this.responseIncludes) { iter152=this.responseIncludes[iter152] output.writeI32(iter152) } } output.writeListEnd() } output.writeFieldEnd() } if (null != this.allowedSources) { output.writeFieldBegin('allowedSources', Thrift.Type.LIST, 7) { output.writeListBegin(Thrift.Type.STRING, this.allowedSources.length) { for(var iter153 in this.allowedSources) { iter153=this.allowedSources[iter153] output.writeString(iter153) } } output.writeListEnd() } output.writeFieldEnd() } if (null != this.llHint) { output.writeFieldBegin('llHint', Thrift.Type.STRUCT, 8) this.llHint.write(output) output.writeFieldEnd() } if (null != this.bounds) { output.writeFieldBegin('bounds', Thrift.Type.STRUCT, 9) this.bounds.write(output) output.writeFieldEnd() } if (null != this.maxInterpretations) { output.writeFieldBegin('maxInterpretations', Thrift.Type.I32, 10) output.writeI32(this.maxInterpretations) output.writeFieldEnd() } output.writeFieldStop() output.writeStructEnd() return } BulkReverseGeocodeRequest = function(args){ this.latlngs = [] this.params = new CommonGeocodeRequestParams() if( args != null ){if (null != args.latlngs) this.latlngs = args.latlngs if (null != args.params) this.params = args.params }} BulkReverseGeocodeRequest.prototype = {} BulkReverseGeocodeRequest.prototype.read = function(input){ var ret = input.readStructBegin() while (1) { var ret = input.readFieldBegin() var fname = ret.fname var ftype = ret.ftype var fid = ret.fid if (ftype == Thrift.Type.STOP) break switch(fid) { case 1:if (ftype == Thrift.Type.LIST) { { var _size154 = 0 var rtmp3 this.latlngs = [] var _etype157 = 0 rtmp3 = input.readListBegin() _etype157 = rtmp3.etype _size154 = rtmp3.size for (var _i158 = 0; _i158 < _size154; ++_i158) { var elem159 = null elem159 = new GeocodePoint() elem159.read(input) this.latlngs.push(elem159) } input.readListEnd() } } else { input.skip(ftype) } break case 2:if (ftype == Thrift.Type.STRUCT) { this.params = new CommonGeocodeRequestParams() this.params.read(input) } else { input.skip(ftype) } break default: input.skip(ftype) } input.readFieldEnd() } input.readStructEnd() return } BulkReverseGeocodeRequest.prototype.write = function(output){ output.writeStructBegin('BulkReverseGeocodeRequest') if (null != this.latlngs) { output.writeFieldBegin('latlngs', Thrift.Type.LIST, 1) { output.writeListBegin(Thrift.Type.STRUCT, this.latlngs.length) { for(var iter160 in this.latlngs) { iter160=this.latlngs[iter160] iter160.write(output) } } output.writeListEnd() } output.writeFieldEnd() } if (null != this.params) { output.writeFieldBegin('params', Thrift.Type.STRUCT, 2) this.params.write(output) output.writeFieldEnd() } output.writeFieldStop() output.writeStructEnd() return } BulkReverseGeocodeResponse = function(args){ this.DEPRECATED_interpretationMap = {} this.interpretations = [] this.interpretationIndexes = [] this.parentFeatures = [] this.debugLines = [] if( args != null ){if (null != args.DEPRECATED_interpretationMap) this.DEPRECATED_interpretationMap = args.DEPRECATED_interpretationMap if (null != args.interpretations) this.interpretations = args.interpretations if (null != args.interpretationIndexes) this.interpretationIndexes = args.interpretationIndexes if (null != args.parentFeatures) this.parentFeatures = args.parentFeatures if (null != args.debugLines) this.debugLines = args.debugLines }} BulkReverseGeocodeResponse.prototype = {} BulkReverseGeocodeResponse.prototype.read = function(input){ var ret = input.readStructBegin() while (1) { var ret = input.readFieldBegin() var fname = ret.fname var ftype = ret.ftype var fid = ret.fid if (ftype == Thrift.Type.STOP) break switch(fid) { case 1:if (ftype == Thrift.Type.MAP) { { var _size161 = 0 var rtmp3 this.DEPRECATED_interpretationMap = {} var _ktype162 = 0 var _vtype163 = 0 rtmp3 = input.readMapBegin() _ktype162= rtmp3.ktype _vtype163= rtmp3.vtype _size161= rtmp3.size for (var _i165 = 0; _i165 < _size161; ++_i165) { key166 = 0 val167 = [] var rtmp = input.readI32() key166 = rtmp.value { var _size168 = 0 var rtmp3 val167 = [] var _etype171 = 0 rtmp3 = input.readListBegin() _etype171 = rtmp3.etype _size168 = rtmp3.size for (var _i172 = 0; _i172 < _size168; ++_i172) { var elem173 = null elem173 = new GeocodeInterpretation() elem173.read(input) val167.push(elem173) } input.readListEnd() } this.DEPRECATED_interpretationMap[key166] = val167 } input.readMapEnd() } } else { input.skip(ftype) } break case 3:if (ftype == Thrift.Type.LIST) { { var _size174 = 0 var rtmp3 this.interpretations = [] var _etype177 = 0 rtmp3 = input.readListBegin() _etype177 = rtmp3.etype _size174 = rtmp3.size for (var _i178 = 0; _i178 < _size174; ++_i178) { var elem179 = null elem179 = new GeocodeInterpretation() elem179.read(input) this.interpretations.push(elem179) } input.readListEnd() } } else { input.skip(ftype) } break case 4:if (ftype == Thrift.Type.LIST) { { var _size180 = 0 var rtmp3 this.interpretationIndexes = [] var _etype183 = 0 rtmp3 = input.readListBegin() _etype183 = rtmp3.etype _size180 = rtmp3.size for (var _i184 = 0; _i184 < _size180; ++_i184) { var elem185 = null { var _size186 = 0 var rtmp3 elem185 = [] var _etype189 = 0 rtmp3 = input.readListBegin() _etype189 = rtmp3.etype _size186 = rtmp3.size for (var _i190 = 0; _i190 < _size186; ++_i190) { var elem191 = null var rtmp = input.readI32() elem191 = rtmp.value elem185.push(elem191) } input.readListEnd() } this.interpretationIndexes.push(elem185) } input.readListEnd() } } else { input.skip(ftype) } break case 5:if (ftype == Thrift.Type.LIST) { { var _size192 = 0 var rtmp3 this.parentFeatures = [] var _etype195 = 0 rtmp3 = input.readListBegin() _etype195 = rtmp3.etype _size192 = rtmp3.size for (var _i196 = 0; _i196 < _size192; ++_i196) { var elem197 = null elem197 = new GeocodeFeature() elem197.read(input) this.parentFeatures.push(elem197) } input.readListEnd() } } else { input.skip(ftype) } break case 2:if (ftype == Thrift.Type.LIST) { { var _size198 = 0 var rtmp3 this.debugLines = [] var _etype201 = 0 rtmp3 = input.readListBegin() _etype201 = rtmp3.etype _size198 = rtmp3.size for (var _i202 = 0; _i202 < _size198; ++_i202) { var elem203 = null var rtmp = input.readString() elem203 = rtmp.value this.debugLines.push(elem203) } input.readListEnd() } } else { input.skip(ftype) } break default: input.skip(ftype) } input.readFieldEnd() } input.readStructEnd() return } BulkReverseGeocodeResponse.prototype.write = function(output){ output.writeStructBegin('BulkReverseGeocodeResponse') if (null != this.DEPRECATED_interpretationMap) { output.writeFieldBegin('DEPRECATED_interpretationMap', Thrift.Type.MAP, 1) { output.writeMapBegin(Thrift.Type.I32, Thrift.Type.LIST, this.DEPRECATED_interpretationMap.length) { for(var kiter204 in this.DEPRECATED_interpretationMap){ var viter205 = this.DEPRECATED_interpretationMap[kiter204] output.writeI32(kiter204) { output.writeListBegin(Thrift.Type.STRUCT, viter205.length) { for(var iter206 in viter205) { iter206=viter205[iter206] iter206.write(output) } } output.writeListEnd() } } } output.writeMapEnd() } output.writeFieldEnd() } if (null != this.interpretations) { output.writeFieldBegin('interpretations', Thrift.Type.LIST, 3) { output.writeListBegin(Thrift.Type.STRUCT, this.interpretations.length) { for(var iter207 in this.interpretations) { iter207=this.interpretations[iter207] iter207.write(output) } } output.writeListEnd() } output.writeFieldEnd() } if (null != this.interpretationIndexes) { output.writeFieldBegin('interpretationIndexes', Thrift.Type.LIST, 4) { output.writeListBegin(Thrift.Type.LIST, this.interpretationIndexes.length) { for(var iter208 in this.interpretationIndexes) { iter208=this.interpretationIndexes[iter208] { output.writeListBegin(Thrift.Type.I32, iter208.length) { for(var iter209 in iter208) { iter209=iter208[iter209] output.writeI32(iter209) } } output.writeListEnd() } } } output.writeListEnd() } output.writeFieldEnd() } if (null != this.parentFeatures) { output.writeFieldBegin('parentFeatures', Thrift.Type.LIST, 5) { output.writeListBegin(Thrift.Type.STRUCT, this.parentFeatures.length) { for(var iter210 in this.parentFeatures) { iter210=this.parentFeatures[iter210] iter210.write(output) } } output.writeListEnd() } output.writeFieldEnd() } if (null != this.debugLines) { output.writeFieldBegin('debugLines', Thrift.Type.LIST, 2) { output.writeListBegin(Thrift.Type.STRING, this.debugLines.length) { for(var iter211 in this.debugLines) { iter211=this.debugLines[iter211] output.writeString(iter211) } } output.writeListEnd() } output.writeFieldEnd() } output.writeFieldStop() output.writeStructEnd() return } BulkSlugLookupRequest = function(args){ this.slugs = [] this.params = new CommonGeocodeRequestParams() if( args != null ){if (null != args.slugs) this.slugs = args.slugs if (null != args.params) this.params = args.params }} BulkSlugLookupRequest.prototype = {} BulkSlugLookupRequest.prototype.read = function(input){ var ret = input.readStructBegin() while (1) { var ret = input.readFieldBegin() var fname = ret.fname var ftype = ret.ftype var fid = ret.fid if (ftype == Thrift.Type.STOP) break switch(fid) { case 1:if (ftype == Thrift.Type.LIST) { { var _size212 = 0 var rtmp3 this.slugs = [] var _etype215 = 0 rtmp3 = input.readListBegin() _etype215 = rtmp3.etype _size212 = rtmp3.size for (var _i216 = 0; _i216 < _size212; ++_i216) { var elem217 = null var rtmp = input.readString() elem217 = rtmp.value this.slugs.push(elem217) } input.readListEnd() } } else { input.skip(ftype) } break case 2:if (ftype == Thrift.Type.STRUCT) { this.params = new CommonGeocodeRequestParams() this.params.read(input) } else { input.skip(ftype) } break default: input.skip(ftype) } input.readFieldEnd() } input.readStructEnd() return } BulkSlugLookupRequest.prototype.write = function(output){ output.writeStructBegin('BulkSlugLookupRequest') if (null != this.slugs) { output.writeFieldBegin('slugs', Thrift.Type.LIST, 1) { output.writeListBegin(Thrift.Type.STRING, this.slugs.length) { for(var iter218 in this.slugs) { iter218=this.slugs[iter218] output.writeString(iter218) } } output.writeListEnd() } output.writeFieldEnd() } if (null != this.params) { output.writeFieldBegin('params', Thrift.Type.STRUCT, 2) this.params.write(output) output.writeFieldEnd() } output.writeFieldStop() output.writeStructEnd() return } BulkSlugLookupResponse = function(args){ this.interpretations = [] this.interpretationIndexes = [] this.parentFeatures = [] this.debugLines = [] if( args != null ){if (null != args.interpretations) this.interpretations = args.interpretations if (null != args.interpretationIndexes) this.interpretationIndexes = args.interpretationIndexes if (null != args.parentFeatures) this.parentFeatures = args.parentFeatures if (null != args.debugLines) this.debugLines = args.debugLines }} BulkSlugLookupResponse.prototype = {} BulkSlugLookupResponse.prototype.read = function(input){ var ret = input.readStructBegin() while (1) { var ret = input.readFieldBegin() var fname = ret.fname var ftype = ret.ftype var fid = ret.fid if (ftype == Thrift.Type.STOP) break switch(fid) { case 1:if (ftype == Thrift.Type.LIST) { { var _size219 = 0 var rtmp3 this.interpretations = [] var _etype222 = 0 rtmp3 = input.readListBegin() _etype222 = rtmp3.etype _size219 = rtmp3.size for (var _i223 = 0; _i223 < _size219; ++_i223) { var elem224 = null elem224 = new GeocodeInterpretation() elem224.read(input) this.interpretations.push(elem224) } input.readListEnd() } } else { input.skip(ftype) } break case 2:if (ftype == Thrift.Type.LIST) { { var _size225 = 0 var rtmp3 this.interpretationIndexes = [] var _etype228 = 0 rtmp3 = input.readListBegin() _etype228 = rtmp3.etype _size225 = rtmp3.size for (var _i229 = 0; _i229 < _size225; ++_i229) { var elem230 = null { var _size231 = 0 var rtmp3 elem230 = [] var _etype234 = 0 rtmp3 = input.readListBegin() _etype234 = rtmp3.etype _size231 = rtmp3.size for (var _i235 = 0; _i235 < _size231; ++_i235) { var elem236 = null var rtmp = input.readI32() elem236 = rtmp.value elem230.push(elem236) } input.readListEnd() } this.interpretationIndexes.push(elem230) } input.readListEnd() } } else { input.skip(ftype) } break case 4:if (ftype == Thrift.Type.LIST) { { var _size237 = 0 var rtmp3 this.parentFeatures = [] var _etype240 = 0 rtmp3 = input.readListBegin() _etype240 = rtmp3.etype _size237 = rtmp3.size for (var _i241 = 0; _i241 < _size237; ++_i241) { var elem242 = null elem242 = new GeocodeFeature() elem242.read(input) this.parentFeatures.push(elem242) } input.readListEnd() } } else { input.skip(ftype) } break case 3:if (ftype == Thrift.Type.LIST) { { var _size243 = 0 var rtmp3 this.debugLines = [] var _etype246 = 0 rtmp3 = input.readListBegin() _etype246 = rtmp3.etype _size243 = rtmp3.size for (var _i247 = 0; _i247 < _size243; ++_i247) { var elem248 = null var rtmp = input.readString() elem248 = rtmp.value this.debugLines.push(elem248) } input.readListEnd() } } else { input.skip(ftype) } break default: input.skip(ftype) } input.readFieldEnd() } input.readStructEnd() return } BulkSlugLookupResponse.prototype.write = function(output){ output.writeStructBegin('BulkSlugLookupResponse') if (null != this.interpretations) { output.writeFieldBegin('interpretations', Thrift.Type.LIST, 1) { output.writeListBegin(Thrift.Type.STRUCT, this.interpretations.length) { for(var iter249 in this.interpretations) { iter249=this.interpretations[iter249] iter249.write(output) } } output.writeListEnd() } output.writeFieldEnd() } if (null != this.interpretationIndexes) { output.writeFieldBegin('interpretationIndexes', Thrift.Type.LIST, 2) { output.writeListBegin(Thrift.Type.LIST, this.interpretationIndexes.length) { for(var iter250 in this.interpretationIndexes) { iter250=this.interpretationIndexes[iter250] { output.writeListBegin(Thrift.Type.I32, iter250.length) { for(var iter251 in iter250) { iter251=iter250[iter251] output.writeI32(iter251) } } output.writeListEnd() } } } output.writeListEnd() } output.writeFieldEnd() } if (null != this.parentFeatures) { output.writeFieldBegin('parentFeatures', Thrift.Type.LIST, 4) { output.writeListBegin(Thrift.Type.STRUCT, this.parentFeatures.length) { for(var iter252 in this.parentFeatures) { iter252=this.parentFeatures[iter252] iter252.write(output) } } output.writeListEnd() } output.writeFieldEnd() } if (null != this.debugLines) { output.writeFieldBegin('debugLines', Thrift.Type.LIST, 3) { output.writeListBegin(Thrift.Type.STRING, this.debugLines.length) { for(var iter253 in this.debugLines) { iter253=this.debugLines[iter253] output.writeString(iter253) } } output.writeListEnd() } output.writeFieldEnd() } output.writeFieldStop() output.writeStructEnd() return }
foursquare/fsqio
src/jvm/io/fsq/twofishes/server/resources/twofishes-static/gen-js/geocoder_types.js
JavaScript
apache-2.0
69,674
import * as types from '../mutation_types' const initTime = { time: new Date().getDate() }; export default { repositoryList({ commit },data) { commit(types.REPOSITORY_LIST, data) }, updateList({commit},list){ commit(types.UPDATE_LIST,list) } };
fangyang888/vue-project
src/store/actions.js
JavaScript
apache-2.0
273
/** * @fileoverview This file is generated by the Angular 2 template compiler. * Do not edit. * @suppress {suspiciousCode,uselessCode,missingProperties} */ /* tslint:disable */ 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 __()); }; import * as import0 from './item-reorder'; import * as import1 from '@angular/core/src/change_detection/change_detection'; import * as import2 from '@angular/core/src/linker/view'; import * as import3 from '@angular/core/src/linker/view_utils'; import * as import5 from '@angular/core/src/metadata/view'; import * as import6 from '@angular/core/src/linker/view_type'; import * as import7 from '@angular/core/src/linker/component_factory'; import * as import8 from './item'; import * as import9 from '@angular/core/src/linker/element_ref'; import * as import10 from '../icon/icon.ngfactory'; import * as import11 from '../../config/config'; import * as import12 from '../icon/icon'; export var Wrapper_ItemReorder = (function () { function Wrapper_ItemReorder(p0, p1, p2, p3) { this._changed = false; this.context = new import0.ItemReorder(p0, p1, p2, p3); this._expr_0 = import1.UNINITIALIZED; this._expr_1 = import1.UNINITIALIZED; this._expr_2 = import1.UNINITIALIZED; } Wrapper_ItemReorder.prototype.ngOnDetach = function (view, componentView, el) { }; Wrapper_ItemReorder.prototype.ngOnDestroy = function () { this.context.ngOnDestroy(); (this.subscription0 && this.subscription0.unsubscribe()); }; Wrapper_ItemReorder.prototype.check_reorder = function (currValue, throwOnChange, forceUpdate) { if ((forceUpdate || import3.checkBinding(throwOnChange, this._expr_0, currValue))) { this._changed = true; this.context.reorder = currValue; this._expr_0 = currValue; } }; Wrapper_ItemReorder.prototype.ngDoCheck = function (view, el, throwOnChange) { var changed = this._changed; this._changed = false; return changed; }; Wrapper_ItemReorder.prototype.checkHost = function (view, componentView, el, throwOnChange) { var currVal_1 = this.context._enableReorder; if (import3.checkBinding(throwOnChange, this._expr_1, currVal_1)) { view.renderer.setElementClass(el, 'reorder-enabled', currVal_1); this._expr_1 = currVal_1; } var currVal_2 = this.context._visibleReorder; if (import3.checkBinding(throwOnChange, this._expr_2, currVal_2)) { view.renderer.setElementClass(el, 'reorder-visible', currVal_2); this._expr_2 = currVal_2; } }; Wrapper_ItemReorder.prototype.handleEvent = function (eventName, $event) { var result = true; return result; }; Wrapper_ItemReorder.prototype.subscribe = function (view, _eventHandler, emit0) { this._eventHandler = _eventHandler; if (emit0) { (this.subscription0 = this.context.ionItemReorder.subscribe(_eventHandler.bind(view, 'ionItemReorder'))); } }; return Wrapper_ItemReorder; }()); export var Wrapper_Reorder = (function () { function Wrapper_Reorder(p0, p1) { this._changed = false; this.context = new import0.Reorder(p0, p1); } Wrapper_Reorder.prototype.ngOnDetach = function (view, componentView, el) { }; Wrapper_Reorder.prototype.ngOnDestroy = function () { }; Wrapper_Reorder.prototype.ngDoCheck = function (view, el, throwOnChange) { var changed = this._changed; this._changed = false; return changed; }; Wrapper_Reorder.prototype.checkHost = function (view, componentView, el, throwOnChange) { }; Wrapper_Reorder.prototype.handleEvent = function (eventName, $event) { var result = true; if ((eventName == 'click')) { var pd_sub_0 = (this.context.onClick($event) !== false); result = (pd_sub_0 && result); } return result; }; Wrapper_Reorder.prototype.subscribe = function (view, _eventHandler) { this._eventHandler = _eventHandler; }; return Wrapper_Reorder; }()); var renderType_Reorder_Host = import3.createRenderComponentType('', 0, import5.ViewEncapsulation.None, [], {}); var View_Reorder_Host0 = (function (_super) { __extends(View_Reorder_Host0, _super); function View_Reorder_Host0(viewUtils, parentView, parentIndex, parentElement) { _super.call(this, View_Reorder_Host0, renderType_Reorder_Host, import6.ViewType.HOST, viewUtils, parentView, parentIndex, parentElement, import1.ChangeDetectorStatus.CheckAlways); } View_Reorder_Host0.prototype.createInternal = function (rootSelector) { this._el_0 = import3.selectOrCreateRenderHostElement(this.renderer, 'ion-reorder', import3.EMPTY_INLINE_ARRAY, rootSelector, null); this.compView_0 = new View_Reorder0(this.viewUtils, this, 0, this._el_0); this._Reorder_0_3 = new Wrapper_Reorder(this.injectorGet(import8.Item, this.parentIndex), new import9.ElementRef(this._el_0)); this.compView_0.create(this._Reorder_0_3.context); var disposable_0 = import3.subscribeToRenderElement(this, this._el_0, new import3.InlineArray2(2, 'click', null), this.eventHandler(this.handleEvent_0)); this.init(this._el_0, (this.renderer.directRenderer ? null : [this._el_0]), [disposable_0]); return new import7.ComponentRef_(0, this, this._el_0, this._Reorder_0_3.context); }; View_Reorder_Host0.prototype.injectorGetInternal = function (token, requestNodeIndex, notFoundResult) { if (((token === import0.Reorder) && (0 === requestNodeIndex))) { return this._Reorder_0_3.context; } return notFoundResult; }; View_Reorder_Host0.prototype.detectChangesInternal = function (throwOnChange) { this._Reorder_0_3.ngDoCheck(this, this._el_0, throwOnChange); this.compView_0.detectChanges(throwOnChange); }; View_Reorder_Host0.prototype.destroyInternal = function () { this.compView_0.destroy(); }; View_Reorder_Host0.prototype.visitRootNodesInternal = function (cb, ctx) { cb(this._el_0, ctx); }; View_Reorder_Host0.prototype.handleEvent_0 = function (eventName, $event) { this.compView_0.markPathToRootAsCheckOnce(); var result = true; result = (this._Reorder_0_3.handleEvent(eventName, $event) && result); return result; }; return View_Reorder_Host0; }(import2.AppView)); export var ReorderNgFactory = new import7.ComponentFactory('ion-reorder', View_Reorder_Host0, import0.Reorder); var styles_Reorder = []; var renderType_Reorder = import3.createRenderComponentType('', 0, import5.ViewEncapsulation.None, styles_Reorder, {}); export var View_Reorder0 = (function (_super) { __extends(View_Reorder0, _super); function View_Reorder0(viewUtils, parentView, parentIndex, parentElement) { _super.call(this, View_Reorder0, renderType_Reorder, import6.ViewType.COMPONENT, viewUtils, parentView, parentIndex, parentElement, import1.ChangeDetectorStatus.CheckAlways); } View_Reorder0.prototype.createInternal = function (rootSelector) { var parentRenderNode = this.renderer.createViewRoot(this.parentElement); this._el_0 = import3.createRenderElement(this.renderer, parentRenderNode, 'ion-icon', new import3.InlineArray4(4, 'name', 'reorder', 'role', 'img'), null); this._Icon_0_3 = new import10.Wrapper_Icon(this.parentView.injectorGet(import11.Config, this.parentIndex), new import9.ElementRef(this._el_0), this.renderer); this.init(null, (this.renderer.directRenderer ? null : [this._el_0]), null); return null; }; View_Reorder0.prototype.injectorGetInternal = function (token, requestNodeIndex, notFoundResult) { if (((token === import12.Icon) && (0 === requestNodeIndex))) { return this._Icon_0_3.context; } return notFoundResult; }; View_Reorder0.prototype.detectChangesInternal = function (throwOnChange) { var currVal_0_0_0 = 'reorder'; this._Icon_0_3.check_name(currVal_0_0_0, throwOnChange, false); this._Icon_0_3.ngDoCheck(this, this._el_0, throwOnChange); this._Icon_0_3.checkHost(this, this, this._el_0, throwOnChange); }; View_Reorder0.prototype.destroyInternal = function () { this._Icon_0_3.ngOnDestroy(); }; return View_Reorder0; }(import2.AppView)); //# sourceMappingURL=item-reorder.ngfactory.js.map
driftyco/ionic-site
content/docs/v3/demos/src/components/item/item-reorder.ngfactory.js
JavaScript
apache-2.0
8,737
var namespaceorg_1_1onosproject_1_1driver_1_1extensions = [ [ "NiciraExtensionTreatmentInterpreter", "classorg_1_1onosproject_1_1driver_1_1extensions_1_1NiciraExtensionTreatmentInterpreter.html", "classorg_1_1onosproject_1_1driver_1_1extensions_1_1NiciraExtensionTreatmentInterpreter" ], [ "NiciraResubmit", "classorg_1_1onosproject_1_1driver_1_1extensions_1_1NiciraResubmit.html", "classorg_1_1onosproject_1_1driver_1_1extensions_1_1NiciraResubmit" ], [ "NiciraSetNshSpi", "classorg_1_1onosproject_1_1driver_1_1extensions_1_1NiciraSetNshSpi.html", "classorg_1_1onosproject_1_1driver_1_1extensions_1_1NiciraSetNshSpi" ], [ "NiciraSetTunnelDst", "classorg_1_1onosproject_1_1driver_1_1extensions_1_1NiciraSetTunnelDst.html", "classorg_1_1onosproject_1_1driver_1_1extensions_1_1NiciraSetTunnelDst" ] ];
onosfw/apis
onos/apis/namespaceorg_1_1onosproject_1_1driver_1_1extensions.js
JavaScript
apache-2.0
815
var mercurius = require('../index.js'); var request = require('supertest'); var crypto = require('crypto'); var should = require('chai').should(); var redis = require('../redis.js'); describe('mercurius register', function() { var token; before(function() { return mercurius.ready; }); var origRandomBytes = crypto.randomBytes; afterEach(function() { crypto.randomBytes = origRandomBytes; }); it('replies with 500 if there\'s an error while generating the token', function(done) { crypto.randomBytes = function(len, cb) { cb(new Error('Fake error.')); }; request(mercurius.app) .post('/register') .send({ machineId: 'machineX', endpoint: 'http://localhost:50005', key: '', }) .expect(500, done); }); it('successfully registers users', function(done) { request(mercurius.app) .post('/register') .send({ machineId: 'machine', endpoint: 'https://localhost:50008', key: '', }) .expect(200) .expect(function(res) { res.body.should.be.an('object'); res.body.machines.should.be.an('object'); res.body.token.should.have.length(16); token = res.body.token; }) .end(done); }); it('successfully registers additional machine', function(done) { request(mercurius.app) .post('/register') .send({ token: token, machineId: 'machine2', endpoint: 'endpoint', key: '', }) .expect(200) .expect(function(res) { res.body.token.should.equal(token); res.body.machines.machine.endpoint.should.equal('https://localhost:50008'); res.body.machines.machine2.endpoint.should.equal('endpoint'); }) .end(done); }); it('successfully registers a machine even if it exists', function(done) { redis.smembers(token) .then(function(machines) { var startlength = machines.length; request(mercurius.app) .post('/register') .send({ token: token, machineId: 'machine2', endpoint: 'endpoint2', key: '', }) .expect(200) .expect(function(res) { res.body.token.should.equal(token); res.body.machines.machine2.endpoint.should.equal('endpoint2'); Object.keys(res.body.machines).should.have.length(startlength); }) .end(done); }); }); it('returns 404 if bad token provided', function(done) { request(mercurius.app) .post('/register') .send({ token: 'notexisting', machineId: 'machine of a not existing token', endpoint: 'endpoint', key: '', }) .expect(404, done); }); });
marco-c/mercurius
test/testRegister.js
JavaScript
apache-2.0
2,638
/** * Created by king on 15-5-20. * * ch10.net_maxconnections_clientB.js */ console.info("------ net getconnections() ------"); console.info(); var net = require("net"); // TODO: 引入网络(Net)模块 var HOST = '127.0.0.1'; // TODO: 定义服务器地址 var PORT = 8877; // TODO: 定义端口号 /** * 使用net.connect()函数方法创建一个TCP客户端实例 */ var client = net.connect(PORT, HOST, function() { console.log('client B connected'); console.info(); client.write('client write : Hello Server!'); //client.end(); }); /** * 为TCP客户端实例添加一个"end"事件处理函数 */ client.on('end', function() { console.log('clientB disconnected'); console.info(); });
0end1/code_base
Node.js_Codebase/chapter10/ServerMaxConnections/ch10.net_maxconnections_clientB.js
JavaScript
apache-2.0
743
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 __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var ts = require("typescript"); var index_1 = require("../../models/index"); var components_1 = require("../components"); var AliasConverter = (function (_super) { __extends(AliasConverter, _super); function AliasConverter() { _super.apply(this, arguments); this.priority = 100; } AliasConverter.prototype.supportsNode = function (context, node, type) { if (!type || !node || !node.typeName) return false; if (!type.symbol) return true; var checker = context.checker; var symbolName = checker.getFullyQualifiedName(type.symbol).split('.'); if (!symbolName.length) return false; if (symbolName[0].substr(0, 1) == '"') symbolName.shift(); var nodeName = ts.getTextOfNode(node.typeName).split('.'); if (!nodeName.length) return false; var common = Math.min(symbolName.length, nodeName.length); symbolName = symbolName.slice(-common); nodeName = nodeName.slice(-common); return nodeName.join('.') != symbolName.join('.'); }; AliasConverter.prototype.convertNode = function (context, node) { var name = ts.getTextOfNode(node.typeName); return new index_1.ReferenceType(name, index_1.ReferenceType.SYMBOL_ID_RESOLVE_BY_NAME); }; AliasConverter = __decorate([ components_1.Component({ name: 'type:alias' }) ], AliasConverter); return AliasConverter; })(components_1.ConverterTypeComponent); exports.AliasConverter = AliasConverter;
aciccarello/typedoc
lib/converter/types/alias.js
JavaScript
apache-2.0
2,391
var SPI = require('spi'); var extend = require('util')._extend; var openSpi = function() { var device = '/dev/spidev0.0'; return new SPI.Spi(device, [], function(s) { s.open(); }); }; var Adc = function(options) { var self = this; var settings = extend( { voltage: 3.3, //3.3V by default spi: null }, options); self.voltage = settings.voltage; self.spi = settings.spi || openSpi(); /** * Read voltage (in a range 0-3.3V by default). * @param channel * @param callback */ self.readVoltage = function(channel, callback) { self.readSpi(channel, function(value) { var voltage = ((value * self.voltage) / self.maxValue); callback(voltage); }); }; /** * Read normalized value (in a range 0-1). * @param channel * @param callback */ self.readNormalizedValue = function(channel, callback) { self.readSpi(channel, function(value) { var normalizedValue = ((value) / self.maxValue); callback(normalizedValue); }); }; /** * Read raw ADC value (the range depends on ADC resolution). * @param channel * @param callback */ self.readRawValue = function(channel, callback) { self.readSpi(channel, callback); } }; module.exports.Mcp3208 = function(options) { var self = this; Adc.call(self, options); self.maxValue = 4095; self.readSpi = function(channel, callback) { var tx = new Buffer([4 | 2 | (channel >> 2), (channel & 3) << 6, 0]); var rx = new Buffer([0, 0, 0]); self.spi.transfer(tx, rx, function(dev, buffer) { var value = ((buffer[1] & 15) << 8) + buffer[2]; callback(value); }) }; }; module.exports.Mcp3008 = function(options) { var self = this; Adc.call(self, options); self.maxValue = 1023; self.readSpi = function(channel, callback) { var tx = new Buffer([1, (8 + channel) << 4, 0]); var rx = new Buffer([0, 0, 0]); self.spi.transfer(tx, rx, function(dev, buffer) { var value = ((buffer[1] & 3) << 8) + buffer[2]; callback(value); }) }; };
anha1/mcp-adc
mcp-adc.js
JavaScript
apache-2.0
2,219
var nbinput = 1; var $collectionHolder; $(function() { var $alreadyUsed = $("#alreadyExistVar").html(); if ($alreadyUsed) { showDialog("#some-exists-dialog"); } // Get the ul that holds the collection of tags $collectionHolder = $('#inputBlock'); // count the current form inputs we have (e.g. 2), use that as the new // index when inserting a new item (e.g. 2) $collectionHolder.data('index', $collectionHolder.find('.fileInput').length); $('#newInputButton').on('click', function(e) { if (nbinput < 5) { // prevent the link from creating a "#" on the URL e.preventDefault(); // add a new tag form (see next code block) addTagForm($collectionHolder); } else { showDialog("#limitFileDialog"); } }); }); $("#confirmOverride").click(function(){ $("#upload-block form").submit(); }); function changeInputFile(element) { var lineInput = $(element).parent().parent().parent(); var filename = $(element).val(); var n = filename.lastIndexOf('.'); var format = filename.substring(n + 1); $('.input-format', lineInput).val(format); $(element).parent().addClass("bg-green"); $(element).parent().removeClass("bg-gray"); } function addTagForm($collectionHolder) { // Get the data-prototype explained earlier var prototype = $collectionHolder.data('prototype'); // get the new index var index = $collectionHolder.data('index'); // Replace '__name__' in the prototype's HTML to // instead be a number based on how many items we have var newForm = prototype.replace(/__name__/g, index); // increase the index with one for the next item $collectionHolder.data('index', index + 1); var $newFormLi = $('<div></div>').append(newForm); var newBlock =$('<div id="lineInput_' + (index+1) + '" class="row cells12 fileInput"></div>'); $('input', $newFormLi).each(function(index, element){ var name = element.name; var $block = $('<div class="input-control text full-size"></div>').append(element); if (contains(name, 'category') || contains(name, 'creator') || contains(name, 'nameAlreadyUsed')) return; if (contains(name, 'initials') || contains(name, 'date')) { $block = $('<div class="cell colspan2"></div>').append($block); if(contains(name, 'initials')) { $('input', $block).val("AM"); } if(contains(name, 'date')) { $('input', $block).val($('#sw_docmanagerbundle_uploadsession_documents_0_date').val()); } } else if (contains(name, 'name')) { $block = $('<div class="cell colspan4"></div>').append($block); } else if (contains(name, 'format') || contains(name, 'code')) { $block = $('<div class="cell colspan1"></div>').append($block); if(contains(name, 'code')) { $('input', $block).val($('#sw_docmanagerbundle_uploadsession_documents_0_code').val()); $('input', $block).attr("readonly","readonly"); } if(contains(name, 'format')) { $('input', $block).attr("class",'input-format'); } } else if (contains(name, 'file')) { $('input', $block).attr("onchange",'changeInputFile(this)'); $block = $('<div class="input-control full-size input-file-custom button full-size bg-gray fg-white">Datei</div>').append(element); $block = $('<div class="cell colspan1"></div>').append($block); } else { return true; } newBlock.append($block); }); var $blockRemove = '<div class="cell colspan1 v-align-middle padding10">'; $blockRemove += '<button onclick="removeLine(lineInput_' + (index+1) + ')" class="removeInputButton button mini-button cycle-button">-</button>'; $blockRemove += '</div>'; newBlock.append($blockRemove); newBlock.hide(); newBlock.appendTo($("#inputBlock")).show("slow"); $("#sw_docmanagerbundle_uploadsession_weiter").prop( 'disabled', ($("#inputBlock").children().length < 1)); } function contains(text, chartext) { return text.indexOf(chartext) > -1; } function removeLine(id) { $(id).remove(); $("#sw_docmanagerbundle_uploadsession_weiter").prop( 'disabled', ($("#inputBlock").children().length < 1)); }
adrienManikon/docmanager
src/SW/DocManagerBundle/Resources/public/js/upload.js
JavaScript
apache-2.0
4,586
/* */ "format esm"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; import { isPresent, isBlank, CONST } from 'angular2/src/facade/lang'; import { ListWrapper, StringMapWrapper } from 'angular2/src/facade/collection'; import { ViewType } from './view_type'; export let StaticNodeDebugInfo = class StaticNodeDebugInfo { constructor(providerTokens, componentToken, refTokens) { this.providerTokens = providerTokens; this.componentToken = componentToken; this.refTokens = refTokens; } }; StaticNodeDebugInfo = __decorate([ CONST(), __metadata('design:paramtypes', [Array, Object, Object]) ], StaticNodeDebugInfo); export class DebugContext { constructor(_view, _nodeIndex, _tplRow, _tplCol) { this._view = _view; this._nodeIndex = _nodeIndex; this._tplRow = _tplRow; this._tplCol = _tplCol; } get _staticNodeInfo() { return isPresent(this._nodeIndex) ? this._view.staticNodeDebugInfos[this._nodeIndex] : null; } get context() { return this._view.context; } get component() { var staticNodeInfo = this._staticNodeInfo; if (isPresent(staticNodeInfo) && isPresent(staticNodeInfo.componentToken)) { return this.injector.get(staticNodeInfo.componentToken); } return null; } get componentRenderElement() { var componentView = this._view; while (isPresent(componentView.declarationAppElement) && componentView.type !== ViewType.COMPONENT) { componentView = componentView.declarationAppElement.parentView; } return isPresent(componentView.declarationAppElement) ? componentView.declarationAppElement.nativeElement : null; } get injector() { return this._view.injector(this._nodeIndex); } get renderNode() { if (isPresent(this._nodeIndex) && isPresent(this._view.allNodes)) { return this._view.allNodes[this._nodeIndex]; } else { return null; } } get providerTokens() { var staticNodeInfo = this._staticNodeInfo; return isPresent(staticNodeInfo) ? staticNodeInfo.providerTokens : null; } get source() { return `${this._view.componentType.templateUrl}:${this._tplRow}:${this._tplCol}`; } get locals() { var varValues = {}; // TODO(tbosch): right now, the semantics of debugNode.locals are // that it contains the variables of all elements, not just // the given one. We preserve this for now to not have a breaking // change, but should change this later! ListWrapper.forEachWithIndex(this._view.staticNodeDebugInfos, (staticNodeInfo, nodeIndex) => { var refs = staticNodeInfo.refTokens; StringMapWrapper.forEach(refs, (refToken, refName) => { var varValue; if (isBlank(refToken)) { varValue = isPresent(this._view.allNodes) ? this._view.allNodes[nodeIndex] : null; } else { varValue = this._view.injectorGet(refToken, nodeIndex, null); } varValues[refName] = varValue; }); }); StringMapWrapper.forEach(this._view.locals, (localValue, localName) => { varValues[localName] = localValue; }); return varValues; } }
tzerb/Learning
WebApplication3/src/WebApplication3/jspm_packages/npm/[email protected]/es6/prod/src/core/linker/debug_context.js
JavaScript
apache-2.0
4,102
"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 __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var di_1 = require('angular2/src/core/di'); var di_2 = require('angular2/src/core/di'); var collection_1 = require('angular2/src/facade/collection'); var lang_1 = require('angular2/src/facade/lang'); var exceptions_1 = require('angular2/src/facade/exceptions'); var metadata_1 = require('../core/metadata'); var view_resolver_1 = require('angular2/src/compiler/view_resolver'); var MockViewResolver = (function (_super) { __extends(MockViewResolver, _super); function MockViewResolver() { _super.call(this); /** @internal */ this._views = new collection_1.Map(); /** @internal */ this._inlineTemplates = new collection_1.Map(); /** @internal */ this._viewCache = new collection_1.Map(); /** @internal */ this._directiveOverrides = new collection_1.Map(); } /** * Overrides the {@link ViewMetadata} for a component. * * @param {Type} component * @param {ViewDefinition} view */ MockViewResolver.prototype.setView = function (component, view) { this._checkOverrideable(component); this._views.set(component, view); }; /** * Overrides the inline template for a component - other configuration remains unchanged. * * @param {Type} component * @param {string} template */ MockViewResolver.prototype.setInlineTemplate = function (component, template) { this._checkOverrideable(component); this._inlineTemplates.set(component, template); }; /** * Overrides a directive from the component {@link ViewMetadata}. * * @param {Type} component * @param {Type} from * @param {Type} to */ MockViewResolver.prototype.overrideViewDirective = function (component, from, to) { this._checkOverrideable(component); var overrides = this._directiveOverrides.get(component); if (lang_1.isBlank(overrides)) { overrides = new collection_1.Map(); this._directiveOverrides.set(component, overrides); } overrides.set(from, to); }; /** * Returns the {@link ViewMetadata} for a component: * - Set the {@link ViewMetadata} to the overridden view when it exists or fallback to the default * `ViewResolver`, * see `setView`. * - Override the directives, see `overrideViewDirective`. * - Override the @View definition, see `setInlineTemplate`. * * @param component * @returns {ViewDefinition} */ MockViewResolver.prototype.resolve = function (component) { var view = this._viewCache.get(component); if (lang_1.isPresent(view)) return view; view = this._views.get(component); if (lang_1.isBlank(view)) { view = _super.prototype.resolve.call(this, component); } var directives = []; var overrides = this._directiveOverrides.get(component); if (lang_1.isPresent(overrides) && lang_1.isPresent(view.directives)) { flattenArray(view.directives, directives); overrides.forEach(function (to, from) { var srcIndex = directives.indexOf(from); if (srcIndex == -1) { throw new exceptions_1.BaseException("Overriden directive " + lang_1.stringify(from) + " not found in the template of " + lang_1.stringify(component)); } directives[srcIndex] = to; }); view = new metadata_1.ViewMetadata({ template: view.template, templateUrl: view.templateUrl, directives: directives }); } var inlineTemplate = this._inlineTemplates.get(component); if (lang_1.isPresent(inlineTemplate)) { view = new metadata_1.ViewMetadata({ template: inlineTemplate, templateUrl: null, directives: view.directives }); } this._viewCache.set(component, view); return view; }; /** * @internal * * Once a component has been compiled, the AppProtoView is stored in the compiler cache. * * Then it should not be possible to override the component configuration after the component * has been compiled. * * @param {Type} component */ MockViewResolver.prototype._checkOverrideable = function (component) { var cached = this._viewCache.get(component); if (lang_1.isPresent(cached)) { throw new exceptions_1.BaseException("The component " + lang_1.stringify(component) + " has already been compiled, its configuration can not be changed"); } }; MockViewResolver = __decorate([ di_2.Injectable(), __metadata('design:paramtypes', []) ], MockViewResolver); return MockViewResolver; }(view_resolver_1.ViewResolver)); exports.MockViewResolver = MockViewResolver; function flattenArray(tree, out) { for (var i = 0; i < tree.length; i++) { var item = di_1.resolveForwardRef(tree[i]); if (lang_1.isArray(item)) { flattenArray(item, out); } else { out.push(item); } } } //# sourceMappingURL=view_resolver_mock.js.map
tzerb/Learning
WebApplication3/src/WebApplication3/jspm_packages/npm/dist/js/cjs/src/mock/view_resolver_mock.js
JavaScript
apache-2.0
6,175
// app/routes/form.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { willTransition: function(transition) { // 如果是使用this.get('key')获取不了页面输入值,因为不是通过action提交表单的 var v = this.controller.get('firstName'); // 任意获取一个作为判断表单输入值 if (v && !confirm("你确定要离开这个页面吗??")) { transition.abort(); } else { return true; } } } });
ubuntuvim/my_emberjs_code
chapter3_routes/app/routes/form.js
JavaScript
apache-2.0
532
/* General Loops - Abstract Case - Free variable */ function f1() { return 1; } function f2() { return 2; } function f3() { return 3; } var b = !Date.now(); // non-deterministic boolean value. var o1 = {x: f1, y: f2, z: f3}; var o2 = {}; var arr = []; if (b) { arr.push("x"); arr.push("y"); } else { arr.push("z"); arr.push("y"); arr.push("x"); } // the array ’arr’ is not concrete when we assume the // path-insensitive analysis. var i = arr.length; while (i--) { // the analysis cannot enumerate all the concrete iterations. var t = arr[i]; var v = o1[t]; o2[t] = (function(v) { return function() { return v; }; }(v)); } var result = o2.x() !== f2; TAJS_assert(result); // TAJS-determinacy: BoolTop // LSA: BoolTop // CompAbs: true
cs-au-dk/TAJS
test-resources/src/micro-different-loop-kinds/AGHeap.js
JavaScript
apache-2.0
813
function f() { return 42} TAJS_assert(f.call.call.call(f) === 42) TAJS_assert(f.apply.apply.apply(f) === 42) TAJS_assert(Function.prototype.apply.apply(f) == 42) TAJS_dumpValue(f.apply.apply.apply(f)) function g(x) { return x + 1} TAJS_assert(Function.prototype.call(g,45) === undefined) TAJS_assert(isNaN(g.call.call(g,45))) TAJS_dumpValue(g.call.call(g,45)) TAJS_assert(Function.prototype.call.call(g, null, 87), 'isMaybeNumUInt||isMaybeNaN'); TAJS_dumpValue(Function.prototype.call.call(g,null,87));
cs-au-dk/TAJS
test-resources/src/micro/test109.js
JavaScript
apache-2.0
514
'use strict'; /** * Get html element by auto-generated (via XPath) class name * @memberof imgix * @static * @private * @param {string} xpath the xpath of the element * @returns {Element} element with the xpath */ imgix.getElementByXPathClassName = function (xpath) { return document.querySelector('.' + imgix.getXPathClass(xpath)); }; /** * Get image from an html element by auto-generated (via XPath) class name * @memberof imgix * @static * @private * @param {string} xpath the xpath of the element to get * @returns {string} url of image on the element */ imgix.getElementImageByXPathClassName = function (xpath) { return imgix.getElementImage(imgix.getElementByXPathClassName(xpath)); }; // Current: https://github.com/firebug/firebug/blob/5026362f2d1734adfcc4b44d5413065c50b27400/extension/content/firebug/lib/xpath.js imgix.getElementTreeXPath = function (element) { var paths = []; // Use nodeName (instead of localName) so namespace prefix is included (if any). for (; element && element.nodeType === Node.ELEMENT_NODE; element = element.parentNode) { var index = 0; for (var sibling = element.previousSibling; sibling; sibling = sibling.previousSibling) { // Ignore document type declaration. if (sibling.nodeType === Node.DOCUMENT_TYPE_NODE) { continue; } if (sibling.nodeName === element.nodeName) { ++index; } } var tagName = (element.prefix ? element.prefix + ':' : '') + element.localName, pathIndex = (index ? '[' + (index + 1) + ']' : ''); paths.splice(0, 0, tagName + pathIndex); } return paths.length ? '/' + paths.join('/') : null; };
kmddev/imgix.js
src/xpath.js
JavaScript
bsd-2-clause
1,664
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); }); router.get('/socket', function(req, res, next){ res.render('socket', {title: 'socket.io test'}) }); module.exports = router;
wushuyi/newClassSystem
server/routes/index.js
JavaScript
bsd-2-clause
309